I am working on an app that plots a graph based on the input from the user. However when I try plotting the graph, the line doesn't go all the way.
The code is below:
v = text_v.get()
i = text_i.get()
v2 = v.split(", ")
i2 = i.split(", ")
outcome = True
#Testing for pairing of values
if range(len(v2)) != range(len(i2)):
tkm.showerror("Incomplete values", "You did not enter an equal number of voltage and resistance values")
outcome = False
#Testing for v-value type
for x in range(len(v2)):
try:
float(v2[x])
outcome = True
except:
tkm.showerror("Wrong value type", "All your voltage values must be floats or integers")
outcome = False
break
#Testing for i-value type
for x in range(len(i2)):
try:
float(i2[x])
except:
tkm.showerror("Wrong value type", "All your current values must be floats or integers")
outcome = False
break
#------------------------Graph plotting function----------------------------
if outcome == True:
v = np.array(list(map(float, v.split(", "))))
i = np.array(list(map(float, i.split(", "))))
fit = np.polyfit(i,v,1)
fit_fn = np.poly1d(fit)
plt.plot(i,v, 'bo', v, fit_fn(v), '--k')
Related
Given two 2d masks m1, m2 (both shape [m,m]), obtain 3d mask m3 (shape [m,m,m]):
if m1[i][j] == True and m2[i][k] == True and i != j and i != k and j != k, then m3[i][j][k] = True
Note that m1 and m2 is diagonal, m1[i][j] = m1[j][i], m2[i][k]=m2[k][i]. but m3[i][k][j] is not necessarily True.
For example:
m1=[[0,1,0],[1,0,0],[0,0,0]]
m2=[[0,0,1],[0,0,0],[1,0,0]]
m3 (shape (3,3,3)) the only True value is m3[0][1][2]
def _get_triplet_mask(mask1, mask2):
indices_equal = tf.cast(tf.eye(tf.shape(mask1)[0]), tf.bool)
indices_not_equal = ~indices_equal
i_not_equal_j = tf.expand_dims(indices_not_equal, 2)
i_not_equal_k = tf.expand_dims(indices_not_equal, 1)
j_not_equal_k = tf.expand_dims(indices_not_equal, 0)
distinct_indices = (i_not_equal_j & i_not_equal_k) & j_not_equal_k
i_j = tf.expand_dims(mask1, 2)
i_k = tf.expand_dims(mask2, 1)
valid_labels = i_j & i_k
return valid_labels & distinct_indices
modified from sentence-transformers/sentence_transformers/losses/BatchHardTripletLoss.py. in tensorflow
I have some data that has duplicate fields with the exception of a single field which I would like to join. In the data everything but the report should stay the same on each day and each company. Companies can file multiple reports on the same day.
I can join using the following code but I am losing the variables which are not in my by function. Any suggestions?
Mock Data
using DataFrames
# Number of observations
n = 100
words = split("the wigdet drop air flat fall fling flap freeze flop tool fox", " ")
df = DataFrame(day = cumsum(rand(0:1, n)), company = rand(0:3, n),
report = [join(rand(words, rand(1:5, 1)[1]), " ") for i in 1:n])
x = df[:, [:day, :company]]
# Number of variables which are identical for each day/company.
nv = 100
for i in 1:nv
df[:, Symbol("v" * string(i))] = ""
end
for i in 1:size(x, 1),j in 1:nv
df[(df.day .== x[i,1]) .& (df.company .== x[i,2]), Symbol("v" * string(j))] =
join(rand('a':'z', 3), "")
end
Collapsed data
outdf = by(df, [:company, :day]) do sub
t = DataFrame(fullreport = join(sub.report, "\n(Joined)\n"))
end
Here are some minor tweaks in your data preparation code:
using DataFrames
# Number of observations
n = 100
words = split("the wigdet drop air flat fall fling flap freeze flop tool fox", " ")
df = DataFrame(day = cumsum(rand(0:1, n)), company = rand(0:3, n),
report = [join(rand(words, rand(1:5, 1)[1]), " ") for i in 1:n])
x = df[:, [:day, :company]]
# Number of variables which are identical for each day/company.
nv = 100
for i in 1:nv
df[:, Symbol("v", i)] .= ""
end
for i in 1:size(x, 1), j in 1:nv
df[(df.day .== x[i,1]) .& (df.company .== x[i,2]), Symbol("v", j)] .= join(rand('a':'z', 3), "")
end
and here is by that keeps all other variables (assuming they are constant per group, this code should be efficient even for relatively large data):
outdf = by(df, [:company, :day]) do sub
merge((fullreport = join(sub.report, "\n(Joined)\n"),),
copy(sub[1, Not([:company, :day, :report])]))
end
I put the fullreport variable as a first one.
Here is the code that would keep all rows from the original data frame:
outdf = by(df, [:company, :day]) do sub
insertcols!(select(sub, Not([:company, :day, :report])), 1,
fullreport = join(sub.report, "\n(Joined)\n"))
end
and now you can e.g. check that unique(outdf) produces the same data frame as the one that was generated by the fist by.
(in the codes above I dropped also :report variable as I guess you did not want it in the result - right?)
I have a Julia DataFrame where the first 4 columns are dimensions and the 5th one contains the actual data.
I would like to plot it using a subplots approach where the two main plot axis concern the first two dimensions and each subplot then is a contour plot over the remaining two dimensions.
I am almost there with the above code:
using DataFrames,Plots
# plotlyjs() # doesn't work with plotlyjs backend
pyplot()
X = [1,2,3,4]
Y = [0.1,0.15,0.2]
I = [2,4,6,8,10,12,14]
J = [10,20,30,40,50,60]
df = DataFrame(X=Int64[], Y=Float64[], I=Float64[], J=Float64[], V=Float64[] )
[push!(df,[x,y,i,j,(5*x+20*y+2)*(0.2*i^2+0.5*j^2+3*i*j+2*i^2*j+1)]) for x in X, y in Y, i in I, j in J]
minvalue = minimum(df[:V])
maxvalue = maximum(df[:V])
function toDict(df, dimCols, valueCol)
toReturn = Dict()
for r in eachrow(df)
keyValues = []
[push!(keyValues,r[d]) for d in dimCols]
toReturn[(keyValues...)] = r[valueCol]
end
return toReturn
end
dict = toDict(df, [:X,:Y,:I,:J], :V )
M = [dict[(x,y,i,j)] for j in J, i in I, y in Y, x in X ]
yL = length(Y)
xL = length(X)
plot(contour(M[:,:,3,1], ylabel="y = $(string(Y[3]))", zlims=(minvalue,maxvalue)), contour(M[:,:,3,2]), contour(M[:,:,3,3]), contour(M[:,:,3,4]),
contour(M[:,:,2,1], ylabel="y = $(string(Y[2]))", zlims=(minvalue,maxvalue)), contour(M[:,:,2,2]), contour(M[:,:,2,3]), contour(M[:,:,2,4]),
contour(M[:,:,1,1], ylabel="y = $(string(Y[1]))", xlabel="x = $(string(X[1]))"), contour(M[:,:,1,2], xlabel="x = $(string(X[2]))"), contour(M[:,:,1,3], xlabel="x = $(string(X[3]))"), contour(M[:,:,3,4], xlabel="x = $(string(X[4]))"),
layout=(yL,xL) )
This produces:
I remain however with the following concerns:
How do I automatize the creation of each subplot in the subplot call ? Do I need to write a macro ?
I would like each subplot to have the same limits in the z axis, but zlims seems not to work. Is zlims not yet supported ?
How do I hide the legend on the z axis on each subplot and plot it instead apart (best would be on the right side of the main/total plot) ?
EDIT:
For the first point I don't need a macro, I can create the subplots in a for loop, add them in a array and pass the array to the plot() call using the ellipsis operator:
plots = []
for y in length(Y):-1:1
for x in 1:length(X)
xlabel = y == 1 ? "x = $(string(X[x]))" : ""
ylabel = x==1 ? "y = $(string(Y[y]))" : ""
println("$y - $x")
plot = contour(I,J,M[:,:,y,x], xlabel=xlabel, ylabel=ylabel, zlims=(minvalue,maxvalue))
push!(plots,plot)
end
end
plot(plots..., layout=(yL,xL))
this is a part of my matrix factorization code (a very weird version of nmf). My issue is that although every time when I iterate, I save the older copies of the W and H matrices, when I compare old_W and W after W finishes updating every time, they are actually the same! So the actual error output is always 0 and the while loop stops after the first iteration. However, "#print old - new" shows that the element W[r][i] is actually updated every time. What is it that I am not seeing?
def csmf(V, l, max_iter, err, alpha=0.01, beta=0.01, lamb=0.01):
W = np.random.rand(V.shape[0], l)
H = np.random.rand(l, V.shape[1])
n = V.shape[0]
N = V.shape[1]
NwOone = 60
NwOtwo = 60
NhOone = 50
NhOtwo = 50
for t in range(max_iter):
old_W = W # save old values
old_H = H
old = criterion(V,old_W,old_H,l,alpha,beta,lamb)
print "iteration ", t
##### update W
print "updating W"
setw = range(0,n)
subset_one = random.sample(setw,NwOone)
subset_two = calcGw(V, W, H, n, l, alpha, beta, NwOtwo)
chosen = np.intersect1d(subset_one,subset_two)
for r in chosen:
for i in range(len(W[0])):
update = wPosNeg(W[r],N,i,l,V,r,beta,H)
old = W[r][i]
W[r][i] = update
new = W[r][i]
#print old - new
##### update H
print "updating H"
seth = range(0,N)
subset_oneh = random.sample(seth,NhOone)
subset_twoh = calcGh(V, W, H, N, l, NhOtwo,lamb)
chosenh = np.intersect1d(subset_oneh,subset_twoh)
for s in chosenh: # column
for i in range(len(H)):
updateh = hPosNeg(H[i],n,i,l,V,s,lamb,W)
H[i][s] = updateh
##### check err
print "Checking criterion"
print criterion(V,W,H,l,alpha,beta,lamb)
print criterion(V,old_W,old_H,l,alpha,beta,lamb)
actual = abs(criterion(V,W,H,l,alpha,beta,lamb) -criterion(V,old_W,old_H,l,alpha,beta,lamb))
if actual <= err: return W, H, actual
return W, H, actual
dmat = np.random.rand(100,80)
W, H, err = csmf(dmat, 1, 10, 0.001, alpha=0.001, beta=0.001, lamb=0.001)
print err
in these lines:
old_W = W # save old values
old_H = H
you are not saving a copy, you are keeping a reference (old_W and W are the same piece of memory).
Try this:
old_W = W.copy() # save old values
old_H = H.copy()
I have a Julia data frame where one column is called 'close' and I want to add another column to the data frame called 'sma' which is a simple moving average of 'close'. Thanks to anyone who can help!
I noticed a problem in the code amrod. It doesn't account for the first length of SMA that doesn't have enough previous data points for a good SMA and also gives double the SMA that is asked for. I changed it to input zeros up to that point, I also changed the variable names when I was figuring out how it works.
function makeSMA(data, SMA)
len = length(data)
y = Vector{Float64}(len)
for i in 1:SMA-1
y[i] = NaN
end
for i in SMA:len
y[i] = mean(data[i-(SMA-1):i])
end
return y
end
check this:
function ma{T <: Real}(x::Vector{T}, wind::Int)
len = length(x)
y = Vector{Float64}(len)
for i in 1:len
lo = max(1, i - wind)
hi = min(len, i + wind)
y[i] = mean(x[lo:hi])
end
return y
end
x = collect(1:100)
y = ma(x, 4)
then you can hcat(x, y).
EDIT:
If you want a backwards-looking MA you can use something like
function ma{T <: Real}(x::Vector{T}, wind::Int)
len = length(x)
y = Vector{Float64}(len)
for i in 1:len
if i < wind
y[i] = NaN
else
y[i] = mean(x[i - wind + 1:i])
end
end
return y
end