# jmatrixsc

#### Juan Domingo

# Please, read this

This is a copy of the vignette of package `jmatrix`. It is included here since `jmatrix` is underlying this package and you will need to know how to prepare your data to be processed by `scellpam`. But you must NOT load package `jmatrix`; all the functions detailed below are already included into `scellpam` and are available just by loading it with `library(scellpam)`.

    library(scellpam)

# Purpose

The package `jmatrix` (Domingo (2023b)) was originally conceived as a tool for other packages, namely `parallelpam` (Domingo (2023c)) and `scellpam` (Domingo (2023a)) which needed to deal with very big matrices which might not fit in the memory of the computer, particularly if their elements are of type `double` (in most modern machines, 8 bytes per element) whereas they could fit if they were matrices of other data types, in particular of floats (4 bytes per element).

Unfortunately, R is not a strongly typed language. Double is the default type in R and it is not easy to work with other data types. Trials like the package float (Schmidt (2022)) have been done, but to use them you have to coerce a matrix already loaded in R memory to a float matrix, and then you can delete it. But, what happens if you computer has not memory enough to hold the matrix in the first place?. This is the problem this package tries to address.

Our idea is to use the disk as temporarily storage of the matrix in a file with a internal binary format (`jmatrix` format). This format has a header of 128 bytes with information like type of matrix (full, sparse or symmetric), data type of each element (char, short, int, long, float, double or long double), number of rows and columns and endianness; then comes the content as binary data (in sparse matrices zeros are not stored; in symmetric matrices only the lower-diagonal is stored) and finally the metadata (currently, names for rows/columns if needed and an optional comment).

Such files are created and loaded by functions written in C++ which are accessible from `R` with Rcpp (Eddelbuettel and François (2011)). The file, once loaded, uses strictly the needed memory for its data type and can be processed by other C++ functions (like the PAM algorithm or any other numeric library written in C++) also from inside `R`.

The matrix contained in a binary data file in `jmatrix` format cannot be loaded directly in `R` memory as a `R` matrix (that would be impossible, anyway, since precisely this package is done for the cases in which such matrix would NOT fit into the available RAM). Nevertheless, limited access through some functions is provided to read one or more rows or one or more columns as `R` vectors or matrices (obviously, coerced to double).

The package `jmatrix` must not be considered as a final, finished software. Currently is mostly an instrumental solution to address our needs and we make available as a separate package just in case it could be useful for anyone else.

# Workflow

## Debug messages

First of all, the package can show quite informative (but sometimes verbose) messages in the console. To turn on/off such messages you can use.

    ScellpamSetDebug(TRUE,TRUE,TRUE)
    #> Debugging for scellpam (biological part) of the package set to ON.
    #> Debugging for parallelpam inside scellpam package set to ON.
    #> Debugging for jmatrix inside scellpam package set to ON.
    # Initially, state of debug is FALSE.

## Data storage

As stated before, the binary matrix files should normally be created from C++ getting the data from an external source like a data file in a format used in bioinformatics or a .csv file. These files should be read by chunks. As an example, look at function `CsvToJMat` in package `scellpam`.

As a convenience and only for testing purposes (to be used in this vignette), we provide the function `JWriteBin` to write a R matrix as a `jmatrix` file.

    # Create a 6x8 matrix of random values
    Rf <- matrix(runif(48),nrow=6)
    # Set row and column names for it
    rownames(Rf) <- c("A","B","C","D","E","F")
    colnames(Rf) <- c("a","b","c","d","e","f","g","h")
    # Let's see the matrix
    Rf
    #>           a         b         c          d          e         f         g
    #> A 0.6696851 0.8578017 0.3020567 0.50658462 0.07616901 0.7832231 0.7009153
    #> B 0.2227856 0.1331562 0.1505534 0.06968315 0.03594645 0.5828077 0.6146703
    #> C 0.6697792 0.3956704 0.8700933 0.58231319 0.63222692 0.4784611 0.2693743
    #> D 0.7396226 0.2343066 0.9294285 0.63964725 0.61226819 0.2167763 0.8224437
    #> E 0.4466017 0.5514376 0.5182877 0.77220898 0.91617740 0.9787335 0.8908885
    #> F 0.3547610 0.5895073 0.9856993 0.18686308 0.76085484 0.7299589 0.6280631
    #>           h
    #> A 0.9617832
    #> B 0.8846715
    #> C 0.9482599
    #> D 0.2063947
    #> E 0.3211114
    #> F 0.1435706
    # and write it as the binary file Rfullfloat.bin
    JWriteBin(Rf,"Rfullfloat.bin",dtype="float",dmtype="full",
              comment="Full matrix of floats")
    #> The passed matrix has row names for the 6 rows and they will be used.
    #> The passed matrix has column names for the 8 columns and they will be used.
    #> Writing binary matrix Rfullfloat.bin of (6x8)
    #> End of block of binary data at offset 320
    #>    Writing row names (6 strings written, from A to F).
    #>    Writing column names (8 strings written, from a to h).
    #>    Writing comment: Full matrix of floats
    # Also, you can write it with double data type:
    JWriteBin(Rf,"Rfulldouble.bin",dtype="double",dmtype="full",
              comment="Full matrix of doubles")
    #> The passed matrix has row names for the 6 rows and they will be used.
    #> The passed matrix has column names for the 8 columns and they will be used.
    #> Writing binary matrix Rfulldouble.bin of (6x8)
    #> End of block of binary data at offset 512
    #>    Writing row names (6 strings written, from A to F).
    #>    Writing column names (8 strings written, from a to h).
    #>    Writing comment: Full matrix of doubles

To get information about the stored file the function `JMatInfo` is provided. Of course, this funcion does not read the complete file in memory but just the header.

    # Information about the float binary file
    JMatInfo("Rfullfloat.bin")
    #> File:               Rfullfloat.bin
    #> Matrix type:        FullMatrix
    #> Number of elements: 48
    #> Data type:          float
    #> Endianness:         little endian (same as this machine)
    #> Number of rows:     6
    #> Number of columns:  8
    #> Metadata:           Stored names of rows and columns.
    #> Metadata comment:  "Full matrix of floats"
    # Same information about the double binary file
    JMatInfo("Rfulldouble.bin")
    #> File:               Rfulldouble.bin
    #> Matrix type:        FullMatrix
    #> Number of elements: 48
    #> Data type:          double
    #> Endianness:         little endian (same as this machine)
    #> Number of rows:     6
    #> Number of columns:  8
    #> Metadata:           Stored names of rows and columns.
    #> Metadata comment:  "Full matrix of doubles"

A jmatrix binary file can be exported to .csv/.tsv table. This is done with the function `JMatToCsv`

    # Create a 6x8 matrix of random values
    Rf <- matrix(runif(48),nrow=6)
    # Set row and column names for it
    rownames(Rf) <- c("A","B","C","D","E","F")
    colnames(Rf) <- c("a","b","c","d","e","f","g","h")
    # Store it as the binary file Rfullfloat.bin
    JWriteBin(Rf,"Rfullfloat.bin",dtype="float",dmtype="full",
              comment="Full matrix of floats")
    #> The passed matrix has row names for the 6 rows and they will be used.
    #> The passed matrix has column names for the 8 columns and they will be used.
    #> Writing binary matrix Rfullfloat.bin of (6x8)
    #> End of block of binary data at offset 320
    #>    Writing row names (6 strings written, from A to F).
    #>    Writing column names (8 strings written, from a to h).
    #>    Writing comment: Full matrix of floats
    # Save the content of this .bin as a .csv file
    JMatToCsv("Rfullfloat.bin","Rfullfloat.csv",csep=",",withquotes=FALSE)
    #> Read full matrix with size (6,8)

The generated file will not have quotes neither around the column names (in its first line) nor around each row name (at the beginning of each line) since withquotes is FALSE but it can be set to TRUE for the opposite behavior. Also, a .tsv (tabulator separated values) would have been generated using csep=“\t”.

Also, a jmatrix binary file can also be generated from a .csv/.tsv file. Such file must have a first line with the names of the columns (possibly surrounded by double quotes, including a first empty double-quote, since the column of row names has no name itself). The rest of its lines must start with a string (possibly surrounded by double quotes) with the row name and the values. In all cases (first line and data lines) each column must be separated from the next by a separation character (usually, a comma). No separation character must be added at the end of each line. This format is compatible with the .csv generated by R with the function `write.csv`.

The function to read .csv files is `CsvToJMat`

    # Create a 6x8 matrix of random values
    Rf <- matrix(runif(48),nrow=6)
    # Set row and column names for it
    rownames(Rf) <- c("A","B","C","D","E","F")
    colnames(Rf) <- c("a","b","c","d","e","f","g","h")
    # Save it as a .csv file with the standard R function...
    write.csv(Rf,"rf.csv")
    # ...and read it to create a jmatrix binary file
    CsvToJMat("rf.csv","rf.bin",mtype="full",csep=",",ctype="raw",valuetype="float",transpose=FALSE,comment="Test matrix generated reading a .csv file")
    #> 8 columns of values (not including the column of names) in file rf.csv.
    #> 6 lines (excluding header) in file rf.csv
    #> Data will be read from each line and stored as float values.
    #> Reading line... 0
    #> Read 6 data lines of file rf.csv, as expected.
    #> Writing binary matrix rf.bin of (6x8)
    #> End of block of binary data at offset 320
    #>    Writing row names (6 strings written, from A to F).
    #>    Writing column names (8 strings written, from a to h).
    #>    Writing comment: Test matrix generated reading a .csv file
    # Let's see the characteristics of the binary file
    JMatInfo("rf.bin")
    #> File:               rf.bin
    #> Matrix type:        FullMatrix
    #> Number of elements: 48
    #> Data type:          float
    #> Endianness:         little endian (same as this machine)
    #> Number of rows:     6
    #> Number of columns:  8
    #> Metadata:           Stored names of rows and columns.
    #> Metadata comment:  "Test matrix generated reading a .csv file"

### Special note for symmetric matrices:

The parameter mtype=“symmetric” will consider the content of the .csv file as a symmetric matrix. This implies that it must be a square matrix (same number of rows and columns) but the upper-diagonal matrix that must be present (it does not matter with which values) will be read, and immediately ignored, i.e.: only the lower-diagonal matrix (including the main diagonal) will be stored.

## Data load

As stated before, no function is provided to read the whole matrix in memory which would contradict the philosophy of this package, but you can get rows or columns from a file.

    # Reads row 1 into vector vf. Float values inside the file are
    # promoted to double.
    (vf<-GetJRow("Rfullfloat.bin",1))
    #>           a           b           c           d           e           f
    #> 0.577359200 0.273662329 0.003547955 0.429528981 0.655562162 0.243750870
    #>           g           h
    #> 0.593012810 0.817924798

Obviously, storage in float provokes a loosing of precision. We have observed this not to be relevant for `PAM` (partitioning around medoids) algorihm but it can be important in other cases. It is the price to pay for halving the needed space.

    # Checks the precision lost
    max(abs(Rf[1,]-vf))
    #> [1] 0.7374214

Nevertheless, storing as double obviously keeps the data intact.

    vd<-GetJRow("Rfulldouble.bin",1)
    max(abs(Rf[1,]-vd))
    #> [1] 0.6004861

Now, let us see examples of some functions to read rows or columns by number or by name, or to read several rows/columns as a R matrix. In all examples numbers for rows and columns are in R-convention (i.e. starting at 1)

    # Read column number 3
    (vf<-GetJCol("Rfullfloat.bin",3))
    #>           A           B           C           D           E           F
    #> 0.003547955 0.919409037 0.700763881 0.423173040 0.787252307 0.682436585
    # Test precision
    max(abs(Rf[,3]-vf))
    #> [1] 0.7066479
    # Read row with name C
    (vf<-GetJRowByName("Rfullfloat.bin","C"))
    #>          a          b          c          d          e          f          g
    #> 0.70377225 0.12205330 0.70076388 0.04194048 0.81096894 0.91793907 0.71686345
    #>          h
    #> 0.21611275
    # Read column with name c
    (vf<-GetJColByName("Rfullfloat.bin","c"))
    #>           A           B           C           D           E           F
    #> 0.003547955 0.919409037 0.700763881 0.423173040 0.787252307 0.682436585
    # Get the names of all rows or columns as vectors of R strings
    (rn<-GetJRowNames("Rfullfloat.bin"))
    #> [1] "A" "B" "C" "D" "E" "F"
    (cn<-GetJColNames("Rfullfloat.bin"))
    #> [1] "a" "b" "c" "d" "e" "f" "g" "h"
    # Get the names of rows and columns simultaneosuly as a list of two elements
    (l<-GetJNames("Rfullfloat.bin"))
    #> $rownames
    #> [1] "A" "B" "C" "D" "E" "F"
    #>
    #> $colnames
    #> [1] "a" "b" "c" "d" "e" "f" "g" "h"
    # Get several rows at once. The returned matrix has the rows in the
    # same order as the passed list,
    # and this list can contain even repeated values
    (vm<-GetJManyRows("Rfullfloat.bin",c(1,4)))
    #>            a          b           c         d         e         f           g
    #> A 0.57735920 0.27366233 0.003547955 0.4295290 0.6555622 0.2437509 0.593012810
    #> D 0.01306094 0.04315013 0.423173040 0.3257324 0.7127851 0.7040681 0.005519667
    #>           h
    #> A 0.8179248
    #> D 0.3110617

    # Of course, columns can be extrated equally
    (vc<-GetJManyCols("Rfulldouble.bin",c(1,4)))
    #>           a          d
    #> A 0.6696851 0.50658462
    #> B 0.2227856 0.06968315
    #> C 0.6697792 0.58231319
    #> D 0.7396226 0.63964725
    #> E 0.4466017 0.77220898
    #> F 0.3547610 0.18686308
    # and similar functions are provided for extracting by names:
    (vm<-GetJManyRowsByNames("Rfulldouble.bin",c("A","D")))
    #>           a         b         c         d          e         f         g
    #> A 0.6696851 0.8578017 0.3020567 0.5065846 0.07616901 0.7832231 0.7009153
    #> D 0.7396226 0.2343066 0.9294285 0.6396473 0.61226819 0.2167763 0.8224437
    #>           h
    #> A 0.9617832
    #> D 0.2063947
    (vc<-GetJManyColsByNames("Rfulldouble.bin",c("a","d")))
    #>           a          d
    #> A 0.6696851 0.50658462
    #> B 0.2227856 0.06968315
    #> C 0.6697792 0.58231319
    #> D 0.7396226 0.63964725
    #> E 0.4466017 0.77220898
    #> F 0.3547610 0.18686308

The package can manage and store sparse and symmetric matrices, too.

    # Generation of a 6x8 sparse matrix
    Rsp <- matrix(rep(0,48),nrow=6)
    sparsity <- 0.1
    nnz <- round(48*sparsity)
    where <- floor(47*runif(nnz))
    val <- runif(nnz)
    for (i in 1:nnz)
    {
     Rsp[floor(where[i]/8)+1,(where[i]%%8)+1] <- val[i]
    }
    rownames(Rsp) <- c("A","B","C","D","E","F")
    colnames(Rsp) <- c("a","b","c","d","e","f","g","h")
    # Let's see the matrix
    Rsp
    #>           a        b c          d         e f g         h
    #> A 0.0000000 0.000000 0 0.08821962 0.0000000 0 0 0.0000000
    #> B 0.6711437 0.000000 0 0.00000000 0.0000000 0 0 0.0000000
    #> C 0.0000000 0.000000 0 0.00000000 0.3650302 0 0 0.0000000
    #> D 0.0000000 0.000000 0 0.00000000 0.0000000 0 0 0.0000000
    #> E 0.0000000 0.378279 0 0.00000000 0.0000000 0 0 0.9786728
    #> F 0.0000000 0.000000 0 0.00000000 0.0000000 0 0 0.0000000
    # Write the matrix as sparse with type float
    JWriteBin(Rsp,"Rspafloat.bin",dtype="float",dmtype="sparse",
              comment="Sparse matrix of floats")
    #> The passed matrix has row names for the 6 rows and they will be used.
    #> The passed matrix has column names for the 8 columns and they will be used.
    #> Writing binary matrix Rspafloat.bin of (6x8)
    #> End of block of binary data at offset 192
    #>    Writing row names (6 strings written, from A to F).
    #>    Writing column names (8 strings written, from a to h).
    #>    Writing comment: Sparse matrix of floats

Notice that the condition of being a sparse matrix and the storage space used can be known with the matrix info.

    JMatInfo("Rspafloat.bin")
    #> File:               Rspafloat.bin
    #> Matrix type:        SparseMatrix
    #> Number of elements: 48
    #> Data type:          float
    #> Endianness:         little endian (same as this machine)
    #> Number of rows:     6
    #> Number of columns:  8
    #> Metadata:           Stored names of rows and columns.
    #> Metadata comment:  "Sparse matrix of floats"
    #> Binary data size:   64 bytes, which is 33.3333% of the full matrix size (which would be 192 bytes).

Be careful: trying to store as sparse a matrix which is not (it has not a majority of 0-entries) works, but produces a matrix larger than the corresponding full matrix.

With respect to symmetric matrices, `JWriteBin` works the same way. Let us generate a \(7 \times 7\) symmetric matrix.

    Rns <- matrix(runif(49),nrow=7)
    Rsym <- 0.5*(Rns+t(Rns))
    rownames(Rsym) <- c("A","B","C","D","E","F","G")
    colnames(Rsym) <- c("a","b","c","d","e","f","g")
    # Let's see the matrix
    Rsym
    #>           a           b          c          d         e         f          g
    #> A 0.9459231 0.500615277 0.38453235 0.67627339 0.5901613 0.6274743 0.47639276
    #> B 0.5006153 0.003367118 0.59336424 0.52558831 0.5265700 0.6185457 0.70061728
    #> C 0.3845323 0.593364236 0.56576417 0.29576158 0.2254669 0.3809581 0.09688214
    #> D 0.6762734 0.525588306 0.29576158 0.77212842 0.7620326 0.4951943 0.08897509
    #> E 0.5901613 0.526569990 0.22546690 0.76203261 0.5166262 0.7804015 0.13477464
    #> F 0.6274743 0.618545682 0.38095806 0.49519430 0.7804015 0.5691856 0.54481534
    #> G 0.4763928 0.700617278 0.09688214 0.08897509 0.1347746 0.5448153 0.30508303
    # Write the matrix as symmetric with type float
    JWriteBin(Rsym,"Rsymfloat.bin",dtype="float",dmtype="symmetric",
              comment="Symmetric matrix of floats")
    #> The passed matrix has row names for the 7 rows and they will be used.
    #> Writing binary matrix Rsymfloat.bin
    #> End of block of binary data at offset 240
    #>    Writing row names (7 strings written, from A to G).
    #>    Writing comment: Symmetric matrix of floats
    # Get the information
    JMatInfo("Rsymfloat.bin")
    #> File:               Rsymfloat.bin
    #> Matrix type:        SymmetricMatrix
    #> Number of elements: 49 (28 really stored)
    #> Data type:          float
    #> Endianness:         little endian (same as this machine)
    #> Number of rows:     7
    #> Number of columns:  7
    #> Metadata:           Stored only names of rows.
    #> Metadata comment:  "Symmetric matrix of floats"

Notice that if you store a R matrix which is NOT symmetric as a symmetric `jmatrix`, only the lower triangular part (including the main diagonal) will be saved. The upper-triangular part will be lost.

The functions to read rows/colums stated before works equally independently of the matrix character (full, sparse or symmetric) so you can play with them using the `Rspafloat.bin` and `Rsymfloat.bin` file to check they work.

If the jmatrix stored in a binary file has names associated to rows or columns, you can filter it using them and generate another jmatrix file with only the rows or columns you wish to keep. The function to do so is ‘FilterJMatByName’.

    Rns <- matrix(runif(49),nrow=7)
    rownames(Rns) <- c("A","B","C","D","E","F","G")
    colnames(Rns) <- c("a","b","c","d","e","f","g")
    # Let's see the matrix
    Rns
    #>             a          b         c         d          e          f         g
    #> A 0.469397791 0.11537064 0.9881718 0.1012687 0.84926888 0.88461990 0.6458684
    #> B 0.533307226 0.66905418 0.2686082 0.2753178 0.48148338 0.94058022 0.3675294
    #> C 0.647232194 0.01073514 0.2820836 0.2470050 0.72307326 0.05315989 0.7615902
    #> D 0.961584122 0.78471743 0.3717574 0.8976698 0.58215172 0.58914916 0.5369714
    #> E 0.768689241 0.07402659 0.4091635 0.1245653 0.15316566 0.07033232 0.2647625
    #> F 0.003652655 0.12835040 0.1298656 0.0962747 0.09495854 0.18638222 0.1648992
    #> G 0.931171369 0.14837874 0.9212196 0.9292377 0.74870132 0.14225576 0.5516723
    # Write the matrix as full with type float
    JWriteBin(Rns,"Rfullfloat.bin",dtype="float",dmtype="full",
              comment="Full matrix of floats")
    #> The passed matrix has row names for the 7 rows and they will be used.
    #> The passed matrix has column names for the 7 columns and they will be used.
    #> Writing binary matrix Rfullfloat.bin of (7x7)
    #> End of block of binary data at offset 324
    #>    Writing row names (7 strings written, from A to G).
    #>    Writing column names (7 strings written, from a to g).
    #>    Writing comment: Full matrix of floats
    # Extract the first two and the last two columns
    FilterJMatByName("Rfullfloat.bin",c("a","b","f","g"),"Rfullfloat_fourcolumns.bin",namesat="cols")
    #> Read full matrix with size (7,7)
    #> 4 columns of the 7 in the original matrix will be kept.
    #> Writing binary matrix Rfullfloat_fourcolumns.bin of (7x4)
    #> End of block of binary data at offset 240
    #>    Writing row names (7 strings written, from A to G).
    #>    Writing column names (4 strings written, from a to g).
    #>    Writing comment: Full matrix of floats
    # Let's load the matrix and let's see it
    vm<-GetJManyRows("Rfullfloat_fourcolumns.bin",c(1,7))
    vm
    #>           a         b         f         g
    #> A 0.4693978 0.1153706 0.8846199 0.6458684
    #> G 0.9311714 0.1483787 0.1422558 0.5516723

Domingo, Juan. 2023a. Applying Partitioning Around Medoids to Single Cell Data with High Number of Cells.
———. 2023b. Jmatrix: Read from/Write to Disk Matrices with Any Data Type in a Binary Format.
———. 2023c. Parallelpam: Applies the Partitioning-Around-Medoids (PAM) Clustering Algorithm to Big Sets of Data Using Parallel Implementation, If Several Cores Are Available.
Eddelbuettel, Dirk, and Romain François. 2011. “Rcpp: Seamless R and C++ Integration.” Journal of Statistical Software 40 (8): 1–18. https://doi.org/10.18637/jss.v040.i08.
Schmidt, Drew. 2022. “float: 32-Bit Floats.” https://cran.r-project.org/package=float.