Skip to content

Commit 1cf78d0

Browse files
committed
better checking for failed polyroot
defaults to 0 if polyroot fails, or smallest imaginary part of root is too large (>1e-6)
1 parent 8a984f5 commit 1cf78d0

File tree

1 file changed

+31
-4
lines changed

1 file changed

+31
-4
lines changed

R/PLSDA_class.R

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -136,12 +136,27 @@ prob=function(x,yhat,ytrue)
136136

137137
# threshold where distributions cross
138138
t=gauss_intersect(m1,m2,s1,s2)
139-
t=Re(t) # only take real part
140-
if (length(t)>1)
141-
{
139+
140+
if (is.complex(t)) {
141+
# get the real values but only if the imaginary part is small
142+
w=which(abs(Im(t)) < 1e-6)
143+
if (length(w)==0){
144+
t=0 # all imaginary parts too large, so default to 0
145+
}
146+
t=Re(t[w])
147+
}
148+
149+
if (length(t)>1) {
142150
# multiple cross over points so choose the one closest to 0
143151
t=t[which.min(abs(t))]
144152
}
153+
154+
if (is.na(t)) {
155+
# if polyroot failed return 0
156+
t=0
157+
}
158+
159+
145160
threshold[i]=t
146161
}
147162
d$ingroup=din/(din+dout) # assume probabilities sum to 1
@@ -160,7 +175,19 @@ gauss_intersect=function(m1,m2,s1,s2)
160175
a=(1/(2*s1*s1))-(1/(2*s2*s2))
161176
b=(m2/(s2*s2)) - (m1/(s1*s1))
162177
c=((m1*m1) / (2*s1*s1)) - ((m2*m2)/(2*s2*s2)) - log(s2/s1)
163-
return(polyroot(c(c,b,a))) # in reverse order vs numpy.roots
178+
t=tryCatch({
179+
g=polyroot(c(c,b,a))
180+
return(g)
181+
},warning=function(w) {
182+
g = NA # polyroot unreliable so return NA
183+
return(g)
184+
}, error=function(e) {
185+
g = NA # polyroot failed so return NA
186+
return(g)
187+
}
188+
)
189+
190+
return() # in reverse order vs numpy.roots
164191
}
165192

166193
vips<-function(object)

0 commit comments

Comments
 (0)