.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/plot_cran.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code or to run this example in your browser via JupyterLite. .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_plot_cran.py: Loading a RDA file with custom types from CRAN ============================================== A more advanced example showing how to read a dataset in the RDATA format from the CRAN repository of R packages that include custom R types. .. GENERATED FROM PYTHON SOURCE LINES 11-30 We will show how to load the graph of the classical `seven bridges of Königsberg problem `_ from the R package igraphdata. .. warning:: This is for illustration purposes only. If you plan to use the same dataset repeatedly it is better to download it, or to use a package that caches it, such as `scikit-datasets `_. We will make use of the function :external+python:func:`urllib.request.urlopen` to load the url, as well as the package rdata. The package is a tar file so we need also to import the :external+python:mod:`tarfile` module. We will use the package `igraph `_ for constructing the graph in Python. Finally, we will import some plotting routines from Matplotlib. .. GENERATED FROM PYTHON SOURCE LINES 30-41 .. code-block:: Python import tarfile from urllib.request import urlopen import igraph import igraph.drawing import matplotlib.pyplot as plt from matplotlib.colors import to_hex import rdata .. GENERATED FROM PYTHON SOURCE LINES 42-43 The following URL contains the link to download the package from CRAN. .. GENERATED FROM PYTHON SOURCE LINES 43-49 .. code-block:: Python pkg_url = ( "https://cran.r-project.org/src/contrib/Archive/" "igraphdata/igraphdata_1.0.0.tar.gz" ) .. GENERATED FROM PYTHON SOURCE LINES 50-54 The dataset is contained in the "data" folder, as it is common for R packages. The file is named Koenisberg and it is in the RDATA format (.rda extension). .. GENERATED FROM PYTHON SOURCE LINES 54-56 .. code-block:: Python data_path = "igraphdata/data/Koenigsberg.rda" .. GENERATED FROM PYTHON SOURCE LINES 57-60 We proceed to open the package using :external+python:func:`~urllib.request.urlopen` and :external+python:mod:`tarfile`. .. GENERATED FROM PYTHON SOURCE LINES 60-72 .. code-block:: Python with urlopen(pkg_url) as package: with tarfile.open(fileobj=package, mode="r|gz") as package_tar: for member in package_tar: if member.name == data_path: dataset = package_tar.extractfile(member) assert dataset with dataset: parsed = rdata.parser.parse_file(dataset) break .. GENERATED FROM PYTHON SOURCE LINES 73-74 We could try to convert this dataset to Python objects. .. GENERATED FROM PYTHON SOURCE LINES 74-78 .. code-block:: Python converted = rdata.conversion.convert(parsed) print(converted) .. rst-class:: sphx-glr-script-out .. code-block:: none /home/docs/checkouts/readthedocs.org/user_builds/rdata/envs/latest/lib/python3.11/site-packages/rdata/conversion/_conversion.py:900: UserWarning: Missing constructor for R class "igraph". The underlying R object is returned instead. warnings.warn( {'Koenigsberg': [array([4.]), array([False]), array([1., 1., 3., 3., 3., 2., 2.]), array([0., 0., 0., 1., 2., 1., 1.]), array([1., 0., 6., 5., 2., 3., 4.]), array([1., 0., 2., 6., 5., 3., 4.]), array([0., 0., 2., 4., 7.]), array([0., 3., 6., 7., 7.]), [array([1., 0., 1.]), {np.str_('name'): array(['The seven bidges of Koenigsberg'], dtype='`_. We will convert it to a :external+igraph:class:`~igraph.Graph` object from the `Python version of the igraph package `_. The attrs dict is empty and will not be used. .. GENERATED FROM PYTHON SOURCE LINES 107-135 .. code-block:: Python def graph_constructor(obj, attrs): """Construct graph object from R representation.""" n_vertices = int(obj[0][0]) is_directed = obj[1] edge_from = obj[2].astype(int) edge_to = obj[3].astype(int) # output_edge_index = obj[4] # input_edge_index = obj[5] # output_vertex_edge_index = obj[6] # input_vertex_edge_index = obj[7] graph_attrs = obj[8][1] vertex_attrs = obj[8][2] edge_attrs = obj[8][3] return igraph.Graph( n=n_vertices, directed=is_directed, edges=list(zip(edge_from, edge_to, strict=True)), graph_attrs=graph_attrs, vertex_attrs=vertex_attrs, edge_attrs=edge_attrs, ) .. GENERATED FROM PYTHON SOURCE LINES 136-142 We create a dict with all the constructors that we want to apply. In this case, we include first the default constructors (which provide transformations for common R classes) and our newly created constructor. The key used for the dictionary entries should be the name of the corresponding R class. .. GENERATED FROM PYTHON SOURCE LINES 142-147 .. code-block:: Python constructor_dict = { **rdata.conversion.DEFAULT_CLASS_MAP, "igraph": graph_constructor, } .. GENERATED FROM PYTHON SOURCE LINES 148-150 We can now call the :func:`rdata.conversion.convert` functtion, supplying the dictionary of constructors to use. .. GENERATED FROM PYTHON SOURCE LINES 150-152 .. code-block:: Python converted = rdata.conversion.convert(parsed, constructor_dict=constructor_dict) .. GENERATED FROM PYTHON SOURCE LINES 153-155 Finally, we check the constructed graph by plotting it using the :external+igraph:func:`igraph.drawing.plot` function. .. GENERATED FROM PYTHON SOURCE LINES 155-168 .. code-block:: Python fig, axes = plt.subplots() plt.subplots_adjust(left=0, right=1, bottom=0, top=1) igraph.drawing.plot( converted["Koenigsberg"], target=axes, vertex_label=converted["Koenigsberg"].vs["name"], vertex_label_size=8, vertex_size=120, vertex_color=to_hex("tab:blue"), edge_label=converted["Koenigsberg"].es["name"], edge_label_size=8, ) plt.show() .. image-sg:: /auto_examples/images/sphx_glr_plot_cran_001.png :alt: plot cran :srcset: /auto_examples/images/sphx_glr_plot_cran_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 1.229 seconds) .. _sphx_glr_download_auto_examples_plot_cran.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: lite-badge .. image:: images/jupyterlite_badge_logo.svg :target: ../lite/lab/index.html?path=auto_examples/plot_cran.ipynb :alt: Launch JupyterLite :width: 150 px .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_cran.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_cran.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_cran.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_