SCM

SCM Repository

[tm] Diff of /pkg/R/corpus.R
ViewVC logotype

Diff of /pkg/R/corpus.R

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 988, Fri Sep 4 12:27:12 2009 UTC revision 1460, Mon Jan 9 17:01:04 2017 UTC
# Line 1  Line 1 
1  # Author: Ingo Feinerer  # Author: Ingo Feinerer
2    
3  .PCorpus <- function(x, cmeta, dmeta, dbcontrol) {  Corpus <-
4      attr(x, "CMetaData") <- cmeta  function(x, readerControl = list(reader = reader(x), language = "en"))
5      attr(x, "DMetaData") <- dmeta  {
6      attr(x, "DBControl") <- dbcontrol      stopifnot(inherits(x, "Source"))
7      class(x) <- c("PCorpus", "Corpus", "list")  
8      x      readerControl <- prepareReader(readerControl, reader(x))
9    
10        if ((inherits(x, "DirSource") || inherits(x, "VectorSource")) &&
11            identical(readerControl$reader, readPlain))
12            SimpleCorpus(x, readerControl)
13        else
14            VCorpus(x, readerControl)
15  }  }
 DBControl <- function(x) attr(x, "DBControl")  
16    
17  PCorpus <- function(x,  PCorpus <-
18                      readerControl = list(reader = x$DefaultReader, language = "eng"),  function(x,
19                      dbControl = list(dbName = "", dbType = "DB1"),           readerControl = list(reader = reader(x), language = "en"),
20                      ...) {           dbControl = list(dbName = "", dbType = "DB1"))
21      readerControl <- prepareReader(readerControl, x$DefaultReader, ...)  {
22        stopifnot(inherits(x, "Source"))
23    
24        readerControl <- prepareReader(readerControl, reader(x))
25    
26      if (!filehash::dbCreate(dbControl$dbName, dbControl$dbType))      if (!filehash::dbCreate(dbControl$dbName, dbControl$dbType))
27          stop("error in creating database")          stop("error in creating database")
28      db <- filehash::dbInit(dbControl$dbName, dbControl$dbType)      db <- filehash::dbInit(dbControl$dbName, dbControl$dbType)
29    
30      # Allocate memory in advance if length is known      x <- open(x)
31      tdl <- if (x$Length > 0)      tdl <- vector("list", length(x))
         vector("list", as.integer(x$Length))  
     else  
         list()  
   
32      counter <- 1      counter <- 1
33      while (!eoi(x)) {      while (!eoi(x)) {
34          x <- stepNext(x)          x <- stepNext(x)
35          elem <- getElem(x)          elem <- getElem(x)
36          doc <- readerControl$reader(elem, readerControl$language, as.character(counter))          doc <- readerControl$reader(elem,
37          filehash::dbInsert(db, ID(doc), doc)                                      readerControl$language,
38          if (x$Length > 0) tdl[[counter]] <- ID(doc)                                      as.character(counter))
39          else tdl <- c(tdl, ID(doc))          filehash::dbInsert(db, meta(doc, "id"), doc)
40            tdl[[counter]] <- meta(doc, "id")
41          counter <- counter + 1          counter <- counter + 1
42      }      }
43        x <- close(x)
44    
45      df <- data.frame(MetaID = rep(0, length(tdl)), stringsAsFactors = FALSE)      p <- list(content = tdl,
46      filehash::dbInsert(db, "DMetaData", df)                meta = CorpusMeta(),
47      dmeta.df <- data.frame(key = "DMetaData", subset = I(list(NA)))                dmeta = data.frame(row.names = seq_along(tdl)),
48                  dbcontrol = dbControl)
49      .PCorpus(tdl, .MetaDataNode(), dmeta.df, dbControl)      class(p) <- c("PCorpus", "Corpus")
50        p
51  }  }
52    
53  .VCorpus <- function(x, cmeta, dmeta) {  SimpleCorpus <-
54      attr(x, "CMetaData") <- cmeta  function(x, control = list(language = "en"))
55      attr(x, "DMetaData") <- dmeta  {
56      class(x) <- c("VCorpus", "Corpus", "list")      stopifnot(inherits(x, "Source"))
57      x  
58        if (!is.null(control$reader) && !identical(control$reader, readPlain))
59            warning("custom reader is ignored")
60    
61        content <- if (inherits(x, "VectorSource")) {
62            if (is.character(x$content)) x$content else as.character(x$content)
63        } else if (inherits(x, "DirSource")) {
64            setNames(as.character(
65                       lapply(x$filelist,
66                              function(f) paste(readContent(f, x$encoding, "text"),
67                                                collapse = "\n"))
68                       ),
69                     basename(x$filelist))
70        } else
71            stop("unsupported source type")
72        s <- list(content = content,
73                  meta = CorpusMeta(language = control$language),
74                  dmeta = data.frame(row.names = seq_along(x)))
75        class(s) <- c("SimpleCorpus", "Corpus")
76        s
77  }  }
78    
79  # The "..." are additional arguments for the FunctionGenerator reader  VCorpus <-
80  VCorpus <- Corpus <- function(x,  function(x, readerControl = list(reader = reader(x), language = "en"))
81                      readerControl = list(reader = x$DefaultReader, language = "eng"),  {
82                      ...) {      stopifnot(inherits(x, "Source"))
     readerControl <- prepareReader(readerControl, x$DefaultReader, ...)  
   
     # Allocate memory in advance if length is known  
     tdl <- if (x$Length > 0)  
         vector("list", as.integer(x$Length))  
     else  
         list()  
83    
84      if (x$Vectorized)      readerControl <- prepareReader(readerControl, reader(x))
85          tdl <- mapply(function(x, id) readerControl$reader(x, readerControl$language, id),  
86        x <- open(x)
87        tdl <- vector("list", length(x))
88        # Check for parallel element access
89        if (is.function(getS3method("pGetElem", class(x), TRUE)))
90            tdl <- mapply(function(elem, id)
91                            readerControl$reader(elem, readerControl$language, id),
92                        pGetElem(x),                        pGetElem(x),
93                        id = as.character(seq_len(x$Length)),                        id = as.character(seq_along(x)),
94                        SIMPLIFY = FALSE)                        SIMPLIFY = FALSE)
95      else {      else {
96          counter <- 1          counter <- 1
97          while (!eoi(x)) {          while (!eoi(x)) {
98              x <- stepNext(x)              x <- stepNext(x)
99              elem <- getElem(x)              elem <- getElem(x)
100              doc <- readerControl$reader(elem, readerControl$language, as.character(counter))              doc <- readerControl$reader(elem,
101              if (x$Length > 0)                                          readerControl$language,
102                                            as.character(counter))
103                  tdl[[counter]] <- doc                  tdl[[counter]] <- doc
             else  
                 tdl <- c(tdl, list(doc))  
104              counter <- counter + 1              counter <- counter + 1
105          }          }
106      }      }
107        x <- close(x)
108    
109      df <- data.frame(MetaID = rep(0, length(tdl)), stringsAsFactors = FALSE)      as.VCorpus(tdl)
     .VCorpus(tdl, .MetaDataNode(), df)  
110  }  }
111    
112  `[.PCorpus` <- function(x, i) {  `[.PCorpus` <-
113      if (missing(i)) return(x)  `[.SimpleCorpus` <-
114      cmeta <- CMetaData(x)  function(x, i)
115      index <- attr(x, "DMetaData")[[1 , "subset"]]  {
116      attr(x, "DMetaData")[[1 , "subset"]] <- if (is.numeric(index)) index[i] else i      if (!missing(i)) {
117      dmeta <- attr(x, "DMetaData")          x$content <- x$content[i]
118      dbcontrol <- DBControl(x)          x$dmeta <- x$dmeta[i, , drop = FALSE]
     class(x) <- "list"  
     .PCorpus(x[i, drop = FALSE], cmeta, dmeta, dbcontrol)  
 }  
   
 `[.VCorpus` <- function(x, i) {  
     if (missing(i)) return(x)  
     cmeta <- CMetaData(x)  
     dmeta <- DMetaData(x)[i, , drop = FALSE]  
     class(x) <- "list"  
     .VCorpus(x[i, drop = FALSE], cmeta, dmeta)  
 }  
   
 `[<-.PCorpus` <- function(x, i, value) {  
     db <- filehash::dbInit(DBControl(x)[["dbName"]], DBControl(x)[["dbType"]])  
     counter <- 1  
     for (id in unclass(x)[i]) {  
         if (identical(length(value), 1)) db[[id]] <- value  
         else db[[id]] <- value[[counter]]  
         counter <- counter + 1  
119      }      }
120      x      x
121  }  }
122    `[.VCorpus` <-
123  `[[.PCorpus` <-  function(x, i) {  function(x, i)
124      db <- filehash::dbInit(DBControl(x)[["dbName"]], DBControl(x)[["dbType"]])  {
125      class(x) <- "list"      if (!missing(i)) {
126      filehash::dbFetch(db, x[[i]])          x$content <- x$content[i]
127  }          x$dmeta <- x$dmeta[i, , drop = FALSE]
128  `[[.VCorpus` <-  function(x, i) {          if (!is.null(x$lazy))
129      lazyTmMap <- meta(x, tag = "lazyTmMap", type = "corpus")              x$lazy$index <- x$lazy$index[i]
     if (!is.null(lazyTmMap))  
         .Call("copyCorpus", x, materialize(x, i))  
     class(x) <- "list"  
     x[[i]]  
 }  
   
 `[[<-.PCorpus` <-  function(x, i, value) {  
     db <- filehash::dbInit(DBControl(x)[["dbName"]], DBControl(x)[["dbType"]])  
     index <- unclass(x)[[i]]  
     db[[index]] <- value  
     x  
130  }  }
 `[[<-.VCorpus` <-  function(x, i, value) {  
     # Mark new objects as not active for lazy mapping  
     lazyTmMap <- meta(x, tag = "lazyTmMap", type = "corpus")  
     if (!is.null(lazyTmMap)) {  
         lazyTmMap$index[i] <- FALSE  
         meta(x, tag = "lazyTmMap", type = "corpus") <- lazyTmMap  
     }  
     # Set the value  
     cl <- class(x)  
     class(x) <- "list"  
     x[[i]] <- value  
     class(x) <- cl  
131      x      x
132  }  }
133    
134  # Update \code{NodeID}s of a CMetaData tree  .map_name_index <-
135  update_id <- function(x, id = 0, mapping = NULL, left.mapping = NULL, level = 0) {  function(x, i)
136      # Traversal of (binary) CMetaData tree with setup of \code{NodeID}s  {
137      set_id <- function(x) {      if (is.character(i))
138          x$NodeID <- id          match(i, meta(x, "id", "local"))
139          id <<- id + 1      else
140          level <<- level + 1          i
         if (length(x$Children) > 0) {  
             mapping <<- cbind(mapping, c(x$Children[[1]]$NodeID, id))  
             left <- set_id(x$Children[[1]])  
             if (level == 1) {  
                 left.mapping <<- mapping  
                 mapping <<- NULL  
141              }              }
             mapping <<- cbind(mapping, c(x$Children[[2]]$NodeID, id))  
             right <- set_id(x$Children[[2]])  
142    
143              x$Children <- list(left, right)  `[[.PCorpus` <-
144          }  function(x, i)
145          level <<- level - 1  {
146          x      i <- .map_name_index(x, i)
147        db <- filehash::dbInit(x$dbcontrol[["dbName"]], x$dbcontrol[["dbType"]])
148        filehash::dbFetch(db, x$content[[i]])
149      }      }
150      list(root = set_id(x), left.mapping = left.mapping, right.mapping = mapping)  `[[.SimpleCorpus` <-
151    function(x, i)
152    {
153        i <- .map_name_index(x, i)
154        n <- names(x$content)
155        PlainTextDocument(x$content[[i]],
156                          id = if (is.null(n)) i else n[i],
157                          language = meta(x, "language"))
158  }  }
159    `[[.VCorpus` <-
160  c2 <- function(x, y, ...) {  function(x, i)
161      # Update the CMetaData tree  {
162      cmeta <- .MetaDataNode(0, list(merge_date = as.POSIXlt(Sys.time(), tz = "GMT"), merger = Sys.getenv("LOGNAME")), list(CMetaData(x), CMetaData(y)))      i <- .map_name_index(x, i)
163      update.struct <- update_id(cmeta)      if (!is.null(x$lazy))
164            .Call(copyCorpus, x, materialize(x, i))
165      new <- .VCorpus(c(unclass(x), unclass(y)), update.struct$root, NULL)      x$content[[i]]
   
     # Find indices to be updated for the left tree  
     indices.mapping <- NULL  
     for (m in levels(as.factor(DMetaData(x)$MetaID))) {  
         indices <- (DMetaData(x)$MetaID == m)  
         indices.mapping <- c(indices.mapping, list(m = indices))  
         names(indices.mapping)[length(indices.mapping)] <- m  
166      }      }
167    
168      # Update the DMetaData data frames for the left tree  `[[<-.PCorpus` <-
169      for (i in 1:ncol(update.struct$left.mapping)) {  function(x, i, value)
170          map <- update.struct$left.mapping[,i]  {
171          DMetaData(x)$MetaID <- replace(DMetaData(x)$MetaID, indices.mapping[[as.character(map[1])]], map[2])      i <- .map_name_index(x, i)
172        db <- filehash::dbInit(x$dbcontrol[["dbName"]], x$dbcontrol[["dbType"]])
173        db[[x$content[[i]]]] <- value
174        x
175      }      }
176    `[[<-.VCorpus` <-
177      # Find indices to be updated for the right tree  function(x, i, value)
178      indices.mapping <- NULL  {
179      for (m in levels(as.factor(DMetaData(y)$MetaID))) {      i <- .map_name_index(x, i)
180          indices <- (DMetaData(y)$MetaID == m)      # Mark new objects as inactive for lazy mapping
181          indices.mapping <- c(indices.mapping, list(m = indices))      if (!is.null(x$lazy))
182          names(indices.mapping)[length(indices.mapping)] <- m          x$lazy$index[i] <- FALSE
183        x$content[[i]] <- value
184        x
185      }      }
186    
187      # Update the DMetaData data frames for the right tree  as.list.PCorpus <- as.list.VCorpus <-
188      for (i in 1:ncol(update.struct$right.mapping)) {  function(x, ...)
189          map <- update.struct$right.mapping[,i]      setNames(content(x), as.character(lapply(content(x), meta, "id")))
190          DMetaData(y)$MetaID <- replace(DMetaData(y)$MetaID, indices.mapping[[as.character(map[1])]], map[2])  
191    as.list.SimpleCorpus <-
192    function(x, ...)
193        as.list(content(x))
194    
195    as.VCorpus <-
196    function(x)
197        UseMethod("as.VCorpus")
198    as.VCorpus.VCorpus <- identity
199    as.VCorpus.list <-
200    function(x)
201    {
202        v <- list(content = x,
203                  meta = CorpusMeta(),
204                  dmeta = data.frame(row.names = seq_along(x)))
205        class(v) <- c("VCorpus", "Corpus")
206        v
207      }      }
208    
209      # Merge the DMetaData data frames  outer_union <-
210      labels <- setdiff(names(DMetaData(y)), names(DMetaData(x)))  function(x, y, ...)
211      na.matrix <- matrix(NA, nrow = nrow(DMetaData(x)), ncol = length(labels), dimnames = list(row.names(DMetaData(x)), labels))  {
212      x.dmeta.aug <- cbind(DMetaData(x), na.matrix)      if (nrow(x) > 0L)
213      labels <- setdiff(names(DMetaData(x)), names(DMetaData(y)))          x[, setdiff(names(y), names(x))] <- NA
214      na.matrix <- matrix(NA, nrow = nrow(DMetaData(y)), ncol = length(labels), dimnames = list(row.names(DMetaData(y)), labels))      if (nrow(y) > 0L)
215      y.dmeta.aug <- cbind(DMetaData(y), na.matrix)          y[, setdiff(names(x), names(y))] <- NA
216      DMetaData(new) <- rbind(x.dmeta.aug, y.dmeta.aug)      res <- rbind(x, y)
217        if (ncol(res) == 0L)
218      new          res <- data.frame(row.names = seq_len(nrow(x) + nrow(y)))
219        res
220  }  }
221    
222  c.Corpus <-  c.VCorpus <-
223  function(x, ..., recursive = FALSE)  function(..., recursive = FALSE)
224  {  {
225      args <- list(...)      args <- list(...)
226        x <- args[[1L]]
227    
228      if (identical(length(args), 0))      if (length(args) == 1L)
229          return(x)          return(x)
230    
231      if (!all(unlist(lapply(args, inherits, class(x)))))      if (!all(unlist(lapply(args, inherits, class(x)))))
232          stop("not all arguments are of the same corpus type")          stop("not all arguments are of the same corpus type")
233    
234      if (inherits(x, "PCorpus"))      v <- list(content = do.call("c", lapply(args, content)),
235          stop("concatenation of corpora with underlying databases is not supported")                meta = CorpusMeta(meta = do.call("c",
236                    lapply(args, function(a) meta(a, type = "corpus")))),
237      Reduce(c2, base::c(list(x), args))                dmeta = Reduce(outer_union, lapply(args, meta)))
238        class(v) <- c("VCorpus", "Corpus")
239        v
240  }  }
241    
242  c.TextDocument <- function(x, ..., recursive = FALSE) {  content.VCorpus <-
243      args <- list(...)  function(x)
244    {
245      if (identical(length(args), 0))      if (!is.null(x$lazy))
246          return(x)          .Call(copyCorpus, x, materialize(x))
247        x$content
248    }
249    
250      if (!all(unlist(lapply(args, inherits, class(x)))))  content.SimpleCorpus <-
251          stop("not all arguments are text documents")  function(x)
252        x$content
253    
254      dmeta <- data.frame(MetaID = rep(0, length(list(x, ...))), stringsAsFactors = FALSE)  content.PCorpus <-
255      .VCorpus(list(x, ...), .MetaDataNode(), dmeta)  function(x)
256    {
257        db <- filehash::dbInit(x$dbcontrol[["dbName"]], x$dbcontrol[["dbType"]])
258        filehash::dbMultiFetch(db, unlist(x$content))
259  }  }
260    
261  print.Corpus <- function(x, ...) {  inspect <-
262      cat(sprintf(ngettext(length(x),  function(x)
263                           "A corpus with %d text document\n",      UseMethod("inspect", x)
264                           "A corpus with %d text documents\n"),  inspect.PCorpus <-
265                  length(x)))  inspect.SimpleCorpus <-
266    inspect.VCorpus <-
267    function(x)
268    {
269        print(x)
270        cat("\n")
271        print(noquote(content(x)))
272      invisible(x)      invisible(x)
273  }  }
274    
275  summary.Corpus <- function(object, ...) {  length.PCorpus <-
276      print(object)  length.SimpleCorpus <-
277      if (length(DMetaData(object)) > 0) {  length.VCorpus <-
278          cat(sprintf(ngettext(length(attr(CMetaData(object), "MetaData")),  function(x)
279                               "\nThe metadata consists of %d tag-value pair and a data frame\n",      length(x$content)
280                               "\nThe metadata consists of %d tag-value pairs and a data frame\n"),  
281                      length(CMetaData(object)$MetaData)))  names.PCorpus <-
282          cat("Available tags are:\n")  names.SimpleCorpus <-
283          cat(strwrap(paste(names(CMetaData(object)$MetaData), collapse = " "), indent = 2, exdent = 2), "\n")  names.VCorpus <-
284          cat("Available variables in the data frame are:\n")  function(x)
285          cat(strwrap(paste(names(DMetaData(object)), collapse = " "), indent = 2, exdent = 2), "\n")      as.character(meta(x, "id", "local"))
     }  
 }  
286    
287  inspect <- function(x) UseMethod("inspect", x)  `names<-.PCorpus` <- `names<-.VCorpus` <-
288  inspect.PCorpus <- function(x) {  function(x, value)
289      summary(x)  {
290      cat("\n")      meta(x, "id", "local") <- as.character(value)
291      db <- filehash::dbInit(DBControl(x)[["dbName"]], DBControl(x)[["dbType"]])      x
     show(filehash::dbMultiFetch(db, unlist(x)))  
 }  
 inspect.VCorpus <- function(x) {  
     summary(x)  
     cat("\n")  
     print(noquote(lapply(x, identity)))  
292  }  }
293    
294  lapply.PCorpus <- function(X, FUN, ...) {  format.PCorpus <-
295      db <- filehash::dbInit(DBControl(X)[["dbName"]], DBControl(X)[["dbType"]])  format.SimpleCorpus <-
296      lapply(filehash::dbMultiFetch(db, unlist(X)), FUN, ...)  format.VCorpus <-
297  }  function(x, ...)
298  lapply.VCorpus <- function(X, FUN, ...) {  {
299      lazyTmMap <- meta(X, tag = "lazyTmMap", type = "corpus")      c(sprintf("<<%s>>", class(x)[1L]),
300      if (!is.null(lazyTmMap))        sprintf("Metadata:  corpus specific: %d, document level (indexed): %d",
301          .Call("copyCorpus", X, materialize(X))                length(meta(x, type = "corpus")),
302      base::lapply(X, FUN, ...)                ncol(meta(x, type = "indexed"))),
303          sprintf("Content:  documents: %d", length(x)))
304  }  }
305    
306  writeCorpus <-  function(x, path = ".", filenames = NULL) {  writeCorpus <-
307    function(x, path = ".", filenames = NULL)
308    {
309      filenames <- file.path(path,      filenames <- file.path(path,
310                             if (is.null(filenames)) unlist(lapply(x, function(x) sprintf("%s.txt", ID(x))))        if (is.null(filenames))
311              sprintf("%s.txt", as.character(meta(x, "id", "local")))
312                             else filenames)                             else filenames)
313      i <- 1  
314      for (o in x) {      stopifnot(length(x) == length(filenames))
315          writeLines(as.PlainTextDocument(o), filenames[i])  
316          i <- i + 1      mapply(function(doc, f) writeLines(as.character(doc), f), x, filenames)
317      }  
318        invisible(x)
319  }  }

Legend:
Removed from v.988  
changed lines
  Added in v.1460

root@r-forge.r-project.org
ViewVC Help
Powered by ViewVC 1.0.0  
Thanks to:
Vienna University of Economics and Business Powered By FusionForge