0% found this document useful (0 votes)
32 views30 pages

Ccs353 Mdcs Lab Manual

The document outlines various programming exercises related to data compression and processing techniques, including Huffman coding, run-length encoding, Lempel-Ziv algorithm, arithmetic coding, video frame extraction, data stream scheduling, content popularity analysis, and RAID striping for data availability. Each exercise includes an aim, algorithm, and program implementation in Python, demonstrating successful execution and output verification. The exercises are designed for students to apply their programming skills in practical scenarios during the academic year 2021-2022.

Uploaded by

abimegha009
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views30 pages

Ccs353 Mdcs Lab Manual

The document outlines various programming exercises related to data compression and processing techniques, including Huffman coding, run-length encoding, Lempel-Ziv algorithm, arithmetic coding, video frame extraction, data stream scheduling, content popularity analysis, and RAID striping for data availability. Each exercise includes an aim, algorithm, and program implementation in Python, demonstrating successful execution and output verification. The exercises are designed for students to apply their programming skills in practical scenarios during the academic year 2021-2022.

Uploaded by

abimegha009
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

Name :

Reg.No: Semester:

Degree: Branch:

Subject: SubjectCode:
BONAFIDE CERTIFICATE

Name of the Student: _

RegisterNo.

This is to certify that this is a bonafide record of the work done by the above student
with Roll No. of Semester B.E

Degree in in

the

_Laboratory during the academic year 2021–2022.

Staff-In-Charge Head of the Dept.

Submitted for the Practical Examination held on -------------------------

Internal Examiner External Examiner


INDEX

EX DATE NAMEOFTHEEXPERIMENT PAGE MARKS STAFFSIGN


NO. NO.
EX.NO 1 Construct Huffman codes for given symbol probabilities
AIM:

To write the program for Huffman codes for given symbol probabilities using python.

ALGORITHM:

STEP1: Create a leaf node for each unique character & build a min heap of all leaf nodes (Min
Heap is used as a priority queue). The value of frequency field is used to compare two nodes in min
heap. Initially, the least frequent character is at root).

STEP2: Extract two nodes with the minimum frequency from the min heap.

STEP3: Create a new internal node with a frequency equal to the sum of the two nodes
frequencies. Make the first extracted node as its left child & the other extracted node as its right
child. Add this node the min heap.

STEP4: Repeat step 2 and 3 until the heap contains only one node. The remaining node is the root
node and the tree is complete.

Program:
import heapq

from collections import defaultdict, Counter

class Node:

def __init__(self, char, freq):

self.char = char

self.freq = freq

self.left = None

self.right = None

def __init__(self, other):

return self.freq < other.freq

def build_huffman_tree(text):

freq_dict = Counter(text)

priority_queue = [Node(char, freq) for char, freq in freq_dict.items()]

heapq.heapify(priority_queue)

while len(priority_queue) > 1:


left = heapq.heappop(priority_queue)

right = heapq.heappop(priority_queue)

merged = Node(None, left.freq + right.freq)

merged.left = left

merged.right = right

heapq.heappush(priority_queue, merged)

return priority_queue[0]

def build_huffman_codes(node, prefix="", codes={}):

if node is not None:

if node.char is not None:

codes[node.char] = prefix

build_huffman_codes(node.left, prefix + "0", codes)

build_huffman_codes(node.right, prefix + "1", codes)

return codes

def encode(text, codes):

encoded_text = ""

for char in text:

encoded_text += codes[char]

return encoded_text

def decode(encoded_text, root):

decoded_text = ""

current_node = root

for bit in encoded_text:

if bit == '0':

current_node = current_node.left

else:

current_node = current_node.right

if current_node.char is not None:

decoded_text += current_node.char

current_node = root

return decoded_text

def huffman_compress(text):
root = build_huffman_tree(text)

codes = build_huffman_codes(root)

encoded_text = encode(text, codes)

return encoded_text, root

def huffman_decompress(encoded_text, root):

return decode(encoded_text, root)

# Example usage:

text = "hello world"

encoded_text, tree_root = huffman_compress(text)

print("Encoded text:", encoded_text)

decoded_text = huffman_decompress(encoded_text, tree_root)

print("Decoded text:", decoded_text)

Output:

Encoded text: 11100001010110111101111001010001


Decoded text: hello world

Result:

Thus the program executed successfully and the output also verified.
Ex.no.2 Encode run lengths with fixed-length code.

Aim:

ALGORITHM:
PROGRAM:

def encode(message):

encoded_message = ""

i=0

while (i <= len(message)-1):

count = 1

ch = message[i]

j=i

while (j < len(message)-1):

if (message[j] == message[j+1]):

count = count+1

j = j+1

else:

break

encoded_message=encoded_message+str(count)+ch

i = j+1

return encoded_message

#Provide different values for message and test your program

encoded_message=encode("ABBBBCCCCCCCCAB")

print(encoded_message)
OUTPUT:

1A4B8C1A1B

RESULT
EX.NO.3 Lempel-Ziv algorithm for adaptive variable-length encoding

Aim:

To write a Lempel Ziv algorithm for adaptive variable-length encoding using python coding.

ALGORITHM:

STEP1: Initialize a dictionary to store mappings of substrings to indices.

STEP2: Append to char current string.

STEP3: Check if current string is in dictionary.

STEP4: Repeat until all characters are processed.

STEP5: Output the Encoded data

PROGRAM:

keys=[]

text = open('test').read() # contain of the string:


AAAABBCDEABCDABCAAABCDEEEEEECBBBBBBDDAAE

index=0

t=time.time()

def sub_strin_check(text,index_num):

n=1

while True:

substring = text[index_num:index_num+n]

if substring not in keys :

print(substring)

keys.append(substring)

# print(keys[-1])
return (index_num+n)

else:

n = n+1

continue

while True:

try:

if text[index] not in keys:

# print (index)

keys.append(text[index])

print(keys.append(text[index]),text[index])

except:

break

else:

try:

index = sub_strin_check(text,index)

print(index)

print(index)

index = index + 1

except:

break

res = str(keys)

print(res)

with open("result","w") as f:

f.write(res)
OUTPUT:

['A', 'A', 'AA', 'AB', 'C', 'C', 'CD', 'ABC', 'ABCA', 'ABCD', 'E', 'E', 'EE', 'EEC', 'B', 'B', 'BB', 'BBD',
'AAE']

RESULT:

Thus the program was executed successfully and the output also verified.

EX.NO:4 Compress the given word using arithmetic coding based on the frequency of the letters
AIM:

To implement a arithmetic coding based on the frequency of the letters.

ALGORITHM:
Step1: Initialization:
Step2:Define a probability model that assigns probabilities to each symbol in the input
alphabet.
Step3:Initialize a range [0, 1) to represent the entire symbol space.
Step4:Symbol Encoding:
Step5:For each symbol in the input sequence:
Step6:Determine the symbol's probability range within the current range.
Step7:Scale the current range to match the probability range of the symbol.
Step8:Update the current range to the scaled subrange of the symbol.
Step9:The final range after encoding represents the entire input sequence with a single
floating-point number.
Step10:Output Encoding:
Step11:output the final range as a floating-point number.
Step12:Decoding (Optional):
Step13:To decode the compressed data:
Step14:Initialize the range to [0, 1) and accumulate the encoded floating-point number.
Step15:Iterate through the input symbols, reversing the encoding process to reconstruct the
original input sequence.

PROGRAM:

F cumulative_freq(freq)

[Int = Int] cf

V total = 0

L(b) 256

I b C freq

cf[b] = total

total += freq[b]

R cf

F arithmethic_coding(bytes, radix)
DefaultDict[Int, Int] freq

L(b) bytes

freq[b.code]++

V cf = cumulative_freq(freq)

BigInt base = bytes.len

BigInt lower = 0

BigInt pf = 1

L(b) bytes

lower = lower * base + cf[b.code] * pf

pf *= freq[b.code]

V upper = lower + pf

BigInt power = 0

pf I/= radix

I pf == 0

L.break

power++

V enc = (upper - 1) I/ BigInt(radix) ^ power


R (enc, power, freq)

F arithmethic_decoding(=enc, radix, =power, freq)

enc *= radix ^ power

V base = sum(freq.values())

V cf = cumulative_freq(freq)

[Int = Int] dict

L(k, v) cf

dict[v] = k

Int? lchar

L(i) 0 .< base

I i C dict

lchar = dict[i]

E I lchar != N

dict[i] = lchar

V decoded = ‘’

L(i) (base - 1 .< -1).step(-1)

power = BigInt(base) ^ i

V div = enc I/ power


V c = dict[Int(div)]

V fv = freq[c]

V cv = cf[c]

V rem = (enc - power * cv) I/ fv

enc = rem

decoded ‘’= Char(code' c)

R decoded

V radix = 10

L(str) ‘DABDDB DABDDBBDDBA ABRACADABRA


TOBEORNOTTOBEORTOBEORNOT’.split(‘ ’)

V (enc, power, freq) = arithmethic_coding(str, radix)

V dec = arithmethic_decoding(enc, radix, power, freq)

print(‘#<25=> #19 * #.^#.’.format(str, enc, radix, power))

I str != dec

X.throw RuntimeError("\tHowever that is incorrect!")

OUTPUT:
DABDDB => 251 * 10^2

DABDDBBDDBA => 167351 * 10^6

ABRACADABRA => 7954170 * 10^4

TOBEORNOTTOBEORTOBEORNOT => 1150764267498783364 * 10^15

RESULT:

Thus the program executed successfully and the output also verified.

Ex. No:5 Write a program to split images from a video without using any primitives

AIM:
To implement the split images from a video without using any primitives.

ALGORITHM:

STEP1:Import the necessary libraries, in this case, OpenCV for video processing and os for file
operations.

STEP2: Define a function split_video_into_frames that takes the path to the video file
(video_path) and the output folder (output_folder) as input parameters.

STEP3: Open the video file using cv2.VideoCapture()

STEP4: Verify if the video file was opened successfully using isOpened().

STEP5: Create the output folder if it doesn't exist.

STEP6: Release the video capture object to free up system resources

PROGRAM:
# Importing all necessary libraries
import cv2
import os

# Read the video from specified path


cam = cv2.VideoCapture("sample.mp4")

try:

# creating a folder named data


if not os.path.exists('data'):
os.makedirs('data')

# if not created then raise error


except OSError:
print ('Error: Creating directory of data')

# frame
currentframe = 0

while(True):

# reading from frame


ret,frame = cam.read()

if ret:
# if video is still left continue creating images
name = './data/frame' + str(currentframe) + '.jpg'
print ('Creating...' + name)

# writing the extracted images


cv2.imwrite(name, frame)

# increasing counter so that it will


# show how many frames are created
currentframe += 1
else:
break

# Release all space and windows once done


cam.release()
cv2.destroyAllWindows()

OUTPUT

All the extracted images


will be saved in a folder
named “data” on the
system.
RESULT:

Thus the program executed successfully and the output also verified.

Ex.No: 6 Program for scheduling requests for data streams.


AIM:
To implement the program for scheduling requests for data streams.

ALGORITHM:

STEP1: Receive incoming requests for data streams.


STEP2: En queue the received requests for processing.
STEP3: Implement scheduling policy to prioritize requests.
STEP4: Allocate resources and process requests accordingly.
STEP5: Monitor system performance and adjust scheduling parameters as needed.
STEP6:Continuously handle incoming requests and optimize resource allocation.

PROGRAM:

import sched
import time

class DataStreamScheduler:
def __init__(self):
self.scheduler = sched.scheduler(time.time, time.sleep)

def schedule_request(self, request_time, data_stream, callback):


self.scheduler.enterabs(request_time, 1, callback, (data_stream,))

def start(self):
self.scheduler.run()

# Example callback function


def process_data_stream(data_stream):
print("Processing data stream:", data_stream)

if __name__ == "__main__":
scheduler = DataStreamScheduler()

# Schedule some data stream requests


scheduler.schedule_request(time.time() + 15, "Stream 1", process_data_stream)
scheduler.schedule_request(time.time() + 10, "Stream 2", process_data_stream)
scheduler.schedule_request(time.time() + 5, "Stream 3", process_data_stream)

# Start the scheduler


scheduler.start()

Output:
Processing data stream: Stream 3
Processing data stream: Stream 2
Processing data stream: Stream 1

RESULT:

Thus the program executed successfully and the output also verified.

Ex.No:7 Write the code for identifying the popularity of content retrieval from media server.

Date:
AIM:
To implement the code for identifying the popularity of content retrievel from media server.

ALGORITHM:

STEP1: Initialize a variable popularity_counter to 0 to track the number of occurrences of the


context.
STEP2: Initialize a variable total_content_count to 0 to count the total number of media content
items.
STEP3: Retrieve media content from the media server based on the provided
context.
STEP4: Iterate through each piece of media content:
a. Extract the context associated with the content.
b. If the extracted context matches the input context, increment popularity_counter by 1.
c. Increment total_content_count by 1.
STEP5: Calculate the popularity score:
a. If total_content_count is greater than 0, calculate the popularity score as
popularity_counter / total_content_count
b. If total_content_count is 0, set the popularity score to 0.
STEP6:Return the popularity score as the output.

PROGRAM:

from collections import Counter


import matplotlib.pyplot as plt

# Sample log data of content retrieval events


log_data = [
{"content_id": 1, "timestamp": "2024-04-26 10:00:00"},
{"content_id": 2, "timestamp": "2024-04-26 10:01:00"},
{"content_id": 1, "timestamp": "2024-04-26 10:02:00"},
{"content_id": 3, "timestamp": "2024-04-26 10:03:00"},
# Add more log entries as needed
]

# Extract content IDs from log data


content_ids = [entry["content_id"] for entry in log_data]

# Count the occurrences of each content ID


popularity_counts = Counter(content_ids)

# Plotting the popularity


plt.bar(popularity_counts.keys(), popularity_counts.values())
plt.xlabel('Content ID')
plt.ylabel('Popularity')
plt.title('Popularity of Content Retrieval')
plt.show()

Output:
RESULT:

Thus the program executed successfully and the output also verified.

EX.NO: 8 Write the code for ensuring data availability in disks using strip based method.
Date:
________________________________________________________________________________
AIM:
To implement the program for ensuring data availability in disks using strip based method.

ALGORITHM:

STEP1: Choose the RAID level based on redundancy and performance requirements.
STEP2:Divide data into stripes (blocks) based on the RAID stripe size.
STEP3:Distribute stripes across disks:
 RAID 0: Distribute stripes evenly across disks.
 RAID 1: Mirror stripes across disks.
 RAID 5: Distribute data and parity stripes across disks.
 Other RAID levels: Distribute data and redundancy information accordingly.
STEP4: Monitor disk health and redundancy.
STEP5: Replace failed disks and rebuild data using redundancy information.
STEP6: Optionally, use hot spare disks and implement proactive monitoring for enhanced
availability.
Step7: Perform regular maintenance and backups for data protection and recovery.

PROGRAM:

class RAIDStrip:
def __init__(self, num_disks, strip_size):
self.num_disks = num_disks
self.strip_size = strip_size
self.disks = [[] for _ in range(num_disks)]

def write_data(self, data):


data_length = len(data)
num_strips = data_length // self.strip_size
if data_length % self.strip_size != 0:
num_strips += 1

for strip_index in range(num_strips):


start = strip_index * self.strip_size
end = min((strip_index + 1) * self.strip_size, data_length)

for disk_index in range(self.num_disks):


self.disks[disk_index].extend(data[start:end]
[disk_index::self.num_disks])

def read_data(self):
reconstructed_data = []
for strip_index in range(len(self.disks[0])):
for disk_index in range(self.num_disks):
strip = self.disks[disk_index][strip_index]
reconstructed_data.append(strip)
return ''.join(reconstructed_data)

def print_disks(self):
for i, disk in enumerate(self.disks):
print(f"Disk {i+1}: {disk}")

if __name__ == "__main__":
num_disks = 4
strip_size = 4
raid = RAIDStrip(num_disks=num_disks, strip_size=strip_size)

# Write data to RAID


data = "Hello, this is some test data for RAID striping!"
raid.write_data(data)

# Print the content of each disk


raid.print_disks()

# Read data from RAID


retrieved_data = raid.read_data()
print("Retrieved data:", retrieved_data)

OUTPUT:

Disk 1: ['H', 'o', 'h', 'i', 'o', 't', ' ', 'a', 'r', 'I', 't', 'i']
Disk 2: ['e', ',', 'i', 's', 'm', 'e', 'd', ' ', ' ', 'D', 'r', 'n']
Disk 3: ['l', ' ', 's', ' ', 'e', 's', 'a', 'f', 'R', ' ', 'i', 'g']
Disk 4: ['l', 't', ' ', 's', ' ', 't', 't', 'o', 'A', 's', 'p', '!']
Retrieved data: Hello, this is some test data for RAID striping!

RESULT:

Thus the program executed successfully and the output also verified.

Ex.no:9 Write a program to convert all images to gif images without using any primitives

Date:
AIM:

To implement the program to convert all the images to gif images without using any primitives.

ALGORITHM:

STEP1: Import necessary libraries for image processing and GIF creation (e.g., PIL, imageio).
STEP2: Load all input images from the provided file paths.
STEP3: Convert each loaded image to the GIF-compatible format.
 Resize images if necessary to ensure consistent dimensions.
 Convert images to the appropriate color mode (e.g., RGB).
STEP4:Create a GIF file and initialize it with the first image.
 Set parameters such as duration (time interval between frames) and loop count if needed.
STEP5: For each remaining image:
 Append the image as a new frame to the GIF file.
 Ensure that the frame duration matches the desired timing.
STEP6:Save the GIF file with the specified output file name.
STEP7:The output is a GIF file containing all input images.

PROGRAM:
from PIL import Image
import os

def jpg_to_gif(input_folder, output_file):


images = []

# Open each JPG image in the input folder and append it to the images list
for filename in os.listdir(input_folder):
if filename.endswith(".jpg"):
img_path = os.path.join(input_folder, filename)
images.append(Image.open(img_path))

# Save the images as a GIF file


images[0].save(output_file, save_all=True, append_images=images[1:], duration=100,
loop=0)

print(f"GIF file saved as {output_file}")

# Specify the input folder containing JPG images and the output GIF file path

input_folder = "/var/pictures"
output_file = "output.gif"

# Call the function to convert JPG images to GIF


jpg_to_gif(input_folder, output_file)

OUTPUT:

RESULT:

Thus the program executed successfully and the output also verified.

You might also like