Creat a inverse distance weighting Function in VBA - python

I want to estimate the inverse distance weighting (IDW) interpolation value of rainfall.
I identified the nearest three stations to the needed station to obtain the interpolated value.
I have the following table:
So, the equation of IDW:
[(Station_valu1/Dist1^2)+(Station_valu2/Dist2^2)+(Station_valu3/Dist3^2)]
—————————————————————————————————————————————————————————————————————————
1/Dist1^2 + 1/Dist2^2 + 1/Dist3^2
There would be several situations trying to address them in this equation:
1) If Value1 or Dist1 are empty and Value2, Dist2, Value3, Dist3 are not
then, disregard Value1, Dist1 from the equation, and consider only Value2, Dist2, and Value3, Dist3.
Result of IDW will be:
[Station_valu2/Dist2^2)+(Station_valu3/Dist3^2)]
————————————————————————————————————————————————
Dist2^2 + 1/Dist3^2
We will have the same scenario with Value2, Dist2, and Value3, Dist3 if anyone of them has null value.
I came up with this code:
Function IDWW(Value1, Value2, Value3, Dist1,Dist2,Dist3)
Dim a1 As Variant
Dim b1 As Variant
Dim a2 As Variant
Dim b2 As Variant
Dim a3 As Variant
Dim b3 As Variant
If Value1 <> "" And Dist1 <> "" Then
a1 = Value1 / (Dist1) ^ 2
b1 = 1 / (Dist1) ^ 2
ElseIF Value1 = "" OR Dist1 = "" Then
a1 = ""
b1 = ""
End If
If Value2 <> "" And Dist2 <> "" Then
a2 = Value2 / (Dist2) ^ 2
b2 = 1 / (Dist2) ^ 2
ElseIF Value1 = "" OR Dist1 = "" Then
a2 = ""
b2 = ""
End If
If Value3 <> "" And Dist3 <> "" Then
a3 = Value3 / (Dist3) ^ 2
b3 = 1 / (Dist3) ^ 2
ElseIF Value3 = "" OR Dist3 = "" Then
a3 = ""
b3 = ""
End If
IDWW = (a1+a2+a3) / (b1+b2+b3)
End Function
Please, I need your help to solve this issue!

As far as I can see, all you want to do is set values to be zero if they are empty:
Function IDWW(Value1, Value2, Value3, Dist1,Dist2,Dist3)
Dim a1 As Variant
Dim b1 As Variant
Dim a2 As Variant
Dim b2 As Variant
Dim a3 As Variant
Dim b3 As Variant
If Value1 <> "" And Dist1 <> "" Then
a1 = Value1 / (Dist1) ^ 2
b1 = 1 / (Dist1) ^ 2
Else
a1 = 0
b1 = 0
End If
If Value2 <> "" And Dist2 <> "" Then
a2 = Value2 / (Dist2) ^ 2
b2 = 1 / (Dist2) ^ 2
Else
a2 = 0
b2 = 0
End If
If Value3 <> "" And Dist3 <> "" Then
a3 = Value3 / (Dist3) ^ 2
b3 = 1 / (Dist3) ^ 2
Else
a3 = 0
b3 = 0
End If
'Avoid a problem if all 3 distances are empty
If b1 + b2 + b3 = 0 Then
IDWW = 0
Else
IDWW = (a1+a2+a3) / (b1+b2+b3)
End If
End Function

Related

Negative values with GCD python program

Iam doing GCD tool in python but for some reason every time I use 2 negative values I get back negative value back. Beceause this is for school i cant use things like obs() ort math etc.. Can some help me with that?
from sys import stdin
a = 0
b = 0
a0 = 0
b0 = 0
a1 = 0
b1 = 0
n = 0
na = 0
nb = 0
q = 0
for line in stdin:
input = line.lstrip().rstrip().split()
if line == '' or len(input) != 2:
break
a, b = [int(x) for x in line.lstrip().rstrip().split()]
if a > b:
a, b = b, a
#
# a | b
# +---------+
# a | 1 | 0 | "( a0, b0 )"
# b | 0 | 1 | "( a1, b1 )"
# n | na | nb | q
# | | |
#
#
a0 = 1
b0 = 0
a1 = 0
b1 = 1
n = a % b
q = a / b
na = a0 - q * a1
nb = b0 - q * b1
a = b
a0 = a1
b0 = b1
b = n
a1 = na
b1 = nb
while n != 0:
n = a % b
q = a // b
na = a0 + q * a1
nb = b0 + q * b1
a = b
a0 = a1
b0 = b1
b = n
a1 = na
b1 = nb
print(a)
I tried messing around with operators. I expect to -888 -2 be 2 not -2 (I need to fix the code not to edit results )
Edit 1 : Here are some examples of what i need
Input Output
7 11 1
888 2 2
905 5 5
-7 11 1
-888 -2 2
905 -5 5

How to create hierarchical path by id column in a dataframe in python?

I have a dataframe which has parent_id, parent_name, id, name, last_category columns. df is like this:
parent_id parent_name id name last_category
NaN NaN 1 b 0
1 b 11 b1 0
11 b1 111 b2 0
111 b2 1111 b3 0
1111 b3 11111 b4 1
NaN NaN 2 a 0
2 a 22 a1 0
22 a1 222 a2 0
222 a2 2222 a3 1
I want to create a hierarchical path of df with last_category column 1. From the root category to the last. So the new dataframe I will create should be like this (df_last):
name_path id_path
b / b1 / b2 / b3 / b4 1 / 11 / 111 / 1111 / 11111
a / a1 / a2 / a3 / a4 2 / 22 / 222 / 2222
How to do this?
A solution using only numpy and pandas :
# It's easier if we index the dataframe with the `id`
# I assume this ID is unique
df = df.set_index("id")
# `parents[i]` returns the parent ID of `i`
parents = df["parent_id"].to_dict()
paths = {}
# Find all nodes with last_category == 1
for id_ in df.query("last_category == 1").index:
child_id = id_
path = [child_id]
# Iteratively travel up the hierarchy until the parent is nan
while True:
pid = parents[id_]
if np.isnan(pid):
break
else:
path.append(pid)
id_ = pid
# The path to the child node is the reverse of
# the path we traveled
paths[int(child_id)] = np.array(path[::-1], dtype="int")
And constructing the result data frame:
result = pd.DataFrame({
id_: (
" / ".join(df.loc[pids, "name"]),
" / ".join(pids.astype("str"))
)
for id_, pids in paths.items()
}, index=["name_path", "id_path"]).T
You can use networkx to resolve the path between root node and leaf node with all_simple_paths function.
# Python env: pip install networkx
# Anaconda env: conda install networkx
import networkx as nx
# Create network from your dataframe
G = nx.from_pandas_edgelist(df, source='parent_id', target='id',
create_using=nx.DiGraph)
nx.set_node_attributes(G, df.set_index('id')[['name']].to_dict('index'))
# Find roots of your graph (a root is a node with no input)
roots = [node for node, degree in G.in_degree() if degree == 0]
# Find leaves of your graph (a leaf is a node with no output)
leaves = [node for node, degree in G.out_degree() if degree == 0]
# Find all paths
paths = []
for root in roots:
for leaf in leaves:
for path in nx.all_simple_paths(G, root, leaf):
# [1:] to remove NaN parent_id
paths.append({'id_path': ' / '.join(str(n) for n in path[1:]),
'name_path': ' / '.join(G.nodes[n]['name'] for n in path[1:])})
out = pd.DataFrame(paths)
Output:
>>> out
id_path name_path
0 1 / 11 / 111 / 1111 / 11111 b / b1 / b2 / b3 / b4
1 2 / 22 / 222 / 2222 a / a1 / a2 / a3

how to covert code from pine script to python

how to convert this type of code from pine script to python
pine script code
get2PoleSSF(src, length) =>
PI = 2 * asin(1)
arg = sqrt(2) * PI / length
a1 = exp(-arg)
b1 = 2 * a1 * cos(arg)
c2 = b1
c3 = -pow(a1, 2)
c1 = 1 - c2 - c3
ssf = 0.0
ssf := c1 * src + c2 * nz(ssf[1]) + c3 * nz(ssf[2])
this is the part im trying to convert it to python
the value of of the code
I tried this
def get2PoleSSD(src,length):
PI = 2* np.arcsin(1)
arg = np.sqrt(2)* PI / length
a1 = np.exp(-arg)
b1 = 2 * a1 *np. cos(arg)
c2 = b1
c3 = -pow(a1, 2)
c1 = 1 - c2 - c3
df['ssf'] = 0.0
df['ssf'] = c1* src
df['ssf_1p'] = df['ssf'].shift(1)
df['ssf_2p'] = df['ssf'].shift(2)
df['ssf_n'] = c1 * src + c2 * df['ssf_1p'] + c3 * df['ssf_2p']
the value from my code
but the value doesn't match at all

Concatenate the columns of a dataframe (with string values) in python-like paste0 function in R [duplicate]

This question already has answers here:
Combine two columns of text in pandas dataframe
(21 answers)
Closed 1 year ago.
Below is the input data
Type Cat Var Dist Count
#joy A1 + B1 x + y + z 0:25:75 4
.cet C1 + D1 p + q 50:50 2
sam E1 + F1 g 100:3:2 10
Below is the intended output
Type Cat Var Dist Count Output
#joy A1 + B1 x + y + z 0:25:75 4 #joyA1 + B1x + y +z
.cet C1 + D1 p + q 50:50 2 .cetC1 + D1p + q
sam E1 + F1 g 100:3:2 10 samE1 + F1g
Below is the try from my end:
df.iloc[:,0:3].dot(['Type','Cat','Var'])
You can do that using
df['output'] = df['Type'].map(str) + df['Cat'].map(str) + df['Var].map(str)
you can simply use:
df['Output']=df['Type']+' '+df['Cat']+' '+df['Var']
output:
Type Cat Var Dist Count output
0 #joy A1 + B1 x + y + z 0.018229167 4 #joy A1 + B1 x + y + z
1 .cet C1 + D1 p + q 50:50:00 2 .cet C1 + D1 p + q
2 sam E1 + F1 g 100:03:02 10 sam E1 + F1 g
Base R: Using paste0
df$Output <- paste0(df$Type, df$Cat, df$Var)
Type Cat Var Dist Count Output
1 #joy A1 + B1 x + y + z 0:25:75 4 #joy A1 + B1 x + y + z
2 .cet C1 + D1 p + q 50:50 2 .cet C1 + D1 p + q
3 sam E1 + F1 g 100:3:2 10 sam E1 + F1 g
OR
library(dplyr)
df %>%
mutate(Output = paste(Type, Cat, Var, sep = ""))
Type Cat Var Dist Count Output
1 #joy A1 + B1 x + y + z 0:25:75 4 #joy A1 + B1 x + y + z
2 .cet C1 + D1 p + q 50:50 2 .cet C1 + D1 p + q
3 sam E1 + F1 g 100:3:2 10 sam E1 + F1 g
OR:
library(tidyr)
df %>%
unite(Output, c(Type, Cat, Var), remove=FALSE)
Output Type Cat Var Dist Count
1 #joy_A1 + B1_x + y + z #joy A1 + B1 x + y + z 0:25:75 4
2 .cet_C1 + D1_p + q .cet C1 + D1 p + q 50:50 2
3 sam_E1 + F1_g sam E1 + F1 g 100:3:2 10

Custom function + groupby Pandas with different conditions on grouped by variables

I want to generate some weights using groupby on a data that originally looks like this :
V1 V2 MONTH CHOICES PRIORITY
X T1 M1 C1 1
X T1 M1 C2 0
X T1 M1 C3 0
X T2 M1 C1 1
X T2 M1 C5 0
X T2 M1 C6 0
X T2 M1 C2 1
X T1 M2 C1 1
X T1 M2 C2 0
X T1 M2 C3 0
X T2 M2 C1 0
X T2 M2 C5 1
X T2 M2 C6 0
X T2 M2 C2 1
Basically, when the MONTH is different than M1, I want to have flagged choices with weights equal to double any non flagged choice.
Example : if you have (C1, C2, C3) and C1 is the only one flagged, weights would be : 0.5 / 0.25 / 0.25.
On the same time, for the first month, I want the weights to be solely focused on flagged choices. Previous example would become (1/0/0).
Precision about the data :
For a given tuple (V1,V2,MONTH), we can have at most two choices flagged as priorities (no priority at all is a possibility).
Here's what I've tried :
def weights_preferences(data):
if (data.MONTH.values != 'M1'):
data['WEIGHTS'] = 1/(len(data)+data[data.PRIORITY==1].shape[0])
data['WEIGHTS'] = data.apply(lambda x : 2*x.WEIGHTS if x.PRIORITY==1 else x.WEIGHTS, axis=1)
elif data.MONTH.values == 'M1' & data[data.PRIORITY==1].shape[0]==0 :
data['WEIGHTS'] = 1/(len(data))
else :
if data[data.PREFERENCE==1].shape[0]==1 :
data['WEIGHTS'] = [1 if x[1].PRIORITY==1 else 0 for x in data.iterrows()]
else :
data['WEIGHTS'] = [0.5 if x[1].PRIORITY==1 else 0 for x in data.iterrows()]
return data
tmp = tmp.groupby(['V1','V2','MONTH']).apply(weights_preferences)
The problem is that since I groupby 'MONTH', it seems that the value no longer appears in data on which 'weights_preferences' is applied.
P.S : Output would look like this
V1 V2 MONTH CHOICES PRIORITY WEIGHTS
X T1 M1 C1 1 1
X T1 M1 C2 0 0
X T1 M1 C3 0 0
X T2 M1 C1 1 0.5
X T2 M1 C5 0 0
X T2 M1 C6 0 0
X T2 M1 C2 1 0.5
X T1 M2 C1 1 0.5
X T1 M2 C2 0 0.25
X T1 M2 C3 0 0.25
X T2 M2 C1 0 0.16
X T2 M2 C5 1 0.33
X T2 M2 C6 0 0.16
X T2 M2 C2 1 0.33
Any suggestions are very welcomed !
Thanks.

Categories

Resources