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

trunk/R/textmin/R/textdoccol.R revision 74, Tue Nov 21 20:04:17 2006 UTC pkg/R/corpus.R revision 1108, Fri Oct 22 18:32:47 2010 UTC
# Line 1  Line 1 
1  # Author: Ingo Feinerer  # Author: Ingo Feinerer
2    
3  # The "..." are additional arguments for the function_generator parser  .PCorpus <- function(x, cmeta, dmeta, dbcontrol) {
4  setGeneric("TextDocCol", function(object, parser = plaintext_parser, ...) standardGeneric("TextDocCol"))      attr(x, "CMetaData") <- cmeta
5  setMethod("TextDocCol",      attr(x, "DMetaData") <- dmeta
6            signature(object = "Source"),      attr(x, "DBControl") <- dbcontrol
7            function(object, parser = plaintext_parser, ...) {      class(x) <- c("PCorpus", "Corpus", "list")
8                if (inherits(parser, "function_generator"))      x
9                    parser <- parser(...)  }
10    DBControl <- function(x) attr(x, "DBControl")
11    
12    PCorpus <- function(x,
13                        readerControl = list(reader = x$DefaultReader, language = "en"),
14                        dbControl = list(dbName = "", dbType = "DB1"),
15                        ...) {
16        readerControl <- prepareReader(readerControl, x$DefaultReader, ...)
17    
18        if (!filehash::dbCreate(dbControl$dbName, dbControl$dbType))
19            stop("error in creating database")
20        db <- filehash::dbInit(dbControl$dbName, dbControl$dbType)
21    
22        # Allocate memory in advance if length is known
23        tdl <- if (x$Length > 0)
24            vector("list", as.integer(x$Length))
25        else
26            list()
27    
               tdl <- list()  
28                counter <- 1                counter <- 1
29                while (!eoi(object)) {      while (!eoi(x)) {
30                    object <- step_next(object)          x <- stepNext(x)
31                    elem <- get_elem(object)          elem <- getElem(x)
32                    # If there is no Load on Demand support          doc <- readerControl$reader(elem, readerControl$language, if (is.null(x$Names)) as.character(counter) else x$Names[counter])
33                    # we need to load the corpus into memory at startup          filehash::dbInsert(db, ID(doc), doc)
34                    if (object@LoDSupport)          if (x$Length > 0) tdl[[counter]] <- ID(doc)
35                        load <- object@Load          else tdl <- c(tdl, ID(doc))
                   else  
                       load <- TRUE  
                   tdl <- c(tdl, list(parser(elem, object@LoDSupport, load, as.character(counter))))  
36                    counter <- counter + 1                    counter <- counter + 1
37                }                }
38        names(tdl) <- x$Names
39    
40                dmeta.df <- data.frame(MetaID = rep(0, length(tdl)), stringsAsFactors = FALSE)      df <- data.frame(MetaID = rep(0, length(tdl)), stringsAsFactors = FALSE)
41                dcmeta.node <- new("MetaDataNode",      filehash::dbInsert(db, "DMetaData", df)
42                              NodeID = 0,      dmeta.df <- data.frame(key = "DMetaData", subset = I(list(NA)))
                             MetaData = list(create_date = date(), creator = Sys.getenv("LOGNAME")),  
                             children = list())  
   
               return(new("TextDocCol", .Data = tdl, DMetaData = dmeta.df, DCMetaData = dcmeta.node))  
           })  
   
 setGeneric("DirSource", function(directory, load = FALSE) standardGeneric("DirSource"))  
 setMethod("DirSource",  
           signature(directory = "character"),  
           function(directory, load = FALSE) {  
               new("DirSource", LoDSupport = TRUE, FileList = dir(directory, full.names = TRUE),  
                   Position = 0, Load = load)  
           })  
   
 setGeneric("CSVSource", function(object) standardGeneric("CSVSource"))  
 setMethod("CSVSource",  
           signature(object = "character"),  
           function(object) {  
               object <- substitute(file(object))  
               con <- eval(object)  
               content <- scan(con, what = "character")  
               close(con)  
               new("CSVSource", LoDSupport = FALSE, URI = object,  
                   Content = content, Position = 0)  
           })  
 setMethod("CSVSource",  
           signature(object = "ANY"),  
           function(object) {  
               object <- substitute(object)  
               con <- eval(object)  
               content <- scan(con, what = "character")  
               close(con)  
               new("CSVSource", LoDSupport = FALSE, URI = object,  
                   Content = content, Position = 0)  
           })  
   
 setGeneric("ReutersSource", function(object) standardGeneric("ReutersSource"))  
 setMethod("ReutersSource",  
           signature(object = "character"),  
           function(object) {  
               object <- substitute(file(object))  
               con <- eval(object)  
               corpus <- paste(readLines(con), "\n", collapse = "")  
               close(con)  
               tree <- xmlTreeParse(corpus, asText = TRUE)  
               content <- xmlRoot(tree)$children  
   
               new("ReutersSource", LoDSupport = FALSE, URI = object,  
                   Content = content, Position = 0)  
           })  
 setMethod("ReutersSource",  
           signature(object = "ANY"),  
           function(object) {  
               object <- substitute(object)  
               con <- eval(object)  
               corpus <- paste(readLines(con), "\n", collapse = "")  
               close(con)  
               tree <- xmlTreeParse(corpus, asText = TRUE)  
               content <- xmlRoot(tree)$children  
   
               new("ReutersSource", LoDSupport = FALSE, URI = object,  
                   Content = content, Position = 0)  
           })  
   
 setGeneric("step_next", function(object) standardGeneric("step_next"))  
 setMethod("step_next",  
           signature(object = "DirSource"),  
           function(object) {  
               object@Position <- object@Position + 1  
               object  
           })  
 setMethod("step_next",  
           signature(object = "CSVSource"),  
           function(object) {  
               object@Position <- object@Position + 1  
               object  
           })  
 setMethod("step_next",  
           signature(object = "ReutersSource"),  
           function(object) {  
               object@Position <- object@Position + 1  
               object  
           })  
   
 setGeneric("get_elem", function(object) standardGeneric("get_elem"))  
 setMethod("get_elem",  
           signature(object = "DirSource"),  
           function(object) {  
               filename <- object@FileList[object@Position]  
               list(content = readLines(filename),  
                    uri = substitute(file(filename)))  
           })  
 setMethod("get_elem",  
           signature(object = "CSVSource"),  
           function(object) {  
               list(content = object@Content[object@Position],  
                    uri = object@URI)  
           })  
 setMethod("get_elem",  
           signature(object = "ReutersSource"),  
           function(object) {  
               # Construct a character representation from the XMLNode  
               con <- textConnection("virtual.file", "w")  
               saveXML(object@Content[[object@Position]], con)  
               close(con)  
   
               list(content = virtual.file, uri = object@URI)  
           })  
   
 setGeneric("eoi", function(object) standardGeneric("eoi"))  
 setMethod("eoi",  
           signature(object = "DirSource"),  
           function(object) {  
               if (length(object@FileList) <= object@Position)  
                   return(TRUE)  
               else  
                   return(FALSE)  
           })  
 setMethod("eoi",  
           signature(object = "CSVSource"),  
           function(object) {  
               if (length(object@Content) <= object@Position)  
                   return(TRUE)  
               else  
                   return(FALSE)  
           })  
 setMethod("eoi",  
           signature(object = "ReutersSource"),  
           function(object) {  
               if (length(object@Content) <= object@Position)  
                   return(TRUE)  
               else  
                   return(FALSE)  
           })  
43    
44  plaintext_parser <- function(...) {      .PCorpus(tdl, .MetaDataNode(), dmeta.df, dbControl)
     function(elem, lodsupport, load, id) {  
         if (!lodsupport || (lodsupport && load)) {  
             doc <- new("PlainTextDocument", .Data = elem$content, URI = elem$uri, Cached = TRUE,  
                        Author = "", DateTimeStamp = date(), Description = "", ID = id, Origin = "", Heading = "")  
         }  
         else {  
             doc <- new("PlainTextDocument", URI = elem$uri, Cached = FALSE,  
                        Author = "", DateTimeStamp = date(), Description = "", ID = id, Origin = "", Heading = "")  
45          }          }
46    
47          return(doc)  .VCorpus <- function(x, cmeta, dmeta) {
48      }      attr(x, "CMetaData") <- cmeta
49        attr(x, "DMetaData") <- dmeta
50        class(x) <- c("VCorpus", "Corpus", "list")
51        x
52  }  }
 class(plaintext_parser) <- "function_generator"  
53    
54  reut21578xml_parser <- function(...) {  # Register S3 corpus classes to be recognized by S4 methods. This is
55      function(elem, lodsupport, load, id) {  # mainly a fix to be compatible with packages which were originally
56          corpus <- paste(elem$content, "\n", collapse = "")  # developed to cooperate with corresponding S4 tm classes. Necessary
57          tree <- xmlTreeParse(corpus, asText = TRUE)  # since tm's class architecture was changed to S3 since tm version 0.5.
58          node <- xmlRoot(tree)  setOldClass(c("VCorpus", "Corpus", "list"))
59    
60          # Mask as list to bypass S4 checks  # The "..." are additional arguments for the FunctionGenerator reader
61          class(tree) <- "list"  VCorpus <- Corpus <- function(x,
62                                  readerControl = list(reader = x$DefaultReader, language = "en"),
63                                  ...) {
64        readerControl <- prepareReader(readerControl, x$DefaultReader, ...)
65    
66          # The <AUTHOR></AUTHOR> tag is unfortunately NOT obligatory!      # Allocate memory in advance if length is known
67          if (!is.null(node[["TEXT"]][["AUTHOR"]]))      tdl <- if (x$Length > 0)
68              author <- xmlValue(node[["TEXT"]][["AUTHOR"]])          vector("list", as.integer(x$Length))
69          else          else
70              author <- ""          list()
71    
72          datetimestamp <- xmlValue(node[["DATE"]])      if (x$Vectorized)
73          description <- ""          tdl <- mapply(function(x, id) readerControl$reader(x, readerControl$language, id),
74          id <- xmlAttrs(node)[["NEWID"]]                        pGetElem(x),
75                          id = if (is.null(x$Names)) as.character(seq_len(x$Length)) else x$Names,
76          # The <TITLE></TITLE> tag is unfortunately NOT obligatory!                        SIMPLIFY = FALSE)
77          if (!is.null(node[["TEXT"]][["TITLE"]]))      else {
78              heading <- xmlValue(node[["TEXT"]][["TITLE"]])          counter <- 1
79            while (!eoi(x)) {
80                x <- stepNext(x)
81                elem <- getElem(x)
82                doc <- readerControl$reader(elem, readerControl$language, if (is.null(x$Names)) as.character(counter) else x$Names[counter])
83                if (x$Length > 0)
84                    tdl[[counter]] <- doc
85          else          else
86              heading <- ""                  tdl <- c(tdl, list(doc))
87                counter <- counter + 1
         topics <- unlist(xmlApply(node[["TOPICS"]], function(x) xmlValue(x)), use.names = FALSE)  
   
         if (!lodsupport || (lodsupport && load)) {  
             doc <- new("XMLTextDocument", .Data = tree, URI = elem$uri, Cached = TRUE, Author = author,  
                        DateTimeStamp = datetimestamp, Description = "", ID = id, Origin = "Reuters-21578 XML",  
                        Heading = heading, LocalMetaData = list(Topics = topics))  
         } else {  
             doc <- new("XMLTextDocument", URI = elem$uri, Cached = FALSE, Author = author,  
                        DateTimeStamp = datetimestamp, Description = "", ID = id, Origin = "Reuters-21578 XML",  
                        Heading = heading, LocalMetaData = list(Topics = topics))  
         }  
   
         return(doc)  
     }  
 }  
 class(reut21578xml_parser) <- "function_generator"  
   
 rcv1_parser <- function(...) {  
     function(elem, lodsupport, load, id) {  
         corpus <- paste(elem$content, "\n", collapse = "")  
         tree <- xmlTreeParse(corpus, asText = TRUE)  
         node <- xmlRoot(tree)  
   
         # Mask as list to bypass S4 checks  
         class(tree) <- "list"  
   
         datetimestamp <- xmlAttrs(node)[["date"]]  
         id <- xmlAttrs(node)[["itemid"]]  
         heading <- xmlValue(node[["title"]])  
   
         if (!lodsupport || (lodsupport && load)) {  
             doc <- new("XMLTextDocument", .Data = tree, URI = elem$uri, Cached = TRUE, Author = "",  
                        DateTimeStamp = datetimestamp, Description = "", ID = id, Origin = "Reuters Corpus Volume 1 XML",  
                        Heading = heading)  
         } else {  
             doc <- new("XMLTextDocument", URI = elem$uri, Cached = FALSE, Author = "",  
                        DateTimeStamp = datetimestamp, Description = "", ID = id, Origin = "Reuters Corpus Volume 1 XML",  
                        Heading = heading)  
         }  
   
         return(doc)  
88      }      }
89  }  }
90  class(rcv1_parser) <- "function_generator"      names(tdl) <- x$Names
91        df <- data.frame(MetaID = rep(0, length(tdl)), stringsAsFactors = FALSE)
92  newsgroup_parser <- function(...) {      .VCorpus(tdl, .MetaDataNode(), df)
     function(elem, lodsupport, load, id) {  
         mail <- elem$content  
         author <- gsub("From: ", "", grep("^From:", mail, value = TRUE))  
         datetimestamp <- gsub("Date: ", "", grep("^Date:", mail, value = TRUE))  
         origin <- gsub("Path: ", "", grep("^Path:", mail, value = TRUE))  
         heading <- gsub("Subject: ", "", grep("^Subject:", mail, value = TRUE))  
         newsgroup <- gsub("Newsgroups: ", "", grep("^Newsgroups:", mail, value = TRUE))  
   
         if (!lodsupport || (lodsupport && load)) {  
             # The header is separated from the body by a blank line.  
             # Reference: \url{http://en.wikipedia.org/wiki/E-mail#Internet_e-mail_format}  
             for (index in seq(along = mail)) {  
                 if (mail[index] == "")  
                     break  
93              }              }
             content <- mail[(index + 1):length(mail)]  
94    
95              doc <- new("NewsgroupDocument", .Data = content, URI = elem$uri, Cached = TRUE,  `[.PCorpus` <- function(x, i) {
96                         Author = author, DateTimeStamp = datetimestamp,      if (missing(i)) return(x)
97                         Description = "", ID = id, Origin = origin,      index <- attr(x, "DMetaData")[[1 , "subset"]]
98                         Heading = heading, Newsgroup = newsgroup)      attr(x, "DMetaData")[[1 , "subset"]] <- if (is.numeric(index)) index[i] else i
99          } else {      dmeta <- attr(x, "DMetaData")
100              doc <- new("NewsgroupDocument", URI = elem$uri, Cached = FALSE, Author = author, DateTimeStamp = datetimestamp,      .PCorpus(NextMethod("["), CMetaData(x), dmeta, DBControl(x))
                        Description = "", ID = id, Origin = origin, Heading = heading, Newsgroup = newsgroup)  
101          }          }
102    
103          return(doc)  `[.VCorpus` <- function(x, i) {
104        if (missing(i)) return(x)
105        .VCorpus(NextMethod("["), CMetaData(x), DMetaData(x)[i, , drop = FALSE])
106      }      }
 }  
 class(newsgroup_parser) <- "function_generator"  
   
 # Parse a <newsitem></newsitem> element from a well-formed RCV1 XML file  
 rcv1_to_plain <- function(node, ...) {  
     datetimestamp <- xmlAttrs(node)[["date"]]  
     id <- xmlAttrs(node)[["itemid"]]  
     origin <- "Reuters Corpus Volume 1 XML"  
     corpus <- unlist(xmlApply(node[["text"]], xmlValue), use.names = FALSE)  
     heading <- xmlValue(node[["title"]])  
   
     new("PlainTextDocument", .Data = corpus, Cached = TRUE, URI = "", Author = "", DateTimeStamp = datetimestamp,  
         Description = "", ID = id, Origin = "Reuters Corpus Volume 1 XML", Heading = heading)  
 }  
   
 # Parse a <REUTERS></REUTERS> element from a well-formed Reuters-21578 XML file  
 reut21578xml_to_plain <- function(node, ...) {  
     # The <AUTHOR></AUTHOR> tag is unfortunately NOT obligatory!  
     if (!is.null(node[["TEXT"]][["AUTHOR"]]))  
         author <- xmlValue(node[["TEXT"]][["AUTHOR"]])  
     else  
         author <- ""  
   
     datetimestamp <- xmlValue(node[["DATE"]])  
     description <- ""  
     id <- xmlAttrs(node)[["NEWID"]]  
   
     origin <- "Reuters-21578 XML"  
107    
108      # The <BODY></BODY> tag is unfortunately NOT obligatory!  `[<-.PCorpus` <- function(x, i, value) {
109      if (!is.null(node[["TEXT"]][["BODY"]]))      db <- filehash::dbInit(DBControl(x)[["dbName"]], DBControl(x)[["dbType"]])
110          corpus <- xmlValue(node[["TEXT"]][["BODY"]])      counter <- 1
111      else      for (id in unclass(x)[i]) {
112          corpus <- ""          if (identical(length(value), 1L)) db[[id]] <- value
113            else db[[id]] <- value[[counter]]
114      # The <TITLE></TITLE> tag is unfortunately NOT obligatory!          counter <- counter + 1
     if (!is.null(node[["TEXT"]][["TITLE"]]))  
         heading <- xmlValue(node[["TEXT"]][["TITLE"]])  
     else  
         heading <- ""  
   
     topics <- unlist(xmlApply(node[["TOPICS"]], function(x) xmlValue(x)), use.names = FALSE)  
   
     new("PlainTextDocument", .Data = corpus, Cached = TRUE, URI = "", Author = author, DateTimeStamp = datetimestamp,  
         Description = description, ID = id, Origin = origin, Heading = heading, LocalMetaData = list(Topics = topics))  
115  }  }
116        x
 setGeneric("load_doc", function(object, ...) standardGeneric("load_doc"))  
 setMethod("load_doc",  
           signature(object = "PlainTextDocument"),  
           function(object, ...) {  
               if (!Cached(object)) {  
                   con <- eval(URI(object))  
                   corpus <- readLines(con)  
                   close(con)  
                   Corpus(object) <- corpus  
                   Cached(object) <- TRUE  
                   return(object)  
               } else {  
                   return(object)  
               }  
           })  
 setMethod("load_doc",  
           signature(object =  "XMLTextDocument"),  
           function(object, ...) {  
               if (!Cached(object)) {  
                   con <- eval(URI(object))  
                   corpus <- paste(readLines(con), "\n", collapse = "")  
                   close(con)  
                   doc <- xmlTreeParse(corpus, asText = TRUE)  
                   class(doc) <- "list"  
                   Corpus(object) <- doc  
                   Cached(object) <- TRUE  
                   return(object)  
               } else {  
                   return(object)  
               }  
           })  
 setMethod("load_doc",  
           signature(object = "NewsgroupDocument"),  
           function(object, ...) {  
               if (!Cached(object)) {  
                   con <- eval(URI(object))  
                   mail <- readLines(con)  
                   close(con)  
                   Cached(object) <- TRUE  
                   for (index in seq(along = mail)) {  
                       if (mail[index] == "")  
                           break  
                   }  
                   Corpus(object) <- mail[(index + 1):length(mail)]  
                   return(object)  
               } else {  
                   return(object)  
               }  
           })  
   
 setGeneric("tm_update", function(object, origin, parser = plaintext_parser, ...) standardGeneric("tm_update"))  
 # Update is only supported for directories  
 # At the moment no other LoD devices are available anyway  
 setMethod("tm_update",  
           signature(object = "TextDocCol", origin = "DirSource"),  
           function(object, origin, parser = plaintext_parser, ...) {  
               if (inherits(parser, "function_generator"))  
                   parser <- parser(...)  
   
               object.filelist <- unlist(lapply(object, function(x) {as.character(URI(x))[2]}))  
               new.files <- setdiff(origin@FileList, object.filelist)  
   
               for (filename in new.files) {  
                   elem <- list(content = readLines(filename),  
                                uri = substitute(file(filename)))  
                   object <- append_doc(object, parser(elem, TRUE, origin@Load, filename), NA)  
               }  
   
               return(object)  
           })  
   
 setGeneric("tm_transform", function(object, FUN, ...) standardGeneric("tm_transform"))  
 setMethod("tm_transform",  
           signature(object = "TextDocCol", FUN = "function"),  
           function(object, FUN, ...) {  
               result <- object  
               result@.Data <- lapply(object, FUN, ..., DMetaData = DMetaData(object))  
               return(result)  
           })  
   
 setGeneric("as.plaintext_doc", function(object, FUN, ...) standardGeneric("as.plaintext_doc"))  
 setMethod("as.plaintext_doc",  
           signature(object = "PlainTextDocument"),  
           function(object, FUN, ...) {  
               return(object)  
           })  
 setMethod("as.plaintext_doc",  
           signature(object = "XMLTextDocument", FUN = "function"),  
           function(object, FUN, ...) {  
               if (!Cached(object))  
                   object <- load_doc(object)  
   
               corpus <- Corpus(object)  
   
               # As XMLDocument is no native S4 class, restore valid information  
               class(corpus) <- "XMLDocument"  
               names(corpus) <- c("doc","dtd")  
   
               return(FUN(xmlRoot(corpus), ...))  
           })  
   
 setGeneric("tm_tolower", function(object, ...) standardGeneric("tm_tolower"))  
 setMethod("tm_tolower",  
           signature(object = "PlainTextDocument"),  
           function(object, ...) {  
               if (!Cached(object))  
                   object <- load_doc(object)  
   
               Corpus(object) <- tolower(object)  
               return(object)  
           })  
   
 setGeneric("strip_whitespace", function(object, ...) standardGeneric("strip_whitespace"))  
 setMethod("strip_whitespace",  
           signature(object = "PlainTextDocument"),  
           function(object, ...) {  
               if (!Cached(object))  
                   object <- load_doc(object)  
   
               Corpus(object) <- gsub("[[:space:]]+", " ", object)  
               return(object)  
           })  
   
 setGeneric("stem_doc", function(object, ...) standardGeneric("stem_doc"))  
 setMethod("stem_doc",  
           signature(object = "PlainTextDocument"),  
           function(object, ...) {  
               if (!Cached(object))  
                   object <- load_doc(object)  
   
               require(Rstem)  
               splittedCorpus <- unlist(strsplit(object, " ", fixed = TRUE))  
               stemmedCorpus <- wordStem(splittedCorpus)  
               Corpus(object) <- paste(stemmedCorpus, collapse = " ")  
               return(object)  
           })  
   
 setGeneric("remove_words", function(object, stopwords, ...) standardGeneric("remove_words"))  
 setMethod("remove_words",  
           signature(object = "PlainTextDocument", stopwords = "character"),  
           function(object, stopwords, ...) {  
               if (!Cached(object))  
                   object <- load_doc(object)  
   
               require(Rstem)  
               splittedCorpus <- unlist(strsplit(object, " ", fixed = TRUE))  
               noStopwordsCorpus <- splittedCorpus[!splittedCorpus %in% stopwords]  
               Corpus(object) <- paste(noStopwordsCorpus, collapse = " ")  
               return(object)  
           })  
   
 setGeneric("tm_filter", function(object, ..., FUN = s_filter, doclevel = FALSE) standardGeneric("tm_filter"))  
 setMethod("tm_filter",  
           signature(object = "TextDocCol"),  
           function(object, ..., FUN = s_filter, doclevel = FALSE) {  
               if (doclevel)  
                   return(object[sapply(object, FUN, ..., DMetaData = DMetaData(object))])  
               else  
                   return(object[FUN(object, ...)])  
           })  
   
 setGeneric("tm_index", function(object, ..., FUN = s_filter, doclevel = FALSE) standardGeneric("tm_index"))  
 setMethod("tm_index",  
           signature(object = "TextDocCol"),  
           function(object, ..., FUN = s_filter, doclevel = FALSE) {  
               if (doclevel)  
                   return(sapply(object, FUN, ..., DMetaData = DMetaData(object)))  
               else  
                   return(FUN(object, ...))  
           })  
   
 s_filter <- function(object, s, ...) {  
     query.df <- DMetaData(object)  
     con <- textConnection(s)  
     tokens <- scan(con, "character")  
     close(con)  
     local.meta <- lapply(object, LocalMetaData)  
     local.used.meta <- lapply(local.meta, function(x) names(x) %in% tokens)  
     l.meta <- NULL  
     for (i in 1:length(object)) {  
         l.meta <- c(l.meta, list(local.meta[[i]][local.used.meta[[i]]]))  
     }  
     # Load local meta data from text documents into data frame  
     for (i in 1:length(l.meta)) {  
         l.meta[[i]] <- c(l.meta[[i]], list(author = Author(object[[i]])))  
         l.meta[[i]] <- c(l.meta[[i]], list(datetimestamp = DateTimeStamp(object[[i]])))  
         l.meta[[i]] <- c(l.meta[[i]], list(description = Description(object[[i]])))  
         l.meta[[i]] <- c(l.meta[[i]], list(identifier = ID(object[[i]])))  
         l.meta[[i]] <- c(l.meta[[i]], list(origin = Origin(object[[i]])))  
         l.meta[[i]] <- c(l.meta[[i]], list(heading = Heading(object[[i]])))  
     }  
     # TODO: Handle entries (\code{m} with length greater 1, i.e., lists)  
     for (i in 1:length(l.meta)) {  
         for (j in 1:length(l.meta[[i]])) {  
             m <- l.meta[[i]][[j]]  
             m.name <- names(l.meta[[i]][j])  
             if (!(m.name %in% names(query.df))) {  
                 before <- rep(NA, i - 1)  
                 after <- rep(NA, length(l.meta) - i)  
                 insert <- c(before, m, after)  
                 query.df <- cbind(query.df, insert, stringsAsFactors = FALSE)  
                 names(query.df)[length(query.df)] <- m.name  
117              }              }
             else {  
                 if (is.null(m))  
                     m <- NA  
                 #if (length(m) > 1)  
                 #    query.df[i,names(l.meta[[i]])] <- list(m)  
                 #else  
                     query.df[i,m.name] <- m  
             }  
         }  
     }  
     attach(query.df)  
     try(result <- rownames(query.df) %in% row.names(query.df[eval(parse(text = s)), ]))  
     detach(query.df)  
     return(result)  
 }  
   
 #s_filter <- function(object, s, ..., DMetaData) {  
 #    b <- TRUE  
 #    for (tag in names(s)) {  
 #        if (tag %in% names(LocalMetaData(object))) {  
 #            b <- b && any(grep(s[[tag]], LocalMetaData(object)[[tag]]))  
 #        } else if (tag %in% names(DMetaData)){  
 #            b <- b && any(grep(s[[tag]], DMetaData[[tag]]))  
 #        } else {  
 #            b <- b && any(grep(s[[tag]], eval(call(tag, object))))  
 #        }  
 #    }  
 #    return(b)  
 #}  
   
 setGeneric("fulltext_search_filter", function(object, pattern, ...) standardGeneric("fulltext_search_filter"))  
 setMethod("fulltext_search_filter",  
           signature(object = "PlainTextDocument", pattern = "character"),  
           function(object, pattern, ...) {  
               if (!Cached(object))  
                   object <- load_doc(object)  
   
               return(any(grep(pattern, Corpus(object))))  
           })  
   
 setGeneric("attach_data", function(object, data) standardGeneric("attach_data"))  
 setGeneric("attach_metadata", function(object, name, metadata) standardGeneric("attach_metadata"))  
   
 setGeneric("append_doc", function(object, data, meta = NULL) standardGeneric("append_doc"))  
 setMethod("append_doc",  
           signature(object = "TextDocCol", data = "TextDocument"),  
           function(object, data, meta = NULL) {  
               object@.Data <- c(object@.Data, list(data))  
               if (length(meta) > 0)  
                   object@DMetaData <- rbind(object@DMetaData, c(MetaID = DCMetaData(object)@NodeID, meta))  
               return(object)  
           })  
   
 setGeneric("append_meta", function(object, dcmeta = list(), dmeta = NULL) standardGeneric("append_meta"))  
 setMethod("append_meta",  
           signature(object = "TextDocCol"),  
           function(object, dcmeta = list(), dmeta = NULL) {  
               object@DCMetaData@MetaData <- c(object@DCMetaData@MetaData, dcmeta)  
               if (length(dmeta) > 0)  
                   object@DMetaData <- cbind(object@DMetaData, dmeta)  
               return(object)  
           })  
   
 setGeneric("remove_metadata", function(object, name) standardGeneric("remove_metadata"))  
 #setMethod("remove_metadata",  
 #          signature(object = "TextDocCol"),  
 #          function(object, name) {  
 #              object@DMetaData <- DMetaData(object)[names(DMetaData(object)) != name]  
 #              return(object)  
 #          })  
   
 setGeneric("modify_metadata", function(object, name, metadata) standardGeneric("modify_metadata"))  
 #setMethod("modify_metadata",  
 #          signature(object = "TextDocCol"),  
 #          function(object, name, metadata) {  
 #              object@DMetaData[[name]] <- metadata  
 #              return(object)  
 #          })  
   
 # TODO: Handle metadata in document slots  
 setGeneric("prescind_meta", function(object, meta) standardGeneric("prescind_meta"))  
 setMethod("prescind_meta",  
           signature(object = "TextDocCol", meta = "character"),  
           function(object, meta) {  
               for (m in meta) {  
                   local.meta <- lapply(object, LocalMetaData)  
                   local.m <- lapply(local.meta, "[[", m)  
                   local.m <- lapply(local.m, function(x) if (is.null(x)) return(NA) else return(x))  
                   if (length(local.m) == length(unlist(local.m)))  
                       local.m <- unlist(local.m)  
                   else  
                       local.m <- I(local.m)  
                   object@DMetaData <- cbind(DMetaData(object), data.frame(m = local.m), stringsAsFactors = FALSE)  
                   names(object@DMetaData)[length(object@DMetaData)] <- m  
               }  
               return(object)  
           })  
   
 setMethod("[",  
           signature(x = "TextDocCol", i = "ANY", j = "ANY", drop = "ANY"),  
           function(x, i, j, ... , drop) {  
               if(missing(i))  
                   return(x)  
118    
119                object <- x  .map_name_index <- function(x, i) {
120                object@.Data <- x@.Data[i, ..., drop = FALSE]      if (is.character(i)) {
121                object@DMetaData <- DMetaData(object)[i, ]          if (is.null(names(x)))
122                return(object)              match(i, meta(x, "ID", type = "local"))
123            })          else
124                match(i, names(x))
125  setMethod("[<-",      }
126            signature(x = "TextDocCol", i = "ANY", j = "ANY", value = "ANY"),      i
127            function(x, i, j, ... , value) {  }
128                object <- x  
129                object@.Data[i, ...] <- value  `[[.PCorpus` <-  function(x, i) {
130                return(object)      i <- .map_name_index(x, i)
131            })      db <- filehash::dbInit(DBControl(x)[["dbName"]], DBControl(x)[["dbType"]])
132        filehash::dbFetch(db, NextMethod("[["))
133  setMethod("[[",  }
134            signature(x = "TextDocCol", i = "ANY", j = "ANY"),  `[[.VCorpus` <-  function(x, i) {
135            function(x, i, j, ...) {      i <- .map_name_index(x, i)
136                return(x@.Data[[i, ...]])      lazyTmMap <- meta(x, tag = "lazyTmMap", type = "corpus")
137            })      if (!is.null(lazyTmMap))
138            .Call("copyCorpus", x, materialize(x, i))
139  setMethod("[[<-",      NextMethod("[[")
140            signature(x = "TextDocCol", i = "ANY", j = "ANY", value = "ANY"),  }
141            function(x, i, j, ..., value) {  
142                object <- x  `[[<-.PCorpus` <-  function(x, i, value) {
143                object@.Data[[i, ...]] <- value      i <- .map_name_index(x, i)
144                return(object)      db <- filehash::dbInit(DBControl(x)[["dbName"]], DBControl(x)[["dbType"]])
145            })      index <- unclass(x)[[i]]
146        db[[index]] <- value
147  # Update \code{NodeID}s of a DCMetaData tree      x
148  # TODO: Avoid global variables outside of update_id function  }
149  update_id <- function(object) {  `[[<-.VCorpus` <-  function(x, i, value) {
150      id <<- 0      i <- .map_name_index(x, i)
151      mapping <<- left.mapping <<- NULL      # Mark new objects as not active for lazy mapping
152      level <<- 0      lazyTmMap <- meta(x, tag = "lazyTmMap", type = "corpus")
153      return(list(root = set_id(object), left.mapping = left.mapping, right.mapping = mapping))      if (!is.null(lazyTmMap)) {
154  }          lazyTmMap$index[i] <- FALSE
155            meta(x, tag = "lazyTmMap", type = "corpus") <- lazyTmMap
156  # Traversal of (binary) DCMetaData tree with setup of \code{NodeID}s      }
157  set_id <- function(object) {      # Set the value
158      object@NodeID <- id      cl <- class(x)
159        y <- NextMethod("[[<-")
160        class(y) <- cl
161        y
162    }
163    
164    # Update NodeIDs of a CMetaData tree
165    .update_id <- function(x, id = 0, mapping = NULL, left.mapping = NULL, level = 0) {
166        # Traversal of (binary) CMetaData tree with setup of NodeIDs
167        set_id <- function(x) {
168            x$NodeID <- id
169      id <<- id + 1      id <<- id + 1
170      level <<- level + 1      level <<- level + 1
171            if (length(x$Children) > 0) {
172      if (length(object@children) > 0) {              mapping <<- cbind(mapping, c(x$Children[[1]]$NodeID, id))
173          mapping <<- cbind(mapping, c(object@children[[1]]@NodeID, id))              left <- set_id(x$Children[[1]])
         left <- set_id(object@children[[1]])  
174          if (level == 1) {          if (level == 1) {
175              left.mapping <<- mapping              left.mapping <<- mapping
176              mapping <<- NULL              mapping <<- NULL
177          }          }
178          mapping <<- cbind(mapping, c(object@children[[2]]@NodeID, id))              mapping <<- cbind(mapping, c(x$Children[[2]]$NodeID, id))
179          right <- set_id(object@children[[2]])              right <- set_id(x$Children[[2]])
180    
181          object@children <- list(left, right)              x$Children <- list(left, right)
182      }      }
183      level <<- level - 1      level <<- level - 1
184            x
185      return(object)      }
186        list(root = set_id(x), left.mapping = left.mapping, right.mapping = mapping)
187  }  }
188    
189  setMethod("c",  # Find indices to be updated for a CMetaData tree
190            signature(x = "TextDocCol"),  .find_indices <- function(x) {
           function(x, y, ..., meta = list(merge_date = date(), merger = Sys.getenv("LOGNAME")), recursive = TRUE) {  
               if (!inherits(y, "TextDocCol"))  
                   stop("invalid argument")  
   
               object <- x  
               # Concatenate data slots  
               object@.Data <- c(as(x, "list"), as(y, "list"))  
   
               # Update the DCMetaData tree  
               dcmeta <- new("MetaDataNode", NodeID = 0, MetaData = meta, children = list(DCMetaData(x), DCMetaData(y)))  
               update.struct <- update_id(dcmeta)  
               object@DCMetaData <- update.struct$root  
   
               # Find indices to be updated for the left tree  
191                indices.mapping <- NULL                indices.mapping <- NULL
192                for (m in levels(as.factor(DMetaData(x)$MetaID))) {                for (m in levels(as.factor(DMetaData(x)$MetaID))) {
193                    indices <- (DMetaData(x)$MetaID == m)                    indices <- (DMetaData(x)$MetaID == m)
194                    indices.mapping <- c(indices.mapping, list(m = indices))                    indices.mapping <- c(indices.mapping, list(m = indices))
195                    names(indices.mapping)[length(indices.mapping)] <- m                    names(indices.mapping)[length(indices.mapping)] <- m
196                }                }
197        indices.mapping
198    }
199    
200    c2 <- function(x, y, ...) {
201        # Update the CMetaData tree
202        cmeta <- .MetaDataNode(0, list(merge_date = as.POSIXlt(Sys.time(), tz = "GMT"), merger = Sys.getenv("LOGNAME")), list(CMetaData(x), CMetaData(y)))
203        update.struct <- .update_id(cmeta)
204    
205        new <- .VCorpus(c(unclass(x), unclass(y)), update.struct$root, NULL)
206    
207        # Find indices to be updated for the left tree
208        indices.mapping <- .find_indices(x)
209    
210                # Update the DMetaData data frames for the left tree                # Update the DMetaData data frames for the left tree
211                for (i in 1:ncol(update.struct$left.mapping)) {                for (i in 1:ncol(update.struct$left.mapping)) {
212                    map <- update.struct$left.mapping[,i]                    map <- update.struct$left.mapping[,i]
213                    x@DMetaData$MetaID <- replace(DMetaData(x)$MetaID, indices.mapping[[as.character(map[1])]], map[2])          DMetaData(x)$MetaID <- replace(DMetaData(x)$MetaID, indices.mapping[[as.character(map[1])]], map[2])
214                }                }
215    
216                # Find indices to be updated for the right tree                # Find indices to be updated for the right tree
217                indices.mapping <- NULL      indices.mapping <- .find_indices(y)
               for (m in levels(as.factor(DMetaData(y)$MetaID))) {  
                   indices <- (DMetaData(y)$MetaID == m)  
                   indices.mapping <- c(indices.mapping, list(m = indices))  
                   names(indices.mapping)[length(indices.mapping)] <- m  
               }  
218    
219                # Update the DMetaData data frames for the right tree                # Update the DMetaData data frames for the right tree
220                for (i in 1:ncol(update.struct$right.mapping)) {                for (i in 1:ncol(update.struct$right.mapping)) {
221                    map <- update.struct$right.mapping[,i]                    map <- update.struct$right.mapping[,i]
222                    y@DMetaData$MetaID <- replace(DMetaData(y)$MetaID, indices.mapping[[as.character(map[1])]], map[2])          DMetaData(y)$MetaID <- replace(DMetaData(y)$MetaID, indices.mapping[[as.character(map[1])]], map[2])
223                }                }
224    
225                # Merge the DMetaData data frames                # Merge the DMetaData data frames
# Line 740  Line 229 
229                labels <- setdiff(names(DMetaData(x)), names(DMetaData(y)))                labels <- setdiff(names(DMetaData(x)), names(DMetaData(y)))
230                na.matrix <- matrix(NA, nrow = nrow(DMetaData(y)), ncol = length(labels), dimnames = list(row.names(DMetaData(y)), labels))                na.matrix <- matrix(NA, nrow = nrow(DMetaData(y)), ncol = length(labels), dimnames = list(row.names(DMetaData(y)), labels))
231                y.dmeta.aug <- cbind(DMetaData(y), na.matrix)                y.dmeta.aug <- cbind(DMetaData(y), na.matrix)
232                object@DMetaData <- rbind(x.dmeta.aug, y.dmeta.aug)      DMetaData(new) <- rbind(x.dmeta.aug, y.dmeta.aug)
233    
234                return(object)      new
235            })  }
236  setMethod("c",  
237            signature(x = "TextDocument"),  c.Corpus <-
238            function(x, ..., recursive = TRUE){  function(x, ..., recursive = FALSE)
239    {
240                args <- list(...)                args <- list(...)
241                if(length(args) == 0)  
242        if (identical(length(args), 0L))
243                    return(x)                    return(x)
244    
245                dmeta.df <- data.frame(MetaID = rep(0, length(list(x, ...))), stringsAsFactors = FALSE)      if (!all(unlist(lapply(args, inherits, class(x)))))
246                dcmeta.node <- new("MetaDataNode",          stop("not all arguments are of the same corpus type")
247                              NodeID = 0,  
248                              MetaData = list(create_date = date(), creator = Sys.getenv("LOGNAME")),      if (inherits(x, "PCorpus"))
249                              children = list())          stop("concatenation of corpora with underlying databases is not supported")
250    
251                return(new("TextDocCol", .Data = list(x, ...), DMetaData = dmeta.df, DCMetaData = dcmeta.node))      l <- base::c(list(x), args)
252            })      if (recursive)
253            Reduce(c2, l)
254  setMethod("length",      else {
255            signature(x = "TextDocCol"),          l <- do.call("c", lapply(l, unclass))
256            function(x){          .VCorpus(l,
257                return(length(as(x, "list")))                   cmeta = .MetaDataNode(),
258      })                   dmeta = data.frame(MetaID = rep(0, length(l)), stringsAsFactors = FALSE))
259        }
260  setMethod("show",  }
261            signature(object = "TextDocCol"),  
262            function(object){  c.TextDocument <- function(x, ..., recursive = FALSE) {
263                cat(sprintf(ngettext(length(object),      args <- list(...)
264                                     "A text document collection with %d text document\n",  
265                                     "A text document collection with %d text documents\n"),      if (identical(length(args), 0L))
266                            length(object)))          return(x)
267      })  
268        if (!all(unlist(lapply(args, inherits, class(x)))))
269  setMethod("summary",          stop("not all arguments are text documents")
270            signature(object = "TextDocCol"),  
271            function(object){      dmeta <- data.frame(MetaID = rep(0, length(list(x, ...))), stringsAsFactors = FALSE)
272                show(object)      .VCorpus(list(x, ...), .MetaDataNode(), dmeta)
273    }
274    
275    print.Corpus <- function(x, ...) {
276        cat(sprintf(ngettext(length(x),
277                             "A corpus with %d text document\n",
278                             "A corpus with %d text documents\n"),
279                    length(x)))
280        invisible(x)
281    }
282    
283    summary.Corpus <- function(object, ...) {
284        print(object)
285                if (length(DMetaData(object)) > 0) {                if (length(DMetaData(object)) > 0) {
286                    cat(sprintf(ngettext(length(DMetaData(object)),          cat(sprintf(ngettext(length(attr(CMetaData(object), "MetaData")),
287                                                "\nThe global metadata consists of %d tag-value pair\n",                               "\nThe metadata consists of %d tag-value pair and a data frame\n",
288                                                "\nThe global metadata consists of %d tag-value pairs\n"),                               "\nThe metadata consists of %d tag-value pairs and a data frame\n"),
289                                         length(DMetaData(object))))                      length(CMetaData(object)$MetaData)))
290                    cat("Available tags are:\n")                    cat("Available tags are:\n")
291                    cat(names(DMetaData(object)), "\n")          cat(strwrap(paste(names(CMetaData(object)$MetaData), collapse = " "), indent = 2, exdent = 2), "\n")
292            cat("Available variables in the data frame are:\n")
293            cat(strwrap(paste(names(DMetaData(object)), collapse = " "), indent = 2, exdent = 2), "\n")
294        }
295                }                }
     })  
296    
297  setGeneric("inspect", function(object) standardGeneric("inspect"))  inspect <- function(x) UseMethod("inspect", x)
298  setMethod("inspect",  inspect.PCorpus <- function(x) {
299            signature("TextDocCol"),      summary(x)
           function(object) {  
               summary(object)  
300                cat("\n")                cat("\n")
301                show(as(object, "list"))      db <- filehash::dbInit(DBControl(x)[["dbName"]], DBControl(x)[["dbType"]])
302            })      show(filehash::dbMultiFetch(db, unlist(x)))
303    }
304    inspect.VCorpus <- function(x) {
305        summary(x)
306        cat("\n")
307        print(noquote(lapply(x, identity)))
308    }
309    
310  # No metadata is checked  lapply.PCorpus <- function(X, FUN, ...) {
311  setGeneric("%IN%", function(x, y) standardGeneric("%IN%"))      db <- filehash::dbInit(DBControl(X)[["dbName"]], DBControl(X)[["dbType"]])
312  setMethod("%IN%",      lapply(filehash::dbMultiFetch(db, unlist(X)), FUN, ...)
313            signature(x = "TextDocument", y = "TextDocCol"),  }
314            function(x, y) {  lapply.VCorpus <- function(X, FUN, ...) {
315                x %in% y      lazyTmMap <- meta(X, tag = "lazyTmMap", type = "corpus")
316            })      if (!is.null(lazyTmMap))
317            .Call("copyCorpus", X, materialize(X))
318        base::lapply(X, FUN, ...)
319    }
320    
321    writeCorpus <-  function(x, path = ".", filenames = NULL) {
322        filenames <- file.path(path,
323                               if (is.null(filenames)) unlist(lapply(x, function(x) sprintf("%s.txt", ID(x))))
324                               else filenames)
325        i <- 1
326        for (o in x) {
327            writeLines(as.PlainTextDocument(o), filenames[i])
328            i <- i + 1
329        }
330    }

Legend:
Removed from v.74  
changed lines
  Added in v.1108

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