Perbandingan Algoritma Elias Gamma Code Dengan Shannon-Fano Untuk Kompresi File Teks

65

LISTING PROGRAM

1. Mainform.cs
using
using
using
using

stem;
Sy
System.Collections.Generic;
System.Drawing;
System.Windows.Forms;

namespace Home
{
///
/// Description of MainForm.
///

public partial class MainForm : Form
{
public MainForm()
{
//
// The InitializeComponent() call is required for Windows
Forms designer support.
//
InitializeComponent();
//
// TODO: Add constructor code after the
InitializeComponent() call.
//
}
void MainFormLoad(object sender, EventArgs e)
{
Home frmcld = new Home();
frmcld.MdiParent=this;
frmcld.Show();
}

void AboutToolStripMenuItemClick(object sender, EventArgs e)
{
About frmcld = new About();
frmcld.MdiParent=this;
frmcld.Show();
}
void EliasGammaCodeToolStripMenuItemClick(object sender, Even
tArgs e)
{
Elias frmcld = new Elias();
frmcld.MdiParent=this;
frmcld.Show();
}
void ShannonFanoToolStripMenuItemClick(object sender, EventAr
gs e)
{
Shannon frmcld = new Shannon();
frmcld.MdiParent=this;
frmcld.Show();


Universitas Sumatera Utara

66

}
void HelpToolStripMenuItemClick(object sender, EventArgs e)
{
Help frmcld = new Help();
frmcld.MdiParent=this;
frmcld.Show();
}
void ExitToolStripMenuItemClick(object sender, EventArgs e)
{
this.Close();
}
void HomeToolStripMenuItemClick(object sender, EventArgs e)
{
Home frmcld = new Home();
frmcld.MdiParent=this;
frmcld.Show();

}
}
}

2. Elias.cs
using stem;
Sy
using System.Drawing;
using System.IO;
using System.Dynamic;
using System.Windows.Forms;
using System.Text;
using System.Collections.Generic;
using IronPython.Hosting;
namespace Home
{
///
/// Description of Elias.
///
public partial class Elias : Form

{
public Elias()
{
//
// The InitializeComponent() call is required for Windows
Forms designer support.
//
InitializeComponent();
//
// TODO: Add constructor code after the
InitializeComponent() call.
//
}
void ButtonBrowseClick(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Document (MsWord)|*.doc";
dialog.Title = "Open file doc : ";
dialog.RestoreDirectory = true;


Universitas Sumatera Utara

67

if(dialog.ShowDialog() == DialogResult.OK){
string dirName =
System.IO.Path.GetDirectoryName(dialog.FileName);
var fileinfo = new FileInfo(dialog.FileName);
var size= fileinfo.Length;
string drive =
dirName.Split(System.IO.Path.VolumeSeparatorChar)[1];
txtUkuranFileE.Text=size.ToString();
textBoxLoadFilePath.Text =
dirName + "\\" + dialog.SafeFileName.ToString();
}
buttonBaca.Enabled = true;
}
void ButtonBacaClick(object sender, EventArgs e)
{
Microsoft.Office.Interop.Word.Application wordApp = new

Microsoft.Office.Interop.Word.ApplicationClass();
object filenameO = textBoxLoadFilePath.Text.ToString();
object objFalse = false;
object objTrue = true;
object missing = System.Reflection.Missing.Value;
object emptyData = string.Empty;
try{
Microsoft.Office.Interop.Word.Document aDoc
= wordApp.Documents.Open(ref filenameO, ref objFalse, ref objTrue, r
ef missing, ref missing, ref missing, ref missing, ref missing, ref m
issing, ref missing, ref objTrue, ref missing, ref missing, ref missi
ng, ref missing);
aDoc.ActiveWindow.Selection.WholeStory();
aDoc.ActiveWindow.Selection.Copy();
IDataObject data =
System.Windows.Forms.Clipboard.GetDataObject();
String fileText =
data.GetData(System.Windows.Forms.DataFormats.Text).ToString();
System.Windows.Forms.Clipboard.SetDataObject(string.E
mpty);

textBoxDisplayText.Text = fileText;
}
catch(Exception err){
MessageBox.Show(err.Message);
}
finally{
MessageBox.Show("File berhasil dibaca");
}
btnCompressEG.Enabled = true;
}
void BtnCompressEGClick(object sender, EventArgs e)
{
var input = textBoxDisplayText.Text;
try
{
var ipy = Python.CreateRuntime();
dynamic eliasgamma =

Universitas Sumatera Utara


68

ipy.UseFil
e
("eliasgamma.py");
DateTime startTime = DateTime.Now;
dynamic CR = eliasgamma.processEG(input);
dynamic RedudancyData =
eliasgamma.processEG1(input);
dynamic hasilCompress =
eliasgamma.processEG2(input);
DateTime endTime = DateTime.Now;
TimeSpan elapsed =
endTime.Subtract(startTime);
txtWaktuKompres.Text =
elapsed.Hours.ToString("00") + ":" +
elapsed.Minutes.ToString("00") + ":" + elapsed.Se
conds.ToString("00") + "." +
elapsed.Milliseconds.ToString("000");
txtRedudancyElias.Text= RedudancyData.ToString();

txtHasil.Text = hasilCompress.ToString();
txtRasio.Text = CR.ToString();
File.WriteAllText("D:/data.txt", txtHasil.Text);
var fileinfo = new FileInfo("D:/data.txt");
var size= fileinfo.Length;
ukuranfile.Text=size.ToString();
}catch(Exception ex){
MessageBox.Show(ex.ToString());
}
btnDecompressEG.Enabled = true;
}
void TimereliasTick(object sender, EventArgs e)
{
}

void BtnDecompressEGClick(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Word 1997-2003|*.doc|Word 20072013|*.docx|Rich Text File|*.rtf|All Files (*.*)|*.*";
saveFileDialog1.Title = "";

var input = textBoxDisplayText.Text;
try
{
var ipy = Python.CreateRuntime();
dynamic eliasgamma =
ipy.UseFile("eliasgamma.py");
DateTime startTime = DateTime.Now;
dynamic hasilDecompress =
eliasgamma.processEG3(input);
DateTime endTime = DateTime.Now;
TimeSpan elapsed =
endTime.Subtract(startTime);
txtWaktuDekompres.Text =
elapsed.Hours.ToString("00") + ":" +
elapsed.Minutes.ToString("00") + ":" + elapsed.Se

Universitas Sumatera Utara

69

conds.ToStri
ng

("00") + "." +
elapsed.Milliseconds.ToString("000");
txtDecompressElias.Text =
hasilDecompress.ToString();
if (saveFileDialog1.ShowDialog() ==
DialogResult.OK)
{
String filetext = txtDecompressElias.Text;
Microsoft.Office.Interop.Word.Application
oWord = new Microsoft.Office.Interop.Word.Application();
//oWord.Visible = true;
var oDoc = oWord.Documents.Add();
//Insert a paragraph at the beginning of the
document.
var paragraph1 =
oDoc.Content.Paragraphs.Add();
paragraph1.Range.Text = filetext;
oDoc.SaveAs(@saveFileDialog1.FileName);
MessageBox.Show("Penyimpanan
berhasil", saveFileDialog1.FileName);
oWord.Quit();
}

}catch(Exception ex){
MessageBox.Show(ex.ToString());
}
btnReset.Enabled = true;
}
void TxtDecompressEliasTextChanged(object sender, EventArgs e)
{
}
void BtnResetClick(object sender, EventArgs e)
{
textBoxLoadFilePath.Text = "";
txtUkuranFileE.Text = "";
ukuranfile.Text = "";
txtRasio.Text = "";
txtWaktuKompres.Text = "";
txtRedudancyElias.Text = "";
txtWaktuDekompres.Text = "";
textBoxDisplayText.Text = "";
txtHasil.Text = "";
txtDecompressElias.Text = "";
buttonBaca.Enabled = false;
btnCompressEG.Enabled = false;
btnDecompressEG.Enabled = false;
btnReset.Enabled = false;

}
}
}

Universitas Sumatera Utara

70

3. Shannon-Fano.cs
using
using
using
using
using
using
using
using

stem;
Sy
System.Drawing;
System.IO;
System.Dynamic;
System.Windows.Forms;
System.Text;
System.Collections.Generic;
IronPython.Hosting;

namespace Home
{
///
/// Description of Shannon.
///
public partial class Shannon : Form
{
public Shannon()
{
//
// The InitializeComponent() call is required for Windows
Forms designer support.
//
InitializeComponent();
//
// TODO: Add constructor code after the
InitializeComponent() call.
//
}
void ButtonBrowseClick(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Document (MsWord)|*.doc";
dialog.Title = "Open file doc : ";
dialog.RestoreDirectory = true;
if(dialog.ShowDialog() == DialogResult.OK){
string dirName =
System.IO.Path.GetDirectoryName(dialog.FileName);
var fileinfo = new FileInfo(dialog.FileName);
var size= fileinfo.Length;
string drive =
dirName.Split(System.IO.Path.VolumeSeparatorChar)[1];
txtUkuranFileS.Text=size.ToString();
textBoxLoadFilePath.Text =
dirName + "\\" + dialog.SafeFileName.ToString();
}
buttonBaca.Enabled=true;
}
void ButtonBacaClick(object sender, EventArgs e)
{
Microsoft.Office.Interop.Word.Application wordApp = new
Microsoft.Office.Interop.Word.ApplicationClass();
object filenameO = textBoxLoadFilePath.Text.ToString();
object objFalse = false;
object objTrue = true;
object missing = System.Reflection.Missing.Value;
object emptyData = string.Empty;

Universitas Sumatera Utara

71

try{
Microsoft.Office.Interop.Word.Document aDoc
= wordApp.Documents.Open(ref filenameO, ref objFalse, ref objTrue, r
ef missing, ref missing, ref missing, ref missing, ref missing, ref m
issing, ref missing, ref objTrue, ref missing, ref missing, ref missi
ng, ref missing);
aDoc.ActiveWindow.Selection.WholeStory();
aDoc.ActiveWindow.Selection.Copy();
IDataObject data =
System.Windows.Forms.Clipboard.GetDataObject();
String fileText =
data.GetData(System.Windows.Forms.DataFormats.Text).ToString();
System.Windows.Forms.Clipboard.SetDataObject(string.E
mpty);
textBoxDisplayText.Text = fileText;
}
catch(Exception err){
MessageBox.Show(err.Message);
}
finally{
MessageBox.Show("File berhasil dibaca");
}
btnCompressSF.Enabled=true;
}
void BtnCompressSFClick(object sender, EventArgs e)
{
var input = textBoxDisplayText.Text;
try
{
var ipy = Python.CreateRuntime();
dynamic shannonfano =
ipy.UseFile("shannonfano.py");
DateTime startTime = DateTime.Now;
dynamic CR = shannonfano.processSF(input);
dynamic RedudancyData =
shannonfano.processSF1(input);
dynamic hasilCompress =
shannonfano.processSF2(input);
DateTime endTime = DateTime.Now;
TimeSpan elapsed =
endTime.Subtract(startTime);
txtWaktuKompres.Text =
elapsed.Hours.ToString("00") + ":" +
elapsed.Minutes.ToString("00") + ":" + elapsed.Se
conds.ToString("00") + "." +
elapsed.Milliseconds.ToString("000");
txtRedudancyShannon.Text=
RedudancyData.ToString();
txtHasil.Text = hasilCompress.ToString();
txtRasio.Text = CR.ToString();
File.WriteAllText("D:/data.txt", txtHasil.Text);
var fileinfo = new FileInfo("D:/data.txt");

Universitas Sumatera Utara

72

var size= fileinfo.Length;
ukuranfile.Text=size.ToString();

}catch(Exception ex){
MessageBox.Show(ex.ToString());
}
btnDecompressSF.Enabled=true;
}
void BtnDecompressSFClick(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Word 1997-2003|*.doc|Word 20072013|*.docx|Rich Text File|*.rtf|All Files (*.*)|*.*";
saveFileDialog1.Title = "";
var input = textBoxDisplayText.Text;
try
{
var ipy = Python.CreateRuntime();
dynamic shannonfano =
ipy.UseFile("shannonfano.py");
DateTime startTime = DateTime.Now;
dynamic hasilDecompress =
shannonfano.processSF3(input);
DateTime endTime = DateTime.Now;
TimeSpan elapsed =
endTime.Subtract(startTime);
txtWaktuDekompres.Text =
elapsed.Hours.ToString("00") + ":" +
elapsed.Minutes.ToString("00") + ":" + elapsed.Se
conds.ToString("00") + "." +
elapsed.Milliseconds.ToString("000");
txtDecompressShannon.Text =
hasilDecompress.ToString();
if (saveFileDialog1.ShowDialog() ==
DialogResult.OK)
{
String filetext = txtDecompressShannon.Text;
Microsoft.Office.Interop.Word.Application
oWord = new Microsoft.Office.Interop.Word.Application();
//oWord.Visible = true;
var oDoc = oWord.Documents.Add();
//Insert a paragraph at the beginning of the
document.
var paragraph1 =
oDoc.Content.Paragraphs.Add();
paragraph1.Range.Text = filetext;
oDoc.SaveAs(@saveFileDialog1.FileName);
MessageBox.Show("Penyimpanan
berhasil", saveFileDialog1.FileName);
oWord.Quit();
}

}catch(Exception ex){

Universitas Sumatera Utara

73

MessageBox.Show(ex.ToString());
}
btnReset.Enabled=true;
}
void BtnResetClick(object sender, EventArgs e)
{
textBoxLoadFilePath.Text = "";
txtUkuranFileS.Text = "";
ukuranfile.Text = "";
txtRasio.Text = "";
txtWaktuKompres.Text = "";
txtRedudancyShannon.Text = "";
txtWaktuDekompres.Text = "";
textBoxDisplayText.Text = "";
txtHasil.Text = "";
txtDecompressShannon.Text = "";
buttonBaca.Enabled = false;
btnCompressSF.Enabled = false;
btnDecompressSF.Enabled = false;
btnReset.Enabled = false;
}
void Label8Click(object sender, EventArgs e)
{
}
}
}

4. Eliasgamma.py
#*- coding: utf-8 -*#title: Elias' Gamma and Shannon-Fano's Algorithm
#purpose: Data Compression
#author: 1.Mohammad Andri Budiman
2.Nurhennida Br Sitepu
#version: 1.3
#date: May 5nd 2014
#time: 18:30
from math import log
#fungsi berikut ini mengembalikan 2 nilai, yaitu:
#(1) list char = karakter apa saja yang ada pada string st
#(2) list freq = berapa frequency masing-masing karakter
def count_freq(st):
char = list(set(st))
freq = []
for i in char:
x = st.count(i)
freq.append(x)
return char, freq
#fungsi berikut ini mengembalikan 2 nilai yaitu:
#(1) list freq yang sudah tersortir descending order
#(2) list char yang sudah tersortir mengikuti urutan freq-nya
def InsertionSort(f, c):
n = len(f)

Universitas Sumatera Utara

74

for i in range(1, n):
for j in range(0, i):
if f[i] > f[j]:
f.insert(j, f.pop(i))
c.insert(j, c.pop(i))
return f, c
#fungsi berikut ini menjumlahkan semua angka yang ada pada list f
def sum(f):
s = 0
for i in f:
s = s + i
return s
#fungsi berikut ini mengembalikan 2 nilai, yaitu:
#(1) difference = beda antara jumlah freq table atas dgn jumlah freq
table bawah
#(2) row = baris tempat pemotongan tabel, dihitung dari bawah
def findrow(f):
difference = sum(f)
row = 1
t = len(f)
for i in range(1, t):
upper = f[0:(t-i)]
lower = f[t - i:]
x = abs(sum(upper) - sum(lower))
if x < difference:
difference = x # difference = beda antara jumlah
freq table atas dgn jumlah freq table bawah
row = i # row = baris tempat pemotongan table
return difference, row

def EliasGamma(st):
if len(st) f[j]:
f.insert(j,
c.insert(j,
return f, c

nilai yaitu:
descending order
mengikuti urutan freq-nya

f.pop(i))
c.pop(i))

#fungsi berikut ini menjumlahkan semua angka yang ada pada list f
def sum(f):
s = 0
for i in f:
s = s + i
return s
#fungsi berikut ini mengembalikan 2 nilai, yaitu:
#(1) difference = beda antara jumlah freq table atas dgn jumlah freq
table bawah
#(2) row = baris tempat pemotongan tabel, dihitung dari bawah
def findrow(f):
difference = sum(f)

Universitas Sumatera Utara

78

row = 1
t = len(f)
for i in range(1, t):
upper = f[0:(t-i)]
lower = f[t - i:]
x = abs(sum(upper) - sum(lower))
if x < difference:
difference = x # difference = beda antara jumlah
freq table atas dgn jumlah freq table bawah
row = i # row = baris tempat pemotongan table
return difference, row
#fungsi berikut ini berfungsi melakukan table splitting secara
rekursif, sekaligus meng-update kode Shannon-Fano
def split(S, F, C, charset, sf):
t = len(S)
if t > 1:
diff, row = findrow(F)
S1 = []
S2 = []
F1 = []
F2 = []
C1 = []
C2 = []
S1 = S[0:t - row]
S2 = S[t - row:]
F1 = F[0:t - row]
F2 = F[t - row:]
for i in range(t):
if i < t - row:
C[i] = str(C[i]) + '0'
else:
C[i] = str(C[i]) + '1'
C1 = C[0:t - row]
C2 = C[t - row:]
if len(S1) == 1:
charset.append(S1[0])
sf.append(C1[0])
if len(S2) == 1:
charset.append(S2[0])
sf.append(C2[0])
split(S1, F1, C1, charset, sf)
split(S2, F2, C2, charset, sf)
#fungsi berikut ini mengembalikan 2 nilai, yaitu:
#(1) charset = character set
#(2) sf = kode Shannon-Fano yang bersesuaian
def ShannonFano(st):
if len(st)