Contribuindo para a documentação do PyMC#

Uma visão geral da documentação do PyMC#

A documentação do PyMC é gerada a partir de dois repositórios GitHub diferentes, cada um contendo um tipo diferente de documentação:

  • pymc: O repositório pymc contém a maior parte do conteúdo de referência na forma de docstrings (strings anexadas ao objeto Python que descrevem), alguns guias sobre a funcionalidade principal e os documentos de contribuição.

  • pymc-examples: O repositório pymc-examples contém uma coleção de mais de 90 notebooks com exemplos de uso, explicações detalhadas e tutoriais sobre PyMC.

Nesta palestra, vamos nos concentrar em contribuir para pymc-examples, que contém documentação cada vez mais diversificada. Começaremos com uma descrição do recurso, seus recursos e como eles se relacionam com nossos objetivos pedagógicos e, em seguida, mergulharemos no uso desses recursos para escrever documentação técnica clara, bonita e bem referenciada.

A ideia: um livro executável feito de blogposts#

Cuidado

Não explicaremos como configurar um site semelhante, isso exigiria outra conversa.

Daremos uma visão geral dos recursos disponíveis e sobre por que os escolhemos para, em seguida, mergulhar em nosso objetivo principal da palestra: Como você, como colaborador da documentação do PyMC, pode aproveitá-los

Nossa lista de desejos:

  • Fácil de escrever

  • Fácil de executar, tanto ao escrever páginas quanto ao lê-las. Devemos ser capazes de executar o código daqui a alguns anos.

  • Navegue através de tags e categorias

  • Pesquisável por si só e pesquisável na documentação da biblioteca pymc

  • Recurso citável

  • Reconhecer os autores (sem fazer disso o foco)

  • Índice automático

  • Acessível

  • DRY: não se repita. Coisas compartilhadas entre vários notebooks devem ser feitas uma vez quando possível.

A implementação: jupyter notebook + sphinx (+ extensões)#

  • Fácil de escrever

    • Markdown

    • suportado via sphinx+myst-parser

  • Fácil de executar, tanto ao escrever páginas quanto ao lê-las. Devemos ser capazes de executar o código daqui a alguns anos.

    • Caderno Jupyter combinado com fichário e distintivos do Google Colab no topo de cada página

    • suportado via sphinx+myst-nb e um modelo html personalizado para os crachás

    • o ambiente usado para executá-los é armazenado automaticamente graças à biblioteca de marcas d’água

  • Navegue através de tags e categorias

    • suportado via sphinx+blog

  • Pesquisável por si só e pesquisável na documentação da biblioteca pymc

    • suportado via sphinx+pydata-sphinx-theme+readthedocs

  • Recurso citável

    • suportado via zenodo+modelo personalizado

  • Reconhecer os autores (sem fazer disso o foco)

    • suportado via blog + modelo personalizado

  • Índice automático

    • suportado via sphinx+pydata-sphinx-theme

  • Acessível

    • pydata-sphinx-theme está trabalhando na acessibilidade do tema e continuará a fazê-lo

  • DRY: não se repita. Coisas compartilhadas entre vários notebooks devem ser feitas uma vez quando possível.

    • Citações centralizadas graças ao sphinx-bibtex, elas são referenciadas nos documentos com 2 palavras-chave

    • Os crachás são automáticos

    • Tags e categorias são automáticas

    • O sumário é automático

    • As 2 últimas seções com informações de licença e citação são geradas a partir de uma fonte centralizada, com apenas 2 linhas necessárias por notebook

Para resumir, graças ao trabalho de várias pessoas incríveis (tanto colaboradores experientes do PyMC quanto novos membros que trabalham conosco via Outreachy e GSoD) e os fundos que arrecadamos durante [PyMCon](https ://discourse.pymc.io/c/pymcon/2020talks/15) e GSoD, mudamos a maior parte de nossa infraestrutura de documentação nos últimos 9 meses.

Você já pode ver uma grande mudança:

imagem de fundo
Current style
imagem de fundo
Old style

O problema: muitos documentos?#

Nossa infraestrutura oferece suporte a todos os pontos acima, mas apenas alguns notebooks foram atualizados para aproveitá-los. Portanto, embora pudéssemos ter tudo isso, ainda estamos longe de lá!

MyST: Markedly Structured Text#

Como acabamos de dizer, já configuramos a infraestrutura para todos os pontos acima, então você não precisa se preocupar com isso. O resto do webinar será um myst quickstart direcionado para contribuir com pymc-examples.

Core markup#

MyST is a superset of ✨✨ Markdown ✨✨. Everything you know and love about markdown is valid MyST markup: italics, code blocks, links, headers, lists…

However, markdown is too limited for technical writing and for resources containing many files. MyST fills this gap by bringing to markdown all the features of restructured text, a similar markup language designed for technical documentation. It does so by extending markdown with a few custom idioms and by supporting roles and directives (covered in the following subsections).

Targets

Targets are used to define custom anchors that you can refer to elsewhere in your documentation using roles. They generally go before section titles, but they can also point to lists or specific bullet points within a list.

Targets are creating with (target_id)= right before the section or item we want them to point to. You can see the equal at the end as an indicator that we are making the target id equivalent to what comes after. Thus, referencing the target id becomes the same as referencing a section header or bullet point.

Math

Like Jupyter notebooks, MyST supports using $ for inline latex math expressions, and $$ for block expressions. Moreover, block mathematical expressions can be given ids in order to reference them elsewhere using roles. Thus:

$$
P(\theta|y) \propto P(y|\theta) P(\theta)
$$ (eq:bayes)

renders as:

(1)#\[ P(\theta|y) \propto P(y|\theta) P(\theta) \]

and can be referenced.

Roles#

Roles provide a way to specify arbitrary inline features. Their base syntax is {role-name}`role-content` and can be divided in two subgroups: cross-referencing and formatting roles, with the cross-referencing use being far more important.

Cross-referencing roles#

Cross-referencing roles can be used in two ways:

{role-name}`target`

{role-name}`custom text for link <target>`

  • ref and numref role is used to link to manually created targets, with (id)=, in figures… ref is replaced by the title of what we are linking to, numref (not valid for all objects) is replaced by its count.

  • doc role is used to link using the path to a file

  • term role is used to link to terms defined in our glossary.

  • python domain references: mod (module), func (function), class or meth (method) are used to link to python objects documented in the API.

    • These can also take a ~ character before the import path to show only the object, not its import path.

  • bibtex citation: cite:p and cite:t are used to cite the scientific literature and tell sphinx to keep a log of citations so we can generate the biblography automatically.

  • eq for equation targets

Examples

  • {ref}`docs/idea` is rendered as A ideia: um livro executável feito de blogposts and points to a title

  • {ref}`the idea <docs/idea>` is rendered as the idea and points to a title

  • {eq}`eq:bayes` is rendered as (1) and points to an equation

  • {ref}`pymc-examples bullet point <docs/pymc-examples-point>` is rendered as pymc-examples bullet point, and points to a bullet point using a custom text for the link. Here as we link to a bullet point we need to use custom text, sphinx can’t use the title itself as link text.

  • {class}`pymc.Normal` is rendered as pymc.Normal and points to the documentation of the Normal class in PyMC

  • {class}`~pymc.Normal` is rendered as Normal and also points to the documentation of the Normal class in PyMC, but showing on Normal.

  • {class}`normal distribution <pymc.Normal>` is rendered as normal distribution and again, also points to the documentation of the Normal class in PyMC but showing custom text.

  • {term}`pymc:posterior` is rendered as posterior and points to the posterior definition in the glossary.

Nota

We can also use cross references for external links. In such cases, the target needs to be prepended by the external website id, we do this with our term cross reference, indicating it should point to the PyMC docs.

If the target doesn’t exist in the current website nor it is repeated among the external websites we have configured we can skip this prefix. We can therefore skip the prefix safely for links to python objects, and we have, the import path is already unique.

Formatting roles#

  • abbr for abbreviations: PPL

  • bdg-<style> for badges: caution. Reference for valid styles.

  • octicon for octicon icons:

  • fas, fab and far for Font Awesome icons:

Directives#

Directives provide a way to specify arbitrary block/paragraph features. They are much more diverse and flexible than roles. Their base syntax is:

:::{directivename} main-argument
:kwarg1: value
:kwarg2: value

Main content of the directive, generally prose but not necessarily.
:::

Out of the 4 blocks (name, argument, keyword arguments and content), only the name is always required. Each directive has its own rules and required (or even forbidden sometimes) blocks.

Figure#

MyST provides a figure-md directive where we can add images with an id and a caption that gets rendered both in pure markdown (unrendered notebook) and in the website (where it looks nicer).

:::{figure-md} imposter

![imposter syndrome](imposter.jpg)

This is a caption in **Markdown**! Captions must be single paragraph.
:::
The image shows two venn diagrams. The left side describes the imposter syndrome.There is a big yellow circle labeled"what I think others know", inside it has a small blue circle labeled "What I know".The right side describes the reality. The blue circle stays the same, but now,it is instead surrounded by many yellow circles of the same size that combinedcover the same area as the big yellow circle in the previous diagram. Now eachyellow circle represents what someone else knows, with no circle being smaller thanthe other.

Fig. 1 Image by David Whittaker#

We really like the image in Fig. 1 and decided to use it here because we think that pymc-examples is a crystallization of this image. Nobody within the PyMC team know everything covered in the examples, the collection of examples was built by developers, power users, first time contributors and progressively ended up covering more and more, just like the yellow circles in the right diagram.

It is also a wink to Melissa’s talk about sphinx which you should look if you are interested in setting sphinx up for your project.

Admonitions#

Admonitions provide a way to highlight a block of content with special relevance. You can use it for warnings, tips or notes. The complete list of admonition styles are available at the jupyterbook website

:::{tip}
Here is an awesome tip if you use this example
:::

Dica

Use admonitions for content you don’t want readers to miss, even if skimming only, chances are they will stop at the admonition blocks.

And more!#

There are still more directives, most of which you don’t need to contribute to pymc examples. In the next section we’ll go over our «jupyter style guide» and cover 3 more directives that are important for pymc-examples.

Our conventions#

To try and ensure some common style and formatting among all the examples even though it is a collaborative effort with many people contributing, we also have some extra conventions. They are outlined in our documentation, at the Jupyter Style Guide page.