<?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/"
	>

<channel>
	<title>Information theory &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/information-theory/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>on web development</description>
	<lastBuildDate>Tue, 13 Feb 2018 08:18:15 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.0.3</generator>
	<item>
		<title>Computer Algorithms: Lossy Image Compression with Run-Length Encoding</title>
		<link>/2012/05/03/computer-algorithms-lossy-image-compression-with-run-length-encoding/</link>
		<comments>/2012/05/03/computer-algorithms-lossy-image-compression-with-run-length-encoding/#comments</comments>
		<pubDate>Thu, 03 May 2012 20:27:06 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Coding theory]]></category>
		<category><![CDATA[Data compression]]></category>
		<category><![CDATA[data compression algorithm]]></category>
		<category><![CDATA[Graphics file formats]]></category>
		<category><![CDATA[image compression]]></category>
		<category><![CDATA[Image processing]]></category>
		<category><![CDATA[Information theory]]></category>
		<category><![CDATA[jpeg]]></category>
		<category><![CDATA[Lossless data compression]]></category>
		<category><![CDATA[lossy algorithm]]></category>
		<category><![CDATA[Lossy compression]]></category>
		<category><![CDATA[PCX]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Pixel]]></category>
		<category><![CDATA[Run-length encoding]]></category>
		<category><![CDATA[suitable algorithm]]></category>
		<category><![CDATA[Technology/Internet]]></category>

		<guid isPermaLink="false">/?p=3078</guid>
		<description><![CDATA[Introduction Run-length encoding is a data compression algorithm that helps us encode large runs of repeating items by only sending one item from the run and a counter showing how many times this item is repeated. Unfortunately this technique is useless when trying to compress natural language texts, because they don’t have long runs of &#8230; <a href="/2012/05/03/computer-algorithms-lossy-image-compression-with-run-length-encoding/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Lossy Image Compression with Run-Length Encoding</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Run-length Encoding">Computer Algorithms: Data Compression with Run-length Encoding </a></li>
<li><a href="/2012/01/16/computer-algorithms-data-compression-with-bitmaps/" rel="bookmark" title="Computer Algorithms: Data Compression with Bitmaps">Computer Algorithms: Data Compression with Bitmaps </a></li>
<li><a href="/2012/01/23/computer-algorithms-data-compression-with-diagram-encoding-and-pattern-substitution/" rel="bookmark" title="Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution">Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution </a></li>
<li><a href="/2012/01/30/computer-algorithms-data-compression-with-relative-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Relative Encoding">Computer Algorithms: Data Compression with Relative Encoding </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p><a href="/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/" title="Computer Algorithms: Data Compression with Run-length Encoding">Run-length encoding</a> is a data compression algorithm that helps us encode large runs of repeating items by only sending one item from the run and a counter showing how many times this item is repeated. Unfortunately this technique is useless when trying to compress natural language texts, because they don’t have long runs of repeating elements. In the other hand RLE is useful when it comes to image compression, because images happen to have long runs pixels with identical color. </p>
<p>As you can see on the following picture we can compress consecutive pixels by only replacing each run with one pixel from it and a counter showing how many items it contains.</p>
<figure id="attachment_3101" style="width: 619px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/05/1.LosslessRLEforImages.png"><img src="/wp-content/uploads/2012/05/1.LosslessRLEforImages.png" alt="Lossless RLE for Images" title="Lossless RLE for Images" width="619" height="216" class="size-full wp-image-3101" srcset="/wp-content/uploads/2012/05/1.LosslessRLEforImages.png 619w, /wp-content/uploads/2012/05/1.LosslessRLEforImages-300x104.png 300w" sizes="(max-width: 619px) 100vw, 619px" /></a><figcaption class="wp-caption-text">Although lossless RLE can be quite effective for image compression, it is still not the best approach!</figcaption></figure>
<p>In this case we can save only counters for pixels that are repeated more than once. Such the input stream “aaaabbaba” will be compressed as “[4]a[2]baba”. </p>
<p>Actually there are several ways run-length encoding can be used for image compression. A possible way of compressing a picture can be either row by row or column by column, as it is shown on the picture below.</p>
<p><figure id="attachment_3102" style="width: 621px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/05/2.RowbyRowandColbyCol.png"><img src="/wp-content/uploads/2012/05/2.RowbyRowandColbyCol.png" alt="Row by row or column by column compression" title="Row by row or column by column compression" width="621" height="300" class="size-full wp-image-3102" srcset="/wp-content/uploads/2012/05/2.RowbyRowandColbyCol.png 621w, /wp-content/uploads/2012/05/2.RowbyRowandColbyCol-300x144.png 300w" sizes="(max-width: 621px) 100vw, 621px" /></a><figcaption class="wp-caption-text">Row by row or column by column compression.</figcaption></figure><span id="more-3078"></span></p>
<p>The problem in practice is that sometimes compressing row by row may be effective, while in other cases the same approach is very ineffective. This is illustrated by the image below.</p>
<figure id="attachment_3103" style="width: 621px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/05/3.EffectiveandIneffectiveCompression.png"><img src="/wp-content/uploads/2012/05/3.EffectiveandIneffectiveCompression.png" alt="Effective and Ineffective Compression" title="Effective and Ineffective Compression" width="621" height="328" class="size-full wp-image-3103" srcset="/wp-content/uploads/2012/05/3.EffectiveandIneffectiveCompression.png 621w, /wp-content/uploads/2012/05/3.EffectiveandIneffectiveCompression-300x158.png 300w" sizes="(max-width: 621px) 100vw, 621px" /></a><figcaption class="wp-caption-text">Sometimes image compression may be done only after some preprocessing that can help us understand the best compression approach!</figcaption></figure>
<p>Obviously run-length encoding is a very good approach when compressing images, however when we talk about big images with millions of pixels it’s somehow natural to come with some lossy compression.</p>
<h2>Overview</h2>
<p>Lossy RLE is a very suitable algorithm when it comes to images, because in most of the cases large images do appear to have big spaces of identical pixel colors, i.e. when the half of the picture is the blue sky. By using lossy compression we can skip very short runs.</p>
<p>First we’ve to say how long will be the shortest run that we will keep in the compression. For instance if 3 is the shortest run, then runs of 2 consecutive elements will be skipped.</p>
<figure id="attachment_3104" style="width: 621px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/05/4.LossessImageRow.png"><img src="/wp-content/uploads/2012/05/4.LossessImageRow.png" alt="Lossless Pixel Row" title="Lossless Pixel Row" width="621" height="173" class="size-full wp-image-3104" srcset="/wp-content/uploads/2012/05/4.LossessImageRow.png 621w, /wp-content/uploads/2012/05/4.LossessImageRow-300x83.png 300w" sizes="(max-width: 621px) 100vw, 621px" /></a><figcaption class="wp-caption-text">Lossless compression of a pixel row in some cases can be very inefective!</figcaption></figure>
<p>Of course if we set the shortest run to be only one element long, this will make our compression completely lossless, which isn’t very effective. However when we talk about millions of pixels even runs of three or more elements are very short, so it’s up to the developer to decide how long will be the shortest run.</p>
<h3>Some Examples</h3>
<p>Let&#8217;s first define the shortest run that we will keep untouched to be at least three element long.</p>
<figure id="attachment_3105" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/05/5.LossyImageRow.png"><img src="/wp-content/uploads/2012/05/5.LossyImageRow.png" alt="Lossy Pixel Row" title="Lossy Pixel Row" width="620" height="273" class="size-full wp-image-3105" srcset="/wp-content/uploads/2012/05/5.LossyImageRow.png 620w, /wp-content/uploads/2012/05/5.LossyImageRow-300x132.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">We can lose some information that is invisbile to the eye.</figcaption></figure>
<p>The above image is compressed more effectively than the lossless pixel row from the previous picture.</p>
<p>The thing is how to merge short runs. For instance the following three runs have to be blended into one color run.</p>
<figure id="attachment_3106" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/05/6.BlendingShortRuns.png"><img src="/wp-content/uploads/2012/05/6.BlendingShortRuns.png" alt="Blending Short Runs" title="Blending Short Runs" width="620" height="199" class="size-full wp-image-3106" srcset="/wp-content/uploads/2012/05/6.BlendingShortRuns.png 620w, /wp-content/uploads/2012/05/6.BlendingShortRuns-300x96.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">We must chose how to blend short runs!</figcaption></figure>
<p>We can choose the middle color (option #1) or not, but this will always depend on the picture and it will be effective in some cases and ineffective in other.</p>
<h2>Implementation</h2>
<p>Implementing run-length encoding is easy in general. Here’s a simple <a href="/category/php/" title="PHP on stoimen.com">PHP</a> code that shows a lossy RLE.</p>
<pre lang="PHP">
/**
 * Compresses an input list of objects by losing some data using
 * run-length encoding
 * 
 * @param mixed $objectList
 * @param int $minLength
 */
function lossyRLE($objectList, $minLength)
{
	$len 		= is_string($objectList) 
			? strlen($objectList)		// string as an input stream
			: count($objectList);		// array as an input stream
	$j 		= 1;
	$compressed = array();				// compressed output
	
	for ($i = 0; $i < $len; $i++) {
		if (isset($objectList[$i+1]) &#038;&#038; $objectList[$i] == $objectList[$i+1]) {
			$j++;
		} else {
			$l = count($compressed);
			// This is where RLE is converted to a lossy algorithm!
			// In case the run is shorter than a predefined length the
			// algorithm will skip these elements and will stretch the last
			// saved run.
			// NOTE: this logic can be changed in order to take other
			// decisions depending on the goals.
			if ($j < $minLength &#038;&#038; $j < $l) {
				$compressed[$l-1]['count'] += $j;
			} else {
				$compressed[] = array('count' => $j, $objectList[$i]);
			}
			$j = 1;
		}
	}
	
	return $compressed;
}

$input = 'aaaabbaabbbbba';

// aaaaaaaabbbbbb
lossyRLE($input, 3);
</pre>
<p>The code above can be modified in order to work with more complex data. Let’s say we have a “pixel” abstraction as on the example above.</p>
<pre lang="PHP">
/**
 * Pixel abstraction
 */
class Pixel
{
	private $_color = null;
	
	public function __construct($color = '')
	{
		$this->_color = $color;
	}
	
	public function getColor() 
	{
		return $this->_color;
	}
}

/**
 * Inits the pixels array
 * 
 * @param array $pixels
 */
function init(array &$pixels = array())
{
	$colors = array('red', 'green', 'blue');
	
	for ($i = 0; $i < 100; $i++) {
		$pixels[] = new Pixel($colors[mt_rand(0, 2)]);
	}
}

/**
 * Compresses an input list of objects by losing some data using
 * run-length encoding
 * 
 * @param mixed $objectList
 * @param int $minLength
 */
function lossyRLE($objectList, $minLength)
{
	$len 		= is_string($objectList) 
			? strlen($objectList)		// string as an input stream
			: count($objectList);		// array as an input stream
	$j 		= 1;
	$compressed = array();				// compressed output
	
	for ($i = 0; $i < $len; $i++) {
		if (isset($objectList[$i+1]) &#038;&#038; $objectList[$i] == $objectList[$i+1]) {
			$j++;
		} else {
			$l = count($compressed);
			// This is where RLE is converted to a lossy algorithm!
			// In case the run is shorter than a predefined length the
			// algorithm will skip these elements and will stretch the last
			// saved run.
			// NOTE: this logic can be changed in order to take other
			// decisions depending on the goals.
			if ($j < $minLength &#038;&#038; $l > $j) {
				$compressed[$l-1]['count'] += $j;
			} else {
				$compressed[] = array('count' => $j, $objectList[$i]);
			}
			$j = 1;
		}
	}
	
	return $compressed;
}

$pixels = array();

// initializes the pixels array
init($pixels);

$compressed = lossyRLE($pixels, 3);

print_r($compressed);
</pre>
<h2>Complexity</h2>
<p>In general lossless RLE compelxity is linear &#8211; O(n) where n is the number of items from the input stream. Even with the small modification above the complexity remains linear. However we can modify the compression in a slightly different manner (in order to get the middle value from consecutive short runs). This will somehow affect the complexity of the algorithm, of course.</p>
<h2>Application</h2>
<p>Run-length encoding isn’t a very effective option when compressing texts, but for images where long runs of the identical pixels happen to occur it is quite useful. </p>
<figure id="attachment_3107" style="width: 622px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/05/7.LossyRLE.png"><img src="/wp-content/uploads/2012/05/7.LossyRLE.png" alt="Lossy RLE in Practice" title="Lossy RLE in Practice" width="622" height="483" class="size-full wp-image-3107" srcset="/wp-content/uploads/2012/05/7.LossyRLE.png 622w, /wp-content/uploads/2012/05/7.LossyRLE-300x232.png 300w" sizes="(max-width: 622px) 100vw, 622px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<p>Nevertheless RLE is easy to convert into a lossy algorithm, that makes it very suitable for image compression.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Run-length Encoding">Computer Algorithms: Data Compression with Run-length Encoding </a></li>
<li><a href="/2012/01/16/computer-algorithms-data-compression-with-bitmaps/" rel="bookmark" title="Computer Algorithms: Data Compression with Bitmaps">Computer Algorithms: Data Compression with Bitmaps </a></li>
<li><a href="/2012/01/23/computer-algorithms-data-compression-with-diagram-encoding-and-pattern-substitution/" rel="bookmark" title="Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution">Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution </a></li>
<li><a href="/2012/01/30/computer-algorithms-data-compression-with-relative-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Relative Encoding">Computer Algorithms: Data Compression with Relative Encoding </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/05/03/computer-algorithms-lossy-image-compression-with-run-length-encoding/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution</title>
		<link>/2012/01/23/computer-algorithms-data-compression-with-diagram-encoding-and-pattern-substitution/</link>
		<comments>/2012/01/23/computer-algorithms-data-compression-with-diagram-encoding-and-pattern-substitution/#respond</comments>
		<pubDate>Mon, 23 Jan 2012 14:58:48 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Coding theory]]></category>
		<category><![CDATA[Computer file formats]]></category>
		<category><![CDATA[Computer science]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[conventional compressing tool]]></category>
		<category><![CDATA[Data compression]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[Information theory]]></category>
		<category><![CDATA[Lossy compression]]></category>
		<category><![CDATA[pattern substitution algorithm]]></category>
		<category><![CDATA[pattern substitution algorithms]]></category>
		<category><![CDATA[Pattern Substitution The pattern substitution algorithm]]></category>
		<category><![CDATA[Run-length encoding]]></category>
		<category><![CDATA[web hosting]]></category>

		<guid isPermaLink="false">/?p=2623</guid>
		<description><![CDATA[Overview Two variants of run-length encoding are the diagram encoding and the pattern substitution algorithms. The diagram encoding is actually a very simple algorithm. Unlike run-length encoding, where the input stream must consists of many repeating elements, as “aaaaaaaa” for instance, which are very rare in a natural language, there are many so called “diagrams” &#8230; <a href="/2012/01/23/computer-algorithms-data-compression-with-diagram-encoding-and-pattern-substitution/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/01/30/computer-algorithms-data-compression-with-relative-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Relative Encoding">Computer Algorithms: Data Compression with Relative Encoding </a></li>
<li><a href="/2012/02/06/computer-algorithms-data-compression-with-prefix-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Prefix Encoding">Computer Algorithms: Data Compression with Prefix Encoding </a></li>
<li><a href="/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Run-length Encoding">Computer Algorithms: Data Compression with Run-length Encoding </a></li>
<li><a href="/2012/01/16/computer-algorithms-data-compression-with-bitmaps/" rel="bookmark" title="Computer Algorithms: Data Compression with Bitmaps">Computer Algorithms: Data Compression with Bitmaps </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Overview</h2>
<p>Two variants of <a href="/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/" title="Computer Algorithms: Data Compression with Run-length Encoding">run-length encoding</a> are the diagram encoding and the pattern substitution algorithms. The diagram encoding is actually a very simple algorithm. Unlike run-length encoding, where the input stream must consists of many repeating elements, as <strong>“aaaaaaaa”</strong> for instance, which are very rare in a natural language, there are many so called “diagrams” in almost any natural language. In plain English there are some diagrams as <strong>“the”</strong>, <strong>“and”</strong>, <strong>“ing”</strong> (in the word “waiting” for example), <strong>“ a”</strong>, <strong>“ t”</strong>, <strong>“ e”</strong> and many doubled letters. Actually we can extend those diagrams by adding surrounding spaces. Thus we can encode not only “the”, but “ the “, which are 5 characters (2 spaces and 3 letters) with something shorter. In the other hand, as I said, in plain English there are two many doubled letters, which unfortunately aren’t something special for run-length encoding and the compression ratio will be small. Even worse the encoded text may happen to be longer than the input message. Let’s see some examples.</p>
<p>Let’s say we’ve to encode the message “successfully accomplished”, which consists of four doubled letters. However to compress it with run-length encoding we’ll need at least 8 characters, which doesn’t help us a lot.</p>
<pre>
// 8 chars replaced by 8 chars!?
input: 	"successfully accomplished"
output:	"su2ce2sfu2ly a2complished"
</pre>
<p>The problem is that if the input text contains numbers, “2” in particular, we’ve to chose an escape symbol (“@” for example), which we’ll use to mark where the encoded run begins. Thus if the input message is “2 successfully accomplished tasks”, it will be encoded as “2 su@2ce@2sfu@2ly a@2complished tasks”. Now the output message is longer!!! than the input string.</p>
<pre>
// the compressed message is longer!!!
input:	"2 successfully accomplished"
output:	"2 su@2ce@2sfu@2ly a@2complished tasks"
</pre>
<p>Again if the input stream contains the escape symbol, we have to find another one, and the problem is that it is often too difficult to find short escape symbol that doesn’t appear in the input text, without a full scan of the text.<span id="more-2623"></span></p>
<p>That is why run-length encoding isn’t a good solution when compressing plain text, where long runs rarely appear. Well, of course, there are exceptions. For example such an exception is the lossy text compression with run-length encoding. It is intuitively clear that compressing text with loss is rarely useful, especially when you’ve to decompress exactly the same text. However there are some cases that lossy compression may be useful. Such case can be removing spaces. Indeed the text <strong>“successfully      accomplished”</strong> brings us exactly the same information as <strong>“successfully accomplished”</strong>. In this case we can simply remove those spaces. Indeed we can use a marker to indicate the long run of spaces like <strong>“successfully@6 accomplished”</strong> in order to decompress the input string with absolutely no loss, but we can also throw those symbols away. This desision depends on the goal. Exactly with the same goal in mind we can remove new lines and tabs, only if we’re sure that the sense of the text is preserved. Yet again, a problem is that such long runs don’t happen to occur in random texts. That is why it’s better to use diagram encoding for plain text compression instead of run-length encoding.</p>
<h2>Few Questions</h2>
<p>After understanding the principles of the diagram encoding, let’s see some examples. In the example above it is better to replace doubled letters with something shorter. Let’s say # for “cc”, @ for “ss” and % for “ll”. Thus the input text will be compressed as “su#e@fu%y a#omplished”,  which is shorter. But yet again what will happen if the input message contains one of the substitutions? Also we can’t say if there are many doubled letters and enough reasonable substitutions for them. A better approach is to replace patterns. </p>
<figure id="attachment_2640" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/DiagramEncodingonTexts.png"><img src="/wp-content/uploads/2012/01/DiagramEncodingonTexts.png" alt="Compressing texts with diagram encoding" title="Compressing texts with diagram encoding" width="620" class="size-full wp-image-2640" srcset="/wp-content/uploads/2012/01/DiagramEncodingonTexts.png 683w, /wp-content/uploads/2012/01/DiagramEncodingonTexts-300x128.png 300w" sizes="(max-width: 683px) 100vw, 683px" /></a><figcaption class="wp-caption-text">Run-length encoding isn&#039;t a good approach for text compression, because long runs rarely appear in a natural language.</figcaption></figure>
<h2>Pattern Substitution</h2>
<p>The pattern substitution algorithm is a variant of the diagram encoding. As I said above in plain English a very commonly used pattern can be “ the “, which is five characters long. We can now replace it with something like “$%” for example. In this case the message <strong>“I send the message”</strong> will become <strong>“I send$%message”</strong>. However there are some obstacles to overcome.</p>
<p>The first problem is that we need to know the language and somehow to define commonly used patterns in a dictionary. What would happen with a message written in some language we don’t know nothing about. Let’s say &#8211; Latin like the example bellow.</p>
<blockquote><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras venenatis, sapien eget suscipit placerat, justo quam blandit mauris, quis tempor ante sapien sodales augue. Praesent ut mauris quam. Phasellus scelerisque, ante quis consequat tristique, metus turpis consectetur leo, vitae facilisis sapien mi eu sapien. Praesent vitae ligula elit, et faucibus augue. Sed rhoncus sodales dolor ut gravida. In quis augue ac nulla auctor mattis sed sed libero. Donec eget purus eget enim tempor porta vitae eget diam. Mauris aliquet malesuada ipsum, non pulvinar urna vestibulum ac. Donec feugiat velit vitae nunc cursus imperdiet. Donec accumsan faucibus dictum. Phasellus sed mauris sapien. Maecenas mi metus, tincidunt sed rhoncus nec, sodales non sapien.</p></blockquote>
<p>Clearly without knowing Latin it isn’t easy to define which are those commonly used patterns. The thing is that it&#8217;s better to use pattern substitution if you know in advance the set of words and characters.</p>
<p>The second problem is related to decompression. It is obvious that we need to define a dictionary and this dictionary must be used when decoding the message. It will be great also if we find more patterns longer than three characters. If not, the compression ratio will be low. Unfortunately such patterns aren’t very common in any natural language.</p>
<figure id="attachment_2643" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/PatternSubstitutiononTexts.png"><img src="/wp-content/uploads/2012/01/PatternSubstitutiononTexts.png" alt="Text compression with diagram encoding and pattern substitution" title="Text compression with diagram encoding and pattern substitution" width="620" class="size-full wp-image-2643" srcset="/wp-content/uploads/2012/01/PatternSubstitutiononTexts.png 683w, /wp-content/uploads/2012/01/PatternSubstitutiononTexts-300x128.png 300w" sizes="(max-width: 683px) 100vw, 683px" /></a><figcaption class="wp-caption-text">Diagram encoding and pattern substitution are far more suitable for text compression than run-length encoding. In fact, pattern substitution is very effective on compressing programming languages.</figcaption></figure>
<h2>Application</h2>
<p>It is interesting to answer the question, how to use diagram encoding or patter substitution to compress text in natural language, especially when we don’t know the language in detail? The answer hides in the question. We wont compress natural languages, but machine language. Exactly machine (programming) languages are limited to a smaller sets of words and symbols. Isn’t it true for any programing language? Like PHP, where words like <strong>“function”</strong>, <strong>“while”</strong>, <strong>“for”</strong>, <strong>“break”</strong>, <strong>“switch”</strong>, <strong>“foreach”</strong> happen to be often in use, or HTML with its defined set of tags. Perhaps the best example is CSS, where only the values of the properties can vary. CSS files also tend to have multiple new lines, tabs and spaces, which only humans read.</p>
<p>The question here is why should we compress those file types. It’s clear that after the compression they will be completely useless, both for humans and machines. Yes, that is true, but what if we have to store versions of those files into a DB. Kind of a backup. Imagine you’re working for a web hosting company that has to store daily versions of the sites it’s hosting. Thus the volume of stored information even for small companies hosting only few sites can be enormous. The problem is that compressing those files with some conventional compressing tool isn’t a good idea. Thus we’ve to save a copy of the entire site every day, but as we know the difference between daily versions of a site can be small. A version control system is another solution, but then you’ve to store the plain text of the files. </p>
<p>Perhaps a better approach is to compress the text using pattern substitution and then saving only differences &#8211; kind of version control, which can be done with “relative encoding”.</p>
<p>Using the above method we can save lots of disk space and in the same time we can compress/decompress easily. Another good thing is that you can save only changes to the initial files, like version control, which can also be compressed.</p>
<h2>Implementation</h2>
<p>The implementation of this algorithm is again on PHP and tries only to describe the main principles of compression. In this case I tried to compress a CSS file using the compression above. Although this example is quite primitive we can see some interesting facts. First of all you only need encoding and decoding dictionaries. Practically the encoding and decoding processes are equal, so you don’t need to implement two different functions. Here in this example a native PHP function is used &#8211; str_replace, because the purpose of this algorithm is not to describe pattern substitution techniques, but pattern substitution. It assumes that today’s programming languages have string manipulation functions for the purposes of this task.</p>
<pre lang="PHP">
$str = file_get_contents('large_style_file.css');

$encoding_dict = array(
	"\n" 		=> '$0',
	'text' 		=> '$1',
	'color' 	=> '$2',
	'display' 	=> '$3',
	'font' 		=> '$4',
	'width' 	=> '$5',
	'height'	=> '$6',	
	' '		=> '',
);

function replace_patterns($input, $dict) 
{
	foreach ($dict as $pattern => $replace) {
		$input = str_replace($pattern, $replace, $input);
	}
	
	return $input;
}

$result = replace_patterns($str, $encoding_dict);
</pre>
<p>By only replacing few CSS properties I achieved almost 40% of compression ratio (as shows the diagram bellow). The initial file is 202 KB, while compressed it&#8217;s only 131 KB. Of course, it all depends on the CSS file, but how about replacing all property names with shorter ones. Perhaps then the compression will be even better.</p>
<figure id="attachment_2647" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/chart_1.png"><img src="/wp-content/uploads/2012/01/chart_1.png" alt="CSS compression with pattern substitution" title="CSS compression with pattern substitution" width="600" height="371" class="size-full wp-image-2647" srcset="/wp-content/uploads/2012/01/chart_1.png 600w, /wp-content/uploads/2012/01/chart_1-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/01/30/computer-algorithms-data-compression-with-relative-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Relative Encoding">Computer Algorithms: Data Compression with Relative Encoding </a></li>
<li><a href="/2012/02/06/computer-algorithms-data-compression-with-prefix-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Prefix Encoding">Computer Algorithms: Data Compression with Prefix Encoding </a></li>
<li><a href="/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Run-length Encoding">Computer Algorithms: Data Compression with Run-length Encoding </a></li>
<li><a href="/2012/01/16/computer-algorithms-data-compression-with-bitmaps/" rel="bookmark" title="Computer Algorithms: Data Compression with Bitmaps">Computer Algorithms: Data Compression with Bitmaps </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/01/23/computer-algorithms-data-compression-with-diagram-encoding-and-pattern-substitution/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Data Compression with Bitmaps</title>
		<link>/2012/01/16/computer-algorithms-data-compression-with-bitmaps/</link>
		<comments>/2012/01/16/computer-algorithms-data-compression-with-bitmaps/#comments</comments>
		<pubDate>Mon, 16 Jan 2012 09:35:24 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[bitmap]]></category>
		<category><![CDATA[bitmap compressing algorithm]]></category>
		<category><![CDATA[Bzip2]]></category>
		<category><![CDATA[Coding theory]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Data compression]]></category>
		<category><![CDATA[gif]]></category>
		<category><![CDATA[Graphics file formats]]></category>
		<category><![CDATA[image compression]]></category>
		<category><![CDATA[Information theory]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[Lossless data compression]]></category>
		<category><![CDATA[Run-length encoding]]></category>
		<category><![CDATA[Technology/Internet]]></category>

		<guid isPermaLink="false">/?p=2604</guid>
		<description><![CDATA[Overview In my previous post we saw how to compress data consisting of very long runs of repeating elements. This type of compression is known as &#8220;run-length encoding&#8221; and can be very handy when transferring data with no loss. The problem is that the data must follow a specific format. Thus the string “aaaaaaaabbbbbbbb” can &#8230; <a href="/2012/01/16/computer-algorithms-data-compression-with-bitmaps/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Data Compression with Bitmaps</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/01/30/computer-algorithms-data-compression-with-relative-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Relative Encoding">Computer Algorithms: Data Compression with Relative Encoding </a></li>
<li><a href="/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Run-length Encoding">Computer Algorithms: Data Compression with Run-length Encoding </a></li>
<li><a href="/2012/01/23/computer-algorithms-data-compression-with-diagram-encoding-and-pattern-substitution/" rel="bookmark" title="Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution">Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution </a></li>
<li><a href="/2012/05/03/computer-algorithms-lossy-image-compression-with-run-length-encoding/" rel="bookmark" title="Computer Algorithms: Lossy Image Compression with Run-Length Encoding">Computer Algorithms: Lossy Image Compression with Run-Length Encoding </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Overview</h2>
<p>In <a href="/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/" title="Computer Algorithms: Data Compression with Run-length Encoding">my previous post</a> we saw how to compress data consisting of very long runs of repeating elements. This type of compression is known as &#8220;run-length encoding&#8221; and can be very handy when transferring data with no loss. The problem is that the data must follow a specific format. Thus the string <strong>“aaaaaaaabbbbbbbb”</strong> can be compressed as <strong>“a8b8”</strong>. Now a string with length 16 can be compressed as a string with length 4, which is 25% of its initial length without loosing any information. There will be a problem in case the characters (elements) were dispersed in a different way. What would happen if the characters are the same, but they don’t form long runs? What if the string was <strong>“abababababababab”</strong>? The same length, the same characters, but we cannot use run-length encoding! Indeed using this algorithm we’ll get at best the same string.</p>
<p>In this case, however, we can see another fact. The string consists of too many repeating elements, although not arranged one after another. We can compress this string with a bitmap. This means that we can save the positions of the occurrences of a given element with a sequence of bits, which can be easily converted into a decimal value. In the example above the string <strong>“abababababababab”</strong> can be compressed as <strong>“1010101010101010”</strong>, which is <strong>43690</strong> in decimals, and even better <strong>AAAA</strong> in hexadecimal. Thus the long string can be compressed. When decompressing (decoding) the message we can convert again from decimal/hexadecimal into binary and match the occurrences of the characters. Well, the example above is too simple, but let’s say only one of the characters is repeating and the rest of the string consists of different characters like this: <strong>“abacadaeafagahai”</strong>. Then we can use bitmap only for the character “a” &#8211; <strong>“1010101010101010”</strong> and compress it as <strong>“AAAA bcdefghi”</strong>. As you can see all the example strings are exactly 16 characters and that is a limitation. To use bitmaps with variable length of the data is a bit tricky and it is not always easy (if possible) to decompress it.</p>
<p><figure id="attachment_2624" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/Run-lengthvs.BitmapCompression.png"><img src="/wp-content/uploads/2012/01/Run-lengthvs.BitmapCompression.png" alt="Bitmap Compression" title="Bitmap Compression" width="620" class="size-full wp-image-2624" srcset="/wp-content/uploads/2012/01/Run-lengthvs.BitmapCompression.png 1140w, /wp-content/uploads/2012/01/Run-lengthvs.BitmapCompression-300x160.png 300w, /wp-content/uploads/2012/01/Run-lengthvs.BitmapCompression-1024x547.png 1024w" sizes="(max-width: 1140px) 100vw, 1140px" /></a><figcaption class="wp-caption-text">Basically bitmap compression saves the positions of an element that is repeated very often in the message!</figcaption></figure><br />
<span id="more-2604"></span><br />
In the other hand bitmap compression  is not only applicable on strings. We can compress also arrays, objects or any kind of data. The example from my previous post is very suitable. Then we had to transfer a large array from a server to the client (browser) using <a href="/tag/json/" title="JSON on stoimen.com/blog">JSON</a>. The data then was very suitable for “run-length encoding”. Now let’s assume we have the same data &#8211; a set of different years, which this time are dispersed in a different way. </p>
<pre lang="PHP">
$data = array(
	0 	=> 1991,
	1 	=> 1992,
	2 	=> 1993,
	3 	=> 1994,
	4 	=> 1991,
	5 	=> 1992,
	6 	=> 1993,
	7 	=> 1992,
	8 	=> 1991,
	9 	=> 1991,
	10 	=> 1991,
	11 	=> 1992,
	12 	=> 1992,
	13 	=> 1991,
	14 	=> 1991,
	15 	=> 1992,	
	...
);
</pre>
<p>The JSON will encoded message will be the following (a simple but yet very large javascript array).</p>
<pre lang="PHP">
[1991,1992,1993,1994,1991,1992,1993,1992,1991,1991,1991,1992,1992,1991,1991,1992, ...]
</pre>
<p>However if we use bitmap compression we’ll get a &#8220;shorter&#8221; array.</p>
<pre lang="PHP">
$data = array(
	0 => array(1991, '1000100011100110'),
	1 => array(1992, '0100010100011001'),
	2 => array(1993, '0010001000000000'),
	3 => array(1994, '0001000000000000'),
);
</pre>
<p>Now the JSON is:</p>
<pre lang="PHP">
[[1991,"1000100011100110"],[1992,"0100010100011001"],[1993,"0010001000000000"],[1994,"0001000000000000"]]
</pre>
<p>It is obvious that the compression ratio is getting better and better as the uncompressed data grows. In fact, most of us know bitmap compression from images, because this algorithm is largely used for image compression. We can imagine how successful it can be when compressing black and white images (as black and white can be represented as 0 and 1s). Actually it is used for more than two colors (256 for instance) and again the level of compression is very high.</p>
<h2>Implementation</h2>
<p>The following implementation on <a href="/category/php/" title="PHP on stoimen.com">PHP</a> aims only to illustrate the bitmap compressing algorithm. As we know this algorithm can be applicable for any kind of data structures. </p>
<pre lang="PHP">
// too many repeating "a" characters
$msg = 'aazahalavaatalawacamaahakafaaaqaaaiauaacaaxaauaxaaaaaapaayatagaaoafaawayazavaaaazaaabararaaaaakakaaqaarazacajaazavanazaaaeanaaoajauaaaaaxalaraaapabataaavaaab';

function bitmap($message) 
{
	$i = 0;
	$bits = $rest = '';
	
	while ($v = $message[$i]) {
		if ($v == 'a') {
			$bits .= '1';
		} else {
			$bits .= '0';
			$rest .= $v;
		}
		$i++;
	}
	
	return number_format(bindec($bits), 0, '.', '') . $rest;;
}

echo bitmap($msg);

// uncompressed: 
acaaaaadaaaabalaaeaaaaganaaxakaavawamaasavajawaaaayaauaaadalanagaeaeamaarafalaazaaaiasaanaahaaazaraxaalaahaaawaaajasamahaajaakarapanaakaoakaanawalaacamauaamaal
// compressed:
152299251941730035874325065523548237677352452096zhlvtlwcmhkfqiucxuxpytgofwyzvzbrrkkqrzcjzvnzenojuxlrpbtvb
</pre>
<h2>Application</h2>
<p>This algorithm is very useful when there is an element in our data that repeats very often, so you need to investigate the nature of the data you want to compress. Actually because of this fact this algorithm is used for image compression as <a href="http://en.wikipedia.org/wiki/Portable_Network_Graphics" title="Portable Network Graphics" target="_blank">PNG8</a> or <a href="http://en.wikipedia.org/wiki/Graphics_Interchange_Format" title="Graphics Interchange Format" target="_blank">GIF</a>.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/01/30/computer-algorithms-data-compression-with-relative-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Relative Encoding">Computer Algorithms: Data Compression with Relative Encoding </a></li>
<li><a href="/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Run-length Encoding">Computer Algorithms: Data Compression with Run-length Encoding </a></li>
<li><a href="/2012/01/23/computer-algorithms-data-compression-with-diagram-encoding-and-pattern-substitution/" rel="bookmark" title="Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution">Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution </a></li>
<li><a href="/2012/05/03/computer-algorithms-lossy-image-compression-with-run-length-encoding/" rel="bookmark" title="Computer Algorithms: Lossy Image Compression with Run-Length Encoding">Computer Algorithms: Lossy Image Compression with Run-Length Encoding </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/01/16/computer-algorithms-data-compression-with-bitmaps/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
