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/trunk/R/textdoccol.R revision 18, Sat Nov 5 19:00:05 2005 UTC pkg/R/corpus.R revision 1259, Sat Sep 21 07:36:25 2013 UTC
# Line 1  Line 1 
1  # Author: Ingo Feinerer  # Author: Ingo Feinerer
2    
3  # S4 class definition  .PCorpus <-
4  # Text document collection  function(x, cmeta, dmeta, dbcontrol)
5  # TODO: Define proper S4 term-document matrix  {
6  setClass("textdoccol", representation(docs = "list",      attr(x, "CMetaData") <- cmeta
7                                        tdm = "matrix"))      attr(x, "DMetaData") <- dmeta
8        attr(x, "DBControl") <- dbcontrol
9  # Accessor function      class(x) <- c("PCorpus", "Corpus", "list")
10  if (!isGeneric("docs")) {      x
11      if (is.function("docs"))  }
12          fun <- docs  
13      else  DBControl <-
14          fun <- function(object) standardGeneric("docs")  function(x)
15      setGeneric("docs", fun)      attr(x, "DBControl")
16  }  
17  setMethod("docs", "textdoccol", function(object) object@docs)  PCorpus <-
18    function(x,
19  setGeneric("textdoccol", function(docs) standardGeneric("textdoccol"))           readerControl = list(reader = x$DefaultReader, language = "en"),
20  # Read in XML text documents           dbControl = list(dbName = "", dbType = "DB1"))
21  # Reuters Corpus Volume 1 (RCV1)  {
22  setMethod("textdoccol", "character", function(docs) {      readerControl <- prepareReader(readerControl, x$DefaultReader)
23      require(XML)  
24        if (is.function(readerControl$init))
25      tree <- xmlTreeParse(docs)          readerControl$init()
26      root <- xmlRoot(tree)  
27        if (is.function(readerControl$exit))
28      # TODO: At each loop node points to the current newsitem          on.exit(readerControl$exit())
29      node <- root  
30        if (!filehash::dbCreate(dbControl$dbName, dbControl$dbType))
31      # TODO: Implement lacking fields.          stop("error in creating database")
32      # For this we need the full RCV1 XML set to know where to find those things      db <- filehash::dbInit(dbControl$dbName, dbControl$dbType)
33      author <- "Not yet implemented"  
34      timestamp <- xmlAttrs(node)[["date"]]      # Allocate memory in advance if length is known
35      description <- "Not yet implemented"      tdl <- if (x$Length > 0)
36      id <- as.integer(xmlAttrs(node)[["itemid"]])          vector("list", as.integer(x$Length))
37      origin <- "Not yet implemented"      else
38      corpus <- unlist(xmlApply(node[["text"]], xmlValue), use.names = FALSE)          list()
39    
40        counter <- 1
41        while (!eoi(x)) {
42            x <- stepNext(x)
43            elem <- getElem(x)
44            id <- if (is.null(x$Names) || is.na(x$Names))
45                    as.character(counter)
46                else
47                    x$Names[counter]
48            doc <- readerControl$reader(elem, readerControl$language, id)
49            filehash::dbInsert(db, ID(doc), doc)
50            if (x$Length > 0) tdl[[counter]] <- ID(doc)
51            else tdl <- c(tdl, ID(doc))
52            counter <- counter + 1
53        }
54        names(tdl) <- x$Names
55    
56        df <- data.frame(MetaID = rep(0, length(tdl)), stringsAsFactors = FALSE)
57        filehash::dbInsert(db, "DMetaData", df)
58        dmeta.df <- data.frame(key = "DMetaData", subset = I(list(NA)))
59    
60        .PCorpus(tdl, .MetaDataNode(), dmeta.df, dbControl)
61    }
62    
63    .VCorpus <-
64    function(x, cmeta, dmeta)
65    {
66        attr(x, "CMetaData") <- cmeta
67        attr(x, "DMetaData") <- dmeta
68        class(x) <- c("VCorpus", "Corpus", "list")
69        x
70    }
71    
72    VCorpus <-
73    Corpus <-
74    function(x, readerControl = list(reader = x$DefaultReader, language = "en"))
75    {
76        readerControl <- prepareReader(readerControl, x$DefaultReader)
77    
78        if (is.function(readerControl$init))
79            readerControl$init()
80    
81        if (is.function(readerControl$exit))
82            on.exit(readerControl$exit())
83    
84        # Allocate memory in advance if length is known
85        tdl <- if (x$Length > 0)
86            vector("list", as.integer(x$Length))
87        else
88            list()
89    
90        if (x$Vectorized)
91            tdl <- mapply(function(x, id) readerControl$reader(x, readerControl$language, id),
92                          pGetElem(x),
93                          id = if (is.null(x$Names) || is.na(x$Names)) as.character(seq_len(x$Length)) else x$Names,
94                          SIMPLIFY = FALSE)
95        else {
96            counter <- 1
97            while (!eoi(x)) {
98                x <- stepNext(x)
99                elem <- getElem(x)
100                id <- if (is.null(x$Names) || is.na(x$Names))
101                    as.character(counter)
102                else
103                    x$Names[counter]
104                doc <- readerControl$reader(elem, readerControl$language, id)
105                if (x$Length > 0)
106                    tdl[[counter]] <- doc
107                else
108                    tdl <- c(tdl, list(doc))
109                counter <- counter + 1
110            }
111        }
112        names(tdl) <- x$Names
113        df <- data.frame(MetaID = rep(0, length(tdl)), stringsAsFactors = FALSE)
114        .VCorpus(tdl, .MetaDataNode(), df)
115    }
116    
117    `[.PCorpus` <-
118    function(x, i)
119    {
120        if (missing(i)) return(x)
121        index <- attr(x, "DMetaData")[[1 , "subset"]]
122        attr(x, "DMetaData")[[1 , "subset"]] <- if (is.numeric(index)) index[i] else i
123        dmeta <- attr(x, "DMetaData")
124        .PCorpus(NextMethod("["), CMetaData(x), dmeta, DBControl(x))
125    }
126    
127    `[.VCorpus` <-
128    function(x, i)
129    {
130        if (missing(i)) return(x)
131        .VCorpus(NextMethod("["), CMetaData(x), DMetaData(x)[i, , drop = FALSE])
132    }
133    
134    `[<-.PCorpus` <-
135    function(x, i, value)
136    {
137        db <- filehash::dbInit(DBControl(x)[["dbName"]], DBControl(x)[["dbType"]])
138        counter <- 1
139        for (id in unclass(x)[i]) {
140            if (identical(length(value), 1L)) db[[id]] <- value
141            else db[[id]] <- value[[counter]]
142            counter <- counter + 1
143        }
144        x
145    }
146    
147    .map_name_index <-
148    function(x, i)
149    {
150        if (is.character(i)) {
151            if (is.null(names(x)))
152                match(i, meta(x, "ID", type = "local"))
153            else
154                match(i, names(x))
155        }
156        i
157    }
158    
159    `[[.PCorpus` <-
160    function(x, i)
161    {
162        i <- .map_name_index(x, i)
163        db <- filehash::dbInit(DBControl(x)[["dbName"]], DBControl(x)[["dbType"]])
164        filehash::dbFetch(db, NextMethod("[["))
165    }
166    `[[.VCorpus` <-
167    function(x, i)
168    {
169        i <- .map_name_index(x, i)
170        lazyTmMap <- meta(x, tag = "lazyTmMap", type = "corpus")
171        if (!is.null(lazyTmMap))
172            .Call("copyCorpus", x, materialize(x, i))
173        NextMethod("[[")
174    }
175    
176    `[[<-.PCorpus` <-
177    function(x, i, value)
178    {
179        i <- .map_name_index(x, i)
180        db <- filehash::dbInit(DBControl(x)[["dbName"]], DBControl(x)[["dbType"]])
181        index <- unclass(x)[[i]]
182        db[[index]] <- value
183        x
184    }
185    `[[<-.VCorpus` <-
186    function(x, i, value)
187    {
188        i <- .map_name_index(x, i)
189        # Mark new objects as not active for lazy mapping
190        lazyTmMap <- meta(x, tag = "lazyTmMap", type = "corpus")
191        if (!is.null(lazyTmMap)) {
192            lazyTmMap$index[i] <- FALSE
193            meta(x, tag = "lazyTmMap", type = "corpus") <- lazyTmMap
194        }
195        # Set the value
196        cl <- class(x)
197        y <- NextMethod("[[<-")
198        class(y) <- cl
199        y
200    }
201    
202    # Update NodeIDs of a CMetaData tree
203    .update_id <-
204    function(x, id = 0, mapping = NULL, left.mapping = NULL, level = 0)
205    {
206        # Traversal of (binary) CMetaData tree with setup of NodeIDs
207        set_id <- function(x) {
208            x$NodeID <- id
209            id <<- id + 1
210            level <<- level + 1
211            if (length(x$Children) > 0) {
212                mapping <<- cbind(mapping, c(x$Children[[1]]$NodeID, id))
213                left <- set_id(x$Children[[1]])
214                if (level == 1) {
215                    left.mapping <<- mapping
216                    mapping <<- NULL
217                }
218                mapping <<- cbind(mapping, c(x$Children[[2]]$NodeID, id))
219                right <- set_id(x$Children[[2]])
220    
221                x$Children <- list(left, right)
222            }
223            level <<- level - 1
224            x
225        }
226        list(root = set_id(x), left.mapping = left.mapping, right.mapping = mapping)
227    }
228    
229    # Find indices to be updated for a CMetaData tree
230    .find_indices <-
231    function(x)
232    {
233        indices.mapping <- NULL
234        for (m in levels(as.factor(DMetaData(x)$MetaID))) {
235            indices <- (DMetaData(x)$MetaID == m)
236            indices.mapping <- c(indices.mapping, list(m = indices))
237            names(indices.mapping)[length(indices.mapping)] <- m
238        }
239        indices.mapping
240    }
241    
242    c2 <-
243    function(x, y, ...)
244    {
245        # Update the CMetaData tree
246        cmeta <- .MetaDataNode(0, list(merge_date = as.POSIXlt(Sys.time(), tz = "GMT"), merger = Sys.getenv("LOGNAME")), list(CMetaData(x), CMetaData(y)))
247        update.struct <- .update_id(cmeta)
248    
249        new <- .VCorpus(c(unclass(x), unclass(y)), update.struct$root, NULL)
250    
251        # Find indices to be updated for the left tree
252        indices.mapping <- .find_indices(x)
253    
254        # Update the DMetaData data frames for the left tree
255        for (i in 1:ncol(update.struct$left.mapping)) {
256            map <- update.struct$left.mapping[,i]
257            DMetaData(x)$MetaID <- replace(DMetaData(x)$MetaID, indices.mapping[[as.character(map[1])]], map[2])
258        }
259    
260        # Find indices to be updated for the right tree
261        indices.mapping <- .find_indices(y)
262    
263        # Update the DMetaData data frames for the right tree
264        for (i in 1:ncol(update.struct$right.mapping)) {
265            map <- update.struct$right.mapping[,i]
266            DMetaData(y)$MetaID <- replace(DMetaData(y)$MetaID, indices.mapping[[as.character(map[1])]], map[2])
267        }
268    
269        # Merge the DMetaData data frames
270        labels <- setdiff(names(DMetaData(y)), names(DMetaData(x)))
271        na.matrix <- matrix(NA,
272                            nrow = nrow(DMetaData(x)),
273                            ncol = length(labels),
274                            dimnames = list(row.names(DMetaData(x)), labels))
275        x.dmeta.aug <- cbind(DMetaData(x), na.matrix)
276        labels <- setdiff(names(DMetaData(x)), names(DMetaData(y)))
277        na.matrix <- matrix(NA,
278                            nrow = nrow(DMetaData(y)),
279                            ncol = length(labels),
280                            dimnames = list(row.names(DMetaData(y)), labels))
281        y.dmeta.aug <- cbind(DMetaData(y), na.matrix)
282        DMetaData(new) <- rbind(x.dmeta.aug, y.dmeta.aug)
283    
284        new
285    }
286    
287    c.Corpus <-
288    function(..., recursive = FALSE)
289    {
290        args <- list(...)
291        x <- args[[1L]]
292    
293      heading <- xmlValue(node[["title"]])      if(length(args) == 1L)
294            return(x)
295    
296      doc <- new("textdocument", author = author, timestamp = timestamp, description = description,      if (!all(unlist(lapply(args, inherits, class(x)))))
297                 id = id, origin = origin, corpus = corpus, heading = heading)          stop("not all arguments are of the same corpus type")
298    
299      new("textdoccol", docs = list(doc), tdm = matrix())      if (inherits(x, "PCorpus"))
300  })          stop("concatenation of corpora with underlying databases is not supported")
301    
302        if (recursive)
303            Reduce(c2, args)
304        else {
305            args <- do.call("c", lapply(args, unclass))
306            .VCorpus(args,
307                     cmeta = .MetaDataNode(),
308                     dmeta = data.frame(MetaID = rep(0, length(args)),
309                                        stringsAsFactors = FALSE))
310        }
311    }
312    
313    c.TextDocument <-
314    function(..., recursive = FALSE)
315    {
316        args <- list(...)
317        x <- args[[1L]]
318    
319        if(length(args) == 1L)
320            return(x)
321    
322        if (!all(unlist(lapply(args, inherits, class(x)))))
323            stop("not all arguments are text documents")
324    
325        dmeta <- data.frame(MetaID = rep(0, length(args)),
326                            stringsAsFactors = FALSE)
327        .VCorpus(args, .MetaDataNode(), dmeta)
328    }
329    
330    print.Corpus <-
331    function(x, ...)
332    {
333        cat(sprintf(ngettext(length(x),
334                             "A corpus with %d text document\n",
335                             "A corpus with %d text documents\n"),
336                    length(x)))
337        invisible(x)
338    }
339    
340    summary.Corpus <-
341    function(object, ...)
342    {
343        print(object)
344        if (length(DMetaData(object)) > 0) {
345            cat(sprintf(ngettext(length(attr(CMetaData(object), "MetaData")),
346                                 "\nThe metadata consists of %d tag-value pair and a data frame\n",
347                                 "\nThe metadata consists of %d tag-value pairs and a data frame\n"),
348                        length(CMetaData(object)$MetaData)))
349            cat("Available tags are:\n")
350            cat(strwrap(paste(names(CMetaData(object)$MetaData), collapse = " "), indent = 2, exdent = 2), "\n")
351            cat("Available variables in the data frame are:\n")
352            cat(strwrap(paste(names(DMetaData(object)), collapse = " "), indent = 2, exdent = 2), "\n")
353        }
354    }
355    
356    inspect <-
357    function(x)
358        UseMethod("inspect", x)
359    inspect.PCorpus <-
360    function(x)
361    {
362        summary(x)
363        cat("\n")
364        db <- filehash::dbInit(DBControl(x)[["dbName"]], DBControl(x)[["dbType"]])
365        show(filehash::dbMultiFetch(db, unlist(x)))
366    }
367    inspect.VCorpus <-
368    function(x)
369    {
370        summary(x)
371        cat("\n")
372        print(noquote(lapply(x, identity)))
373    }
374    
375    lapply.PCorpus <-
376    function(X, FUN, ...)
377    {
378        db <- filehash::dbInit(DBControl(X)[["dbName"]], DBControl(X)[["dbType"]])
379        lapply(filehash::dbMultiFetch(db, unlist(X)), FUN, ...)
380    }
381    lapply.VCorpus <-
382    function(X, FUN, ...)
383    {
384        lazyTmMap <- meta(X, tag = "lazyTmMap", type = "corpus")
385        if (!is.null(lazyTmMap))
386            .Call("copyCorpus", X, materialize(X))
387        base::lapply(X, FUN, ...)
388    }
389    
390    writeCorpus <-
391    function(x, path = ".", filenames = NULL)
392    {
393        filenames <- file.path(path,
394                               if (is.null(filenames)) unlist(lapply(x, function(x) sprintf("%s.txt", ID(x))))
395                               else filenames)
396        i <- 1
397        for (o in x) {
398            writeLines(as.PlainTextDocument(o), filenames[i])
399            i <- i + 1
400        }
401    }

Legend:
Removed from v.18  
changed lines
  Added in v.1259

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