-
Notifications
You must be signed in to change notification settings - Fork 0
/
ZMX.R
80 lines (68 loc) · 2.42 KB
/
ZMX.R
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
#Read/write a PB ZMX file
#
#Ben Stabler, [email protected], 080509
#Brian Gregor, [email protected], 052913
#Write updated to use 7zip - requires 7zip installed: http://www.7-zip.org
# Ben Stabler, [email protected], 01/23/15
#Read updated to use gzcon and unz, which is much faster than before
# Ben Stabler, [email protected], 01/22/16
#
#readZipMat("sovDistAm.zmx")
#writeZipMat(Matrix, "sovDistAm.zmx")
#Read ZMX File
readZipMat = function(fileName) {
#define matrix
rowCon = unz(fileName,"_rows")
colCon = unz(fileName,"_columns")
xRowNumCon = unz(fileName,"_external row numbers")
xColNumCon = unz(fileName,"_external column numbers")
nrows = as.integer(scan(rowCon, what="", quiet=T))
ncols = as.integer(scan(colCon, what="", quiet=T))
rowNames = strsplit(scan(xRowNumCon, what="", quiet=T),",")[[1]]
colNames = strsplit(scan(xColNumCon, what="", quiet=T),",")[[1]]
close(rowCon)
close(colCon)
close(xRowNumCon)
close(xColNumCon)
#create matrix
outMat = matrix(0, nrows, ncols)
rownames(outMat) = rowNames
colnames(outMat) = colNames
#read records
zipEntries = paste("row_", 1:nrows, sep="")
for(i in 1:nrows) {
con = unz(fileName,zipEntries[i],"rb")
outMat[i,] = readBin(con,what=double(),n=ncols, size=4, endian="big")
close(con)
}
#return matrix
return(outMat)
}
#Write ZMX File
writeZipMat = function(Matrix, FileName, SevenZipExe="C:/Program Files/7-Zip/7z.exe") {
#Make a temporary directory to put unzipped files into
tempDir = tempdir()
print(tempDir)
oldDir = getwd()
setwd(tempDir)
#Write matrix attributes
cat(2, file="_version")
cat(FileName, file="_name")
cat(FileName, file="_description")
cat(nrow(Matrix), file="_rows")
cat(ncol(Matrix), file="_columns")
cat(paste(rownames(Matrix),collapse=","), file="_external row numbers")
cat(paste(colnames(Matrix),collapse=","), file="_external column numbers")
#Write rows
for(i in 1:nrow(Matrix)) {
writeBin(Matrix[i,], paste("row_", i, sep=""), size=4, endian="big")
}
#Create file
filesToInclude = normalizePath(dir(tempDir, full.names=T))
filesToInclude = paste(paste('"', filesToInclude, '"\n', sep=""), collapse=" ")
listFileName = paste(tempDir, "\\listfile.txt", sep="")
write(filesToInclude, listFileName)
setwd(oldDir)
command = paste(paste('"', SevenZipExe, '"', sep=""), " a -tzip ", FileName, " @", listFileName, sep="")
system(command)
}