-
Notifications
You must be signed in to change notification settings - Fork 3
/
NormalizeQuantiles.jl
310 lines (280 loc) · 10.1 KB
/
NormalizeQuantiles.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
module NormalizeQuantiles
export normalizeQuantiles
export sampleRanks
export qnTiesMethods,tmMin,tmMax,tmOrder,tmReverse,tmRandom,tmAverage
using Distributed
using SharedArrays
using Random
using Statistics
@enum qnTiesMethods tmMin tmMax tmOrder tmReverse tmRandom tmAverage
function checkForNotANumber(x::Any)
(!isa(x,Integer) && !isa(x,Real)) || isnan(x)
end
@doc "
### qnmatrix::Array{Float64} function normalizeQuantiles(matrix::AbstractArray)
Calculate the quantile normalized data for the input matrix
Parameter:
matrix::AbstractArray
The input data as an array of values interpreted as matrix(rows,columns)
Return value:
qnmatrix::Array{Float64}
The quantile normalized data as Array{Float64}
Example:
using NormalizeQuantiles
array = [ 3.0 2.0 1.0 ; 4.0 5.0 6.0 ; 9.0 7.0 8.0 ; 5.0 2.0 8.0 ]
qn = normalizeQuantiles(array)
row = 2
column = 2
array=convert(Array{Any},array)
array[row,column] = missing
qn = normalizeQuantiles(array)
"
function normalizeQuantiles(matrix::AbstractArray)
if ndims(matrix) > 2
throw(ArgumentError("normalizeQuantiles expects an array of dimension 2"))
end
nrows=size(matrix,1)
ncols=size(matrix,2)
# preparing the result matrix
qnmatrix=SharedArray{Float64}(nrows,ncols)
if ncols>0 && nrows>0
# foreach column: sort the values without NAs; put NAs (if any) back into sorted list
NormalizeQuantiles.sortColumns!(matrix,qnmatrix)
# foreach row: set all values to the mean of the row, except NAs
NormalizeQuantiles.meanRows!(qnmatrix)
# foreach column: equal values in original column should all be mean of normalized values
# foreach column: reorder the values back to the original order
NormalizeQuantiles.equalValuesInColumnAndOrderToOriginal!(matrix,qnmatrix,nrows)
end
convert(Array{Float64},qnmatrix)
end
function sortColumns!(matrix::AbstractArray,qnmatrix::SharedArray{Float64})
ncols=size(matrix,2)
tcols=1:ncols
scolumns=collect(eachindex(matrix[end,:]))
@inbounds @sync @distributed for tcol in tcols
scolumn=scolumns[tcol]
sortcol=[ NormalizeQuantiles.checkForNotANumber(x) ? NaN : Float64(x) for x in matrix[:,scolumn] ]
missingIndices=findall(isnan.(sortcol))
sort!(sortcol)
#putting original NaNs back into place:
nMissPos=lastindex(missingIndices)
delta=nMissPos
index=lastindex(sortcol)
while nMissPos>0
missingPos=missingIndices[nMissPos]
if index==missingPos
sortcol[index]=NaN
nMissPos-=1
delta-=1
else
sortcol[index]=sortcol[index-delta]
end
index-=1
end
qnmatrix[:,tcol]=sortcol
end
end
function meanRows!(qnmatrix::SharedArray{Float64})
@inbounds @sync @distributed for srow = eachindex(qnmatrix[:,end])
goodIndices=.!isnan.(qnmatrix[srow,:])
rowView=view(qnmatrix,srow,goodIndices)
#rowmean=mean(rowView)
#
#in julia function sum the order of summing up the elements can vary on different
#types of AbstractArray (e.g. qnmatrix[row,goodIndices] and rowView). Summing over
#a large number of floats in different order yield different results because of
#floating point precision, so we calculate the sum in a well defined way:
lrow=length(rowView)
sum=0.0
for i in eachindex(rowView)
sum+=rowView[i]
end
rowmean=sum/lrow
rowView.=rowmean
end
end
function equalValuesInColumnAndOrderToOriginal!(matrix::AbstractArray,qnmatrix::SharedArray{Float64},nrows)
ncols=size(matrix,2)
tcols=1:ncols
scolumns=collect(eachindex(matrix[end,:]))
@inbounds @sync @distributed for tcol in tcols
scolumn=scolumns[tcol]
goodIndices=.!isnan.(qnmatrix[:,tcol])
#matrix can be an OffsetArray
colview=view(matrix,collect(eachindex(matrix[:,scolumn]))[goodIndices],scolumn)
sortp=sortperm(Float64.(colview))
if length(sortp)>0
NormalizeQuantiles.setMeanForEqualOrigValues!(colview[sortp],qnmatrix,tcol,goodIndices)
end
qnmatrix[(1:nrows)[goodIndices][sortp],tcol]=qnmatrix[goodIndices,tcol]
end
end
function setMeanForEqualOrigValues!(sortedArrayNoNAs::AbstractArray,qnmatrix::SharedArray{Float64},column::Int,goodIndices)
nrows=length(sortedArrayNoNAs)
foundIndices=zeros(Int,nrows)
goodIndices2=findall(goodIndices)
count=1
lastValue=sortedArrayNoNAs[1]
for i in 2:nrows
nextValue=sortedArrayNoNAs[i]
foundIndices[count]=goodIndices2[i-1]
if nextValue==lastValue
count+=1
else
if count>1
qnmatrix[foundIndices[1:count],column].=mean(qnmatrix[foundIndices[1:count],column])
count=1
end
end
lastValue=nextValue
end
foundIndices[count]=goodIndices2[nrows]
if count>1
qnmatrix[foundIndices[1:count],column].=mean(qnmatrix[foundIndices[1:count],column])
end
end
@doc "
### (Array{Union{Missing,Int}},Dict{Int,Array{Int}}) sampleRanks(array::AbstractArray;tiesMethod::qnTiesMethods=tmMin,naIncreasesRank=false,resultMatrix=false)
Calculate ranks of the values of a given vector.
Parameters:
array: the input array
tiesMethod: the method how ties (equal values) are treated
possible values: tmMin tmMax tmOrder tmReverse tmRandom tmAverage
default is tmMin
naIncreasesRank: if true than any NA increases the following ranks by 1
resultMatrix: if true than return a dictionary of rank keys and array of indices values
Example:
using NormalizeQuantiles
a = [ 5.0 2.0 4.0 3.0 1.0 ]
(r,m)=sampleRanks(a)
(r,m)=sampleRanks(a,tiesMethod=tmMin,naIncreasesRank=false,resultMatrix=true)
r is the vector of ranks.
m is a dictionary with rank as keys and as value the indices of all values of this rank.
"
function sampleRanks(array::AbstractArray;tiesMethod::qnTiesMethods=tmMin,naIncreasesRank::Bool=false,resultMatrix::Bool=false)
nrows=length(array)
naCounts=zeros(Int,nrows)
goodIndices=falses(nrows)
naCount=0
reducedIndex=1
goodIndex=1
for arrayIndex in eachindex(array)
if NormalizeQuantiles.checkForNotANumber(array[arrayIndex])
naCount+=1
else
goodIndices[goodIndex]=true
naCounts[reducedIndex]=naCount
reducedIndex+=1
end
goodIndex+=1
end
reducedArraySorted=Float64.(array[goodIndices])
reducedArraySortedIndices=sortperm(reducedArraySorted)
reducedArraySorted=reducedArraySorted[reducedArraySortedIndices]
result=Array{Union{Missing,Int}}(missing,nrows)
rankMatrix=Dict{Int,Array{Int}}()
group = Array{Int,1}()
firstFound = true
lastFound = NaN
nextRank=1
rankIncrement=0
doIncreaseRank=false
headingNA=false
groupIndex=1
offset=firstindex(array)-groupIndex
for resultIndex in eachindex(array)
if goodIndices[resultIndex]
if headingNA
headingNA=false
if doIncreaseRank
nextRank+=rankIncrement
rankIncrement=0
doIncreaseRank=false
end
end
reducedArrayIndex=reducedArraySortedIndices[groupIndex]
if !firstFound && lastFound != reducedArraySorted[groupIndex]
nextRank = NormalizeQuantiles.setRank!(group,nextRank,offset,tiesMethod,result,resultMatrix,rankMatrix)
group = [naCounts[reducedArrayIndex]+reducedArrayIndex+offset]
if doIncreaseRank
nextRank+=rankIncrement
rankIncrement=0
doIncreaseRank=false
end
else
push!(group,naCounts[reducedArrayIndex]+reducedArrayIndex+offset)
end
lastFound = reducedArraySorted[groupIndex]
firstFound = false
groupIndex+=1
else
if naIncreasesRank
doIncreaseRank=true
rankIncrement+=1
end
if firstFound
headingNA=true
end
end
end
NormalizeQuantiles.setRank!(group,nextRank,offset,tiesMethod,result,resultMatrix,rankMatrix)
(result,rankMatrix)
end
function setRank!(group::Array{Int},nextRank::Int,offset::Int,tiesMethod::qnTiesMethods,result::Array{Union{Missing,Int}},resultMatrix::Bool,rankMatrix::Dict{Int,Array{Int}})
ranksCount=length(group)
ranks=nextRank:(nextRank+ranksCount-1)
if tiesMethod==tmMin
minRank=minimum(ranks)
result[group.-offset].=minRank
if resultMatrix
rankMatrix[minRank]=group
end
nextRank+=1
elseif tiesMethod==tmMax
maxRank=maximum(ranks)
result[group.-offset].=maxRank
if resultMatrix
rankMatrix[maxRank]=group
end
nextRank=maxRank+1
elseif tiesMethod==tmOrder
maxRank=maximum(ranks)
result[group.-offset]=ranks
if resultMatrix
for rankIndex in 1:length(ranks)
rankMatrix[ranks[rankIndex]]=[group[rankIndex]]
end
end
nextRank=maxRank+1
elseif tiesMethod==tmReverse
maxRank=maximum(ranks)
ranks=reverse(ranks,dims=1)
result[group.-offset]=ranks
if resultMatrix
for rankIndex in 1:length(ranks)
rankMatrix[ranks[rankIndex]]=[group[rankIndex]]
end
end
nextRank=maxRank+1
elseif tiesMethod==tmRandom
maxRank=maximum(ranks)
ranks=ranks[randperm(ranksCount)]
result[group.-offset]=ranks
if resultMatrix
for rankIndex in 1:length(ranks)
rankMatrix[ranks[rankIndex]]=[group[rankIndex]]
end
end
nextRank=maxRank+1
elseif tiesMethod==tmAverage
rankMean=round(Int,mean(ranks))
result[group.-offset].=rankMean
if resultMatrix
rankMatrix[rankMean]=group
end
nextRank=rankMean+1
end
nextRank
end
end # module