Implementing the Simplex Method in C

Overview The Simplex method is an algorithm for solving linear programming problems. This program takes the number of equations and variables as input, along with their coefficients, and then performs the Simplex method to find the optimal solution. Step 1: Include the Standard I/O Library The program begins by including the standard input-output library for handling input and output functions. #include <stdio.h> Step 2: Main Function The main function is where the program execution starts. It declares variables, collects inputs, and performs the Simplex algorithm. ...

July 4, 2024 · 7 min · Yogesh Sharma Neupane

Reservoir Optimization

Imports and Constants The script starts by importing the necessary libraries: numpy and pandas. It then defines the following constants: gamma: Acceleration due to gravity (9.81 m/s²) effi: Efficiency of the hydropower plant (0.9) env_flow: Environmental flow in m³/month Loading Data The script then loads data from a CSV file named “inflow_data1.csv”. The data includes: inflow_data: Inflow to the reservoir in m³/s pet_data: Potential evapotranspiration in mm/day dt_data: Demand or release from the reservoir in m³/s Important Information The script also defines several important parameters related to the reservoir: ...

July 4, 2024 · 4 min · Yogesh Sharma Neupane

Hydraulic Simulation using Manning Equation

The program begins by importing the necessary libraries, NumPy and Matplotlib, which will be used for numerical computations and data visualization, respectively. Next, we define the constants for this problem: B: the width of the channel in meters n: Manning’s roughness coefficient, which is a measure of the channel’s resistance to flow S: the slope of the energy grade line, which represents the energy loss per unit length of the channel The calculate_parameters function is the core of this program. It takes an array of water depths as input and calculates the following hydraulic parameters: ...

June 19, 2024 · 5 min · Yogesh Sharma Neupane

Numpy Basics

The following program is sourced from Bao Nguyen Installing NumPy Before using NumPy, ensure it is installed on your system. Run the following command in the terminal or command prompt: pip install numPy Importing NumPy First, import the NumPy library. This allows us to use its functionality in your code. import numpy as np Basics of NumPy Arrays Creating an Array a = np.array([1, 2, 3]) print(f"Array = {a}") np.array([1, 2, 3]): Creates a one-dimensional NumPy array with elements 1, 2, and 3. print(f"Array = {a}"): Prints the array. Array Attributes ...

June 19, 2024 · 7 min · Yogesh Sharma Neupane

Matrix Input and Display Program

Matrix Input and Display Program This program takes the number of rows and columns from the user, then accepts matrix elements row-wise, and finally prints the matrix in a formatted way. 1. Input the Number of Rows and Columns R = int(input("Enter number of rows: ")) C = int(input("Enter number of columns: ")) int(input("Enter number of rows: ")): Prompts the user to enter the number of rows for the matrix and converts the input to an integer. int(input("Enter number of columns: ")): Prompts the user to enter the number of columns for the matrix and converts the input to an integer. 2. Initialize the Matrix matrix = [] matrix = []: Initializes an empty list to hold the rows of the matrix. This will be a list of lists, where each sublist represents a row in the matrix. 3. Input Matrix Elements Row-wise print("Enter the entries row-wise:\n") for i in range(R): a = [] for j in range(C): a.append(int(input())) matrix.append(a) print("Enter the entries row-wise:\n"): Prints a message indicating that the user should enter the matrix elements row-wise. for i in range(R):: Iterates over the range of rows (from 0 to R-1). a = []: Initializes an empty list to hold the elements of the current row. for j in range(C):: Iterates over the range of columns (from 0 to C-1). a.append(int(input())): Prompts the user to input an integer and appends it to the current row list a. matrix.append(a): Appends the completed row a to the matrix. 4. Print the Matrix for i in range(R): for j in range(C): print(matrix[i][j], end="\t") print() for i in range(R):: Iterates over the range of rows. for j in range(C):: Iterates over the range of columns within each row. print(matrix[i][j], end="\t"): Prints the element at position [i][j] in the matrix, followed by a tab space instead of a new line. This ensures elements in the same row are printed on the same line, separated by tabs. print(): Prints a new line after each row to move to the next line for the subsequent row. Explanation of Python Rules Used Input Function (input()): Used to take input from the user. It reads a line from input, converts it to a string, and returns it. Type Conversion (int()): Converts a string input to an integer. Lists: Python lists are used to store multiple items in a single variable. In this program, a list of lists is used to represent the matrix. For Loop: Used to iterate over a sequence (in this case, the range of rows and columns). Append Method (append()): Used to add an item to the end of a list. Print Function (print()): Used to output data to the console. The end parameter in print() specifies what to print at the end of the output (default is a newline character). Example Usage If the user enters 3 for rows and 3 for columns, the program will prompt for 9 integers to fill the matrix. The matrix might look like this: Enter number of rows: 3 Enter number of columns: 3 Enter the entries row-wise: 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 Additional Explanation: Indentation Rules in Python Indentation in Python is crucial for defining the structure and flow of the program. Unlike some other programming languages that use braces {} to define code blocks, Python uses indentation to signify a block of code. Here are the key rules regarding indentation: ...

June 18, 2024 · 14 min · Yogesh Sharma Neupane

BigM Method, Python Program

This is done as per the assignment of System Mathematics in First Semester of Hydropower Engineering by Yogesh Sharma Neupane and Submitted to Prof Dr. Bhola Nath Ghimire. Linear Programming ~~ Simplex Method This Python script solves linear programming problems using the Simplex Method. The code handles both maximization and minimization problems and includes error handling to ensure valid user input. Step 1: Import Libraries and Define Helper Functions Import Libraries import numpy as np # For defining arrays and performing numerical operations np.set_printoptions(precision=2, floatmode="fixed") # For printing only two decimal places numpy: This library is used to handle array operations efficiently. set_printoptions: Configures the display of numpy arrays to show only two decimal places. Define wrong_input Function def wrong_input(): # Print an error message for invalid input print("Error!!! Invalid Input. Please input the valid data: ") wrong_input: This function prints an error message when the user provides invalid input. Define find_zj Function def find_zj(): # Calculate Zj value which is the sum of the product of basic values and corresponding xi for j in range(total_col): sum = 0 for i in range(m): sum = sum + basic_vars[i] * table[i][j] zj[j] = sum if j < col_index: zj_cj[j] = sum - cj[j] find_zj: This function calculates the Zj values, representing the objective function coefficients for the current solution. Step 2: Define Functions to Find Pivot Column and Row Define find_pivot_col Function def find_pivot_col(): # Finds the entering variable (pivot column) for the next iteration if opt_type == 'M': smallest = np.min(zj_cj) if smallest >= 0: return None else: largest = np.max(zj_cj) if largest <= 0: return None pc = np.argmin(zj_cj) if opt_type == 'M' else np.argmax(zj_cj) return pc find_pivot_col: This function identifies the pivot column, which determines the entering variable for the next iteration. Define find_pivot_row Function def find_pivot_row(): # Finds the leaving variable (pivot row) for the next iteration min_ratio = float('inf') pivot_row = None for i in range(m): if table[i][pc] > 0 and table[i][col_index] > 0: ratio = table[i][col_index] / table[i][pc] if ratio < min_ratio: min_ratio = ratio pivot_row = i if min_ratio == float('inf'): return None basic_vars[pivot_row] = cj[pc] # Update basic_vars with the leaving variable's coefficient print("Basic vars\n", basic_vars) return pivot_row find_pivot_row: This function identifies the pivot row, which determines the leaving variable for the next iteration. Step 3: Update Rows Based on Pivot Element def new_rows(): # Updates the table by performing row operations to find the new pivot row pivot_element = table[pr][pc] for j in range(total_col): table[pr][j] = table[pr][j] / pivot_element # To find other rows except pivot row for i in range(m): if i != pr: pivot_coeff = table[i][pc] for j in range(total_col): table[i][j] -= pivot_coeff * table[pr][j] new_rows: This function updates the table by performing row operations to ensure all rows (except the pivot row) are adjusted correctly. Step 4: Print Final Output def final_output(): # Prints the final solution and the optimum value if opt_type == 'M': print("\n********** Maximization Successful!!! ************\n") else: print("\n********** Minimization Successful!!! ************\n") for i in range(m): for j in range(n): if table[i][j] == 1: if np.sum(table[:, j]) == 1: print(f"\t for X{j+1} == {table[i][col_index]:.2f}") print(f"\nThe Optimum value is {zj[col_index]:.2f}") final_output: This function prints the final solution and the optimum value. Step 5: Get User Input for Equations and Variables print("************* LINEAR PROGRAMMING ~~ Simplex Method **********************\n") m = int(input("Enter the number of equations: ")) n = int(input("Enter the number of variables: ")) # Initialize matrix A = np.zeros((m, n)) # ARRAY signs = [] b = [] M = 10000000 # Big value for artificial variables # Ask coefficients, signs, and rhs for i in range(m): print(f"Equation {i+1}") for j in range(n): while True: try: A[i, j] = float(input(f"Enter coefficient for X{j+1}: ")) break except ValueError: wrong_input() sign = input("Enter sign (E for '=', G for '>=', S for '<='): ") if sign not in ['G', 'g', 'E', 'e', 'S', 's']: sign = 'S' signs.append(sign) while True: try: rhs = float(input("Enter RHS Value: ")) break except ValueError: wrong_input() b.append(rhs) # Get coefficients of the objective function c = np.zeros(n) for j in range(n): while True: try: c[j] = float(input(f"Enter coefficient for Z function, X{j+1}: ")) break except ValueError: wrong_input() # Ask for type of optimization (max or min) while True: opt_type = input("Enter optimization type M for max and m for min: ") if opt_type in ['M', 'm']: break else: wrong_input() User Input: This section collects the number of equations, variables, coefficients, signs, RHS values, and the type of optimization from the user. Step 6: Initialize and Set Up Matrices count_a = 0 for i in range(m): if signs[i] in ['G', 'g', 'E', 'e']: count_a += 1 artificial_var = np.zeros((m, m)) s_var = np.zeros((m, m)) for i in range(m): if signs[i] in ['G', 'g']: for j in range(m): s_var[i][j] = -1 if i == j else 0 artificial_var[i][j] = 1 if i == j else 0 elif signs[i] in ['S', 's']: for j in range(m): s_var[i][j] = 1 if i == j else 0 artificial_var[i][j] = 0 if i == j else 0 elif signs[i] in ['E', 'e']: for j in range(m): s_var[i][j] = 0 artificial_var[i][j] = 1 if i == j else 0 combined_table = np.hstack((A, s_var, artificial_var)) combined_table = combined_table[:, ~np.all(combined_table == 0, axis=0)] b = np.reshape(b, (m, 1)) table = np.hstack((combined_table, b)) col_index = combined_table.shape[1] total_col = table.shape[1] cj = np.zeros(col_index) for i in range(col_index - count_a, col_index): cj[i] = -M if opt_type == 'M' else M for i in range(n): cj[i] = c[i] print("Total number of artificial variable introduced is ", count_a) print("\n cj: ", cj) print(table) Initialize Matrices: This section sets up the initial matrices, including slack and artificial variables, and combines them into the final tableau. Step 7: Define Basic Variables and Perform Simplex Iterations basic_vars = np.zeros(m) for i in range(m): for j in range(n + 1, col_index): if combined_table[i][j] == 1: basic_vars[i] = cj[j] print("Initial Basic values are: ", basic_vars) zj = np.zeros(total_col) zj_cj = np.zeros(col_index) counter = 1 while True: find_zj() pc = find_pivot_col() if pc is None: print("Solution is found") message = 1 break print("\nPivot column: ", pc) pr = find_pivot_row() if pr is None: print("No solution is found") message = 0 break print("\nPivot row: ", pr) new_rows() print("\nIteration ", counter) print(table.round( 2)) counter += 1 if message == 1: final_output() else: print("The problem has no feasible solution") Define Basic Variables: This section initializes the basic variables and performs the Simplex iterations until the optimal solution is found or the problem is determined to be infeasible. Full Code import numpy as np #for defining array np.set_printoptions(precision=2, floatmode="fixed") #for printing only two points after decimals def wrong_input(): #print Error message for invalid input print("Error!!! Invalid Input. Please input the valid data: ") def find_zj(): # calculate Zj value which is basically the sum of product of basicvalues and corresponding xi for j in range(total_col): sum = 0 for i in range(m): sum = sum + basic_vars[i]*table[i][j] zj[j] = sum if j < col_index: zj_cj[j]=sum - cj[j] def find_pivot_col(): """ finds the entering variable( pivot column) for the next iteration """ if opt_type == 'M': smallest = np.min(zj_cj) if smallest >= 0: return None else: largest = np.max(zj_cj) if largest <= 0: return None pc = np.argmin(zj_cj) if opt_type == 'M' else np.argmax(zj_cj) return pc def find_pivot_row(): """ Finds the leaving variable (pivot row) for the next iteration. """ min_ratio =float('inf') pivot_row =None for i in range(m): if(table[i][pc]>0 and table[i][col_index] > 0): ratio = table[i][col_index]/table[i][pc] if ratio < min_ratio: min_ratio = ratio pivot_row = i if(min_ratio == float('inf')): return None basic_vars[pivot_row] = cj[pc] # Update basic_vars with leaving variable's coefficient print("basic var \n", basic_vars) return pivot_row def new_rows(): """ Updates the table by performing row operations to find the new pivot row. """ pivot_element = table[pr][pc] for j in range(total_col): table[pr][j]=table[pr][j]/pivot_element #to find other rows except pivot row for i in range(m): if i != pr: pivot_coeff = table[i][pc] for j in range(total_col): table[i][j] -=pivot_coeff*table[pr][j] def final_output(): """ Prints the final solution and the optimum value. """ if(opt_type== 'M'): print ("\n ********** Maximization Successful!!!************\n") else: print ("\n ********** Minimization Successful!!!************\n") for i in range(m): for j in range(n): if table[i][j]==1: if np.sum(table[:, j]) == 1: print(f"\t for X{j+1} == {table[i][col_index]:.2f}") print(f"\n The Optimum value is { zj[col_index]:.2f}") #Ask for equations and variables print("************* LINEAR PROGRAMMING ~~ Simplex Method **********************\n") m = int(input("Enter the number of equations: ")) n = int(input("Enter the number of variables: ")) #Initialize matrix A=np.zeros((m,n)) #ARRAY signs = [] b=[] M = 10000000 # Putting big value #ask coefficients, signs and rhs for i in range(m): print(f"Equation {i+1}") for j in range(n): #Error handling using try and except, to make sure user input only numbers as coefficients while True: try: A[i, j] = float(input(f"Enter coefficient for X{j+1}: ")) break # Break out of the loop if valid input is entered except ValueError: wrong_input() sign=input("Enter sign (E for '=', G for'>=' , S for '<='): ") if sign not in ['G', 'g', 'E', 'e', 'S', 's']: sign = 'S' signs.append(sign) while True: try: rhs=float(input("Enter RHS Value: ")) break #for valid input except ValueError: wrong_input() b.append(rhs) # Get coefficient of the objective function c=np.zeros(n) for j in range(n): while True: try: c[j] = float(input(f"Enter coefficient for Z function, X{j+1}: ")) break except ValueError: wrong_input() #Ask for type of optimization (mac or min) while True: opt_type = input("Enter optimization type M for max and m for min: ") if(opt_type in ['M','m']): break else: wrong_input() #Count number of greater or equal to function count_a=0 for i in range(m): if signs[i] in ['G', 'g', 'E', 'e']: count_a = count_a +1 #adding slack/surplus and artificial artificial_var =np.zeros((m,m)) s_var=np.zeros((m,m)) for i in range(m): if signs[i] in ['G','g']: for j in range(m): s_var[i][j] = -1 if i==j else 0 artificial_var[i][j] = 1 if i==j else 0 elif signs[i] in ['S','s']: for j in range(m): s_var[i][j] = 1 if i==j else 0 artificial_var[i][j] = 0 if i==j else 0 elif signs[i] in ['E','e']: for j in range(m): s_var[i][j] = 0 artificial_var[i][j] = 1 if i == j else 0 #print(s_var, artificial_var) # Combine matrices A, s_var, artificial_var by excluding columns with all zeros combined_table = np.hstack((A, s_var, artificial_var)) combined_table = combined_table[:, ~np.all(combined_table == 0, axis=0)] #reshape b to column vector b=np.reshape(b,(m,1)) #combine table table = np.hstack((combined_table,b)) col_index = combined_table.shape[1] total_col = table.shape[1] cj = np.zeros(col_index) for i in range(col_index-count_a,col_index): cj[i]= -M if opt_type == 'M' else M for i in range(n): cj[i]=c[i] print("Total number of artificial variable introduced is ", count_a) print("\n cj: ",cj) print(table) # define basic variables basic_vars = np.zeros(m) for i in range(m): for j in range(n+1,col_index): if combined_table[i][j] == 1: basic_vars[i] = cj[j] print("Initial Basic values are : ", basic_vars) zj=np.zeros(total_col) zj_cj = np.zeros(col_index) counter = 1 while True: find_zj() pc = find_pivot_col() if pc == None: print("Solution is found") message = 1 break print("\nPivot column: ",pc) pr = find_pivot_row() if pr == None: print(" No solution is found") message = 0 break print("\nPivot row: ",pr) new_rows() print("\n Iteration ", counter ) print(table.round(2)) counter +=1 if message == 1: final_output() else: print("Unbounded solution, Please try again")

June 17, 2024 · 9 min · Yogesh Sharma Neupane

Dynamic Programming- Water Allocation

Step 1: Import Libraries and Define Functions import numpy as np numpy: This library is used to handle array operations efficiently. Define the print_table_row Function def print_table_row(s, x, f, y=None, total_return=None): # Print a row of the table with the given values. if y is None: print(f"{s}\t\t{x}\t\t{f}\t") else: print(f"{s}\t\t{x}\t\t{f}\t\t{y}\t\t{total_return}") print_table_row: This function prints a row of the table. It adjusts the number of columns based on the current iteration. Define the table Function def table(i): # Print the table header based on the current iteration. if i == 2: print("Available\tAllocated\tReturn") else: print("Available\tAllocated\tReturn\tRemaining\tTotalReturn") table: This function prints the table header based on the current iteration. If i is 2, it prints a header with three columns; otherwise, it prints a header with five columns. Step 2: Initialize Variables user = [[0, 5, 8, 9, 8, 5, 0], [0, 5, 6, 3, -4, -15, -30], [0, 7, 12, 15, 16, 15, 12]] q = 7 ff = 0 xx = 0 fmat = np.zeros((3, 7)) xmat = np.zeros((3, 7)) allocation = np.zeros(3) k = 0 user: A list of lists containing user data. q: The total number of units available. ff: A variable to store the maximum return found so far. xx: A variable to store the optimal allocation for the current iteration. fmat: A 3x7 matrix (array) to store the optimized values. xmat: A 3x7 matrix (array) to store the allocations. allocation: An array to store the final allocation of units. k: A counter for tracking the current iteration. Step 3: Generate Tables and Optimize Values for i in range(2, -1, -1): table(i) ff = 0 for s in range(q): for x in range(s + 1): if i == 2: f = int(user[i][x]) print_table_row(s, x, f) if ff < f: ff = f xx = x else: y = s - x f = int(user[i][x] + int(fmat[i + 1][y])) print_table_row(s, x, int(user[i][x]), y, f) if ff < f: ff = f xx = x fmat[i][s] = ff xmat[i][s] = xx print(f"Optimized value from table {k+1}: {ff} at x={xx}, s={s}\n") k += 1 Outer Loop (i): Iterates through the levels (2, 1, 0). Inner Loop (s): Iterates through each unit from 0 to q-1. Innermost Loop (x): Iterates through each possible allocation from 0 to s. If i == 2: Calculate the return and print the table row. Update ff and xx if a higher return is found. Else: Calculate the return considering the next level’s optimized value and print the table row. Update ff and xx if a higher return is found. Store the optimized value (ff) and the corresponding allocation (xx) in fmat and xmat. Print the optimized value for each table. Step 4: Calculate Final Allocation total_unit = 6 allocation[0] = xx total_allocated = xx for i in range(3): if i != 0: total_available = total_unit - total_allocated allocation[i] = xmat[i][total_available] if i != 2: total_allocated = total_allocated + int(allocation[i]) total_unit: The total number of units available for allocation. allocation[0]: Set the first allocation based on the optimized value. total_allocated: Track the total allocated units. Loop (i): Calculate the remaining allocation for each level and update the total allocated units. Step 5: Print Results # Print the results print("Maximum Benefit is", ff, "for the allocation", allocation) print("Optimized table:\n", fmat) print("Respective allocation:\n", xmat) Print the maximum benefit and the corresponding allocation. Print the optimized tables (fmat and xmat). Full Code import numpy as np def print_table_row(s, x, f, y=None, total_return=None): # Print a row of the table with the given values. if y is None: print(f"{s}\t\t{x}\t\t{f}\t") else: print(f"{s}\t\t{x}\t\t{f}\t\t{y}\t\t{total_return}") def table(i): # Print the table header based on the current iteration. if i == 2: print("Available\tAllocated\tReturn") else: print("Available\tAllocated\tReturn\tRemaining\tTotalReturn") user = [[0, 5, 8, 9, 8, 5, 0], [0, 5, 6, 3, -4, -15, -30], [0, 7, 12, 15, 16, 15, 12]] q = 7 ff = 0 xx = 0 fmat = np.zeros((3, 7)) xmat = np.zeros((3, 7)) allocation = np.zeros(3) k = 0 # Generate the tables and optimize the values for i in range(2, -1, -1): table(i) ff = 0 for s in range(q): for x in range(s + 1): if i == 2: f = int(user[i][x]) print_table_row(s, x, f) if ff < f: ff = f xx = x else: y = s - x f = int(user[i][x] + int(fmat[i + 1][y])) print_table_row(s, x, int(user[i][x]), y, f) if ff < f: ff = f xx = x fmat[i][s] = ff xmat[i][s] = xx print(f"Optimized value from table {k+1}: {ff} at x={xx}, s={s}\n") k += 1 # Allocation total_unit = 6 allocation[0] = xx total_allocated = xx for i in range(3): if i != 0: total_available = total_unit - total_allocated allocation[i] = xmat[i][total_available] if i != 2: total_allocated = total_allocated + int(allocation[i]) # Print the results print("Maximum Benefit is", ff, "for the allocation", allocation) print("Optimized table:\n", fmat) print("Respective allocation:\n", xmat)

June 17, 2024 · 4 min · Yogesh Sharma Neupane

Basic- Manning Equation

Solving the Manning Equation for Open Channel Flow In this tutorial, we’ll walk through how to solve the Manning equation for open channel flow using Python. The Manning equation is widely used in hydraulic engineering to calculate the flow rate in open channels. We’ll prompt the user for the necessary inputs, perform the calculations, and output the discharge capacity of the channel. Code Explanation # Solving the Manning Equation for open channel flow # Prompt the user for the width of the channel b = float(input("Enter the width of the channel (meters): ")) # Prompt the user for the depth of the channel y = float(input("Enter the depth of the channel (meters): ")) # Assume the slope of the channel is 1 in 1000 s = 1 / 1000 # Assume the Manning coefficient n = 0.015 (This value can vary based on the channel material) n = 0.015 # Calculate the cross-sectional area of flow (A = width * depth) A = b * y print("Cross-sectional area A is:", A, "square meters") # Calculate the wetted perimeter (P = width + 2 * depth) P = b + 2 * y print("Wetted perimeter P is:", P, "meters") # Calculate the hydraulic radius (R = A / P) R = A / P print("Hydraulic radius R is:", R, "meters") # Calculate the discharge capacity (Q) using the Manning equation # Q = (A * R^(2/3) * s^(1/2)) / n Q = (A * (R ** (2/3)) * (s ** 0.5)) / n # Print the discharge capacity, formatted to 3 decimal places print("Discharge Q is {:.3f} cubic meters per second".format(Q)) Step-by-Step Breakdown Inputs: ...

June 17, 2024 · 3 min · Yogesh Sharma Neupane

Data handling - Monthly Flow

Note: The explanation of the code is generated with the assistance of AI Importing Libraries import pandas as pd import matplotlib.pyplot as plt pandas (pd): A powerful Python library for data manipulation and analysis. It provides data structures and functions to efficiently handle structured data, including tabular data such as spreadsheets and SQL tables. matplotlib.pyplot (plt): A Python plotting library that provides a MATLAB-like interface for creating a variety of charts, including line plots, scatter plots, histograms, and more. Loading the CSV File file_path = 'discharge_ai.csv' # Replace with the path to your CSV file df = pd.read_csv(file_path) pd.read_csv(file_path): This function reads a CSV file into a DataFrame. The DataFrame is a two-dimensional labeled data structure with columns of potentially different types. It is similar to an Excel spreadsheet or SQL table, or a dictionary of Series objects. Displaying the First Few Rows of the DataFrame print(df.head()) df.head(): This method returns the first n rows for the object based on position. It is useful for quickly testing if your object has the right type of data in it. By default, it returns the first 5 rows. Converting the ‘Date’ Column to Datetime Format df['Date'] = pd.to_datetime(df['Date']) pd.to_datetime(): This method converts various types of date formats into a standardized datetime format. It is useful for handling date and time data in a consistent manner. Setting the ‘Date’ Column as the Index df.set_index('Date', inplace=True) df.set_index(‘Date’, inplace=True): This method sets the ‘Date’ column as the index of the DataFrame. This allows for efficient data manipulation and analysis based on the date. Checking for Missing Values print(df.isna().sum()) df.isna(): This method returns a boolean DataFrame showing whether each element is missing (NaN) or not. .sum(): This method returns the sum of the boolean values, effectively counting the number of missing values. Handling Missing Values (Forward Fill) df.fillna(method='ffill', inplace=True) df.fillna(): This method fills missing values in the DataFrame. It can be used to fill missing values with a specific value or to forward fill missing values. method=‘ffill’: This method fills missing values by propagating the last valid observation forward. inplace=True: This parameter modifies the DataFrame in place, meaning it changes the original DataFrame. Resampling the Data to Calculate Monthly Averages monthly_avg = df.resample('M').mean() df.resample(‘M’): This method resamples the DataFrame by grouping it by a specified period. In this case, it groups the data by months. .mean(): This method calculates the mean of the resampled data. Displaying the Monthly Averages print(monthly_avg.head()) monthly_avg.head(): This method returns the first n rows for the object based on position. It is useful for quickly testing if your object has the right type of data in it. By default, it returns the first 5 rows. Plotting the Monthly Averages plt.figure(figsize=(10, 6)) plt.plot(monthly_avg.index, monthly_avg['Discharge'], marker='o', linestyle='-') plt.title('Monthly Average River Discharge') plt.xlabel('Date') plt.ylabel('Discharge (cubic meters per second)') plt.grid(True) plt.show() plt.figure(figsize=(10, 6)): This method creates a new figure with the specified size. plt.plot(): This method creates a line plot of the data. plt.title(): This method sets the title of the plot. plt.xlabel() and plt.ylabel(): These methods set the labels for the x and y axes. plt.grid(True): This method adds a grid to the plot. plt.show(): This method displays the plot. Full Script import pandas as pd import matplotlib.pyplot as plt from datetime import datetime # Load the CSV file file_path = 'discharge_ai.csv' df = pd.read_csv(file_path) # Define a function to convert the 'Date' column to datetime format def convert_date(df): df['Date'] = pd.to_datetime(df['Date']) return df # Define a function to set the 'Date' column as the index def set_index(df): df.set_index('Date', inplace=True) return df # Define a function to check for missing values def check_missing(df): print(df.isna().sum()) return df # Define a function to handle missing values def handle_missing(df): df.fillna(method='ffill', inplace=True) return df # Define a function to resample the data to calculate monthly averages def resample_data(df): monthly_avg = df.resample('M').mean() return monthly_avg # Define a function to plot the monthly averages def plot_data(monthly_avg): plt.figure(figsize=(10, 6)) plt.plot(monthly_avg.index, monthly_avg['Discharge'], marker='o', linestyle='-') plt.title('Monthly Average River Discharge') plt.xlabel('Date') plt.ylabel('Discharge (cubic meters per second)') plt.grid(True) plt.show() # Load the CSV file df = pd.read_csv(file_path) # Convert the 'Date' column to datetime format df = convert_date(df) # Set the 'Date' column as the index df = set_index(df) # Check for missing values df = check_missing(df) # Handle missing values df = handle_missing(df) # Resample the data to calculate monthly averages monthly_avg = resample_data(df) # Plot the monthly averages plot_data(monthly_avg) Download CSV File ...

June 2, 2024 · 4 min · Yogesh Sharma Neupane

Assignment1

Here are five questions that you can use as assignments based on the concepts covered in our Python learning and tutorial: Data Handling with Pandas: Create a Pandas DataFrame from scratch with at least three columns (e.g., Hydropower_name, Hydropower_capacity, Location). Display the first five rows of the DataFrame. Data Analysis with Pandas: Load a CSV file containing student grades data (columns: StudentID, Subject, Grade). Compute and print the average grade for each subject. Data Visualization with Matplotlib: ...

May 31, 2024 · 1 min · Yogesh Sharma Neupane

Pipeflow

Introduction In this tutorial, we’ll explore a Python script that calculates the Reynolds number, classifies the flow type, and determines the head loss in pipes. We’ll also learn how to process multiple pipes with different properties. This code is useful for engineers and students who need to analyze fluid flow in pipes. Prerequisites Before diving into the code, make sure you have Python installed on your system. If you’re new to Python, you can download it from the official website: https://www.python.org/downloads/ ...

May 31, 2024 · 4 min · Yogesh Sharma Neupane

How Matplotlib and Pandas are used? The Basics

In this tutorial, we will be working with streamflow data and using the pandas and matplotlib libraries to analyze and visualize the data. Streamflow Data We will start by generating random streamflow data using the numpy library. We will create an array of 365 random numbers between 5 and 15, representing the streamflow for each day of the year. num_days = 365 streamflow = np.random.uniform(low=5,high=15,size=num_days) Creating a Date Range Next, we will create a date range for the data using the pandas library. We will create a date range from January 26, 2000 to December 31, 2000, with 365 days. ...

May 28, 2024 · 3 min · Yogesh Sharma Neupane