Practical Session 10 - Huffman code, Lempel Zivdsis162/wiki.files/ps09-Lempel... · Web viewHuffman...

19
y 1 x 1 e 2 0 s 7 2 9 2 9 0 0 0 1 1 1 Practical Session 10 - Huffman code, Lempel Ziv Huffman Code Huffman coding is an encoding algorithm used for lossless data compression, using a priority queue. Given data comprised of symbols from the set C (C can be the English alphabet, for example), Huffman code uses a priority queue (Minimum Heap based on symbol frequency) to assign encodings to the different symbols in the set. The algorithm builds a binary tree (the Huffman tree) whose leafs are the elements of C. Every symbol in C is associated with a leaf in the Huffman tree. The binary encoding of a symbol is as long as the depth of the leaf associated with it, and contains a 0 bit for every left move and a 1 bit for every right move on the path from the root to that leaf. Algorithm Descripti on Example Huffman tree with 4 symbols (C={e,s,x,y}) Numbers signify symbol frequency. Encoding: e: 0 s: 10 x:110 y: 111 Example Huffman (C) n ← |C| Q ← { new priority queue for the letters in C } for i ← 1 to n-1 z ← allocate new node x ← Extract_Min(Q) y ← Extract_Min(Q) z.left ← x z.right ← y frequency (z) ← frequency (x) + frequency (y) Insert(Q, z) Pseudo code

Transcript of Practical Session 10 - Huffman code, Lempel Zivdsis162/wiki.files/ps09-Lempel... · Web viewHuffman...

Page 1: Practical Session 10 - Huffman code, Lempel Zivdsis162/wiki.files/ps09-Lempel... · Web viewHuffman coding is an encoding algorithm used for lossless data compression, using a priority

y1

x1

e20

s7

2

9

29

0

00

1

1

1

Practical Session 10 - Huffman code, Lempel ZivHuffman Code

Huffman coding is an encoding algorithm used for lossless data compression, using a priority queue.Given data comprised of symbols from the set C (C can be the English alphabet, for example), Huffman code uses a priority queue (Minimum Heap based on symbol frequency) to assign encodings to the different symbols in the set.The algorithm builds a binary tree (the Huffman tree) whose leafs are the elements of C. Every symbol in C is associated with a leaf in the Huffman tree. The binary encoding of a symbol is as long as the depth of the leaf associated with it, and contains a 0 bit for every left move and a 1 bit for every right move on the path from the root to that leaf.

Algorithm Description

Example Huffman tree with 4 symbols(C={e,s,x,y})Numbers signify symbol frequency.Encoding:e: 0s: 10x:110y: 111

Example

Huffman (C)n ← |C|Q ← { new priority queue for the letters in C }for i ← 1 to n-1

z ← allocate new nodex ← Extract_Min(Q)y ← Extract_Min(Q)z.left ← xz.right ← yfrequency (z) ← frequency (x) + frequency (y)Insert(Q, z)

Pseudo code

Page 2: Practical Session 10 - Huffman code, Lempel Zivdsis162/wiki.files/ps09-Lempel... · Web viewHuffman coding is an encoding algorithm used for lossless data compression, using a priority

a1

b1

c2

d3

e5

f8

g13

h21

2

4

7

12

2033

54

Question 1

A. What is the optimal Huffman code for the following set of frequencies, based on the first 8 Fibonacci numbers? a:1 b:1 c:2 d:3 e:5 f:8 g:13 h:21B. Generalize your answer to find the optimal code when the frequencies are the first n Fibonacci numbers, for a general n.

Solution:

A. Since there are 8 letters in the alphabet, the initial queue size is n = 8, and 7 merge steps are required to build the tree. The final tree represents the optimal prefix code. The codeword for a letter is the sequence of the edge labels on the path from the root to the letter. Thus, the optimal Huffman code is as follows:

B. As we can see, the tree is one long limb with leaves hanging off. This is true for Fibonacci weights in general, because in Fibonacci the recurrence implies that

Fn+2=∑i=0

n

F i+1

We can prove this by induction. The numbers 1,1,2,3 provide a sufficient base.We assume the equality holds for all Fibonacci numbers smaller than Fn+2.Step: We prove correctness for Fn+2:

Fn+2=Fn+1+Fn=∑i=0

n−1

F i+1+Fn=∑i=0

n

F i+1

Therefore Fn+2>∑i=0

n

F i and clearly Fn+1<Fn+2 so Fn+2 is chosen after all smaller Fibonacci numbers have been merged into a single tree.

Page 3: Practical Session 10 - Huffman code, Lempel Zivdsis162/wiki.files/ps09-Lempel... · Web viewHuffman coding is an encoding algorithm used for lossless data compression, using a priority

1210

555

7

4

223

Question 2

A. Given the frequency series for a Huffman code as follows:

f i={4 i=12i i∈ {2 .. n }

Draw the structure of the Huffman Tree that describes this series.

Solution A:

B. Write a frequency list that the Huffman code of this frequency would deterministically create the following structure.

Solution B:

Frequencies: 2,2,3,5,5,5

tree diagramExplanationon each level of the tree, f j can be written as: f j= f 1+ f 2+. ..+ f j−1Therefore, on each level we will choose the node with the root of

the subtree of f 1−−−f i−1created before, and we will get the tree  in the diagram

Page 4: Practical Session 10 - Huffman code, Lempel Zivdsis162/wiki.files/ps09-Lempel... · Web viewHuffman coding is an encoding algorithm used for lossless data compression, using a priority

C. Write a frequency formula so that the Huffman code of this frequency would deterministically create the following structure.

Solution C:

In order to create this structure, we want that the next two elements on the series will be chosen before the unification of the existent subtree. The pattern of the series is based on the principle that on each level the frequency of each of the next two elements is smaller than the sum of the frequencies till now.The following recurrence formula that satisfy this quality:

f i={some constant c≥1 i≤4f i−1 i is even

( ∑1≤ j≤i−1

f j)−1 otherwise

An example of the function f that creates the series: =⟨1,1,1,1,3,3,9,9 ,27 ,27 ,81 ,81 ,…⟩ is:

f i={some constant c≥1 i≤4f i−1 i is even

3( i−3

2 )otherwise

Page 5: Practical Session 10 - Huffman code, Lempel Zivdsis162/wiki.files/ps09-Lempel... · Web viewHuffman coding is an encoding algorithm used for lossless data compression, using a priority

: Lempel-Ziv אלגוריתם

אלגוריתם לדחיסת נתונים. האלגוריתם מאפשר לשחזר את המידע הדחוס במלואו. משפחה של אלגוריתמים 1977-8שמקורם בשני אלגוריתמים עיקריים שפותחו על ידי יעקב זיו ואברהם למפל בשנת

אברהם למפליעקב זיו

GIF image ו-ZIPאלגוריתמים ששייכים למשפחה זו של אלגוריתמים, מיושמים באפליקציות כגון compression .

.LZ78 - 1978 שמקורו באלגוריתם משנת אחת מהגרסאות של האלגוריתםבתרגול זה נראה את : כל מילה בקידוד היא המילה הארוכה ביותר שנראתה עד כה בתוספת שלהרעיון שעומד בבסיסו של הקידוד

אות אחת. Prefix tree או Trieעל מנת לעשות חיפוש יעיל של המילים שכבר קודדו נממש מבנה נתונים עצי שנקרא

(ראו דוגמה בהמשך). העץ יהיה מעין מילון שנבנה בצורה דינמית ומייצג מילים שכבר קודדו בצורה יעילה. מבנה הנתונים הוא היררכי. לכל צומת יש אבא ורשימה של ילדים. בנוסף כל צומת צריך לשמור שני שדות: אינדקס – המסמן באיזה שלב הצומת הזה נוצר, ותו שמחבר את הצומת הזה לאבא שלו (מידע שמופיע על

הצלעות בדוגמה המופיעה מטה). ששייכות לא"ב של הטקסט המקודד. השרשור שלשונותצלעות שיוצאות מצומת מסוים מייצגות אותיות

האותיות במסלול מהשורש לצומת מסוים מייצג מילים או רישאות של מילים שקודדו.

כקלט. מומלץ לעבור עליו במקביל עם הדוגמהTextלפניכם הפסאודו קוד של אלגוריתם הקידוד המקבל המופיעה בהמשך.

הפסאודו–קוד של האלגוריתם:0אינדקס=.1צור רשימת זוגות ריקה..2צור שורש של העץ. סמן אותו בערכו של האינדקס..3:Text > 0כל עוד אורך ה-.4

.1קדם את האינדקס ב-.4.1 שמופיעה בעץ, במסלול כלשהו מהשורשText) הארוכה ביותר של ה-prefixמצא את הרישא (.4.2

.v1לאיזושהו צומת אם אורך הטקסט < אורך הרישא .4.3

.Text בן חדש, סמן אותו באינדקס, חבר ביניהם בתו שבא אחרי הרישא ב-vהוסף לצומת .4.3.1קצץ מתחילת הטקסט את הרישא והאות שבאה אחריה..4.3.2

ומהאות שבאה אחרי הרישאvהוסף לרשימת הזוגות, זוג שמורכב מהאינדקס של צומת .4.4).2(במידה ואין אות כזו, כלומר הגענו לסוף המילה הוסיפו תו '*'

הניחו שהטקסט המקורי לא יכיל את התו '*'.

Page 6: Practical Session 10 - Huffman code, Lempel Zivdsis162/wiki.files/ps09-Lempel... · Web viewHuffman coding is an encoding algorithm used for lossless data compression, using a priority

החיפוש יתבצע על ידי טיול במקביל על הטקסט ועל הצמתים של העץ: מתחילים מהאות הראשונה של 1 . מחפשים מביןv ואת הצומת הנוכחי בעץ ב-cהטקסט ומהשורש של העץ. נסמן את האות הנוכחית בטקסט ב-

) ומתקדמים בטקסט לאותv. אם כן, מתקדמים אליו (עכשיו הוא c האם מישהו מחובר אליו באות vהבנים של . כשמסיימים, מחזיריםc עם האות v). חוזרים על התהליך עד שלא ניתן להתקדם מצומת cהבאה (עכשיו היא

). 4.3.1 (זה הצומת שאליו נחבר בן חדש בשלב vאת הצומת ראו את השלב האחרון של הדוגמה למטה.2

:Bהדגמה של ריצת האלגוריתם על הטקסט הבא

.0בונים עץ התחלתי ששורשו מסומן ב- מאתחלים את רשימת הזוגות אשר מייצגת את הקידוד להיות רשימה ריקה ואת האינדקס הרץ מאתחלים

לאפס.

(אנו כעת במילה הראשונה שמקודדת). עוברים על הטקסט. מתחילים עם האות1מקדמים את האינדקס ל- זהv ולכן עוצרים את החיפוש כאשר aהראשונה בטקסט ועם השורש של העץ. לשורש אין בן שמחובר אליו ב-

, אשר מחובר לאבא שלו באות1 בן חדש המסומן באינדקס vהשורש והרישא היא מילה ריקה. מוסיפים לצומת a) 0. מוסיפים לרשימת הזוגות זוג חדש,aאשר מסמן שהמילה הראשונה מורכבת מהרישא שנמצאת על – (

. מורידים מהטקסט אתa (מילה ריקה במקרה זה) בתוספת של האות 0המסלול מהשורש לצומת המסומן ב- לתחילת הלולאה.acgacgat וחוזרים עם הטקסט המקוצץ aהרישא ואת האות

Page 7: Practical Session 10 - Huffman code, Lempel Zivdsis162/wiki.files/ps09-Lempel... · Web viewHuffman coding is an encoding algorithm used for lossless data compression, using a priority

. הרישאa. מחפשים את הרישא הארוכה ביותר של הטקסט שנמצאת בעץ – 2מקדמים את האינדקס ל- ומחברים אותה לצומת האב שלה עם2. מוסיפים לצומת בן חדש עם אינדקס 1מסתיימת בצומת המסומן ב-

) – שמסמן שהמילה השנייה מורכבתc,1. מוסיפים לרשימת הזוגות את הזוג (cהאות שבאה אחרי הרישא – . מקצצים את המילה,c, ותוספת של האות a, כלומר 1מהרישא שנמצאת על המסלול מהשורש לצומת

.gacgatונשארים עם

. מחפשים את הרישא הארוכה ביותר של הטקסט שנמצאת בעץ – מילה ריקה.3מקדמים את האינדקס ל- ומחברים אותו לצומת3 (בשורש). מוסיפים לצומת בן חדש עם אינדקס 0הרישא מסתיימת בצומת המסומן ב-

) – שמסמן שהמילהg,0. מוסיפים לרשימת הזוגות את הזוג (gהאב שלו עם האות שבאה אחרי הרישא – .g, כלומר מילה ריקה, ותוספת של האות 0השלישית מורכבת מהרישא שנמצאת על המסלול מהשורש לצומת

.acgatמקצצים את המילה, ונשארים עם

Page 8: Practical Session 10 - Huffman code, Lempel Zivdsis162/wiki.files/ps09-Lempel... · Web viewHuffman coding is an encoding algorithm used for lossless data compression, using a priority

. הרישאac. מחפשים את הרישא הארוכה ביותר של הטקסט שנמצאת בעץ – 4מקדמים את האינדקס ל- ומחברים אותו לצומת האב שלו עם4. מוסיפים לצומת בן חדש עם אינדקס 2מסתיימת בצומת המסומן ב-

) – שמסמן שהמילה הרביעית מורכבתg,2. מוסיפים לרשימת הזוגות את הזוג (gהאות שבאה אחרי הרישא – . מקצצים את המילה,g, ותוספת של האות ac, כלומר 2מהרישא שנמצאת על המסלול מהשורש לצומת

.atונשארים עם

. הרישאa. מחפשים את הרישא הארוכה ביותר של הטקסט שנמצאת בעץ – 5מקדמים את האינדקס ל- ומחברים אותו לצומת האב שלו עם5. מוסיפים לצומת בן חדש עם אינדקס 1מסתיימת בצומת המסומן ב-

) – שמסמן שהמילה החמישית מורכבתt,1. מוסיפים לרשימת הזוגות את הזוג (tהאות שבאה אחרי הרישא – . מקצצים את המילה,t, ותוספת של האות a, כלומר 1מהרישא שנמצאת על המסלול מהשורש לצומת

ונשארים עם מילה ריקה..Pairs הינו רשימת הזוגות שאגרנו במשתנה Bהקידוד הסופי עבור המילה

:a הוא הטקסט הקודם בתוספת של האות Bכעת נניח שהטקסט

Page 9: Practical Session 10 - Huffman code, Lempel Zivdsis162/wiki.files/ps09-Lempel... · Web viewHuffman coding is an encoding algorithm used for lossless data compression, using a priority

. מחפשים את הרישא הארוכה6עושים את חמשת השלבים הקודמים. בשלב השישי, מקדמים את האינדקס ל- . הרישא הארוכה ביותר מגיעה1. הרישא מסתיימת בצומת המסומן ב-aביותר של הטקסט שנמצאת בעץ –

לסוף הטקסט ואין איך להאריך אותה יותר באות אחת, לכן לא עושים יותר שינויים על העץ. כדי לא לאבד,*) לרשימת הזוגות.1אינפורמציה על הקידוד של המילה הזו אנחנו מוסיפים את הזוג (

: מה קורה עם נבצע זאת עם הטקסטנקודה למחשבה** lovesmedoesnotlovemelovesmedoesnotlovemelovesmedoesnotlovemelovesmedoesnotloveme

שחזור:ניתן לשחזר את הטקסט המקודד מתוך רשימת הזוגות בלבד בדרך הבאה:

), נשרשר למילה שבמקוםi,x במערך יהיה ריק. עבור כל זוג (0. האיבר ה-1נחזיק מערך, ואינדקס שמתחיל מ- ונכתוב את התוצאה במקום האינדקס במערך. כמו כן נוסיף את התוצאה לטקסטx במערך את האות iה-

. (במידה ונתקלנו ב-* רק נוסיף את המילה לטקסט המשוחזר)1המשחוזר ונקדם את אינדקס ב-דוגמא:

Page 10: Practical Session 10 - Huffman code, Lempel Zivdsis162/wiki.files/ps09-Lempel... · Web viewHuffman coding is an encoding algorithm used for lossless data compression, using a priority
Page 11: Practical Session 10 - Huffman code, Lempel Zivdsis162/wiki.files/ps09-Lempel... · Web viewHuffman coding is an encoding algorithm used for lossless data compression, using a priority
Page 12: Practical Session 10 - Huffman code, Lempel Zivdsis162/wiki.files/ps09-Lempel... · Web viewHuffman coding is an encoding algorithm used for lossless data compression, using a priority
Page 13: Practical Session 10 - Huffman code, Lempel Zivdsis162/wiki.files/ps09-Lempel... · Web viewHuffman coding is an encoding algorithm used for lossless data compression, using a priority

Question 3

A text with an alphabet consisting of 27 possible characters ('a','b','c',…,'z',' ') is coded by Lempel-Ziv into n pairs.

What is the length of the longest possible text that was encoded? Give an example when this can happen.

What is the length of the shortest possible text that was encoded? Give an example when this can happen.

Solution

Page 14: Practical Session 10 - Huffman code, Lempel Zivdsis162/wiki.files/ps09-Lempel... · Web viewHuffman coding is an encoding algorithm used for lossless data compression, using a priority

The longest text happens when the first pair is an encoding of length 1, the second pair an encoding of length 2,…, the nth pair is an encoding of length n.

Therefore, the length of the longest text is 1+2+3+…+n=n (n+1 )2

=θ(n2)

This can happen if the text is all the same character, for example "aaaa…"

Another way this can happen is the text "aababcabcd…"

The shortest possible text happens for a completely balanced Trie. If we denote by L the number of levels in a completely balanced Trie, then L ≈ log27 ( n ): The first level has 27 nodes, the second level has 272 nodes, …, the Lth level has 27L nodes. So

n=27+272+…+27L⇒L≈ log27n

Therefore, the shortest text has length 27+2 ⋅272+…+ L⋅27L=27+2 ⋅272+…+ log27 (n )⋅27 log27( n)=θ (n log(n))

One way that this can happen is the text "abcd…z aaabacad…"

Page 15: Practical Session 10 - Huffman code, Lempel Zivdsis162/wiki.files/ps09-Lempel... · Web viewHuffman coding is an encoding algorithm used for lossless data compression, using a priority

Lossless vs. Lossy compressionsA lossless compression is a compression algorithm that does not loses information when decompressing the data.

A lossy compression is an algorithm that loses information when decompressing, mainly un-important or non-relevant data.

Lossless Lossy

Pictures  RAW, BMP, PNG JPEG ,GIF

Audio WAV, FLAC, ALAC MP3, MP4, OGG

Video QuickTime, H.264 lossless , JPEG 2000 lossless

MPEG (all)

Mp3, for example, compresses by removing all the frequencies above and below our range of hearing, therefore we don’t even notice the data loss.

Page 16: Practical Session 10 - Huffman code, Lempel Zivdsis162/wiki.files/ps09-Lempel... · Web viewHuffman coding is an encoding algorithm used for lossless data compression, using a priority

Compression Ratios

Static data: Compression ratio = uncompressed ¿¿compressed ¿¿¿¿

Streamed data: Compression ratio = uncompressed ratecompressed rate

Usually better compression ratio "costs" more cpu time and more memory Best compression recorded today (English language) is 6.27 and it takes more

than 5 hours to decompress 100MB file on 2Ghz P4 computer.

Question 4

1. De-compress the following compressed string:

0s,0h,0e,0' ',1a,1l,3s,4s,3a,8h,3l,6s,4b,0y,4t,2e,8e,0a,10o,0r,3*

(0,s), (0,h), (0,e), (0,' '), (1,a), (1,l), (3,s), (4,s), (3,a), (8,h), (3,l), (6,s), (4,b),(0,y), (4,t), (2,e), (8,e), (0,a), (10,o), (0,r), (3,*)

2. What is the compression ratio of the string using LZ78?

Page 17: Practical Session 10 - Huffman code, Lempel Zivdsis162/wiki.files/ps09-Lempel... · Web viewHuffman coding is an encoding algorithm used for lossless data compression, using a priority

Solution:

1.

The decompression dictionary result in the following table:

Index string0 Null1 s2 h3 e4 ' '5 sa6 l7 es8 ' 's9 ea10 ' 'sh11 el12 ls13 ' 'b14 y15 ' 't16 he17 ' 'se18 a19 ' 'sho20 r

The resulting string is "she sales sea shells by the sea shore".

2.

- The length of the compressed string is 43 characters

- The length of the un-compressed string is 37 characters

So the compression ratio is 3743

=0.8605

We see that the compression did not help us actually make the data smaller in this case. This can happen for too-short strings and for already "naturally organized" strings.