Exemple #1
0
 def list_views(self, e):  # @UnusedVariable
     available = []
     mf = MakeFiguresNDP(None)
     for x in sorted(mf.available()): 
         data_formats = mf.available_formats(x)
         available.append((x, data_formats))
     return {
         'available': available,
     } 
Exemple #2
0
def figint01():
    ndp = parse_ndp("""
        mcdp {
        
        }
    """)
    mf = MakeFiguresNDP(ndp=ndp, image_source=None, yourname=None)

    for name in mf.available():
        formats = mf.available_formats(name)
        res = mf.get_figure(name, formats)
        print('%s -> %s %s ' %
              (name, formats, map(len, [res[f] for f in formats])))
Exemple #3
0
def allformats(context, id_ndp, ndp, libname):
    mf = MakeFiguresNDP(ndp=ndp, image_source=None, yourname=None)
    for name in mf.available():

        do_it = libname in ['basic', 'libtemplates', 'solver'] or \
            toss_coin(id_ndp, MCDPConstants.test_fraction_of_allreports)

        if do_it:
            r = context.comp(allformats_report,
                             id_ndp,
                             ndp,
                             libname,
                             name,
                             job_id=name)

            if MCDPConstants.test_allformats_report_write:
                context.add_report(r, 'allformats', id_ndp=id_ndp, which=name)
Exemple #4
0
    def __call__(self, data):
        ndp = get_ndp(data)
        library = data['library']
        paths = library.get_images_paths()
        image_source = ImagesFromPaths(paths)
        mf = MakeFiguresNDP(ndp=ndp, image_source=image_source, yourname=None)

        formats = mf.available_formats(self.name)
        res = mf.get_figure(self.name, formats)

        results = [(_, self.name, res[_]) for _ in formats]
        return results


mf = MakeFiguresNDP(ndp=None)
for name in mf.available():
    allplots.add((name, MFCall(name)))


@contract(returns='tuple(str,*)')
def parse_kv(x):
    return tuple(x.split('='))


def parse_params(p):
    p = p.strip()
    if not p:
        return {}
    seq = p.split(',')

    return dict(parse_kv(_) for _ in seq)
Exemple #5
0
def make_figures(library, soup, res, location, raise_error_dp,
                 raise_error_others, realpath, generate_pdf):
    """ Looks for codes like:

    <pre><code class="mcdp_ndp_graph_templatized">mcdp {
        # empty model
    }
    </code></pre>

        and creates a link to the image
    """
    def go(s0, func):
        selectors = s0.split(',')
        for selector_ in selectors:
            for tag in soup.select(selector_):
                try:
                    r = func(tag)
                    tag.replaceWith(r)
                except (DPSyntaxError, DPSemanticError) as e:
                    if raise_error_dp:
                        raise
                    else:
                        res.note_error(str(e), HTMLIDLocation.for_element(tag))
                        continue
                except Exception as e:
                    if raise_error_others:
                        raise
                    else:
                        res.note_error(str(e), HTMLIDLocation.for_element(tag))
                        continue

    def make_tag(tag0, klass, data, ndp=None, template=None, poset=None):
        svg = data['svg']

        tag_svg = BeautifulSoup(svg, 'lxml', from_encoding='utf-8').svg

        assert tag_svg.name == 'svg'
        if tag_svg.has_attr('width'):
            ws = tag_svg['width']
            hs = tag_svg['height']
            assert 'pt' in ws
            w = float(ws.replace('pt', ''))
            h = float(hs.replace('pt', ''))
            scale = MCDPConstants.scale_svg

            w2 = w * scale
            h2 = h * scale
            tag_svg['width'] = w2
            tag_svg['height'] = h2
            tag_svg['rescaled'] = 'Rescaled from %s %s, scale = %s' % (ws, hs,
                                                                       scale)
        else:
            print('no width in SVG tag: %s' % tag_svg)

        tag_svg['class'] = klass

        if tag0.has_attr('style'):
            tag_svg['style'] = tag0['style']
        if tag0.has_attr('id'):
            tag_svg['id'] = tag0['id']

        if generate_pdf:
            pdf0 = data['pdf']
            pdf = crop_pdf(pdf0, margins=0)

            div = Tag(name='div')

            att = MCDPConstants.ATTR_LOAD_NAME
            if tag0.has_attr('id'):
                basename = tag0['id']
            elif ndp is not None and hasattr(ndp, att):
                basename = getattr(ndp, att)
            elif template is not None and hasattr(template, att):
                basename = getattr(template, att)
            elif poset is not None and hasattr(poset, att):
                basename = getattr(poset, att)
            else:
                hashcode = hashlib.sha224(tag0.string).hexdigest()[-8:]
                basename = 'code-%s' % hashcode

            docname = os.path.splitext(os.path.basename(realpath))[0]
            download = docname + "." + basename + "." + klass + '.pdf'
            a = create_a_to_data(download=download,
                                 data_format='pdf',
                                 data=pdf)
            a['class'] = 'pdf_data'
            a.append(NavigableString(download))
            div.append(tag_svg)
            div.append(a)
            return div
        else:
            return tag_svg

    image_source = ImagesFromPaths(library.get_images_paths())

    mf0 = MakeFiguresNDP(None, None, None)
    available_ndp = set(mf0.available()) | set(mf0.aliases)
    for which in available_ndp:

        def callback(tag0):
            assert tag0.parent is not None
            context = Context()
            load = lambda x: library.load_ndp(x, context=context)
            parse = lambda x: library.parse_ndp(
                x, realpath=realpath, context=context)
            ndp = load_or_parse_from_tag(tag0, load, parse)

            mf = MakeFiguresNDP(ndp=ndp,
                                image_source=image_source,
                                yourname=None)  # XXX
            formats = ['svg']
            if generate_pdf:
                formats.append('pdf')
            data = mf.get_figure(which, formats)
            tag = make_tag(tag0, which, data, ndp=ndp, template=None)
            return tag

        selector = 'render.%s,pre.%s,img.%s' % (which, which, which)
        go(selector, callback)

    mf0 = MakeFiguresTemplate(None, None, None)
    available_template = set(mf0.available()) | set(mf0.aliases)
    for which in available_template:

        def callback(tag0):
            context = Context()
            load = lambda x: library.load_spec(
                SPEC_TEMPLATES, x, context=context)
            parse = lambda x: library.parse_template(
                x, realpath=realpath, context=context)
            template = load_or_parse_from_tag(tag0, load, parse)

            mf = MakeFiguresTemplate(template=template,
                                     library=library,
                                     yourname=None)  # XXX
            formats = ['svg']
            if generate_pdf:
                formats.append('pdf')
            data = mf.get_figure(which, formats)
            tag = make_tag(tag0, which, data, ndp=None, template=template)
            return tag

        selector = 'render.%s,pre.%s,img.%s' % (which, which, which)
        go(selector, callback)

    mf0 = MakeFiguresPoset(None, None)
    available_poset = set(mf0.available()) | set(mf0.aliases)
    for which in available_poset:

        def callback(tag0):
            context = Context()
            load = lambda x: library.load_poset(x, context=context)
            parse = lambda x: library.parse_poset(
                x, realpath=realpath, context=context)
            poset = load_or_parse_from_tag(tag0, load, parse)

            mf = MakeFiguresPoset(poset=poset, image_source=image_source)
            formats = ['svg']
            if generate_pdf:
                formats.append('pdf')
            data = mf.get_figure(which, formats)
            tag = make_tag(tag0,
                           which,
                           data,
                           ndp=None,
                           template=None,
                           poset=poset)
            return tag

        selector = 'render.%s,pre.%s,img.%s' % (which, which, which)
        go(selector, callback)

    unsure = list(soup.select('render'))
    unsure = [_ for _ in unsure if 'errored' not in _.attrs.get('class', '')]
    for _ in unsure:
        msg = 'Invalid "render" element.'
        # msg += '\n\n' + '\n\n'.join(str(_) for _ in unsure)

        msg += '\n\n' + " Available for NDPs: %s." % ", ".join(
            sorted(available_ndp))
        msg += '\n\n' + " Available for templates: %s." % ", ".join(
            sorted(available_template))
        msg += '\n\n' + " Available for posets: %s." % ", ".join(
            sorted(available_poset))
        # raise ValueError(msg)
        res.note_error(msg, HTMLIDLocation.for_element(_))
    return to_html_stripping_fragment(soup)