Showing posts with label formula. Show all posts
Showing posts with label formula. Show all posts

Wednesday, May 2, 2018

Solve Manning's Equation with Python Scipy library

from scipy.optimize import root

def manningC(d, args):
    Q, w,h,sSlopeL,sSlopeR,nMann,lSlope = args
    #left side slope can be different from right side slope
    area = ((((d*sSlopeL)+(d*sSlopeR)+w)+w)/2)*d
    # wet perimeter
    wPer = w+(d*(sSlopeL*sSlopeL+1)**0.5)+(d*(sSlopeR*sSlopeR+1)**0.5)
    #Hydraulic Radius
    hR = area/ wPer
    # following formula must be zero
    # manipulation of Manning's formula
    mannR = (Q*nMann/lSlope**0.5)-(area*hR**(2.0/3.0))
    return mannR
    
###### MAIN CODE
# the following are input data to our open channel manning calculation
# flow, width, height, left side slope, right side slope, 
# Manning coefficient, longitudinal slope
args0 = [2.5,2,.5,1.0,1.0,.015,.005]
initD = .00001  # initial water depth value

# then we call the root scipy function to the manningC
sol =root(manningC,initD, args=(args0,))    
# print the root found
print(sol.x)

Thursday, August 31, 2017

Calculate the centroid of a polygon with python


In this post I will show a way to calculate the centroid of a non-self-intersecting closed polygon.

I used the following formulas,

C_{\mathrm {x} }={\frac {1}{6A}}\sum _{i=0}^{n-1}(x_{i}+x_{i+1})(x_{i}\ y_{i+1}-x_{i+1}\ y_{i})

C_{\mathrm {y} }={\frac {1}{6A}}\sum _{i=0}^{n-1}(y_{i}+y_{i+1})(x_{i}\ y_{i+1}-x_{i+1}\ y_{i})

A={\frac {1}{2}}\sum _{i=0}^{n-1}(x_{i}\ y_{i+1}-x_{i+1}\ y_{i})\;

as shown in https://en.wikipedia.org/wiki/Centroid#Centroid_of_a_polygon .

In the following code, the function receives the coordinates as a list of lists or as a list of tuples.

from math import sqrt

def centroid(lstP):
    sumCx = 0
    sumCy = 0
    sumAc= 0
    for i in range(len(lstP)-1):
        cX = (lstP[i][0]+lstP[i+1][0])*(lstP[i][0]*lstP[i+1][1]-lstP[i+1][0]*lstP[i][1])
        cY = (lstP[i][1]+lstP[i+1][1])*(lstP[i][0]*lstP[i+1][1]-lstP[i+1][0]*lstP[i][1])
        pA = (lstP[i][0]*lstP[i+1][1])-(lstP[i+1][0]*lstP[i][1])
        sumCx+=cX
        sumCy+=cY
        sumAc+=pA
        print cX,cY,pA
    ar = sumAc/2.0
    print ar
    centr = ((1.0/(6.0*ar))*sumCx,(1.0/(6.0*ar))*sumCy)
    return centr