This portfolio is split up into 4 separate tasks which will test your knowledge of mathematics, C programming and concurrency. Each task should be zipped up into a single zip folder containing all C and resource files for the submission on Canvas.
Linear Regression (20% - 100 marks)
This task will test your knowledge of file input and mathematical formulas. Basic linear regression (LR) is used to find a relationship between two types of data. For example, you could use LR to find the relationship between glucose intake and heart rate. These initially would be plotted on a graph where the x axis represents glucose and the y axis represents heart rate. Using the LR formula, you can find y=bx+a (equation of a straight line (more commonly known as y=mx+c) between "n" number of points on a graph. Below are the formulas to find "a" and "b".
A = (Σy)(Σx^2) - (Σx)(Σxy) / n(Σx^2) - (Σx)^2
B = n(Σxy) - (Σx)(Σy) / n(Σx^2) - (Σx)^2
You will be given multiple text files containing "n" number of coordinates. Your program will read in the coordinates (x,y) and use the LR formula to produce the gradient (a) and the constant (b), and being able to print out y=bx+a. For example, if a = 0.5 and b=-2, your program will print out y=-2x+0.5. This equation now represents the trend in the data you will be given. Finally, your program will ask the user to type in a value of x which will then calculate y.
Read data from file appropriately (30 marks)
Use LR formula to process the data and print out the correct equation of a straight line (50 marks)
Find new value of "y" using user input (20 marks)
Calculating Pi using Leibniz formula and multithreading (20% - 100 marks)
The Leibniz formula is an infinite series method of calculating Pi. The formula is a very simple way of calculating Pi, however, it takes a large amount of iterations to produce a low precision value of Pi. This task requires a large amount of computation and therefore it is vital that you use multithreading to speed up the program. Below is the Leibniz formula:
Σ ((-1)^n) / (2n + 1) = π/4
(The summation runs from n=0 to infinity)
As the series can be iterated infinite amount of times, your program should allow the user to take in 2 command line arguments; the first is the number of iterations (argv[1]) and the second is the amount of threads (argv[2]) the user would like to use. This means that the slicing of workload needs to be dynamic. NOTE – this program should work with any amount of threads.
Calculating Pi using Leibniz formula (20 marks)
Using multithreading with appropriate slicing (60 marks)
Correct value of Pi printed out depending on iteration count (20 marks)
Finding prime numbers in a text file using multithreading (30% - 100 marks)
You will be given a file containing a list of numbers. The amount and numbers themselves will be random. You will create a C program which counts the number of prime numbers there are within the file and output to a file the amount of prime numbers found, along with the prime numbers themselves. The aim of this task is to use POSIX threads to parallelise the task to take advantage of the multicore processor within your machine to speed up the task. The threads you spawn within the program must compute an equal or close to an equal amount of computations to make the program more efficient in relation to speed. For this section, as you will only be reading one file and splitting it across many threads (determined by argv[1]), you should load in the file and split the file into equal parts, then process each slice within your threads. This task also tests your knowledge of dynamic memory allocation. NOTE – this program should work with any amount of threads.
Reading in an image file into a single or 2D array (10 marks)
Applying Box filter on image (20 marks)
Using multithreading appropriately to apply Box filter (40 marks)
Using dynamic memory – malloc (10 marks)
Outputting the correct image with Box Blur applied (20 marks)
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
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:
c
#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:
Σx, Σy, Σxy, Σx²
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}
]
typedef struct {
long start;
long end;
double partial_sum;
} ThreadData;
b. Thread Function:
c
#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:
c
#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:
c
#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:
c
typedef struct {
long* numbers;
long start;
long end;
long* primes;
long prime_count;
} PrimeThreadData;
c. Thread Function:
c
#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:
c
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.
c
#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:
c
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:
c
#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.