Search code examples
pyagrum

PyAgrum CPT's outside of a Jupyter Notebook environment


I am working on converting my Jupter notebook PyAgrum bayesian network visualization to a .py file. I am using the pyAgrum.lib.image.exportInference() to get the bayesian network saved but I was wondering if there was anything I could do for the pyAgrum.lib.notebook.showCPTs() and if there was a way I could save the visualization to a .pdf like I am doing for the actual bayesian network. Or Is there a way I can access the html that the pyAgrum.lib.notebook.showCPTs() creates and displays in the Jupyter notebook but in my .py file. Thank you for the help in advance!


Solution

  • You can use playwright to generate pdf (or png) from HTML :

    import pyAgrum as gum
    import pyAgrum.lib.notebook as gnb 
    
    
    async def exportPotentialAsPDF(p:gum.Potential,filename:str):# in Jupyter
        from playwright.async_api import async_playwright
        
        async with async_playwright() as pw:
            browser = await pw.chromium.launch(headless=True)
            page = await browser.new_page()
            await page.set_content(gnb.getPotential(p))
            await page.pdf(path=filename,
                           print_background=True)
            await browser.close()
    
    async def exportPotentialAsPNG(p:gum.Potential,filename:str):# in Jupyter
        from playwright.async_api import async_playwright
        
        async with async_playwright() as pw:
            browser = await pw.chromium.launch(headless=True)
            page = await browser.new_page()
            await page.set_content(gnb.getPotential(p))
            await page.screenshot(path=filename)
            await browser.close()
    
    bn=gum.fastBN("A->B<-C")
    await exportPotentialAsPDF(bn.cpt("B"),"test.pdf")
    await exportPotentialAsPNG(bn.cpt("B"),"test.png")