├── DAA ├── ConnectivityByBFS.md ├── Djikstra.md ├── Floyds.md ├── HeapSort.md ├── HorspoolAlgo.md ├── KnapSack.md ├── NQueens.md ├── PreSort.md ├── PrimsAlgo.md ├── QuickSort.md ├── SubSetProblem.md ├── TopoSort.md └── mergeSort.md ├── IoT ├── DHT11.md ├── GasSensor.md ├── HeartBeatSensor.md ├── LCD.md ├── LDRwithRaspberryPi.md ├── LEDblinking.md ├── PIR.md └── WaterLevel.md ├── README.md └── backend.ipynb /DAA/ConnectivityByBFS.md: -------------------------------------------------------------------------------- 1 | ## Check the connectivity of Graph by BFS 2 | ### code 3 | ``` c 4 | #include 5 | #include 6 | 7 | #define MAX 100 8 | 9 | int adjMatrix[MAX][MAX], visited[MAX]; 10 | int queue[MAX], front = -1, rear = -1; 11 | int n; // Number of vertices 12 | 13 | void enqueue(int v) { 14 | if (rear == MAX - 1) { 15 | printf("Queue is full\n"); 16 | return; 17 | } 18 | if (front == -1) front = 0; 19 | rear++; 20 | queue[rear] = v; 21 | } 22 | 23 | int dequeue() { 24 | if (front == -1 || front > rear) { 25 | printf("Queue is empty\n"); 26 | return -1; 27 | } 28 | int v = queue[front]; 29 | front++; 30 | return v; 31 | } 32 | 33 | int isQueueEmpty() { 34 | return front == -1 || front > rear; 35 | } 36 | 37 | void BFS(int start) { 38 | enqueue(start); 39 | visited[start] = 1; 40 | 41 | while (!isQueueEmpty()) { 42 | int currentVertex = dequeue(); 43 | for (int i = 0; i < n; i++) { 44 | if (adjMatrix[currentVertex][i] == 1 && !visited[i]) { 45 | enqueue(i); 46 | visited[i] = 1; 47 | } 48 | } 49 | } 50 | } 51 | 52 | int isGraphConnected() { 53 | // Check connectivity by starting BFS from vertex 0 54 | BFS(0); 55 | 56 | // If any vertex is not visited, the graph is not connected 57 | for (int i = 0; i < n; i++) { 58 | if (!visited[i]) { 59 | return 0; // Graph is not connected 60 | } 61 | } 62 | return 1; // Graph is connected 63 | } 64 | 65 | int main() { 66 | printf("Enter the number of vertices: "); 67 | scanf("%d", &n); 68 | 69 | printf("Enter the adjacency matrix (space separated, 0/1 for each element):\n"); 70 | for (int i = 0; i < n; i++) { 71 | for (int j = 0; j < n; j++) { 72 | scanf("%d", &adjMatrix[i][j]); 73 | } 74 | } 75 | 76 | // Initialize visited array to 0 77 | for (int i = 0; i < n; i++) { 78 | visited[i] = 0; 79 | } 80 | 81 | if (isGraphConnected()) { 82 | printf("The graph is connected.\n"); 83 | } else { 84 | printf("The graph is not connected.\n"); 85 | } 86 | 87 | return 0; 88 | } 89 | 90 | ``` 91 | ### input 92 | ```bash 93 | Enter the number of vertices: 4 94 | Enter the adjacency matrix (space separated, 0/1 for each element):
95 | 0 1 0 0 96 | 1 0 0 0 97 | 0 0 0 1 98 | 0 0 1 0 99 | 100 | ``` 101 | 102 | ### output 103 | ``` bash 104 | The graph is not connected. 105 | ``` 106 | -------------------------------------------------------------------------------- /DAA/Djikstra.md: -------------------------------------------------------------------------------- 1 | # Djikstra Shortest Path Algorithm 2 | 3 | ### code 4 | ``` cpp 5 | #include 6 | #define INFINITY 999 7 | 8 | void dijk(int cost[10][10], int n, int source, int v[10], int d[10]) { 9 | int least, i, j, u; 10 | 11 | v[source] = 1; 12 | 13 | for (i = 1; i <= n; i++) { 14 | least = INFINITY; 15 | // Find the next nearest node u 16 | for (j = 1; j <= n; j++) { 17 | if (v[j] == 0 && d[j] < least) { 18 | least = d[j]; 19 | u = j; 20 | } 21 | } 22 | v[u] = 1; 23 | 24 | // Update the distance for remaining nodes 25 | for (j = 1; j <= n; j++) { 26 | if (d[j] > d[u] + cost[u][j]) { 27 | d[j] = d[u] + cost[u][j]; 28 | } 29 | } 30 | } 31 | } 32 | 33 | int main() { 34 | int n; 35 | int cost[10][10]; 36 | int source; // Source node 37 | int v[10]; // Visited array 38 | int d[10]; // Distance array 39 | int i, j; // Index variables 40 | 41 | // Read number of nodes 42 | printf("Enter n: "); 43 | scanf("%d", &n); 44 | 45 | // Read the cost adjacency matrix of the graph 46 | printf("Enter Cost matrix:\n"); 47 | for (i = 1; i <= n; i++) { 48 | for (j = 1; j <= n; j++) { 49 | scanf("%d", &cost[i][j]); 50 | } 51 | } 52 | 53 | // Read source node 54 | printf("Enter source: "); 55 | scanf("%d", &source); 56 | 57 | // Initialize d[] to distance from source to each node 58 | // Initialize v[] to 0, indicating none of the nodes are visited 59 | for (i = 1; i <= n; i++) { 60 | d[i] = cost[source][i]; 61 | v[i] = 0; 62 | } 63 | d[source] = 0; // Distance from source to itself is 0 64 | 65 | // Call function to compute shortest distance 66 | dijk(cost, n, source, v, d); 67 | 68 | // Print shortest distance from source to all other nodes 69 | printf("Shortest distance from source %d:\n", source); 70 | for (i = 1; i <= n; i++) { 71 | printf("%d --> %d = %d\n", source, i, d[i]); 72 | } 73 | 74 | return 0; 75 | } 76 | 77 | ``` 78 | 79 | ### Output 80 | 81 | ``` bash 82 | 83 | Enter n: 4 84 | Enter Cost matrix: 85 | 0 10 15 20 86 | 10 0 35 25 87 | 15 35 0 30 88 | 20 25 30 0 89 | 90 | Enter source: 1 91 | Shortest distance from source 1: 92 | 1 --> 1 = 0 93 | 1 --> 2 = 10 94 | 1 --> 3 = 15 95 | 1 --> 4 = 20 96 | 97 | ``` 98 | -------------------------------------------------------------------------------- /DAA/Floyds.md: -------------------------------------------------------------------------------- 1 | ## Floyd's Algorithm 2 | ```c 3 | #include 4 | 5 | int min(int a, int b) 6 | { 7 | return (a < b ? a : b); 8 | } 9 | 10 | void floyd(int D[10][10], int n) 11 | { 12 | for (int k = 0; k < n; k++) 13 | for (int i = 0; i < n; i++) 14 | for (int j = 0; j < n; j++) 15 | D[i][j] = min(D[i][j], D[i][k] + D[k][j]); 16 | } 17 | 18 | int main() 19 | { 20 | int n, cost[10][10]; 21 | printf("\nEnter the number of vertices: "); 22 | scanf("%d", &n); 23 | if (n > 10) 24 | { 25 | printf("Maximum allowed vertices is 10.\n"); 26 | return -1; 27 | } 28 | 29 | printf("\nEnter the cost matrix (use a large number for INF):\n"); 30 | for (int i = 0; i < n; i++) 31 | { 32 | for (int j = 0; j < n; j++) 33 | { 34 | printf("cost[%d][%d]: ", i, j); 35 | scanf("%d", &cost[i][j]); 36 | } 37 | } 38 | 39 | floyd(cost, n); 40 | 41 | printf("\nAll pair shortest path matrix:\n"); 42 | for (int i = 0; i < n; i++) 43 | { 44 | for (int j = 0; j < n; j++) 45 | { 46 | printf("%d ", cost[i][j]); 47 | } 48 | printf("\n"); 49 | } 50 | 51 | return 0; 52 | } 53 | 54 | ``` 55 | -------------------------------------------------------------------------------- /DAA/HeapSort.md: -------------------------------------------------------------------------------- 1 | ## 1. Heap Sort 2 | 3 | ### Code 4 | 5 | ```c 6 | #include 7 | #include 8 | #include 9 | #define N 32000 10 | 11 | int heapify(int a[], int n) { 12 | int i, j, k, v, flag, count = 0; 13 | for (i = n / 2; i >= 1; i--) { 14 | k = i; 15 | v = a[k]; 16 | flag = 0; 17 | while (!flag && 2 * k <= n) { 18 | j = 2 * k; 19 | if (j < n && a[j] < a[j + 1]) { 20 | j = j + 1; 21 | } 22 | if (v >= a[j]) { 23 | flag = 1; 24 | } else { 25 | a[k] = a[j]; 26 | k = j; 27 | count++; 28 | } 29 | } 30 | if (k != i) { 31 | a[k] = v; 32 | count++; 33 | } 34 | } 35 | return count; 36 | } 37 | 38 | int heapSort(int a[], int n) { 39 | int i, temp, swapCount = 0; 40 | swapCount += heapify(a, n); 41 | for (i = n; i >= 2; i--) { 42 | temp = a[1]; 43 | a[1] = a[i]; 44 | a[i] = temp; 45 | swapCount++; 46 | swapCount += heapify(a, i - 1); 47 | } 48 | return swapCount; 49 | } 50 | 51 | int main() { 52 | int n, i, ch, a[N]; 53 | 54 | printf("Enter choice: 1.Correctness 2.Complexity - "); 55 | scanf("%d", &ch); 56 | switch(ch) { 57 | case 1: 58 | printf("Enter the size of array: "); 59 | scanf("%d", &n); 60 | printf("Enter %d array elements -\n", n); 61 | for (i = 1; i <= n; i++) { 62 | scanf("%d", &a[i]); 63 | } 64 | int swaps = heapSort(a, n); 65 | printf("Sorted array is:\n"); 66 | for (i = 1; i <= n; i++) { 67 | printf("%d ", a[i]); 68 | } 69 | printf("\nNumber of swaps: %d\n", swaps); 70 | break; 71 | case 2: { 72 | int arr[N], size, i, j, t1, t2, t3; 73 | double ln; 74 | printf("\nEnter initial size of array for complexity calculation: "); 75 | scanf("%d", &size); 76 | printf("\nSize\tAscending\tcnlog(n)\tDescending\tcnlog(n)\tRandom\t\tcnlog(n)\n"); 77 | for (i = 1; i <= 5; i++) { 78 | if (size > N) break; // Prevent array overflow 79 | ln = 2 * size * log2((double)size); 80 | 81 | // Ascending order 82 | for (j = 1; j <= size; j++) arr[j] = j; 83 | t1 = heapSort(arr, size); 84 | 85 | // Descending order 86 | for (j = 1; j <= size; j++) arr[j] = size - j + 1; 87 | t2 = heapSort(arr, size); 88 | 89 | // Random order 90 | for (j = 1; j <= size; j++) arr[j] = rand() % N; 91 | t3 = heapSort(arr, size); 92 | 93 | printf("%d\t%d\t\t%.0f\t\t%d\t\t%.0f\t\t%d\t\t%.0f\n", size, t1, ln, t2, ln, t3, ln); 94 | 95 | size *= 2; // Double the size for next iteration 96 | } 97 | printf("(Considering c as 2 here)\n"); 98 | break; 99 | } 100 | default: 101 | exit(0); 102 | } 103 | return 0; 104 | } 105 | 106 | ``` 107 | 108 | ### How to run ? 109 | 1. Save the file as heapSort.c 110 | 2. run the command gcc heapSort.c -lm 111 | 3. run ./a.out 112 | 4. Enter the input 113 | 114 | ### Output 115 | ```bash 116 | Enter choice: 1.Correctness 2.Complexity - Enter the size of array: Enter 6 array elements - 117 | Sorted array is: 118 | 1 7 9 11 23 45 119 | Number of swaps: 18 120 | ``` 121 | 122 | ## Time complexity Analysis 123 | **Input:**: 2 16 124 | 125 | ```bash 126 | 127 | Enter choice: 1.Correctness 2.Complexity - 128 | Enter initial size of array for complexity calculation: 129 | Size Ascending cnlog(n) Descending cnlog(n) Random cnlog(n) 130 | 16 80 128 55 128 74 128 131 | 32 192 320 142 320 174 320 132 | 64 456 768 350 768 416 768 133 | 128 1040 1792 828 1792 962 1792 134 | 256 2354 4096 1896 4096 2167 4096 135 | (Considering c as 2 here) 136 | 137 | ``` 138 | -------------------------------------------------------------------------------- /DAA/HorspoolAlgo.md: -------------------------------------------------------------------------------- 1 | # Horspool string matching algorithm 2 | 3 | ``` c 4 | #include 5 | #include 6 | #define MAX 256 7 | 8 | int t[MAX]; // Shift table 9 | int count = 0; // For counting the number of shifts 10 | 11 | // Function to create the shift table 12 | void shifttable(char pat[]) { 13 | int i, m; 14 | m = strlen(pat); // Length of the pattern 15 | for (i = 0; i < MAX; i++) 16 | t[i] = m; // Initialize all shifts to the length of the pattern 17 | for (i = 0; i < m - 1; i++) 18 | t[(int)pat[i]] = m - 1 - i; // Set shift values for each character in the pattern 19 | } 20 | 21 | int horspool(char src[], char pat[]) { 22 | int i, j, k, m, n; 23 | n = strlen(src); // Length of the source string 24 | m = strlen(pat); // Length of the pattern 25 | i = m - 1; // Start from the end of the first window 26 | 27 | while (i < n) { 28 | k = 0; 29 | while ((k < m) && (pat[m - 1 - k] == src[i - k])) // Compare pattern with current window 30 | k++; 31 | if (k == m) // If match is found 32 | return i - m + 1; 33 | else 34 | i += t[(int)src[i]]; // Shift the window according to the shift table 35 | count++; 36 | } 37 | 38 | return -1; // If no match is found 39 | } 40 | 41 | int main() { 42 | char src[100], pat[10]; 43 | int pos; 44 | 45 | printf("\nEnter the main source string: "); 46 | gets(src); 47 | 48 | printf("\nEnter the pattern to be searched: "); 49 | gets(pat); 50 | 51 | shifttable(pat); // Create the shift table 52 | 53 | pos = horspool(src, pat); // Search for the pattern 54 | 55 | if (pos >= 0) 56 | printf("\nFound at %d position", pos + 1); 57 | else 58 | printf("\nString match failed"); 59 | 60 | printf("\nNumber of shifts are %d\n", count); 61 | return 0; 62 | } 63 | 64 | ``` 65 | 66 | ### output 67 | 68 | ``` bash 69 | Enter the main source string:This is a test text to search the pattern tester 70 | 71 | Enter the pattern to be searched: tester 72 | 73 | Found at 42 position 74 | Number of shifts are 11 75 | ``` 76 | -------------------------------------------------------------------------------- /DAA/KnapSack.md: -------------------------------------------------------------------------------- 1 | ### 0/1 Knapsack 2 | 3 | ### code 4 | ``` c 5 | 6 | #include 7 | 8 | int c = 0; 9 | 10 | //Knapsack problem using top-down dynamic programming 11 | int knapsack_TD_DP(int n, int W, int B[][100], int w[], int v[]) { 12 | int c1, c2; 13 | c++; 14 | if (B[n][W] < 0) { 15 | if (W < w[n]) 16 | B[n][W] = knapsack_TD_DP(n - 1, W, B, w, v); 17 | else { 18 | c1 = knapsack_TD_DP(n - 1, W, B, w, v); 19 | c2 = v[n] + knapsack_TD_DP(n - 1, W - w[n], B, w, v); 20 | B[n][W] = (c1 > c2) ? c1 : c2; 21 | } 22 | } 23 | return B[n][W]; 24 | } 25 | 26 | // print the items included in the optimal solution 27 | void print_selected_items(int n, int W, int B[][100], int w[], int v[]) { 28 | printf("Items included in the optimal solution:\n"); 29 | while (n > 0 && W > 0) { 30 | if (B[n][W] != B[n-1][W]) { // Item n is included 31 | printf("Item %d (weight: %d, value: %d)\n", n, w[n], v[n]); 32 | W -= w[n]; 33 | } 34 | n--; 35 | } 36 | } 37 | 38 | int main() { 39 | int n, W, i, j; 40 | 41 | printf("Enter the number of items: "); 42 | scanf("%d", &n); 43 | 44 | int w[n+1], v[n+1]; // Arrays for weights and values (1-indexed) 45 | 46 | // Taking weights and values as input 47 | for (i = 1; i <= n; i++) { 48 | printf("Enter weight and value of item %d: ", i); 49 | scanf("%d %d", &w[i], &v[i]); 50 | } 51 | 52 | // Taking the knapsack capacity as input 53 | printf("Enter the knapsack capacity: "); 54 | scanf("%d", &W); 55 | 56 | int B[n+1][100]; // DP table to store optimal solutions for subproblems 57 | 58 | // Initializing the DP table 59 | for (i = 0; i <= n; i++) 60 | for (j = 0; j <= W; j++) 61 | if (i == 0 || j == 0) 62 | B[i][j] = 0; 63 | else 64 | B[i][j] = -1; 65 | 66 | // Solving the Knapsack problem 67 | knapsack_TD_DP(n, W, B, w, v); 68 | 69 | // Printing the DP table 70 | printf("Knapsack table:\n"); 71 | for (i = 0; i <= n; i++) { 72 | for (j = 0; j <= W; j++) 73 | printf("%d\t", B[i][j]); 74 | printf("\n"); 75 | } 76 | 77 | // Printing the optimal value and the selected items 78 | printf("\nMaximum value: %d\n", B[n][W]); 79 | print_selected_items(n, W, B, w, v); 80 | 81 | return 0; 82 | } 83 | 84 | ``` 85 | 86 | ### output 87 | ``` bash 88 | Enter the number of items: 4 89 | Enter weight and value of item 1: 2 12 90 | Enter weight and value of item 2: 1 10 91 | Enter weight and value of item 3: 3 20 92 | Enter weight and value of item 4: 2 15 93 | Enter the knapsack capacity: 5 94 | Knapsack table: 95 | 0 0 0 0 0 0 96 | 0 0 12 12 12 12 97 | 0 -1 12 22 -1 22 98 | 0 -1 -1 22 -1 32 99 | 0 -1 -1 -1 -1 37 100 | 101 | Maximum value: 37 102 | Items included in the optimal solution: 103 | Item 4 (weight: 2, value: 15) 104 | Item 2 (weight: 1, value: 10) 105 | Item 1 (weight: 2, value: 12) 106 | ``` 107 | -------------------------------------------------------------------------------- /DAA/NQueens.md: -------------------------------------------------------------------------------- 1 | # N Queens Problem 2 | 3 | ### Code 4 | 5 | ``` c 6 | #include 7 | int count = 0; 8 | 9 | int canPlace(int r,int c,int n,char board[n][n]){ 10 | int row = r,col = c; 11 | //check for row above 12 | while(row>=0){ 13 | if(board[row][c] == 'Q') return 0; 14 | row--; 15 | } 16 | 17 | row = r,col = c; 18 | //check for right diagnol 19 | while(row>=0 && col=0 && col>=0){ 28 | if(board[row][col]=='Q') return 0; 29 | row--; 30 | col--; 31 | } 32 | 33 | return 1; 34 | } 35 | 36 | void nqueens(int row,int n,char board[n][n]){ 37 | if(row == n){ 38 | count++; 39 | for(int i=0;i 9 | #include 10 | 11 | #define N 32000 12 | 13 | void merge(int arr[], int low, int mid, int high) { 14 | 15 | int left = low; 16 | int right = mid + 1; 17 | 18 | int temp[high - low + 1]; 19 | int k = 0; 20 | 21 | while (left <= mid && right <= high) { 22 | if (arr[left] <= arr[right]) { 23 | temp[k++] = arr[left++]; 24 | } else { 25 | temp[k++] = arr[right++]; 26 | } 27 | } 28 | 29 | while (left <= mid) { 30 | temp[k++] = arr[left++]; 31 | } 32 | 33 | while (right <= high) { 34 | temp[k++] = arr[right++]; 35 | } 36 | 37 | for (int i = low; i <= high; i++) { 38 | arr[i] = temp[i - low]; 39 | } 40 | 41 | } 42 | 43 | void MergeSort(int arr[], int low, int end) { 44 | if (low >= end) return; 45 | int mid = (low + end) / 2; 46 | MergeSort(arr, low, mid); 47 | MergeSort(arr, mid + 1, end); 48 | merge(arr, low, mid, end); 49 | } 50 | 51 | ``` 52 | 53 | ### code 54 | file from where mergeSort function will be called 55 | ``` c 56 | #include 57 | #include "mergeSort.h" 58 | 59 | void main(){ 60 | printf("Enter the number of elements\n"); 61 | int size; 62 | scanf("%d",&size); 63 | int arr[size]; 64 | for (int i=0;i 5 | int cost[10][10], n; 6 | void prim() 7 | { 8 | int vt[10] = {0}; 9 | int a = 0, b = 0, min, mincost = 0, ne = 0; 10 | // start from the first vertex 11 | vt[0] = 1; 12 | while (ne < n - 1) 13 | { 14 | // Find the nearest neighbour 15 | min = 999; 16 | for (int i = 0; i < n; i++) 17 | { 18 | if (vt[i] == 1) 19 | for (int j = 0; j < n; j++) 20 | if (cost[i][j] < min && vt[j] == 0) 21 | { 22 | min = cost[i][j]; 23 | a = i; 24 | b = j; 25 | } 26 | } 27 | // Include nearest neighbour 'b' into MST 28 | printf("Edge from vertex %d to vertex %d and the cost %d\n", a, b, min); 29 | vt[b] = 1; 30 | ne++; 31 | mincost += min; 32 | cost[a][b] = cost[b][a] = 999; 33 | } 34 | printf("minimum spanning tree cost is %d", mincost); 35 | } 36 | void main() 37 | { 38 | printf("Enter the no. of vertices: "); 39 | scanf("%d", &n); 40 | printf("Enter the cost matrix\n"); 41 | for (int i = 0; i < n; i++) 42 | for (int j = 0; j < n; j++) 43 | scanf("%d", &cost[i][j]); 44 | prim(); 45 | } 46 | 47 | ``` 48 | 49 | -------------------------------------------------------------------------------- /DAA/QuickSort.md: -------------------------------------------------------------------------------- 1 | # Quick Sort 2 | 3 | ### code 4 | 5 | ```c 6 | 7 | #include 8 | #include 9 | #include 10 | 11 | int N; 12 | 13 | int QuickSort(int[], int, int); 14 | int *Partition(int[], int, int); 15 | void swap(int *, int *); 16 | 17 | 18 | int QuickSort(int arr[N], int left, int right) 19 | { 20 | if (left>=right || left < 0 || right < 0) 21 | return 0; 22 | 23 | int s, c1 = 0, c2 = 0, count = 0, *c; 24 | 25 | c = Partition(arr, left, right); 26 | s = c[0]; 27 | count = c[1]; 28 | 29 | c1 = QuickSort(arr, left, s - 1); 30 | c2 = QuickSort(arr, s + 1, right); 31 | 32 | // free(c); 33 | return count + c1 + c2; 34 | } 35 | 36 | int *Partition(int arr[N], int left, int right) 37 | { 38 | int i = left + 1, j = right, count = 0; 39 | int pivot = arr[left]; 40 | int *c = (int *)malloc(sizeof(int) * 2); 41 | 42 | while (i <= j) 43 | { 44 | while (pivot>=arr[i] && i<=right) 45 | { 46 | i++; 47 | count++; 48 | } 49 | while (pivot 7 | #define MAX 10 8 | int s[MAX],vis[MAX]; 9 | int d; 10 | void sumofsub(int currSum, int ind, int remSum){ 11 | //mark the current element as visited 12 | vis[ind] = 1; 13 | //check is the currSum ( that is till now, excluding curr element ) is equal to d 14 | if(currSum + s[ind] == d){ 15 | //print the solution 16 | for(int i = 1;i<=ind;i++){ 17 | if(vis[i]==1) 18 | printf("%d\t",s[i]);} 19 | printf("\n"); 20 | } 21 | else if(currSum + s[ind] + s[ind+1] <= d){ 22 | //if the sum + currElement does not lead to the d so we pick this element, 23 | //we add another condition, we take it only if we could take the next element 24 | sumofsub(currSum + s[ind],ind+1,remSum - s[ind]); 25 | } 26 | 27 | //Notpick condition is that we remove the curr element and check for 2 condition before proceeding 28 | if((currSum + remSum - s[ind] >= d) && (currSum + s[ind+1]<=d)){ 29 | vis[ind] = 0; 30 | sumofsub(currSum,ind+1,remSum-s[ind]); //we need to subtract from remSum 31 | } 32 | } 33 | int main(){ 34 | int i,n,sum=0; 35 | printf("Enter size of the array: "); 36 | scanf("%d",&n); 37 | printf("\n Enter the elements in increasing order : \n"); 38 | for(i=1;i<=n;i++){ 39 | scanf("%d",&s[i]); 40 | sum=sum + s[i]; 41 | } 42 | 43 | printf("\n Enter the subset sum value: "); 44 | scanf("%d",&d); 45 | 46 | if (sum d) 47 | printf("n No subset possible"); 48 | else{ 49 | sumofsub(0,1,sum); 50 | } 51 | } 52 | 53 | ``` 54 | 55 | 56 | ### Output 57 | 58 | ``` bash 59 | 60 | Enter size of the array: 5 61 | 62 | Enter the elements in increasing order : 63 | 1 2 3 4 5 64 | 65 | Enter the subset sum value: 8 66 | 1 2 5 67 | 1 3 4 68 | 3 5 69 | 70 | 71 | ``` 72 | -------------------------------------------------------------------------------- /DAA/TopoSort.md: -------------------------------------------------------------------------------- 1 | # Topological sorting using DFS 2 | 3 | ### code 4 | 5 | ``` c 6 | #include 7 | #include 8 | #define MAX 100 9 | int stack[MAX]; 10 | int top = -1; 11 | 12 | void push(int v) { 13 | stack[++top] = v; 14 | } 15 | 16 | int pop() { 17 | return stack[top--]; 18 | } 19 | 20 | int dfs(int node, int visited[], int recStack[], int adj[MAX][MAX], int V) { 21 | visited[node] = 1; 22 | recStack[node] = 1; // Mark the current node as being part of the recursion stack 23 | 24 | for (int i = 0; i < V; i++) { 25 | if (adj[node][i] == 1) { 26 | if (!visited[i]) { 27 | if (dfs(i, visited, recStack, adj, V)) { 28 | return 1; 29 | } 30 | } 31 | // If the adjacent vertex is already in the recursion stack, cycle is detected 32 | else if (recStack[i]) { 33 | return 1; // Cycle detected 34 | } 35 | } 36 | } 37 | 38 | recStack[node] = 0; // Remove the vertex from the recursion stack after finishing DFS 39 | push(node); // Push the vertex to the stack after all its neighbors are visited 40 | return 0; 41 | } 42 | 43 | 44 | int topologicalSort(int adj[MAX][MAX], int V) { 45 | int visited[MAX] = {0}; // Array to track visited vertices 46 | int recStack[MAX] = {0}; // Array to track vertices in the recursion stack 47 | 48 | for (int i = 0; i < V; i++) { 49 | if (!visited[i]) { 50 | if (dfs(i, visited, recStack, adj, V)) { 51 | return 0; // Cycle detected, no topological sort possible 52 | } 53 | } 54 | } 55 | 56 | // If no cycle is detected, print the topological order by popping from the stack 57 | printf("Topological Sorting: "); 58 | while (top != -1) { 59 | printf("%d ", pop()); 60 | } 61 | printf("\n"); 62 | return 1; 63 | } 64 | 65 | int main() { 66 | int V, E, src, dest; 67 | int adj[MAX][MAX] = {0}; // Adjacency matrix initialization 68 | 69 | printf("Topological sorting for DIRECTED ACYCLIC GRAPH using DFS method\n"); 70 | printf("Enter the number of vertices: "); 71 | scanf("%d", &V); 72 | printf("Enter the number of edges: "); 73 | scanf("%d", &E); 74 | 75 | int a[E][2]; 76 | 77 | printf("Enter %d pairs of edges (source -> destination): \n", E); 78 | for (int i = 0; i < E; i++) { 79 | scanf("%d %d", &a[i][0], &a[i][1]); 80 | 81 | // Check if the entered edge is valid (no repeated edges, no invalid vertex references) 82 | for (int j = 0; j < i; j++) { 83 | if ((a[i][0] == a[j][0]) && (a[i][1] == a[j][1])) { 84 | printf("WRONG INPUT! Cannot enter repeated edges, try again...\n"); 85 | exit(0); 86 | } 87 | } 88 | if ((a[i][0] < 0 || a[i][0] >= V) || (a[i][1] < 0 || a[i][1] >= V)) { 89 | printf("WRONG INPUT! Edges having invalid vertex reference...\n"); 90 | exit(0); 91 | } 92 | 93 | adj[a[i][0]][a[i][1]] = 1; // Fill adjacency matrix 94 | } 95 | 96 | // Output the vertices and edges 97 | printf("Vertices: "); 98 | for (int i = 0; i < V; i++) { 99 | printf("%d ", i); 100 | } 101 | printf("\nEdges:\n"); 102 | for (int i = 0; i < E; i++) { 103 | printf("%d -> %d\n", a[i][0], a[i][1]); 104 | } 105 | 106 | // Perform topological sorting 107 | if (!topologicalSort(adj, V)) { 108 | printf("No Topological Order exists (Graph contains a cycle)\n"); 109 | } 110 | 111 | return 0; 112 | } 113 | 114 | 115 | ``` 116 | 117 | ### Reason why this works for detecting cycle 118 | * Cycle detection in a directed graph during DFS for topological sorting works by tracking the vertices currently being processed in the recursion stack. 119 | * As we perform DFS, if we encounter a vertex that is already in the recursion stack, it indicates a cycle, since a back edge to a vertex in the same DFS path forms a loop. 120 | * This condition implies that the graph contains a cycle, making topological sorting impossible because topological order can only be achieved in Directed Acyclic Graphs (DAGs). 121 | * Thus, detecting such revisits helps identify cycles in the graph. 122 | 123 | ### output 124 | ``` bash 125 | Topological sorting for DIRECTED ACYCLIC GRAPH using DFS method 126 | Enter the number of vertices: 6 127 | Enter the number of edges: 6 128 | Enter 6 pairs of edges (source -> destination): 129 | 5 1 130 | 5 1 131 | WRONG INPUT! Cannot enter repeated edges, try again... 132 | 133 | ``` 134 | 135 | ``` bash 136 | Topological sorting for DIRECTED ACYCLIC GRAPH using DFS method 137 | Enter the number of vertices: 6 138 | Enter the number of edges: 6 139 | Enter 6 pairs of edges (source -> destination): 140 | 5 2 141 | 5 0 142 | 4 0 143 | 4 1 144 | 2 3 145 | 3 1 146 | Vertices: 0 1 2 3 4 5 147 | Edges: 148 | 5 -> 2 149 | 5 -> 0 150 | 4 -> 0 151 | 4 -> 1 152 | 2 -> 3 153 | 3 -> 1 154 | Topological Sorting: 5 4 2 3 1 0 155 | 156 | ``` 157 | -------------------------------------------------------------------------------- /DAA/mergeSort.md: -------------------------------------------------------------------------------- 1 | ## 1. Merge Sort 2 | 3 | ### Code 4 | 5 | ```c 6 | #include 7 | #include 8 | #include 9 | 10 | #define N 32000 11 | 12 | 13 | int merge(int arr[], int low, int mid, int high) { 14 | 15 | int count = 0; 16 | 17 | int left = low; 18 | int right = mid + 1; 19 | 20 | int temp[high - low + 1]; 21 | int k = 0; 22 | 23 | while (left <= mid && right <= high) { 24 | if (arr[left] <= arr[right]) { 25 | temp[k++] = arr[left++]; 26 | } else { 27 | temp[k++] = arr[right++]; 28 | } 29 | count++; 30 | } 31 | 32 | while (left <= mid) { 33 | temp[k++] = arr[left++]; 34 | count++; 35 | } 36 | 37 | while (right <= high) { 38 | temp[k++] = arr[right++]; 39 | count++; 40 | } 41 | 42 | for (int i = low; i <= high; i++) { 43 | arr[i] = temp[i - low]; 44 | } 45 | 46 | return count; 47 | } 48 | 49 | int MergeSort(int arr[], int low, int end) { 50 | int cnt = 0; 51 | if (low >= end) return 0; 52 | int mid = (low + end) / 2; 53 | cnt += MergeSort(arr, low, mid); 54 | cnt += MergeSort(arr, mid + 1, end); 55 | cnt += merge(arr, low, mid, end); 56 | return cnt; 57 | } 58 | 59 | int main() { 60 | int n, i, ch, a[N]; 61 | 62 | printf("Enter choice: 1.Correctness 2.Complexity - "); 63 | scanf("%d", &ch); 64 | 65 | switch(ch) { 66 | case 1: 67 | printf("Enter the size of array: "); 68 | scanf("%d", &n); 69 | printf("Enter %d array elements -\n", n); 70 | for (i = 0; i < n; i++) { 71 | scanf("%d", &a[i]); 72 | } 73 | MergeSort(a, 0, n - 1); 74 | printf("Sorted array is:\n"); 75 | for (i = 0; i < n; i++) { 76 | printf("%d ", a[i]); 77 | } 78 | printf("\n"); 79 | break; 80 | 81 | case 2: { 82 | int arr[32000], size, i, j, t1, t2, t3; 83 | float ln; 84 | printf("\nEnter size of array for complexity calculation of array of its next 5 multiples: "); 85 | scanf("%d", &size); 86 | printf("\nSize\tAscending\tcnlog(n)\tDescending\tcnlog(n)\tRandom\t\tcnlog(n)\n"); 87 | 88 | for (i = 1; i <= 5; i++, size *= 2) { 89 | ln = 2 * size * log(size) / log(2); 90 | for (j = 0; j < size; j++) { 91 | arr[j] = j; 92 | } 93 | t1 = MergeSort(arr, 0, size - 1); 94 | 95 | for (j = 0; j < size; j++) { 96 | arr[j] = size - j; 97 | } 98 | t2 = MergeSort(arr, 0, size - 1); 99 | 100 | for (j = 0; j < size; j++) { 101 | arr[j] = rand() % 32000; 102 | } 103 | t3 = MergeSort(arr, 0, size - 1); 104 | 105 | printf("%d\t%d\t\t%.0f\t\t%d\t\t%.0f\t\t%d\t\t%.0f\n", size, t1, ln, t2, ln, t3, ln); 106 | } 107 | printf("(Considering c as 2 here)\n"); 108 | break; 109 | } 110 | 111 | default: 112 | exit(0); 113 | } 114 | return 0; 115 | } 116 | 117 | ``` 118 | 119 | ### How to run ? 120 | 1. Save the file as mergeSort.c 121 | 2. run the command gcc mergeSort.c -lm 122 | 3. run ./a.out 123 | 4. Enter the input 124 | 125 | ### Output 126 | ```bash 127 | Enter choice: 1.Correctness 2.Complexity - Enter the size of array: Enter 6 array elements - 128 | Sorted array is: 129 | 3 9 27 38 43 82 130 | ``` 131 | 132 | ## Time complexity Analysis 133 | **Input:**: 2 16 134 | 135 | ```bash 136 | 137 | Enter choice: 1.Correctness 2.Complexity - Enter size of array for complexity calculation of array of its next 5 multiples: 138 | Size Ascending cnlog(n) Descending cnlog(n) Random cnlog(n) 139 | 16 64 128 64 128 64 128 140 | 32 160 320 160 320 160 320 141 | 64 384 768 384 768 384 768 142 | 128 896 1792 896 1792 896 1792 143 | 256 2048 4096 2048 4096 2048 4096 144 | (Considering c as 2 here) 145 | 146 | ``` 147 | -------------------------------------------------------------------------------- /IoT/DHT11.md: -------------------------------------------------------------------------------- 1 | # Measuring Temperature and Humidity of weather using the DHT11 Sensor with the raspberryPi 2 | 3 | ### Pre - work 4 | 5 | * create virtual environment in new folder 6 | ```bash 7 | python -m venv 8 | source /bin/activate 9 | ``` 10 | * within the virtual environment execute following commands: 11 | * ```pip install Adafruit-Blinka ``` (in order to use board) 12 | * ```pip install adafruit-circuitpython-dht``` (to use adafruit_dht) 13 | * create python file (eg dht11.py) within the virtual environment folder 14 | * open thonny, paste the below code in that python file and save 15 | * run the code on the terminal within the virtual environment using python3 dht11.py 16 | 17 | ### Code 18 | ``` python 19 | import time 20 | import board 21 | import adafruit_dht 22 | 23 | # Initialize the sensor 24 | sensor = adafruit_dht.DHT11(board.D4, use_pulseio=False) 25 | 26 | while True: 27 | try: 28 | temperature_c = sensor.temperature 29 | temperature_f = temperature_c * (9 / 5) + 32 30 | humidity = sensor.humidity 31 | 32 | print(f"Temp={temperature_c:0.1f}C, Temp={temperature_f:0.1f}F, Humidity={humidity:0.1f}%") 33 | 34 | except RuntimeError as error: 35 | print(f"Runtime error: {error.args[0]}") 36 | time.sleep(2.0) # Delay before retrying 37 | 38 | except Exception as error: 39 | print(f"Unhandled exception: {error}") 40 | sensor.exit() 41 | break # Exit the loop if there's a critical error 42 | 43 | time.sleep(1) 44 | 45 | ``` 46 | ### code with cloud 47 | 48 | ``` python 49 | import time 50 | import board 51 | import adafruit_dht 52 | import thingspeak 53 | from rpi_lcd import LCD 54 | 55 | # Define your ThingSpeak channel parameters 56 | channel_id = 2595470 57 | write_key = '86CNU3LZRKBSRJW9' 58 | # Initialize the ThingSpeak channel 59 | channel = thingspeak.Channel(id=channel_id, api_key=write_key) 60 | 61 | # Initialize the LCD 62 | lcd = LCD() 63 | 64 | # Initialize the sensor (DHT11 connected to GPIO 4) 65 | sensor = adafruit_dht.DHT11(board.D4, use_pulseio=False) 66 | 67 | 68 | while True: 69 | try: 70 | # Read the sensor data 71 | temperature_c = sensor.temperature 72 | temperature_f = temperature_c * (9 / 5) + 32 73 | humidity = sensor.humidity 74 | 75 | # Print the values to the serial port 76 | print("Temp={0:0.1f}C, Temp={1:0.1f}F, Humidity={2:0.1f}%".format(temperature_c, temperature_f, humidity)) 77 | 78 | # Display the values on the LCD 79 | lcd.text("Temp={0}C".format(temperature_c), 1) 80 | lcd.text("Humi={0}%".format(humidity), 2) 81 | 82 | # Send the data to ThingSpeak 83 | response = channel.update({'field1': temperature_c, 'field2': humidity}) 84 | print("Data sent to ThingSpeak. Response:", response) 85 | 86 | except RuntimeError as error: 87 | # Errors happen fairly often with DHT sensors, just keep going 88 | print(error.args[0]) 89 | time.sleep(2.0) 90 | continue 91 | except Exception as error: 92 | sensor.exit() 93 | raise error 94 | 95 | # Wait before taking the next reading 96 | time.sleep(15) 97 | 98 | 99 | 100 | ``` 101 | 102 | 103 | ### Methodology 104 | 105 | * Make the required connections and run the python file. 106 | -------------------------------------------------------------------------------- /IoT/GasSensor.md: -------------------------------------------------------------------------------- 1 | # Develope an USB powered gas detector with an LED display using arduino 2 | 3 | ### Code 4 | 5 | ``` c 6 | const int gasPin = A0; 7 | const int ledPin = 13; 8 | 9 | void setup() { 10 | pinMode(ledPin, OUTPUT); 11 | pinMode(gasPin,INPUT); 12 | Serial.begin(9600); 13 | } 14 | 15 | void loop() { 16 | 17 | int gasValue = analogRead(gasPin); 18 | float voltage = gasValue * (5.0 / 1023.0); 19 | 20 | Serial.print("Gas Value: "); 21 | Serial.print(gasValue); 22 | Serial.print("\tVoltage: "); 23 | Serial.println(voltage, 3); 24 | 25 | 26 | if (voltage > 1.5) { 27 | digitalWrite(ledPin, HIGH); 28 | Serial.print("led on\n"); 29 | } else { 30 | digitalWrite(ledPin, LOW); 31 | Serial.print("led off\n"); 32 | 33 | } 34 | 35 | delay(1000); 36 | } 37 | 38 | ``` 39 | -------------------------------------------------------------------------------- /IoT/HeartBeatSensor.md: -------------------------------------------------------------------------------- 1 | ## 2. Heart Beat Sensor 2 | 3 | ### Code 4 | 5 | ``` c 6 | #include 7 | 8 | // Create an instance of the PulseSensorPlayground class 9 | PulseSensorPlayground pulseSensor; 10 | 11 | const int pulsePin = A0; // Analog pin where the pulse sensor is connected 12 | 13 | void setup() { 14 | Serial.begin(9600); 15 | 16 | // Initialize the PulseSensorPlayground library 17 | pulseSensor.analogInput(pulsePin); 18 | pulseSensor.setThreshold(550); 19 | pulseSensor.begin(); 20 | } 21 | 22 | void loop() { 23 | // Read the value from the sensor 24 | int signal = pulseSensor.getBeatsPerMinute(); 25 | 26 | // Print the heart rate if it is valid 27 | if (signal > 0) { 28 | Serial.print("Heart Rate: "); 29 | Serial.print(signal); 30 | Serial.println(" bpm"); 31 | } else { 32 | Serial.println("No pulse detected."); 33 | } 34 | 35 | // Delay for 1 second 36 | delay(1000); 37 | } 38 | 39 | ``` 40 | 41 | ### method 42 | 43 | * Install PulseSensor Playground library from the library manager. 44 | 45 | ### Connections 46 | * Heart beat sensor has 3 pins, analog pin, ground and vcc, connect the analog pin to A0 47 | -------------------------------------------------------------------------------- /IoT/LCD.md: -------------------------------------------------------------------------------- 1 | # Interface Arduino Uno to show network utilisation, cpu and disk usage on LCD 2 | 3 | ``` c 4 | #include 5 | #include 6 | 7 | LiquidCrystal_I2C lcd(0x27, 16, 2); 8 | 9 | void setup() { 10 | lcd.init(); 11 | lcd.backlight(); 12 | lcd.setCursor(0, 0); 13 | lcd.print("System Monitor"); 14 | lcd.setCursor(0, 1); 15 | lcd.print("Initializing...."); 16 | delay(2000); 17 | } 18 | 19 | void loop() { 20 | float networkUtilization = getNetworkUtilization(); 21 | float cpuLoad = getCPULoad(); 22 | float diskSpace = getDiskSpace(); 23 | 24 | lcd.clear(); 25 | lcd.setCursor(0, 0); 26 | lcd.print("Network : "); 27 | lcd.print(networkUtilization); 28 | lcd.print("%"); 29 | 30 | lcd.setCursor(0, 1); 31 | lcd.print("CPU : "); 32 | lcd.print(cpuLoad); 33 | lcd.print("% Disk: "); 34 | lcd.print(diskSpace); 35 | lcd.print("GB"); 36 | 37 | delay(5000); 38 | } 39 | 40 | float getNetworkUtilization() { 41 | return 50.5; 42 | } 43 | 44 | float getCPULoad() { 45 | return 30.2; 46 | } 47 | 48 | float getDiskSpace() { 49 | return 25.7; 50 | } 51 | 52 | 53 | ``` 54 | 55 | 56 | ### Methodology 57 | 58 | * Install LiquidCrystall library from the library manager for using the above header . 59 | -------------------------------------------------------------------------------- /IoT/LDRwithRaspberryPi.md: -------------------------------------------------------------------------------- 1 | # Smart lighting application with LDR and buzzer 2 | 3 | ### Code 4 | 5 | ``` python 6 | 7 | import time 8 | import RPi.GPIO as GPIO 9 | import urllib.parse 10 | import http.client 11 | BUZZER_PIN = 33 12 | LDR_PIN = 3 13 | LED= 11 14 | 15 | 16 | key = "" # add thingspeak key here 17 | 18 | def setup_gpio(): 19 | GPIO.setmode(GPIO.BOARD) 20 | GPIO.setup(BUZZER_PIN, GPIO.OUT) 21 | GPIO.setup(LDR_PIN, GPIO.IN) 22 | GPIO.setup(LED,GPIO.OUT) 23 | 24 | def ldr(): 25 | while True: 26 | ldr_value = GPIO.input(LDR_PIN) 27 | 28 | if ldr_value == 1: 29 | print("High: Switch on buzzer") 30 | GPIO.output(BUZZER_PIN,True) 31 | print("led ON") 32 | GPIO.output(LED,True) 33 | else: 34 | print("Low: Don't switch on buzzer") 35 | GPIO.output(BUZZER_PIN, False) 36 | print("led OFF") 37 | GPIO.output(LED,False) 38 | 39 | time.sleep(0.3) 40 | 41 | LDRData = ldr_value 42 | BuzzerData = 1 if ldr_value == 1 else 0 43 | 44 | params = urllib.parse.urlencode({'field1': LDRData, 'field2': BuzzerData, 'key': key}) 45 | headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"} 46 | conn = http.client.HTTPConnection("api.thingspeak.com", 80) 47 | try: 48 | conn.request("POST", "/update", params, headers) 49 | response = conn.getresponse() 50 | print(LDRData) 51 | print(BuzzerData) 52 | print(response.status, response.reason) 53 | data = response.read() 54 | conn.close() 55 | except Exception as e: 56 | print("Connection failed:", e) 57 | 58 | if __name__ == "__main__": 59 | setup_gpio() # Initialize GPIO once 60 | try: 61 | ldr() # Start the LDR monitoring loop 62 | except KeyboardInterrupt: 63 | print("Program interrupted") 64 | finally: 65 | GPIO.cleanup() # Clean up GPIO settings 66 | 67 | ``` 68 | ### With thingspeak module 69 | ``` python 70 | import time 71 | import RPi.GPIO as GPIO 72 | import thingspeak 73 | 74 | BUZZER_PIN = 33 75 | LDR_PIN = 3 76 | LED = 11 77 | 78 | channel_id = "" # Add your ThingSpeak channel ID here 79 | write_key = "" # Add your ThingSpeak write API key here 80 | 81 | def setup_gpio(): 82 | GPIO.setmode(GPIO.BOARD) 83 | GPIO.setup(BUZZER_PIN, GPIO.OUT) 84 | GPIO.setup(LDR_PIN, GPIO.IN) 85 | GPIO.setup(LED, GPIO.OUT) 86 | 87 | def ldr(): 88 | channel = thingspeak.Channel(id=channel_id, api_key=write_key) 89 | while True: 90 | ldr_value = GPIO.input(LDR_PIN) 91 | 92 | if ldr_value == 1: 93 | print("High: Switch on buzzer") 94 | GPIO.output(BUZZER_PIN, True) 95 | print("LED ON") 96 | GPIO.output(LED, True) 97 | else: 98 | print("Low: Don't switch on buzzer") 99 | GPIO.output(BUZZER_PIN, False) 100 | print("LED OFF") 101 | GPIO.output(LED, False) 102 | 103 | time.sleep(0.3) 104 | 105 | LDRData = ldr_value 106 | BuzzerData = 1 if ldr_value == 1 else 0 107 | 108 | # Send data to ThingSpeak 109 | try: 110 | response = channel.update({'field1': LDRData, 'field2': BuzzerData}) 111 | print(f"LDRData: {LDRData}, BuzzerData: {BuzzerData}") 112 | print("ThingSpeak Response:", response) 113 | except Exception as e: 114 | print("Connection failed:", e) 115 | 116 | if __name__ == "__main__": 117 | setup_gpio() # Initialize GPIO once 118 | try: 119 | ldr() # Start the LDR monitoring loop 120 | except KeyboardInterrupt: 121 | print("Program interrupted") 122 | finally: 123 | GPIO.cleanup() # Clean up GPIO settings 124 | ``` 125 | ### Methodology 126 | * There are 3 components - LDR, LED and Buzzer. 127 | * Connect that to the pins of Raspberry Pi, open thingspeak - channel - take the id 128 | 129 | 130 | -------------------------------------------------------------------------------- /IoT/LEDblinking.md: -------------------------------------------------------------------------------- 1 | # Set up timer and delay for each of the LED lights using arduino 2 | 3 | ### Code 4 | 5 | ``` c 6 | const int led1 = 11; 7 | const int led2 = 12; 8 | const int led3 = 13; 9 | 10 | void setup() { 11 | pinMode(led1, OUTPUT); 12 | pinMode(led2, OUTPUT); 13 | pinMode(led3, OUTPUT); 14 | } 15 | 16 | void loop() { 17 | digitalWrite(led1, HIGH); 18 | delay(1000); 19 | digitalWrite(led1, LOW); 20 | digitalWrite(led2, HIGH); 21 | delay(2000); 22 | digitalWrite(led2, LOW); 23 | digitalWrite(led3, HIGH); 24 | delay(3000); 25 | digitalWrite(led3, LOW); 26 | } 27 | 28 | 29 | ``` 30 | -------------------------------------------------------------------------------- /IoT/PIR.md: -------------------------------------------------------------------------------- 1 | ## 5 Object Detection using PIR sensor and LED interfacing with RaspberryPi 2 | 3 | ### Code without cloud 4 | This is the one that is there for lab test 5 | 6 | ```python 7 | import time 8 | import RPi.GPIO as GPIO 9 | 10 | pir_pin = 12 11 | led = 11 12 | GPIO.setmode(GPIO.BOARD) 13 | GPIO.setup(pir_pin,GPIO.IN) 14 | GPIO.setup(led,GPIO.OUT) 15 | 16 | try: 17 | print("PIR sensor test (ctrl +c to exit ") 18 | time.sleep(2) 19 | print("Ready") 20 | 21 | while True: 22 | if GPIO.input(pir_pin): 23 | print("Motion detected") 24 | GPIO.output(led,GPIO.HIGH) 25 | time.sleep(2) 26 | GPIO.output(led,GPIO.LOW) 27 | time.sleep(1) 28 | except KeyboardInterrupt: 29 | print("Exit..") 30 | 31 | finally : 32 | GPIO.cleanup() 33 | ``` 34 | 35 | ### Code 36 | 37 | ``` python 38 | import http.client #uses classes for http client side 39 | import urllib.parse #parses URL string and uses http url scheme 40 | import time 41 | import RPi.GPIO as GPIO 42 | import time 43 | 44 | GPIO.setmode(GPIO.BOARD) 45 | GPIO.setup(7, GPIO.IN) 46 | GPIO.setup(18, GPIO.OUT) 47 | GPIO.setwarnings(False) 48 | key = "76I4VO9R18ABOURD" # Put your API Key here 49 | def PIR(): 50 | while True: 51 | if GPIO.input(7): #If there is a movement, PIR sensor gives input to GPIO 16 52 | GPIO.output(18, True) 53 | print("object detected") 54 | #Output given to Buzzer through GPIO 18 55 | time.sleep(5) #Buzzer turns on for 1 second 56 | else: 57 | GPIO.output(18, False) 58 | print("no detection") 59 | time.sleep(5) 60 | # time.sleep(0.1) 61 | Intrusion = (GPIO.input(7)) 62 | params = urllib.parse.urlencode({'field1':Intrusion, 'key':key }) 63 | headers = {"Content-typZZe": "application/x-www-form-urlencoded","Accept": "text/plain"} 64 | #create instances that connect to the HTTP server at the same host and port 65 | conn = http.client.HTTPConnection("api.thingspeak.com:80") 66 | try: 67 | conn.request("POST", "/update", params, headers) 68 | response = conn.getresponse() 69 | print(Intrusion) 70 | print(response.status, response.reason) 71 | data = response.read() 72 | conn.close() 73 | except: 74 | print("connection failed") 75 | break 76 | if __name__ == "__main__": 77 | while True: 78 | PIR() 79 | 80 | ``` 81 | 82 | ### methodolgy 83 | * Connect the two pins of LED and PIR to the pins of Raspberry Pi. 84 | -------------------------------------------------------------------------------- /IoT/WaterLevel.md: -------------------------------------------------------------------------------- 1 | ## 7. Water Level Sensor 2 | 3 | ### Code 4 | 5 | ``` python 6 | import RPi.GPIO as GPIO 7 | import smtplib 8 | from email.mime.text import MIMEText 9 | import time 10 | 11 | # Email settings 12 | EMAIL_ADDRESS = 'xyz@gmail.com' # Your email address 13 | EMAIL_PASSWORD = ' ' # Your email password 14 | TO_EMAIL = '' # Recipient's email address 15 | 16 | # Set up GPIO 17 | WPIN = 4 18 | BUZZERPIN=17 19 | GPIO.setmode(GPIO.BCM) 20 | GPIO.setup(WPIN, GPIO.IN) 21 | GPIO.setup(BUZZERPIN, GPIO.OUT) 22 | 23 | # Function to send email notification 24 | def send_email(): 25 | msg = MIMEText('Water sensor detected water!') 26 | msg['Subject'] = 'Alert:Water sensor is wet!' 27 | msg['From'] = EMAIL_ADDRESS 28 | msg['To'] = TO_EMAIL 29 | 30 | try: 31 | with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server: 32 | server.login(EMAIL_ADDRESS, EMAIL_PASSWORD) 33 | server.send_message(msg) 34 | print("Email sent successfully") 35 | except Exception as e: 36 | print(f"Failed to send email: {e}") 37 | 38 | # Main loop 39 | try: 40 | print("Water Sensor with email (CTRL+C to exit)") 41 | time.sleep(2) 42 | print("Ready") 43 | 44 | while True: 45 | if GPIO.input(WPIN): # If water is detected 46 | print("Water sensor is wet!") 47 | GPIO.output(BUZZERPIN,True) 48 | send_email() 49 | time.sleep(5) # Delay to avoid multiple detections 50 | GPIO.output(BUZZERPIN,False) 51 | 52 | except KeyboardInterrupt: 53 | print("Program terminated") 54 | finally: 55 | GPIO.cleanup() # Clean up GPIO on exit 56 | 57 | ``` 58 | 59 | ### methodolgy 60 | * The connections are asusual for any other sensor. 61 | * step1: create a gmail account 62 | * step2: click on profile pic, click manage account settings. 63 | * step3: go to security tab, and enable 2-step Verification (found under the heading "how you sign into google") 64 | * step4: Search for 'App Passwords' under Manage Accounts 65 | * step5: Under 'Your App Passwords" enter ```preferred_name``` for App name 66 | * step6: Copy the Generated App password 67 | * step7: run the code. 68 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | This repository contains the program list as well as programs for the 4th sem IoT lab and DAA lab 2 |
3 | Please follow the templateIot.md and templateDAA.md for the reference. 4 | 5 | 6 | ### Internet of Things 7 | 8 | | No. | Experiment Title | Description | 9 | |---| ----- | -------- | 10 | |1|Arduino LED Blinking|[description](./IoT/LEDblinking.md)| 11 | |2|Arduino Heartbeat|[description](./IoT/HeartBeatSensor.md)| 12 | |3|Arduino LCD Interfacing|[description](./IoT/LCD.md)| 13 | |4|Arduino Smoke Detector|[description](./IoT/GasSensor.md)| 14 | |5|Raspberry Pi - PIR sensor|[description](./IoT/PIR.md)| 15 | |6|Raspberry Pi DHT11 |[description](./IoT/DHT11.md)| 16 | |7|Raspberry Pi Water Level sensing|[description](./IoT/WaterLevel.md)| 17 | |8|Raspberry Pi LDR & Thingspeak|[description](./IoT/LDRwithRaspberryPi.md)| 18 | 19 | 20 | 21 | ### Design and Analysis of Algorithms 22 | 23 | | No. | Program Title | Code | 24 | |---| ----- | -------- | 25 | |1|Merge Sort|[code](./DAA/mergeSort.md)| 26 | |2|Topological Sort|[code](./DAA/TopoSort.md)| 27 | |3|Presorting|[code](./DAA/PreSort.md)| 28 | |4|Horspool String Matching|[code](./DAA/HorspoolAlgo.md)| 29 | |5|0/1 Knapsack using DP|[code](./DAA/KnapSack.md)| 30 | |6|Dijkstra's Algorithm|[code](./DAA/Djikstra.md)| 31 | |7|Sum of Subset|[code](./DAA/SubSetProblem.md)| 32 | |8|N Queens|[code](./DAA/NQueens.md)| 33 | |9|Heap Sort|[code](./DAA/HeapSort.md)| 34 | |10|Floyd Algorithm|[code](./DAA/Floyds.md)| 35 | |11|Connectivity of graph by BFS|[code](./DAA/ConnectivityByBFS.md)| 36 | |12|Quick Sort|[code](./DAA/QuickSort.md)| 37 | |13|Prims Algorithm - MST|[code](./DAA/PrimsAlgo.md)| 38 | 39 | 40 | ### Note 41 | The code in this repository has been compiled and tested once. While it has shown expected results during initial testing, I cannot guarantee that it will work perfectly in all cases. Please feel free to review and test it further. 42 | -------------------------------------------------------------------------------- /backend.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "provenance": [], 7 | "authorship_tag": "ABX9TyMdgBvMzN+xOWYArmccgB1q", 8 | "include_colab_link": true 9 | }, 10 | "kernelspec": { 11 | "name": "python3", 12 | "display_name": "Python 3" 13 | }, 14 | "language_info": { 15 | "name": "python" 16 | } 17 | }, 18 | "cells": [ 19 | { 20 | "cell_type": "markdown", 21 | "metadata": { 22 | "id": "view-in-github", 23 | "colab_type": "text" 24 | }, 25 | "source": [ 26 | "\"Open" 27 | ] 28 | }, 29 | { 30 | "cell_type": "code", 31 | "execution_count": null, 32 | "metadata": { 33 | "id": "OA4yvB8tXkXy" 34 | }, 35 | "outputs": [], 36 | "source": [ 37 | "%%capture\n", 38 | "!pip -q install --upgrade folium\n", 39 | "!apt install libspatialindex-dev\n", 40 | "!pip -q install rtree\n", 41 | "!pip -q install geopandas\n", 42 | "!pip -q install geojson\n", 43 | "!pip -q install geemap==0.17.3\n", 44 | "!pip -q uninstall tornado -y\n", 45 | "!yes | pip install tornado==5.1.0\n", 46 | "!pip -q install rasterio\n", 47 | "!pip -q install tqdm\n", 48 | "!pip -q install eeconvert\n", 49 | "!pip install fastapi uvicorn pyngrok pydantic" 50 | ] 51 | }, 52 | { 53 | "cell_type": "code", 54 | "source": [ 55 | "# Standard imports\n", 56 | "import os\n", 57 | "from tqdm.notebook import tqdm\n", 58 | "import requests\n", 59 | "import json\n", 60 | "\n", 61 | "import pandas as pd\n", 62 | "import numpy as np\n", 63 | "from PIL import Image\n", 64 | "\n", 65 | "# Geospatial processing packages\n", 66 | "import geopandas as gpd\n", 67 | "import geojson\n", 68 | "\n", 69 | "import shapely\n", 70 | "import rasterio as rio\n", 71 | "from rasterio.plot import show\n", 72 | "import rasterio.mask\n", 73 | "from shapely.geometry import box\n", 74 | "from fastapi.middleware.cors import CORSMiddleware\n", 75 | "\n", 76 | "# Mapping and plotting libraries\n", 77 | "import matplotlib.pyplot as plt\n", 78 | "import matplotlib.colors as cl\n", 79 | "import ee\n", 80 | "import eeconvert as eec\n", 81 | "import geemap\n", 82 | "import geemap.eefolium as emap\n", 83 | "import folium\n", 84 | "\n", 85 | "# Deep learning libraries\n", 86 | "import torch\n", 87 | "from torchvision import datasets, models, transforms\n", 88 | "\n", 89 | "from fastapi import FastAPI, HTTPException\n", 90 | "from pydantic import BaseModel\n", 91 | "from pyngrok import ngrok\n", 92 | "import nest_asyncio\n", 93 | "import uvicorn\n", 94 | "from typing import List, Dict\n", 95 | "from pydantic import BaseModel\n", 96 | "import time\n", 97 | "import asyncio\n", 98 | "import logging\n", 99 | "from collections import Counter\n", 100 | "import uuid" 101 | ], 102 | "metadata": { 103 | "id": "bJzb-nJwYU4a" 104 | }, 105 | "execution_count": null, 106 | "outputs": [] 107 | }, 108 | { 109 | "cell_type": "code", 110 | "source": [ 111 | "from google.colab import drive\n", 112 | "drive.mount('/content/drive')" 113 | ], 114 | "metadata": { 115 | "id": "WR9OsHh5YtRS", 116 | "colab": { 117 | "base_uri": "https://localhost:8080/" 118 | }, 119 | "outputId": "90f02725-b81a-4d7a-b3b6-66e1da45c64d" 120 | }, 121 | "execution_count": null, 122 | "outputs": [ 123 | { 124 | "output_type": "stream", 125 | "name": "stdout", 126 | "text": [ 127 | "Mounted at /content/drive\n" 128 | ] 129 | } 130 | ] 131 | }, 132 | { 133 | "cell_type": "code", 134 | "source": [ 135 | "ee.Authenticate()\n", 136 | "ee.Initialize(project=\"lulc-sde-el\")" 137 | ], 138 | "metadata": { 139 | "id": "xXB3_I3mY0U9" 140 | }, 141 | "execution_count": null, 142 | "outputs": [] 143 | }, 144 | { 145 | "cell_type": "code", 146 | "source": [ 147 | "app = FastAPI()\n", 148 | "app.add_middleware(\n", 149 | " CORSMiddleware,\n", 150 | " allow_origins=[\"*\"],\n", 151 | " allow_credentials=True,\n", 152 | " allow_methods=[\"*\"],\n", 153 | " allow_headers=[\"*\"],\n", 154 | ")" 155 | ], 156 | "metadata": { 157 | "id": "iBtI7nclY3l7" 158 | }, 159 | "execution_count": null, 160 | "outputs": [] 161 | }, 162 | { 163 | "cell_type": "code", 164 | "source": [ 165 | "class CoordinatePoint(BaseModel):\n", 166 | " lat: float\n", 167 | " lng: float\n", 168 | "\n", 169 | "class InputData(BaseModel):\n", 170 | " data: List[CoordinatePoint]\n", 171 | " shape_name: str\n" 172 | ], 173 | "metadata": { 174 | "id": "RHXaJ2JoY7CR" 175 | }, 176 | "execution_count": null, 177 | "outputs": [] 178 | }, 179 | { 180 | "cell_type": "code", 181 | "source": [ 182 | "logging.basicConfig(\n", 183 | " format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n", 184 | " level=logging.DEBUG\n", 185 | ")\n", 186 | "logger = logging.getLogger(__name__)" 187 | ], 188 | "metadata": { 189 | "id": "M38qHTpyxUxZ" 190 | }, 191 | "execution_count": null, 192 | "outputs": [] 193 | }, 194 | { 195 | "cell_type": "code", 196 | "source": [ 197 | "classes = [\n", 198 | " 'AnnualCrop',\n", 199 | " 'Forest',\n", 200 | " 'HerbaceousVegetation',\n", 201 | " 'Highway',\n", 202 | " 'Industrial',\n", 203 | " 'Pasture',\n", 204 | " 'PermanentCrop',\n", 205 | " 'Residential',\n", 206 | " 'River',\n", 207 | " 'SeaLake'\n", 208 | "]\n", 209 | "\n", 210 | "# Colors for visualization\n", 211 | "colors = {\n", 212 | " 'AnnualCrop': 'lightgreen',\n", 213 | " 'Forest': 'forestgreen',\n", 214 | " 'HerbaceousVegetation': 'yellowgreen',\n", 215 | " 'Highway': 'gray',\n", 216 | " 'Industrial': 'red',\n", 217 | " 'Pasture': 'mediumseagreen',\n", 218 | " 'PermanentCrop': 'chartreuse',\n", 219 | " 'Residential': 'magenta',\n", 220 | " 'River': 'dodgerblue',\n", 221 | " 'SeaLake': 'blue'\n", 222 | "}" 223 | ], 224 | "metadata": { 225 | "id": "Lt68WHCpv-d4" 226 | }, 227 | "execution_count": null, 228 | "outputs": [] 229 | }, 230 | { 231 | "cell_type": "code", 232 | "source": [ 233 | "device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n", 234 | "\n", 235 | "# Model transformation\n", 236 | "imagenet_mean, imagenet_std = [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]\n", 237 | "transform = transforms.Compose([\n", 238 | " transforms.Resize(224),\n", 239 | " transforms.CenterCrop(224),\n", 240 | " transforms.ToTensor(),\n", 241 | " transforms.Normalize(imagenet_mean, imagenet_std)\n", 242 | "])" 243 | ], 244 | "metadata": { 245 | "id": "vYewe6zouxHZ" 246 | }, 247 | "execution_count": null, 248 | "outputs": [] 249 | }, 250 | { 251 | "cell_type": "code", 252 | "source": [ 253 | "MODEL_PATH = './drive/My Drive/Colab Notebooks/models/best_model.pth'\n", 254 | "\n", 255 | "def load_model(model_path: str):\n", 256 | " logger.info(f\"Loading model from {model_path}\")\n", 257 | " model = models.resnet50(pretrained=True)\n", 258 | " num_ftrs = model.fc.in_features\n", 259 | " model.fc = torch.nn.Linear(num_ftrs, len(classes))\n", 260 | " model.load_state_dict(torch.load(model_path, map_location=device))\n", 261 | " model.eval().to(device)\n", 262 | " logger.info(\"Model loaded and set to eval mode\")\n", 263 | " return model\n", 264 | "\n", 265 | "model = load_model(MODEL_PATH)" 266 | ], 267 | "metadata": { 268 | "id": "XIHYrqQCxSIs" 269 | }, 270 | "execution_count": null, 271 | "outputs": [] 272 | }, 273 | { 274 | "cell_type": "code", 275 | "source": [ 276 | "def generate_image(region, product='COPERNICUS/S2',\n", 277 | " min_date='2019-01-01', max_date='2020-01-01',\n", 278 | " range_min=0, range_max=2000, cloud_pct=10):\n", 279 | " logger.debug(\"Starting image generation\")\n", 280 | " image = ee.ImageCollection(product)\n", 281 | " image = image.filterBounds(region)\n", 282 | " logger.debug(f\"Filtered bounds with region: {region.getInfo()['coordinates']}\")\n", 283 | " image = image.filterDate(min_date, max_date)\n", 284 | " image = image.filter(ee.Filter.lt(\"CLOUDY_PIXEL_PERCENTAGE\", cloud_pct))\n", 285 | " logger.debug(f\"Filtered images between {min_date} and {max_date} with <{cloud_pct}% clouds\")\n", 286 | " image = image.median()\n", 287 | " image = image.visualize(bands=['B4', 'B3', 'B2'], min=range_min, max=range_max)\n", 288 | " logger.debug(\"RGB visualization applied to image\")\n", 289 | " clipped = image.clip(region)\n", 290 | " logger.debug(\"Image clipped to region\")\n", 291 | " return clipped\n", 292 | "\n", 293 | "# Export to Drive with poll\n", 294 | "def export_image(image, filename, region, folder):\n", 295 | " logger.info(f\"Exporting image {filename} to Drive folder {folder}\")\n", 296 | " task = ee.batch.Export.image.toDrive(\n", 297 | " image=image,\n", 298 | " driveFolder=folder,\n", 299 | " description=filename,\n", 300 | " fileNamePrefix=filename,\n", 301 | " scale=10,\n", 302 | " region=region.geometry(),\n", 303 | " fileFormat='GeoTIFF',\n", 304 | " crs='EPSG:4326',\n", 305 | " maxPixels=9e6\n", 306 | " )\n", 307 | " task.start()\n", 308 | " while True:\n", 309 | " status = task.status()['state']\n", 310 | " logger.debug(f\"Image export task status: {status}\")\n", 311 | " if status == 'COMPLETED':\n", 312 | " logger.info(\"Image export completed\")\n", 313 | " break\n", 314 | " if status in ('FAILED', 'CANCELLED'):\n", 315 | " logger.error(f\"Image export failed: {task.status()}\")\n", 316 | " raise RuntimeError(f\"Export task ended with status {status}\")\n", 317 | " time.sleep(5)\n", 318 | " return task\n", 319 | "\n", 320 | "# Generate tiles\n", 321 | "def generate_tiles(image_file, output_file, area_str, size=64):\n", 322 | " logger.info(f\"Generating {size}x{size} tiles for {image_file}\")\n", 323 | " raster = rio.open(image_file)\n", 324 | " width, height = raster.shape\n", 325 | " geo_dict = {'id': [], 'geometry': []}\n", 326 | " idx = 0\n", 327 | " for w in range(0, width, size):\n", 328 | " for h in range(0, height, size):\n", 329 | " window = rio.windows.Window(h, w, size, size)\n", 330 | " bbox = rio.windows.bounds(window, raster.transform)\n", 331 | " geom = box(*bbox)\n", 332 | " uid = f\"{area_str.lower().replace(' ', '_')}-{idx}\"\n", 333 | " geo_dict['id'].append(uid)\n", 334 | " geo_dict['geometry'].append(geom)\n", 335 | " idx += 1\n", 336 | " tiles = gpd.GeoDataFrame(geo_dict, crs='EPSG:4326')\n", 337 | " tiles.to_file(output_file, driver=\"GeoJSON\")\n", 338 | " raster.close()\n", 339 | " logger.info(f\"Saved {len(tiles)} tiles to {output_file}\")\n", 340 | " return tiles\n", 341 | "\n", 342 | "# Predict crop on one tile\n", 343 | "def predict_crop(image_path, shapes, classes, model):\n", 344 | " try:\n", 345 | " with rio.open(image_path) as src:\n", 346 | " out_image, out_transform = rio.mask.mask(src, shapes, crop=True)\n", 347 | " logger.debug(\"Cropped image for prediction\")\n", 348 | " # Remove zero border\n", 349 | " _, xnz, ynz = np.nonzero(out_image)\n", 350 | " cropped = out_image[:, xnz.min():xnz.max(), ynz.min():ynz.max()]\n", 351 | " # Save to temp file\n", 352 | " temp_file = f\"temp_{uuid.uuid4().hex}.tif\"\n", 353 | " meta = src.meta.copy()\n", 354 | " meta.update({\"height\": cropped.shape[1],\n", 355 | " \"width\": cropped.shape[2],\n", 356 | " \"transform\": out_transform})\n", 357 | " with rio.open(temp_file, 'w', **meta) as dest:\n", 358 | " dest.write(cropped)\n", 359 | " logger.debug(f\"Written temp file {temp_file}\")\n", 360 | " img = Image.open(temp_file)\n", 361 | " inp = transform(img).unsqueeze(0).to(device)\n", 362 | " out = model(inp)\n", 363 | " _, pred = torch.max(out, 1)\n", 364 | " label = classes[pred.item()]\n", 365 | " os.remove(temp_file)\n", 366 | " logger.debug(f\"Prediction: {label}\")\n", 367 | " return label\n", 368 | " except Exception as e:\n", 369 | " logger.error(f\"predict_crop error: {e}\")\n", 370 | " raise\n", 371 | "\n", 372 | "@app.post(\"/predict\")\n", 373 | "def predict(input_data: InputData):\n", 374 | " try:\n", 375 | " coords = [[p.lng, p.lat] for p in input_data.data]\n", 376 | " polygon = ee.Geometry.Polygon([coords])\n", 377 | " region = ee.FeatureCollection([ee.Feature(polygon)])\n", 378 | " shape_name = input_data.shape_name\n", 379 | " output_dir = \"/content/drive/My Drive/google_pic\"\n", 380 | " os.makedirs(output_dir, exist_ok=True)\n", 381 | "\n", 382 | " # Image generation and export\n", 383 | " image = generate_image(region)\n", 384 | " export_image(image, shape_name, region, 'google_pic')\n", 385 | " tif_path = os.path.join(output_dir, f\"{shape_name}.tif\")\n", 386 | "\n", 387 | " # Boundary via getInfo\n", 388 | " boundary_geo = polygon.getInfo()['coordinates']\n", 389 | " boundary_file = os.path.join(output_dir, f\"{shape_name}_boundary.geojson\")\n", 390 | " with open(boundary_file, 'w') as bf:\n", 391 | " json.dump({'type':'Polygon','coordinates': boundary_geo}, bf)\n", 392 | " boundary = gpd.read_file(boundary_file)\n", 393 | " logger.info(\"Boundary GeoJSON loaded\")\n", 394 | "\n", 395 | " # Tiles\n", 396 | " tiles_file = os.path.join(output_dir, f\"{shape_name}.geojson\")\n", 397 | " tiles = generate_tiles(tif_path, tiles_file, shape_name)\n", 398 | " tiles = gpd.sjoin(tiles, boundary, predicate='within')\n", 399 | " logger.info(f\"Filtered tiles count: {len(tiles)}\")\n", 400 | "\n", 401 | " # Predictions\n", 402 | " labels = []\n", 403 | " for _idx in tqdm(range(len(tiles)), desc=\"Predicting tiles\"):\n", 404 | " labels.append(predict_crop(tif_path, [tiles.geometry.iloc[_idx]], classes, model))\n", 405 | " tiles['pred'] = labels\n", 406 | "\n", 407 | " # Compute distribution\n", 408 | " tile_counts = Counter(labels)\n", 409 | " total = len(labels)\n", 410 | " class_pct = {cls: (tile_counts.get(cls,0)/total)*100 for cls in classes}\n", 411 | " logger.info(f\"Class percentages: {class_pct}\")\n", 412 | "\n", 413 | " # Save preds\n", 414 | " preds_file = os.path.join(output_dir, f\"{shape_name}_preds.geojson\")\n", 415 | " tiles.to_file(preds_file, driver=\"GeoJSON\")\n", 416 | "\n", 417 | " # Return payload\n", 418 | " return {\n", 419 | " \"status\": \"success\",\n", 420 | " \"shape_name\": shape_name,\n", 421 | " \"class_distribution\": {cls: {\"count\": tile_counts.get(cls,0), \"percent\": class_pct[cls]} for cls in classes},\n", 422 | " \"predictions_file\": preds_file\n", 423 | " }\n", 424 | " except Exception as e:\n", 425 | " logger.exception(\"Error in /predict\")\n", 426 | " raise HTTPException(status_code=500, detail=str(e))\n", 427 | "\n", 428 | "@app.on_event(\"startup\")\n", 429 | "async def startup_event():\n", 430 | " # Setup ngrok\n", 431 | " # Note: You'll need an ngrok authtoken for this to work\n", 432 | " import nest_asyncio\n", 433 | " ngrok.set_auth_token(\"\")\n", 434 | "\n", 435 | " public_url = ngrok.connect(8000)\n", 436 | " print(\"FastAPI running on:\", public_url)" 437 | ], 438 | "metadata": { 439 | "id": "vKl-DwncZZ2e", 440 | "colab": { 441 | "base_uri": "https://localhost:8080/" 442 | }, 443 | "outputId": "024706db-da4d-4a19-f05c-670f4ef0e02d" 444 | }, 445 | "execution_count": null, 446 | "outputs": [ 447 | { 448 | "output_type": "stream", 449 | "name": "stderr", 450 | "text": [ 451 | ":153: DeprecationWarning: \n", 452 | " on_event is deprecated, use lifespan event handlers instead.\n", 453 | "\n", 454 | " Read more about it in the\n", 455 | " [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/).\n", 456 | " \n", 457 | " @app.on_event(\"startup\")\n" 458 | ] 459 | } 460 | ] 461 | }, 462 | { 463 | "cell_type": "markdown", 464 | "source": [], 465 | "metadata": { 466 | "id": "1VtEYnFW8Wy_" 467 | } 468 | }, 469 | { 470 | "cell_type": "code", 471 | "source": [ 472 | "nest_asyncio.apply()\n", 473 | "uvicorn.run(app, host=\"0.0.0.0\", port=8000)" 474 | ], 475 | "metadata": { 476 | "id": "cslpX-WkZaxP", 477 | "colab": { 478 | "base_uri": "https://localhost:8080/", 479 | "height": 925 480 | }, 481 | "outputId": "146b87bc-33f5-45bf-96e3-211d3f30a4ea" 482 | }, 483 | "execution_count": null, 484 | "outputs": [ 485 | { 486 | "output_type": "stream", 487 | "name": "stderr", 488 | "text": [ 489 | "INFO: Started server process [313]\n", 490 | "INFO: Waiting for application startup.\n", 491 | "WARNING:pyngrok.process.ngrok:t=2025-05-12T18:39:19+0000 lvl=warn msg=\"failed to start tunnel\" pg=/api/tunnels id=21fc948171fc02d1 err=\"failed to start tunnel: Your account may not run more than 3 tunnels over a single ngrok agent session.\\nThe tunnels already running on this session are:\\ntn_2x0Vj5Noy5A5oV6e1r1H3M8hNAB, tn_2x0Vj2QJyuCP1NZhev5rj4uCRYl, tn_2x0Vj5Lfk8HQmcRDU69H21hNDQf\\n\\r\\n\\r\\nERR_NGROK_324\\r\\n\"\n", 492 | "ERROR: Traceback (most recent call last):\n", 493 | " File \"/usr/local/lib/python3.11/dist-packages/pyngrok/ngrok.py\", line 622, in api_request\n", 494 | " response = urlopen(request, encoded_data, timeout)\n", 495 | " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", 496 | " File \"/usr/lib/python3.11/urllib/request.py\", line 216, in urlopen\n", 497 | " return opener.open(url, data, timeout)\n", 498 | " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", 499 | " File \"/usr/lib/python3.11/urllib/request.py\", line 525, in open\n", 500 | " response = meth(req, response)\n", 501 | " ^^^^^^^^^^^^^^^^^^^\n", 502 | " File \"/usr/lib/python3.11/urllib/request.py\", line 634, in http_response\n", 503 | " response = self.parent.error(\n", 504 | " ^^^^^^^^^^^^^^^^^^\n", 505 | " File \"/usr/lib/python3.11/urllib/request.py\", line 563, in error\n", 506 | " return self._call_chain(*args)\n", 507 | " ^^^^^^^^^^^^^^^^^^^^^^^\n", 508 | " File \"/usr/lib/python3.11/urllib/request.py\", line 496, in _call_chain\n", 509 | " result = func(*args)\n", 510 | " ^^^^^^^^^^^\n", 511 | " File \"/usr/lib/python3.11/urllib/request.py\", line 643, in http_error_default\n", 512 | " raise HTTPError(req.full_url, code, msg, hdrs, fp)\n", 513 | "urllib.error.HTTPError: HTTP Error 502: Bad Gateway\n", 514 | "\n", 515 | "During handling of the above exception, another exception occurred:\n", 516 | "\n", 517 | "Traceback (most recent call last):\n", 518 | " File \"/usr/local/lib/python3.11/dist-packages/starlette/routing.py\", line 692, in lifespan\n", 519 | " async with self.lifespan_context(app) as maybe_state:\n", 520 | " File \"/usr/local/lib/python3.11/dist-packages/starlette/routing.py\", line 569, in __aenter__\n", 521 | " await self._router.startup()\n", 522 | " File \"/usr/local/lib/python3.11/dist-packages/starlette/routing.py\", line 669, in startup\n", 523 | " await handler()\n", 524 | " File \"\", line 341, in startup_event\n", 525 | " public_url = ngrok.connect(8000)\n", 526 | " ^^^^^^^^^^^^^^^^^^^\n", 527 | " File \"/usr/local/lib/python3.11/dist-packages/pyngrok/ngrok.py\", line 389, in connect\n", 528 | " tunnel = NgrokTunnel(api_request(f\"{api_url}/api/tunnels\", method=\"POST\", data=options,\n", 529 | " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", 530 | " File \"/usr/local/lib/python3.11/dist-packages/pyngrok/ngrok.py\", line 643, in api_request\n", 531 | " raise PyngrokNgrokHTTPError(f\"ngrok client exception, API returned {status_code}: {response_data}\",\n", 532 | "pyngrok.exception.PyngrokNgrokHTTPError: ngrok client exception, API returned 502: {\"error_code\":103,\"status_code\":502,\"msg\":\"failed to start tunnel\",\"details\":{\"err\":\"failed to start tunnel: Your account may not run more than 3 tunnels over a single ngrok agent session.\\nThe tunnels already running on this session are:\\ntn_2x0Vj5Noy5A5oV6e1r1H3M8hNAB, tn_2x0Vj2QJyuCP1NZhev5rj4uCRYl, tn_2x0Vj5Lfk8HQmcRDU69H21hNDQf\\n\\r\\n\\r\\nERR_NGROK_324\\r\\n\"}}\n", 533 | "\n", 534 | "\n", 535 | "ERROR: Application startup failed. Exiting.\n" 536 | ] 537 | }, 538 | { 539 | "output_type": "error", 540 | "ename": "SystemExit", 541 | "evalue": "3", 542 | "traceback": [ 543 | "An exception has occurred, use %tb to see the full traceback.\n", 544 | "\u001b[0;31mSystemExit\u001b[0m\u001b[0;31m:\u001b[0m 3\n" 545 | ] 546 | } 547 | ] 548 | } 549 | ] 550 | } --------------------------------------------------------------------------------