/usr/lib/python3/dist-packages/rpy2/robjects/help.py is in python3-rpy2 2.8.5-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 | """
R help system.
"""
import sys, os
from collections import namedtuple
import sqlite3
import rpy2.rinterface as rinterface
from rpy2.rinterface import StrSexpVector
from rpy2.robjects.packages_utils import get_packagepath, _libpaths, _packages
import rpy2.rlike.container as rlc
if sys.version_info[0] == 2:
range = xrange
tmp = rinterface.baseenv['R.Version']()
tmp_major = int(tmp[tmp.do_slot('names').index('major')][0])
tmp_minor = float(tmp[tmp.do_slot('names').index('minor')][0])
if (tmp_major > 2) or (tmp_major == 2 and tmp_minor >= 13):
readRDS = rinterface.baseenv['readRDS']
else:
readRDS = rinterface.baseenv['.readRDS']
del(tmp)
del(tmp_major)
del(tmp_minor)
_eval = rinterface.baseenv['eval']
def quiet_require(name, lib_loc = None):
""" Load an R package /quietly/ (suppressing messages to the console). """
if lib_loc == None:
lib_loc = "NULL"
expr_txt = "suppressPackageStartupMessages(base::require(%s, lib.loc=%s))" \
%(name, lib_loc)
expr = rinterface.parse(expr_txt)
ok = _eval(expr)
return ok
quiet_require('tools')
_get_namespace = rinterface.baseenv['getNamespace']
_lazyload_dbfetch = rinterface.baseenv['lazyLoadDBfetch']
tools_ns = _get_namespace(StrSexpVector(('tools',)))
#_Rd_get_argument_table = tools_ns['.Rd_get_argument_table']
_Rd_db = tools_ns['Rd_db']
_Rd_deparse = tools_ns['.Rd_deparse']
__rd_meta = os.path.join('Meta', 'Rd.rds')
__package_meta = os.path.join('Meta', 'package.rds')
def create_metaRd_db(dbcon):
""" Create an database to store R help pages.
dbcon: database connection (assumed to be SQLite - may or may not work
with other databases)
"""
dbcon.execute('''
CREATE TABLE package (
name TEXT UNIQUE,
title TEXT,
version TEXT,
description TEXT
);
''')
dbcon.execute('''
CREATE TABLE rd_meta (
id INTEGER, file TEXT UNIQUE, name TEXT, type TEXT, title TEXT, encoding TEXT,
package_rowid INTEGER
);
''')
dbcon.execute('''
CREATE INDEX type_idx ON rd_meta (type);
''')
dbcon.execute('''
CREATE TABLE rd_alias_meta (
rd_meta_rowid INTEGER, alias TEXT
);
''')
dbcon.execute('''
CREATE INDEX alias_idx ON rd_alias_meta (alias);
''')
dbcon.commit()
def populate_metaRd_db(package_name, dbcon, package_path = None):
""" Populate a database with the meta-information
associated with an R package: version, description, title, and
aliases (those are what the R help system is organised around).
- package_name: a string
- dbcon: a database connection
- package_path: path the R package installation (default: None)
"""
if package_path is None:
package_path = get_packagepath(package_name)
rpath = StrSexpVector((os.path.join(package_path,
__package_meta),))
rds = readRDS(rpath)
desc = rds[rds.do_slot('names').index('DESCRIPTION')]
db_res = dbcon.execute('insert into package values (?,?,?,?)',
(desc[desc.do_slot('names').index('Package')],
desc[desc.do_slot('names').index('Title')],
desc[desc.do_slot('names').index('Version')],
desc[desc.do_slot('names').index('Description')],
))
package_rowid = db_res.lastrowid
rpath = StrSexpVector((os.path.join(package_path,
__rd_meta),))
rds = readRDS(rpath)
FILE_I = rds.do_slot("names").index('File')
NAME_I = rds.do_slot("names").index('Name')
TYPE_I = rds.do_slot("names").index('Type')
TITLE_I = rds.do_slot("names").index('Title')
ENCODING_I = rds.do_slot("names").index('Encoding')
ALIAS_I = rds.do_slot("names").index('Aliases')
for row_i in range(len(rds[0])):
db_res = dbcon.execute('insert into rd_meta values (?,?,?,?,?,?,?)',
(row_i,
rds[FILE_I][row_i],
rds[NAME_I][row_i],
rds[TYPE_I][row_i],
rds[TITLE_I][row_i],
rds[ENCODING_I][row_i],
package_rowid))
rd_rowid = db_res.lastrowid
for alias in rds[ALIAS_I][row_i]:
dbcon.execute('insert into rd_alias_meta values (?,?)',
(rd_rowid, alias))
Item = namedtuple('Item', 'name value')
class Page(object):
""" An R documentation page.
The original R structure is a nested sequence of components,
corresponding to the latex-like .Rd file
An help page is divided into sections, the names for the sections
are the keys for the dict attribute 'sections', and a given section
can be extracted with the square-bracket operator.
In R, the S3 class 'Rd' is the closest entity to this class.
"""
def __init__(self, struct_rdb, _type = ''):
sections = rlc.OrdDict()
for elt in struct_rdb:
rd_tag = elt.do_slot("Rd_tag")[0][1:]
if rd_tag == 'section':
rd_section = rd_tag[0]
lst = sections.get(rd_tag)
if lst is None:
lst = []
sections[rd_tag] = lst
for sub_elt in elt:
lst.append(sub_elt)
self._sections = sections
self._type = _type
def _section_get(self):
return self._sections
sections = property(_section_get, None,
"Sections in the in help page, as a dict.")
def __getitem__(self, item):
""" Get a section """
return self.sections[item]
def arguments(self):
""" Get the arguments and their description as a list of tuples. """
section = self._sections.get('arguments')
res = list()
if section is None:
return res
for item in section:
if item.do_slot("Rd_tag")[0] == '\\item':
if len(item) != 2:
continue
arg_name = _Rd_deparse(item[0])[0]
arg_desc = _Rd_deparse(item[1])[0]
for x in arg_name.split(','):
x = x.lstrip()
if x.endswith('\\dots'):
x = '...'
res.append(Item(x, arg_desc))
else:
continue
return res
def description(self):
""" Get the description of the entry """
section = self._sections.get('description', None)
if section is None:
return ''
else:
res = ''.join(_Rd_deparse(x)[0] for x in section)
return res
def title(self):
""" Get the title """
section = self._sections['title']
res = ''.join(_Rd_deparse(x)[0] for x in section)
return res
def value(self):
""" Get the value returned """
section = self._sections.get('value', None)
if section is None:
return ''
else:
res = ''.join(_Rd_deparse(x)[0] for x in section)
return res
def seealso(self):
""" Get the other documentation entries recommended """
section = self._sections.get('seealso', None)
if section is None:
return ''
else:
res = ''.join(_Rd_deparse(x)[0] for x in section)
return res
def usage(self):
""" Get the usage for the object """
section = self._sections.get('usage', None)
if section is None:
res = ''
else:
res = (_Rd_deparse(x)[0] for x in section)
res = ''.join(res)
return res
def iteritems(self):
""" iterator through the sections names and content
in the documentation Page. """
return self.sections.iteritems
def to_docstring(self, section_names = None):
""" section_names: list of section names to consider. If None
all sections are used.
Returns a string that can be used as a Python docstring. """
s = []
if section_names is None:
section_names = self.sections.keys()
def walk(tree):
if not isinstance(tree, str):
for elt in tree:
walk(elt)
else:
s.append(tree)
s.append(' ')
for name in section_names:
s.append(name)
s.append(os.linesep)
s.append('-' * len(name))
s.append(os.linesep)
s.append(os.linesep)
walk(self.sections[name])
s.append(os.linesep)
s.append(os.linesep)
return ''.join(s)
class Package(object):
"""
The R documentation page (aka help) for a package.
"""
__package_path = None
__package_name = None
__aliases_info = 'aliases.rds'
__hsearch_meta = os.path.join('Meta', 'hsearch.rds')
__paths_info = 'paths.rds'
__anindex_info = 'AnIndex'
def __package_name_get(self):
return self.__package_name
name = property(__package_name_get, None, None,
'Name of the package as known by R')
def __init__(self, package_name, package_path = None):
self.__package_name = package_name
if package_path is None:
package_path = get_packagepath(package_name)
self.__package_path = package_path
rd_meta_dbcon = sqlite3.connect(':memory:')
create_metaRd_db(rd_meta_dbcon)
populate_metaRd_db(package_name, rd_meta_dbcon, package_path = package_path)
self._dbcon = rd_meta_dbcon
path = os.path.join(package_path, 'help', package_name + '.rdx')
self._rdx = readRDS(StrSexpVector((path, )))
def fetch(self, alias):
""" Fetch the documentation page associated with a given alias.
For S4 classes, the class name is *often* suffixed with '-class'.
For example, the alias to the documentation for the class
AnnotatedDataFrame in the package Biobase is 'AnnotatedDataFrame-class'.
"""
c = self._dbcon.execute('SELECT rd_meta_rowid, alias FROM rd_alias_meta WHERE alias=?',
(alias, ))
res_alias = c.fetchall()
if len(res_alias) == 0:
raise HelpNotFoundError("No help could be fetched",
topic = alias, package = self.__package_name)
c = self._dbcon.execute('SELECT file, name, type FROM rd_meta WHERE rowid=?',
(res_alias[0][0], ))
# since the selection is on a verified rowid we are sure to exactly get one row
res = c.fetchall()
rkey = StrSexpVector((res[0][0][:-3], ))
_type = res[0][2]
rpath = StrSexpVector((os.path.join(self.package_path,
'help',
self.__package_name + '.rdb'),))
rdx_variables = self._rdx[self._rdx.do_slot('names').index('variables')]
_eval = rinterface.baseenv['eval']
devnull_func = rinterface.parse('function(x) {}')
devnull_func = _eval(devnull_func)
res = _lazyload_dbfetch(rdx_variables[rdx_variables.do_slot('names').index(rkey[0])],
rpath,
self._rdx[self._rdx.do_slot('names').index("compressed")],
devnull_func)
p_res = Page(res, _type = _type)
return p_res
package_path = property(lambda self: str(self.__package_path),
None, None,
"Path to the installed R package")
def __repr__(self):
r = 'R package %s %s' %(self.__package_name,
super(Package, self).__repr__())
return r
class HelpNotFoundError(KeyError):
""" Exception raised when an help topic cannot be found. """
def __init__(self, msg, topic=None, package=None):
super(HelpNotFoundError, self).__init__(msg)
self.topic = topic
self.package = package
def pages(topic):
""" Get help pages corresponding to a given topic. """
res = list()
for path in _libpaths():
for name in _packages(**{'all.available': True,
'lib.loc': StrSexpVector((path,))}):
#FIXME: what if the same package is installed
# at different locations ?
pack = Package(name)
try:
page = pack.fetch(topic)
res.append(page)
except HelpNotFoundError as hnfe:
pass
return tuple(res)
def docstring(package, alias, sections=['usage', 'arguments']):
if not isinstance(package, Package):
package = Package(package)
page = package.fetch(alias)
return page.to_docstring(sections)
|