Certainly! It looks like you have a comprehensive portfolio assignment that covers various aspects of C programming, mathematics, and concurrency. Below, I’ve broken down each task with guidance on how to approach them, including important considerations and sample code snippets to help you get started.
1. Linear Regression (20% - 100 Marks)
Objective:
- Read coordinate data from files.
- Apply the Linear Regression formula to determine the relationship between
x and y.
- Allow user input to calculate a new
y value based on the derived equation.
a. Reading Data from Files (30 Marks)
Approach:
- File Handling in C: Use standard file I/O functions like
fopen(), fscanf(), and fclose().
- Data Storage: Store the
x and y values in dynamically allocated arrays or structures to handle an unknown number of points.
Sample Code:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
double x;
double y;
} Point;
Point* read_coordinates(const char* filename, int* n) {
FILE *file = fopen(filename, "r");
if (!file) {
perror("Unable to open file!");
exit(EXIT_FAILURE);
}
// First, count the number of points
*n = 0;
double x, y;
while (fscanf(file, "%lf %lf", &x, &y) == 2) {
(*n)++;
}
// Allocate memory
Point* points = malloc(sizeof(Point) * (*n));
if (!points) {
perror("Memory allocation failed!");
exit(EXIT_FAILURE);
}
// Reset file and read data
rewind(file);
int i = 0;
while (fscanf(file, "%lf %lf", &points[i].x, &points[i].y) == 2) {
i++;
}
fclose(file);
return points;
}
b. Applying the Linear Regression Formula (50 Marks)
Approach:
- Calculate the necessary summations:
- Apply the formulas for
A and B:
[
A = \frac{(Σy)(Σx^2) - (Σx)(Σxy)}{n(Σx^2) - (Σx)^2}
]
[
B = \frac{n(Σxy) - (Σx)(Σy)}{n(Σx^2) - (Σx)^2}
]
- Form the equation:
y = Bx + A
Sample Code:
void linear_regression(Point* points, int n, double* A, double* B) {
double sum_x = 0, sum_y = 0, sum_xy = 0, sum_x2 = 0;
for(int i = 0; i < n; i++) {
sum_x += points[i].x;
sum_y += points[i].y;
sum_xy += points[i].x * points[i].y;
sum_x2 += points[i].x * points[i].x;
}
double denominator = n * sum_x2 - sum_x * sum_x;
if (denominator == 0) {
fprintf(stderr, "Denominator is zero, cannot compute regression.\n");
exit(EXIT_FAILURE);
}
*A = (sum_y * sum_x2 - sum_x * sum_xy) / denominator;
*B = (n * sum_xy - sum_x * sum_y) / denominator;
}
c. Calculating New y Value Using User Input (20 Marks)
Approach:
- Prompt the User: Ask for an
x value.
- Compute
y: Use the derived equation to calculate y = Bx + A.
- Handle Input Validation: Ensure the user inputs a valid number.
Sample Code:
int main(int argc, char* argv[]) {
if (argc < 2) {
printf("Usage: %s <datafile>\n", argv[0]);
return EXIT_FAILURE;
}
int n;
Point* points = read_coordinates(argv[1], &n);
double A, B;
linear_regression(points, n, &A, &B);
printf("The linear regression equation is: y = %.4fx + %.4f\n", B, A);
double x_input;
printf("Enter a value for x to calculate y: ");
if (scanf("%lf", &x_input) != 1) {
fprintf(stderr, "Invalid input!\n");
free(points);
return EXIT_FAILURE;
}
double y_output = B * x_input + A;
printf("For x = %.4f, y = %.4f\n", x_input, y_output);
free(points);
return EXIT_SUCCESS;
}
Considerations:
- Error Handling: Ensure robust error handling for file operations and memory allocations.
- Precision: Use appropriate data types (
double) for precision in calculations.
- Code Optimization: Consider reusing variables and minimizing redundant calculations.
2. Calculating Pi Using Leibniz Formula and Multithreading (20% - 100 Marks)
Objective:
- Implement the Leibniz formula to approximate Pi.
- Utilize multithreading to distribute the computational workload dynamically based on user-specified thread count.
Leibniz Formula:
[
\sum_{n=0}^{\infty} \frac{(-1)^n}{2n + 1} = \frac{\pi}{4}
]
Overall Approach:
-
Parse Command-Line Arguments:
argv[1]: Number of iterations.
argv[2]: Number of threads.
-
Divide Workload Among Threads:
- Each thread calculates a portion of the series.
- Use thread-safe mechanisms to accumulate results.
-
Calculate Pi from the Series:
- Multiply the sum by 4 to approximate Pi.
Sample Implementation:
a. Struct to Pass Data to Threads:
typedef struct {
long start;
long end;
double partial_sum;
} ThreadData;
b. Thread Function:
#include <pthread.h>
void* calculate_partial_sum(void* arg) {
ThreadData* data = (ThreadData*)arg;
double sum = 0.0;
for(long i = data->start; i < data->end; i++) {
sum += (i % 2 == 0 ? 1.0 : -1.0) / (2.0 * i + 1.0);
}
data->partial_sum = sum;
pthread_exit(NULL);
}
c. Main Function:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int main(int argc, char* argv[]) {
if(argc != 3){
fprintf(stderr, "Usage: %s <iterations> <num_threads>\n", argv[0]);
return EXIT_FAILURE;
}
long iterations = atol(argv[1]);
int num_threads = atoi(argv[2]);
if(iterations <=0 || num_threads <=0){
fprintf(stderr, "Iterations and number of threads must be positive integers.\n");
return EXIT_FAILURE;
}
pthread_t threads[num_threads];
ThreadData thread_data[num_threads];
long chunk = iterations / num_threads;
long remainder = iterations % num_threads;
long current = 0;
for(int i = 0; i < num_threads; i++){
thread_data[i].start = current;
thread_data[i].end = current + chunk + (i < remainder ? 1 : 0);
thread_data[i].partial_sum = 0.0;
current = thread_data[i].end;
pthread_create(&threads[i], NULL, calculate_partial_sum, &thread_data[i]);
}
double total_sum = 0.0;
for(int i = 0; i < num_threads; i++){
pthread_join(threads[i], NULL);
total_sum += thread_data[i].partial_sum;
}
double pi = total_sum * 4;
printf("Approximated Pi = %.15f\n", pi);
return EXIT_SUCCESS;
}
Considerations:
- Dynamic Workload: Ensure that the workload is evenly distributed, especially when
iterations is not perfectly divisible by num_threads.
- Thread Safety: Although each thread works on separate data, accumulation (
total_sum) is done after all threads have joined, maintaining thread safety.
- Performance Optimization: Be mindful of the overhead of creating too many threads. Test with different thread counts to find an optimal balance.
- Precision: Use
long for iteration counts to handle large numbers if necessary.
3. Finding Prime Numbers in a Text File Using Multithreading (30% - 100 Marks)
Objective:
- Read a list of numbers from a file.
- Use POSIX threads to identify prime numbers efficiently.
- Output the count and list of prime numbers to a file.
Overall Approach:
-
Read the Numbers from the File:
- Similar to reading coordinate data, read all numbers into an array.
-
Divide the Workload Among Threads:
- Split the array into chunks, each processed by a separate thread.
-
Check for Primes:
- Implement an efficient prime-checking function.
-
Collect and Output Results:
- Synchronize access to shared data structures to store prime numbers.
Sample Implementation:
a. Prime Checking Function:
#include <math.h>
#include <stdbool.h>
bool is_prime(long num){
if(num < 2) return false;
if(num == 2) return true;
if(num % 2 == 0) return false;
long sqrt_num = (long)sqrt((double)num);
for(long i = 3; i <= sqrt_num; i += 2){
if(num % i == 0) return false;
}
return true;
}
b. Struct to Pass Data to Threads:
typedef struct {
long* numbers;
long start;
long end;
long* primes;
long prime_count;
} PrimeThreadData;
c. Thread Function:
#include <pthread.h>
void* find_primes(void* arg){
PrimeThreadData* data = (PrimeThreadData*)arg;
data->prime_count = 0;
for(long i = data->start; i < data->end; i++){
if(is_prime(data->numbers[i])){
data->primes[data->prime_count++] = data->numbers[i];
}
}
pthread_exit(NULL);
}
d. Main Function:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int main(int argc, char* argv[]) {
if(argc != 3){
fprintf(stderr, "Usage: %s <input_file> <num_threads>\n", argv[0]);
return EXIT_FAILURE;
}
char* input_filename = argv[1];
int num_threads = atoi(argv[2]);
if(num_threads <= 0){
fprintf(stderr, "Number of threads must be positive.\n");
return EXIT_FAILURE;
}
// Read numbers from file
FILE* file = fopen(input_filename, "r");
if(!file){
perror("Unable to open input file");
return EXIT_FAILURE;
}
// First, count numbers
long count = 0;
long temp;
while(fscanf(file, "%ld", &temp) == 1){
count++;
}
// Allocate memory
long* numbers = malloc(sizeof(long) * count);
if(!numbers){
perror("Memory allocation failed!");
fclose(file);
return EXIT_FAILURE;
}
// Read numbers into array
rewind(file);
long index = 0;
while(fscanf(file, "%ld", &numbers[index]) == 1){
index++;
}
fclose(file);
// Prepare threads
pthread_t threads[num_threads];
PrimeThreadData thread_data[num_threads];
long chunk = count / num_threads;
long remainder = count % num_threads;
// Allocate memory for primes
long** thread_primes = malloc(sizeof(long*) * num_threads);
long* thread_prime_counts = malloc(sizeof(long) * num_threads);
for(int i = 0; i < num_threads; i++){
thread_data[i].start = i * chunk + (i < remainder ? i : remainder);
thread_data[i].end = thread_data[i].start + chunk + (i < remainder ? 1 : 0);
thread_data[i].numbers = numbers;
// Allocate maximum possible primes for each thread
long thread_size = thread_data[i].end - thread_data[i].start;
thread_primes[i] = malloc(sizeof(long) * thread_size);
if(!thread_primes[i]){
perror("Memory allocation failed!");
exit(EXIT_FAILURE);
}
thread_data[i].primes = thread_primes[i];
thread_data[i].prime_count = 0;
pthread_create(&threads[i], NULL, find_primes, &thread_data[i]);
}
// Wait for threads to finish
long total_primes = 0;
for(int i = 0; i < num_threads; i++){
pthread_join(threads[i], NULL);
total_primes += thread_data[i].prime_count;
}
// Collect all primes
long* primes = malloc(sizeof(long) * total_primes);
if(!primes){
perror("Memory allocation failed!");
exit(EXIT_FAILURE);
}
long pos = 0;
for(int i = 0; i < num_threads; i++){
for(long j = 0; j < thread_data[i].prime_count; j++){
primes[pos++] = thread_primes[i][j];
}
free(thread_primes[i]);
}
free(thread_primes);
free(thread_prime_counts);
free(numbers);
// Write primes to output file
FILE* out = fopen("primes_output.txt", "w");
if(!out){
perror("Unable to open output file");
free(primes);
return EXIT_FAILURE;
}
fprintf(out, "Total Prime Numbers Found: %ld\n", total_primes);
for(long i = 0; i < total_primes; i++){
fprintf(out, "%ld\n", primes[i]);
}
fclose(out);
free(primes);
return EXIT_SUCCESS;
}
Considerations:
- Memory Management: Ensure all dynamically allocated memory is freed appropriately to avoid memory leaks.
- Synchronization: In this approach, each thread writes to its own
primes array, eliminating the need for mutexes or other synchronization primitives.
- Scalability: The program should handle large input files and varying numbers of threads efficiently.
- Error Handling: Validate all file operations and memory allocations.
4. Applying Box Filter on an Image Using Multithreading (Details Missing in Original Prompt)
Note: It seems there was a mix-up in task descriptions combining parts of prime number finding and image processing. Assuming the image processing task involves applying a Box Blur filter, here's how you can approach it.
Objective:
- Read an image file into a 2D array.
- Apply a Box Blur filter using multithreading.
- Output the blurred image.
Overall Approach:
-
Read the Image File:
- Use a suitable image format (e.g., PPM for simplicity) to read pixel data into a 2D array.
-
Apply Box Filter:
- A Box Blur averages the color values of neighboring pixels.
- Handle edge cases where neighbors might be out of bounds.
-
Use Multithreading to Parallelize the Operation:
- Divide the image into sections, each processed by a separate thread.
-
Write the Blurred Image to a File:
- Save the processed 2D array back into an image file.
Sample Implementation:
a. Simple PPM Image Handling:
PPM (Portable Pixmap) is chosen for its simplicity.
#include <stdio.h>
#include <stdlib.h>
typedef struct {
unsigned char r, g, b;
} Pixel;
typedef struct {
int width;
int height;
Pixel** data;
} Image;
Image* read_ppm(const char* filename){
FILE* fp = fopen(filename, "rb");
if(!fp){
perror("Unable to open image file");
exit(EXIT_FAILURE);
}
char format[3];
fscanf(fp, "%2s", format);
if(format[0] != 'P' || format[1] != '6'){
fprintf(stderr, "Unsupported image format!\n");
fclose(fp);
exit(EXIT_FAILURE);
}
// Skip comments
int c = fgetc(fp);
while(c == '#'){
while(fgetc(fp) != '\n');
c = fgetc(fp);
}
ungetc(c, fp);
Image* img = malloc(sizeof(Image));
fscanf(fp, "%d %d", &img->width, &img->height);
int max;
fscanf(fp, "%d", &max);
fgetc(fp); // Consume the newline after max color value
// Allocate memory for pixels
img->data = malloc(img->height * sizeof(Pixel*));
for(int i = 0; i < img->height; i++){
img->data[i] = malloc(img->width * sizeof(Pixel));
fread(img->data[i], sizeof(Pixel), img->width, fp);
}
fclose(fp);
return img;
}
void write_ppm(const char* filename, Image* img){
FILE* fp = fopen(filename, "wb");
if(!fp){
perror("Unable to open output file");
exit(EXIT_FAILURE);
}
fprintf(fp, "P6\n%d %d\n255\n", img->width, img->height);
for(int i = 0; i < img->height; i++){
fwrite(img->data[i], sizeof(Pixel), img->width, fp);
}
fclose(fp);
}
b. Applying Box Blur:
typedef struct {
Image* original;
Image* blurred;
int start_row;
int end_row;
} BlurData;
void apply_box_blur(BlurData* data){
for(int i = data->start_row; i < data->end_row; i++){
for(int j = 0; j < data->original->width; j++){
int count = 0;
int sum_r = 0, sum_g = 0, sum_b = 0;
// Iterate over the 3x3 grid
for(int di = -1; di <= 1; di++){
for(int dj = -1; dj <= 1; dj++){
int ni = i + di;
int nj = j + dj;
if(ni >=0 && ni < data->original->height && nj >=0 && nj < data->original->width){
sum_r += data->original->data[ni][nj].r;
sum_g += data->original->data[ni][nj].g;
sum_b += data->original->data[ni][nj].b;
count++;
}
}
}
data->blurred->data[i][j].r = sum_r / count;
data->blurred->data[i][j].g = sum_g / count;
data->blurred->data[i][j].b = sum_b / count;
}
}
}
c. Multithreading Implementation:
#include <pthread.h>
int main(int argc, char* argv[]) {
if(argc != 4){
fprintf(stderr, "Usage: %s <input_ppm> <output_ppm> <num_threads>\n", argv[0]);
return EXIT_FAILURE;
}
char* input_file = argv[1];
char* output_file = argv[2];
int num_threads = atoi(argv[3]);
if(num_threads <= 0){
fprintf(stderr, "Number of threads must be positive.\n");
return EXIT_FAILURE;
}
Image* original = read_ppm(input_file);
Image* blurred = malloc(sizeof(Image));
blurred->width = original->width;
blurred->height = original->height;
// Allocate memory for blurred image
blurred->data = malloc(blurred->height * sizeof(Pixel*));
for(int i = 0; i < blurred->height; i++){
blurred->data[i] = malloc(blurred->width * sizeof(Pixel));
}
// Prepare threads
pthread_t threads[num_threads];
BlurData thread_data[num_threads];
int chunk = original->height / num_threads;
int remainder = original->height % num_threads;
int current_row = 0;
for(int i = 0; i < num_threads; i++){
thread_data[i].original = original;
thread_data[i].blurred = blurred;
thread_data[i].start_row = current_row;
thread_data[i].end_row = current_row + chunk + (i < remainder ? 1 : 0);
current_row = thread_data[i].end_row;
pthread_create(&threads[i], NULL, (void*(*)(void*))apply_box_blur, &thread_data[i]);
}
// Wait for threads to finish
for(int i = 0; i < num_threads; i++) {
pthread_join(threads[i], NULL);
}
// Write blurred image
write_ppm(output_file, blurred);
// Free memory
for(int i = 0; i < original->height; i++) free(original->data[i]);
free(original->data);
free(original);
for(int i = 0; i < blurred->height; i++) free(blurred->data[i]);
free(blurred->data);
free(blurred);
return EXIT_SUCCESS;
}
Considerations:
- Image Format Choice: PPM is used for simplicity. For more complex formats like JPEG or PNG, consider using libraries like
libjpeg or libpng.
- Edge Handling: The Box Blur implementation handles edges by only averaging existing neighboring pixels.
- Memory Allocation: Efficiently allocate and deallocate memory to handle large images.
- Thread Synchronization: Since each thread works on separate rows, there's no need for mutexes.
- Performance Optimization: Balance the number of threads with the image size to optimize performance.
General Tips for the Portfolio:
-
Modular Code Structure:
- Break down your code into functions and modules for readability and maintainability.
- Use header files (
.h) to declare function prototypes and shared structures.
-
Dynamic Memory Allocation:
- Use
malloc(), calloc(), and free() appropriately to manage memory.
- Always check the return values of memory allocation functions to handle allocation failures.
-
Error Handling:
- Provide meaningful error messages for users.
- Ensure that your program can handle unexpected inputs gracefully.
-
Concurrency Best Practices:
- Minimize shared data to reduce the need for synchronization.
- Ensure that each thread has its own data to work on to avoid race conditions.
- Use
pthread_join() to wait for threads to finish their tasks.
-
Testing:
- Test your programs with various input sizes and thread counts to ensure correctness and performance.
- Validate the outputs against known results or mathematical tools.
-
Documentation:
- Comment your code to explain complex sections.
- Provide a README file in your zip folder explaining how to compile and run each task.
-
Code Optimization:
- Optimize loops and computationally intensive sections for performance.
- Avoid unnecessary computations within loops, especially in multithreaded sections.
-
Compliance with Assignment Requirements:
- Ensure that your submission meets all specified requirements, such as file naming conventions and output formats.
- Double-check that your programs compile without warnings or errors using
-Wall flag in gcc.
Submission Checklist:
- Source Code: All
.c and .h files for each task.
- Resource Files: Any input files, image files, or other resources used for testing.
- Makefile: (Optional) A Makefile to compile all tasks easily.
- README: Instructions on how to compile and run each program, along with any dependencies.
- Output Files: Sample output files demonstrating the correctness of your programs.
Ensure that all files are organized clearly within separate folders if necessary and compressed into a single .zip archive before submitting to Canvas.
Good luck with your portfolio assignment! If you have specific questions or need further assistance with any part of the tasks, feel free to ask.