예제 #1
0
    def process(tag):
        """
        Converts html "latex" tag to actual latex.
        """

        if isinstance(tag, elements.LatexNavigableString):
            yield utf8tolatex(tag.strip('\n'), non_ascii_only=True, brackets=False)

        elif isinstance(tag, bs4.element.NavigableString):
            yield utf8tolatex(Translator.escape(tag).strip('\n'),
                              non_ascii_only=True,
                              brackets=False)

        else:
            yield tag.get('data-latex-open')
            yield tag.get('data-latex-begin-prefix')
            yield tag.get('data-latex-begin')
            yield tag.get('data-latex-begin-suffix')

            for child in tag.children:
                for p in Translator.process(child):
                    yield p

            yield tag.get('data-latex-end-prefix')
            yield tag.get('data-latex-end')
            yield tag.get('data-latex-end-suffix')
            yield tag.get('data-latex-close')
예제 #2
0
def generate_latex_label(label):
    """Convert a label to a valid latex string."""
    if not HAS_PYLATEX:
        raise MissingOptionalLibraryError(
            libname="pylatexenc",
            name="the latex and latex_source circuit drawers",
            pip_install="pip install pylatexenc",
        )

    regex = re.compile(r"(?<!\\)\$(.*)(?<!\\)\$")
    match = regex.search(label)
    if not match:
        label = label.replace(r"\$", "$")
        final_str = utf8tolatex(label, non_ascii_only=True)
    else:
        mathmode_string = match.group(1).replace(r"\$", "$")
        before_match = label[: match.start()]
        before_match = before_match.replace(r"\$", "$")
        after_match = label[match.end() :]
        after_match = after_match.replace(r"\$", "$")
        final_str = (
            utf8tolatex(before_match, non_ascii_only=True)
            + mathmode_string
            + utf8tolatex(after_match, non_ascii_only=True)
        )
    return final_str.replace(" ", "\\,")  # Put in proper spaces
def _add_caption(label, caption):
    """Adds a caption to a label using LaTeX"""
    full_label = ''
    if label != '' or caption != '':
        if label != '':
            label = utf8tolatex(label)
            label = label + r'\\*'
        if caption != '':
            caption = utf8tolatex(caption)
            caption = r'\textit{\small{' + caption + r'}}'
        full_label = r'\begin{center}' + label + caption + r'\end{center}'
    return full_label
예제 #4
0
    def create_template(self,
                        oral,
                        fp1,
                        template='template.tex',
                        comment=False,
                        dirname='papers'):
        def read_template(filename):
            # with open(filename, 'r', encoding='utf-8') as template_file:
            with open(filename, 'r') as template_file:
                template_file_content = template_file.read()
            return Template(template_file_content)

        T_paper = read_template(template)

        kwargs = {}
        kwargs['FNAME'] = utf8tolatex(oral['firstname'])
        kwargs['FNAMEI'] = utf8tolatex(oral['firstname'][:1])
        kwargs['LNAME'] = utf8tolatex(oral['lastname'])
        if 'Affiliation' in oral:
            kwargs['INAME'] = utf8tolatex(oral['Affiliation'])
        if 'affiliation' in oral:
            kwargs['INAME'] = utf8tolatex(oral['affiliation'])
        kwargs['EMAIL'] = oral['email']
        if 'Title' in oral:
            kwargs['TITLE'] = utf8tolatex(oral['Title'])
        if 'title' in oral:
            kwargs['TITLE'] = utf8tolatex(oral['title'])
        if 'Abstract' in oral:
            kwargs['ABSTRACT'] = utf8tolatex(oral['Abstract'])
        if 'abstract' in oral:
            kwargs['ABSTRACT'] = utf8tolatex(oral['abstract'])
        kwargs['F1'] = '$^1$'
        kwargs['F2'] = '$^2$'
        kwargs['F3'] = '$^3$'
        kwargs['LENA'] = str(len(kwargs['ABSTRACT']))
        kwargs['LENW'] = ""
        kwargs['PCODE'] = oral['pcode'].replace('.', '-')
        pcode = oral['pcode'].replace('.', '-')
        if comment:
            kwargs['COMMENT'] = "%"
            kwargs['NOCOMMENT'] = ""
        else:
            kwargs['COMMENT'] = ""
            kwargs['NOCOMMENT'] = "%"
        t1 = T_paper.substitute(**kwargs)
        fn = dirname + '/' + pcode + '.tex'  #   no, it should be P1-12.tex, not P1.12.tex
        print("Writing %s" % fn)
        fp = open(fn, 'w')
        fp.write(t1)
        fp.close()
        msg = '\\tocinsertentry[r]{%s}{%s.~%s}{authors/%s_inc}\n' % (
            kwargs['TITLE'], oral['firstname'], oral['lastname'],
            oral['pcode'])
        fp1.write(msg)
예제 #5
0
def toascii(val):
    val = utf8tolatex(val)
    for old, new in [(r"{\textquoteright}", "`"), (r"{\textbackslash}", "\\"),
                     (r"{\{}", "{"), (r"{\}}", "}"), (r"\''", r'\"'),
                     (r"{\$}", "$"), (r"{\textasciitilde}", "~")]:
        val = val.replace(old, new)
    return val
예제 #6
0
def format_paper_list_entry(arxiv_id, submission_comment='', desired_authors=None, author_list_length_limit=10):
    import re
    from pylatexenc.latexencode import utf8tolatex
    import textwrap
    wrapper = textwrap.TextWrapper(initial_indent='  ', subsequent_indent='    ', width=70,
                                   break_long_words=False, break_on_hyphens=False)
    entry = get_entry_by_arxiv_id(arxiv_id)
    authors = [author['name'] for author in entry['authors']]
    authors = limit_author_list(authors, desired_authors=desired_authors, author_list_length_limit=author_list_length_limit)
    authors = [utf8tolatex(a).replace(r'{\textasciitilde}', '~') for a in authors]
    author_list = ', '.join(authors)
    title = r'\textit{{{0}}}'.format(entry['title'])
    submission_comment = submission_comment.strip()
    if not submission_comment:
        journal_ref = get_journal_reference(entry, r'{pub} \textbf{{{volume}}}, {issue} ({year})')
        if journal_ref:
            submission_comment = ', published as ' + journal_ref.strip()
        else:
            submission_comment = get_submission_comment(entry)
    if submission_comment and not submission_comment.startswith(','):
        submission_comment = ', ' + submission_comment
    arxiv_url = re.sub('v[0-9]*$', '', entry['id'].replace('http://', 'https://'))
    entry = r'\item {0}, {1}{2}; available at \url{{{3}}}'.format(author_list, title, submission_comment, arxiv_url)
    entry = wrapper.fill(' '.join(entry.split()))
    return entry
예제 #7
0
    def format_entry(self, record):
        """
        Special customization function for BibTex entries. Sanitizes HTML characters from any part of the entry, ensures
        that page ranges use two dashes, and abbreviates journals if possible.
        :param record: the entry dict to modify
        :return: the modified dict
        """
        for key, value in record.items():
            record[key] = sanitize_html_strings(value)

        record = bibtexparser.customization.page_double_hyphen(record)
        if 'journal' in record:
            record['journal'] = abbreviate_journal(record['journal'])

        # This should happen after we've sanitized the author string for miscellanceous HTML crud.
        record['ID'] = self.format_id(record)

        for key, value in record.items():
            if key != 'ID':
                # This needs to happen after we create the ID, because the id creation can remove accents from unicode
                # characters but not Latex accents. The non_ascii_only is needed to avoid escaping special Latex
                # characters already present, like with e.g. {NO}$_2$
                record[key] = utf8tolatex(record[key], non_ascii_only=True)

        return record
예제 #8
0
 def thefilter(x):
     if (self.fix_swedish_a):
         x = re.sub(r'\\AA\s+', r'\AA{}', x);
     if (self.encode_utf8_to_latex):
         x = latexencode.utf8tolatex(x, non_ascii_only=True);
     if (self.encode_latex_to_utf8):
         x = latex2text.latex2text(x);
     return x
예제 #9
0
    def test_basic(self):

        input = u"\"\N{LATIN CAPITAL LETTER A WITH GRAVE} votre sant\N{LATIN SMALL LETTER E WITH ACUTE}!\" s'exclama le ma\N{LATIN SMALL LETTER I WITH CIRCUMFLEX}tre de maison \N{LATIN SMALL LETTER A WITH GRAVE} 100%."
        self.assertEqual(
            utf8tolatex(input),
            u"''{\\`A} votre sant{\\'e}!'' s'exclama le ma{\\^\\i}tre de maison {\\`a} 100{\\%}."
        )

        self.assertEqual(
            utf8tolatex(input, non_ascii_only=True),
            u"\"{\\`A} votre sant{\\'e}!\" s'exclama le ma{\\^\\i}tre de maison {\\`a} 100%."
        )

        # TODO: in the future, be clever and avoid breaking macros like this ("\itre"):
        self.assertEqual(
            utf8tolatex(input, brackets=False),
            u"''\\`A votre sant\\'e!'' s'exclama le ma\\^\\itre de maison \\`a 100\%."
        )

        ascii_chars_convert = u" \" # $ % & \\ _ { } ~ "
        self.assertEqual(utf8tolatex(ascii_chars_convert, non_ascii_only=True),
                         ascii_chars_convert)
        self.assertEqual(
            utf8tolatex(ascii_chars_convert, non_ascii_only=False),
            u" '' {\\#} {\\$} {\\%} {\\&} {\\textbackslash} {\\_} {\\{} {\\}} {\\textasciitilde} "
        )

        # generates warnings -- that's good
        test_bad_chars = u"A unicode character: \N{THAI CHARACTER THO THONG}"
        self.assertEqual(
            utf8tolatex(test_bad_chars, substitute_bad_chars=False),
            test_bad_chars)  # unchanged
        self.assertEqual(
            utf8tolatex(test_bad_chars, substitute_bad_chars=True),
            u"A unicode character: {\\bfseries ?}")
예제 #10
0
def cleanUpText(string):
    # clean up text

    cleanedUpText = latexencode.utf8tolatex(string, substitute_bad_chars=True)
    cleanedUpText = re.sub("- ", "", string)
    cleanedUpText = re.sub(r"([><])", r"$\1$", cleanedUpText)
    cleanedUpText = re.sub("([a-z])([A-Z])", r"\1 \2", cleanedUpText)

    return cleanedUpText
예제 #11
0
 def latex(self):
     """Return the corresponding math mode latex string."""
     try:
         from pylatexenc.latexencode import utf8tolatex
     except ImportError as ex:
         raise MissingOptionalLibraryError("pylatexenc",
                                           "latex-from-qasm exporter",
                                           "pip install pylatexenc") from ex
     return utf8tolatex(self.sym())
예제 #12
0
def generate_latex_label(label):
    """Convert a label to a valid latex string."""
    from pylatexenc.latexencode import utf8tolatex

    regex = re.compile(r"(?<!\\)\$(.*)(?<!\\)\$")
    match = regex.search(label)
    if not match:
        label = label.replace(r"\$", "$")
        final_str = utf8tolatex(label, non_ascii_only=True)
    else:
        mathmode_string = match.group(1).replace(r"\$", "$")
        before_match = label[:match.start()]
        before_match = before_match.replace(r"\$", "$")
        after_match = label[match.end():]
        after_match = after_match.replace(r"\$", "$")
        final_str = (utf8tolatex(before_match, non_ascii_only=True) +
                     mathmode_string +
                     utf8tolatex(after_match, non_ascii_only=True))
    return final_str.replace(" ", "\\,")  # Put in proper spaces
예제 #13
0
def encode_laTex(text):
    """

    :param text:
    :return:
    """
    # make sure the input has unicode type
    if (isinstance(text, str)):
        text = unicode(text)
    # character subtitution
    return utf8tolatex(text)
예제 #14
0
 def latex(self, prec=15, nested_scope=None):
     """Return the corresponding math mode latex string."""
     del prec, nested_scope  # unused
     try:
         from pylatexenc.latexencode import utf8tolatex
     except ImportError:
         raise ImportError("To export latex from qasm "
                           "pylatexenc needs to be installed. Run "
                           "'pip install pylatexenc' before using this "
                           "method.")
     return utf8tolatex(self.value)
예제 #15
0
def generate_latex_label(label):
    """Convert a label to a valid latex string."""
    if not HAS_PYLATEX:
        raise ImportError('The latex and latex_source drawers need '
                          'pylatexenc installed. Run "pip install '
                          'pylatexenc" before using the latex or '
                          'latex_source drawers.')

    regex = re.compile(r"(?<!\\)\$(.*)(?<!\\)\$")
    match = regex.search(label)
    if not match:
        label = label.replace(r'\$', '$')
        return utf8tolatex(label)
    else:
        mathmode_string = match.group(1).replace(r'\$', '$')
        before_match = label[:match.start()]
        before_match = before_match.replace(r'\$', '$')
        after_match = label[match.end():]
        after_match = after_match.replace(r'\$', '$')
        return utf8tolatex(before_match) + mathmode_string + utf8tolatex(
            after_match)
예제 #16
0
def parse_accents_str(string):
    """Function that reads a string and translates
    all the known unicode characters into latex commands.

    Parameters:
        string: the string to be translated

    Output:
        the processed string
    """
    if string is not None and string != "":
        string = utf8tolatex(string, non_ascii_only=True)
    return string
예제 #17
0
 def thefilter(x):
     if (self.fix_space_after_escape):
         x = do_fix_space_after_escape(x)
     if (self.fix_swedish_a):
         # OBSOLETE, but still accepted for backwards compatibility
         x = re.sub(r'\\AA\s+', r'\AA{}', x);
         x = re.sub(r'\\o\s+', r'\o{}', x);
     if (self.encode_utf8_to_latex):
         # Need non_ascii_only=True because we might have e.g. braces or other
         # LaTeX code we want to preserve.
         x = latexencode.utf8tolatex(x, non_ascii_only=True);
     if (self.encode_latex_to_utf8):
         x = latex2text.latex2text(x);
     return x
예제 #18
0
    def test_all(self):

        loglevel = logging.getLogger().level
        logging.getLogger().setLevel(logging.CRITICAL)

        def fn(x, bdir=os.path.realpath(os.path.abspath(os.path.dirname(__file__)))):
            return os.path.join(bdir, x)

        with codecs.open(fn('_tmp_uni_chars_test.temp.txt'), 'w', encoding='utf-8') as testf:
            
            for i in range(0x10FFFF):
                # iter over all valid unicode characters
                try:
                    chrname = unicodedata.name(unichr(i)) # test if valid, i.e., it has a UNICODE NAME
                except ValueError:
                    continue

                line = "0x%04X %-50s    |%s|\n"%(i, '['+chrname+']', unichr(i))

                # try to encode it using utf8tolatex
                try:
                    enc = utf8tolatex(line, fail_bad_chars=True)
                except ValueError:
                    continue
                testf.write(enc)

        with codecs.open(fn('uni_chars_test_previous.txt'), 'r', encoding='utf-8') as reff, \
             codecs.open(fn('_tmp_uni_chars_test.temp.txt'), 'r', encoding='utf-8') as testf:
            a = reff.readlines()
            b = testf.readlines()
            
        logging.getLogger().setLevel(loglevel)
        logger = logging.getLogger(__name__)

        # only check up to the supported unicode range
        if sys.maxunicode < 0x10FFFF:
            logger.warning("Only checking up to unicode U+%X, you python build doesn't support higher",
                           sys.maxunicode)
            afiltered = [ aline for aline in a
                          if int(aline[:aline.find(' ')], 0) < sys.maxunicode ]
            a = afiltered
            
        s = difflib.unified_diff(a, b,
                                 fromfile='uni_chars_test_previous.txt',
                                 tofile='_tmp_uni_chars_test.temp.txt')
        diffmsg = "".join(list(s)).strip()
        if diffmsg:
            print(diffmsg)
            raise self.failureException("Unicode coverage tests failed. See full diff above.")
예제 #19
0
 def latex(self, prec=None, nested_scope=None):
     """Return the corresponding math mode latex string."""
     if prec is not None:
         warnings.warn('Parameter \'BinaryOp.latex(..., prec)\' is no longer used '
                       'and is being deprecated.', DeprecationWarning, 2)
     if nested_scope is not None:
         warnings.warn('Parameter \'BinaryOp.latex(..., nested_scope)\' is no longer used '
                       'and is being deprecated.', DeprecationWarning, 2)
     try:
         from pylatexenc.latexencode import utf8tolatex
     except ImportError:
         raise ImportError("To export latex from qasm "
                           "pylatexenc needs to be installed. Run "
                           "'pip install pylatexenc' before using this "
                           "method.")
     return utf8tolatex(self.sym())
예제 #20
0
 def export_to_bytes(self):
     tiers = self.createTiers(self.conjugations)
     formatted_tiers = []
     for t in tiers:
         tier_list = []
         for item in BUILD_CONFIG['filemaker']['latex_tiers']:
             if item['name'] == 'translation':
                 tier_list.append(t['translation'])
             else:
                 tier_list.append(
                     self.appendTier(t[item['name']], item['sep']))
         formatted_tiers.append(tier_list)
     data = {"title": self.title, "conjugations": formatted_tiers}
     tex = utf8tolatex(self.sanitize(self.template.render(data=data)),
                       non_ascii_only=True)
     return bytes(tex, encoding='utf8')
예제 #21
0
 def write_to_temp(self, ftype="tex"):
     formatted_tiers = [[conjugation["output"] for conjugation in x]
                        for x in self.formatted_data]
     data = {
         "title": self.settings["heading"],
         "conjugations": formatted_tiers
     }
     tex = utf8tolatex(self.sanitize(self.template.render(data=data)),
                       non_ascii_only=True)
     fd, path = mkstemp()
     if ftype == "pdf":
         pdf = build_pdf(tex)
         pdf.save_to(path)
     else:
         with open(path, "w") as f:
             f.write(tex)
     return path
예제 #22
0
파일: analytics.py 프로젝트: TQRG/physalia
def _flush_output(out, out_buffer, convert_to_latex):
    output = out_buffer.getvalue()
    out_buffer.close()
    if convert_to_latex:
        from pylatexenc.latexencode import utf8tolatex
        output = (
            "\\documentclass{article}\\begin{document}"
            "\\section{Physalia Hypothesis Test}\n" + utf8tolatex(output)
        ).replace(GREEK_ALPHABET["H0"], "$H_0$").replace(
            GREEK_ALPHABET["H1"], "$H_1$"
        ).replace("<", "\\ensuremath{<}").replace("\n", "\n\n").replace(
            "1.", '\\begin{enumerate}\n\\item '
        ).replace("2.", '\\item ').replace(
            "3. All populations have equal standard deviation.",
            '\\item All populations have equal standard deviation.\n\\end{enumerate}'
        ) + "\\end{document}"
    out.write(output)
예제 #23
0
def parse_accents_record(record):
    """Function that reads the fields inside a bibtex dictionary
    and translates all the known unicode characters into latex commands.

    Parameters:
        record: the bibtex dictionary generated by bibtexparser

    Output:
        the dictionary after having processed all the fields
    """
    for val in record:
        if val != "ID" and len(record[val].strip()) > 0:
            tmp = utf8tolatex(record[val], non_ascii_only=True)
            if tmp != record[val]:
                pBLogger.info(pastr.converting % record["ID"])
                pBLogger.info(pastr.infodashes + tmp.encode("utf-8"))
                accents_changed.append(record["ID"])
            record[val] = tmp
    return record
예제 #24
0
def sanitize(text):
    """
    This is a helper function that should be used to sanitize text for LaTeX output.
    You'll probably need to edit the LaTeX slightly afterwards, but it should look pretty good!
    """
    results = text
    # Fix quotation marks
    if results.startswith('"'):
        results = "``" + results[1:]
    if results.startswith("'"):
        results = "`" + results[1:]
    results = results.replace(" '", ' `')
    results = results.replace(' "', ' ``')
    results = results.replace('"', "''")
    # Fix unicode characters. Bad characters are replaced by a bold '?'
    results = utf8tolatex(results, substitute_bad_chars=True)
    # Fix math entries a^b
    results = re.sub(r'(.\^.)', r'$\1$', results)
    # Fix math entries a_b (note that utf8tolatex has converted _ to {\_})
    results = re.sub(r'(.){\\_}(.)', r'$\1_\2$', results)
    return results
예제 #25
0
def get_latex_from_LT(LT_list, page_number, image_res=None):
    latex_str = ""

    prevfontname = ""
    prevfontstyle = ""

    for i in range(len(LT_list)):
        if isinstance(LT_list[i], LTChar):
            attr = re.split(",|-", LT_list[i].fontname)
            if (prevfontname != attr[0]):
                # latex_str += "\\fontfamily{" + attr[0] + "}\\selectfont "
                prevfontname = attr[0]
            if (len(attr) > 1 and prevfontstyle != attr[1]):
                if prevfontstyle:
                    latex_str += "}"
                prevfontstyle = attr[1]
                if prevfontstyle.startswith("Bold"):
                    latex_str += "\\textbf{"
                elif prevfontstyle.startswith("Italic"):
                    latex_str += "\\textit{"
            elif len(attr) == 1:
                if prevfontstyle:
                    latex_str += "}"
                    prevfontstyle = ""
            latex_str += utf8tolatex(LT_list[i].get_text())
        elif isinstance(LT_list[i], LTFigure) or isinstance(
                LT_list[i], LTImage):
            if prevfontstyle:
                latex_str += "}"
                prevfontstyle = ""
            img_name = save_image(LT_list[i], page_number, "images", image_res)
            if img_name:
                latex_str += "\\begin{figure}\\includegraphics[width=\\linewidth]{" + str(
                    img_name) + "}\\end{figure}"
        # elif isinstance(LT_list[i], LTAnno):
        # 	latex_str += "\\newline\n"
    if prevfontstyle:
        latex_str += "}"
        prevfontstyle = ""
    return latex_str
예제 #26
0
 def latex(self, prec=None, nested_scope=None):
     """Return the corresponding math mode latex string."""
     if prec is not None:
         warnings.warn(
             "Parameter 'Real.latex(..., prec)' is no longer used and is being deprecated.",
             DeprecationWarning,
             2,
         )
     if nested_scope is not None:
         warnings.warn(
             "Parameter 'Real.latex(..., nested_scope)' is no longer used and is "
             "being deprecated.",
             DeprecationWarning,
             2,
         )
     try:
         from pylatexenc.latexencode import utf8tolatex
     except ImportError as ex:
         raise MissingOptionalLibraryError("pylatexenc",
                                           "latex-from-qasm exporter",
                                           "pip install pylatexenc") from ex
     return utf8tolatex(self.value)
def plot_lines(y_vectors,
               x=None,
               labels=None,
               title='Loss',
               xlabel='',
               ylabel='',
               caption='',
               out_file=None):
    """Plots a line graph for each y vector in a list of y vectors"""
    # Ensure all y_vectors are the same length
    lens = np.array([len(_) for _ in y_vectors])
    if not np.all(len(y_vectors[0]) == lens):
        raise ValueError('All vectors in y_vectors must be the same length')

    # Default x and labels to array indices
    if x is None:
        x = range(len(y_vectors[0]))
    if labels is None:
        labels = [str(_) for _ in range(len(y_vectors[0]))]

    rc('text', usetex=True)
    full_xlabel = _add_caption(xlabel, caption)

    for y, label in zip(y_vectors, labels):
        plt.plot(x, y, label=utf8tolatex(label))

    plt.legend(loc='best')
    plt.title(title)
    plt.xlabel(full_xlabel)
    plt.ylabel(ylabel)

    # Output to file or to screen
    if out_file is not None:
        plt.savefig(out_file)
    else:
        plt.show()
    rc('text', usetex=False)

    plt.close()
예제 #28
0
def dblp_comp(inputfile, outputfile):
    # counters
    dblp_cnt = 0
    local_cnt = 0

    parser = BibTexParser()
    parser.customization = homogeneize_latex_encoding
    with open(inputfile) as input_file:
        bib_database = bibtexparser.load(input_file, parser=parser)

    for entry in bib_database.entries:
        try:
            title = entry['title']
        except:
            pprint(style.FAIL, 'LOCL', '(Unknown)',
                   'entry does not have a title')
            local_cnt += 1
            continue
        title = title.replace('}', '')
        title = title.replace('{', '')
        title = title.replace('\n', ' ')
        searchstr = re.sub(' ', '$.', title)
        searchstr = re.sub('$', '$', searchstr)
        try:
            xmlstr = urllib2.urlopen(
                "http://dblp.org/search/publ/api/?q=" + searchstr + "&format=xml&h=1").read()
        except:
            pprint(style.FAIL, 'LOCL', title,
                   'failed to fetch results from DBLP')
            local_cnt += 1
            continue
        xml = ET.fromstring(xmlstr)
        hit = xml.find('./hits/hit/info/url')
        if hit != None:
            xmlstr = urllib2.urlopen(
                re.sub('/rec/', '/rec/xml/', hit.text)).read()
            xml = ET.fromstring(xmlstr)
            hit = xml.find('./')
            t = re.sub('\.$', '', hit.find('title').text)
            t2 = t
            t2 = t2.replace('}', '')
            t2 = t2.replace('{', '')
            if t2.lower() == title.lower():
                # we found the same title; add the information on DBLP
                pprint(style.OKGREEN, 'DBLP', t)
                dblp_cnt += 1
                entrytype = entry['ENTRYTYPE']
                entryid = entry['ID']
                entry.clear()
                entry['ENTRYTYPE'] = entrytype
                entry['ID'] = entryid
                # Title. Use t2 if you wish a title without brackets
                entry['title'] = latexencode.utf8tolatex(t)
                # Authors
                alist = ''
                first = True
                for a in hit.findall('author'):
                    if not first:
                        alist += " and "
                    first = False
                    alist += a.text
                entry['author'] = latexencode.utf8tolatex(alist)
                # DOI
                try:
                    doi = hit.find('ee').text.split('/')[
                        3] + '/' + hit.find('ee').text.split('/')[4]
                    entry['doi'] = latexencode.utf8tolatex(doi)
                except:
                    pass
                # Other fields
                for i in hit:
                    if i.tag not in exceptions:
                        entry[i.tag] = latexencode.utf8tolatex(i.text)
            else:
                # if we don't find results, we keep our old data
                pprint(style.WARNING, 'LOCL', t2, 'titles do not match', title)
                local_cnt += 1
        else:
            pprint(style.WARNING, 'LOCL', title, 'entry not found')
            local_cnt += 1

        # As recommended by DBLP, sleep before continuing the search
        time.sleep(1)

    # write entries to output
    writer = BibTexWriter()
    writer.indent = '  '
    with open(outputfile, 'w') as output_file:
        bibtexparser.dump(bib_database, output_file)

    print('')
    if sys.stdout.isatty():
        print('Database updated. ' + style.OKGREEN + str(dblp_cnt) + style.ENDC + ' entries updated from DBLP, ' +
              style.WARNING + str(local_cnt) + style.ENDC + ' entries kept as they were.')
    else:
        print('Database updated. ' + str(dblp_cnt) + ' entries updated from DBLP, ' +
              str(local_cnt) + ' entries kept as they were.')
    print('')
예제 #29
0
    def _build_latex_array(self, aliases=None):
        """Returns an array of strings containing \\LaTeX for this circuit.

        If aliases is not None, aliases contains a dict mapping
        the current qubits in the circuit to new qubit names.
        We will deduce the register names and sizes from aliases.
        """

        # Rename qregs if necessary
        if aliases:
            qregdata = {}
            for q in aliases.values():
                if q[0] not in qregdata:
                    qregdata[q[0]] = q[1] + 1
                elif qregdata[q[0]] < q[1] + 1:
                    qregdata[q[0]] = q[1] + 1
        else:
            qregdata = self.qregs

        for column, layer in enumerate(self.ops, 1):
            for op in layer:
                if op.condition:
                    mask = self._get_mask(op.condition[0])
                    cl_reg = self.clbit_list[self._ffs(mask)]
                    if_reg = cl_reg[0]
                    pos_2 = self.img_regs[cl_reg]
                    if_value = format(op.condition[1],
                                      'b').zfill(self.cregs[if_reg])[::-1]
                if op.name not in [
                        'measure', 'barrier', 'snapshot', 'load', 'save',
                        'noise'
                ]:
                    nm = op.name
                    qarglist = op.qargs
                    if aliases is not None:
                        qarglist = map(lambda x: aliases[x], qarglist)
                    if len(qarglist) == 1:
                        pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]

                        if op.condition:
                            mask = self._get_mask(op.condition[0])
                            cl_reg = self.clbit_list[self._ffs(mask)]
                            if_reg = cl_reg[0]
                            pos_2 = self.img_regs[cl_reg]

                            if nm == "x":
                                self._latex[pos_1][column] = "\\gate{X}"
                            elif nm == "y":
                                self._latex[pos_1][column] = "\\gate{Y}"
                            elif nm == "z":
                                self._latex[pos_1][column] = "\\gate{Z}"
                            elif nm == "h":
                                self._latex[pos_1][column] = "\\gate{H}"
                            elif nm == "s":
                                self._latex[pos_1][column] = "\\gate{S}"
                            elif nm == "sdg":
                                self._latex[pos_1][column] = "\\gate{S^\\dag}"
                            elif nm == "t":
                                self._latex[pos_1][column] = "\\gate{T}"
                            elif nm == "tdg":
                                self._latex[pos_1][column] = "\\gate{T^\\dag}"
                            elif nm == "u0":
                                self._latex[pos_1][
                                    column] = "\\gate{U_0(%s)}" % (
                                        op.op.params[0])
                            elif nm == "u1":
                                self._latex[pos_1][
                                    column] = "\\gate{U_1(%s)}" % (
                                        op.op.params[0])
                            elif nm == "u2":
                                self._latex[pos_1][column] = \
                                    "\\gate{U_2\\left(%s,%s\\right)}" % (
                                        op.op.params[0], op.op.params[1])
                            elif nm == "u3":
                                self._latex[pos_1][column] = (
                                    "\\gate{U_3(%s,%s,%s)}" %
                                    (op.op.params[0], op.op.params[1],
                                     op.op.params[2]))
                            elif nm == "rx":
                                self._latex[pos_1][
                                    column] = "\\gate{R_x(%s)}" % (
                                        op.op.params[0])
                            elif nm == "ry":
                                self._latex[pos_1][
                                    column] = "\\gate{R_y(%s)}" % (
                                        op.op.params[0])
                            elif nm == "rz":
                                self._latex[pos_1][
                                    column] = "\\gate{R_z(%s)}" % (
                                        op.op.params[0])
                            else:
                                self._latex[pos_1][column] = ("\\gate{%s}" %
                                                              utf8tolatex(nm))

                            gap = pos_2 - pos_1
                            for i in range(self.cregs[if_reg]):
                                if if_value[i] == '1':
                                    self._latex[pos_2 + i][column] = \
                                        "\\control \\cw \\cwx[-" + str(gap) + "]"
                                    gap = 1
                                else:
                                    self._latex[pos_2 + i][column] = \
                                        "\\controlo \\cw \\cwx[-" + str(gap) + "]"
                                    gap = 1

                        else:
                            if nm == "x":
                                self._latex[pos_1][column] = "\\gate{X}"
                            elif nm == "y":
                                self._latex[pos_1][column] = "\\gate{Y}"
                            elif nm == "z":
                                self._latex[pos_1][column] = "\\gate{Z}"
                            elif nm == "h":
                                self._latex[pos_1][column] = "\\gate{H}"
                            elif nm == "s":
                                self._latex[pos_1][column] = "\\gate{S}"
                            elif nm == "sdg":
                                self._latex[pos_1][column] = "\\gate{S^\\dag}"
                            elif nm == "t":
                                self._latex[pos_1][column] = "\\gate{T}"
                            elif nm == "tdg":
                                self._latex[pos_1][column] = "\\gate{T^\\dag}"
                            elif nm == "u0":
                                self._latex[pos_1][
                                    column] = "\\gate{U_0(%s)}" % (
                                        op.op.params[0])
                            elif nm == "u1":
                                self._latex[pos_1][
                                    column] = "\\gate{U_1(%s)}" % (
                                        op.op.params[0])
                            elif nm == "u2":
                                self._latex[pos_1][column] = \
                                    "\\gate{U_2\\left(%s,%s\\right)}" % (
                                        op.op.params[0], op.op.params[1])
                            elif nm == "u3":
                                self._latex[pos_1][column] = (
                                    "\\gate{U_3(%s,%s,%s)}" %
                                    (op.op.params[0], op.op.params[1],
                                     op.op.params[2]))
                            elif nm == "rx":
                                self._latex[pos_1][
                                    column] = "\\gate{R_x(%s)}" % (
                                        op.op.params[0])
                            elif nm == "ry":
                                self._latex[pos_1][
                                    column] = "\\gate{R_y(%s)}" % (
                                        op.op.params[0])
                            elif nm == "rz":
                                self._latex[pos_1][
                                    column] = "\\gate{R_z(%s)}" % (
                                        op.op.params[0])
                            elif nm == "reset":
                                self._latex[pos_1][column] = (
                                    "\\push{\\rule{.6em}{0em}\\ket{0}\\"
                                    "rule{.2em}{0em}} \\qw")
                            else:
                                self._latex[pos_1][column] = ("\\gate{%s}" %
                                                              utf8tolatex(nm))

                    elif len(qarglist) == 2:
                        pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
                        pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]

                        if op.condition:
                            pos_3 = self.img_regs[(if_reg, 0)]
                            temp = [pos_1, pos_2, pos_3]
                            temp.sort(key=int)
                            bottom = temp[1]

                            gap = pos_3 - bottom
                            for i in range(self.cregs[if_reg]):
                                if if_value[i] == '1':
                                    self._latex[pos_3 + i][column] = \
                                        "\\control \\cw \\cwx[-" + str(gap) + "]"
                                    gap = 1
                                else:
                                    self._latex[pos_3 + i][column] = \
                                        "\\controlo \\cw \\cwx[-" + str(gap) + "]"
                                    gap = 1

                            if nm == "cx":
                                self._latex[pos_1][column] = \
                                    "\\ctrl{" + str(pos_2 - pos_1) + "}"
                                self._latex[pos_2][column] = "\\targ"
                            elif nm == "cz":
                                self._latex[pos_1][column] = \
                                    "\\ctrl{" + str(pos_2 - pos_1) + "}"
                                self._latex[pos_2][column] = "\\control\\qw"
                            elif nm == "cy":
                                self._latex[pos_1][column] = \
                                    "\\ctrl{" + str(pos_2 - pos_1) + "}"
                                self._latex[pos_2][column] = "\\gate{Y}"
                            elif nm == "ch":
                                self._latex[pos_1][column] = \
                                    "\\ctrl{" + str(pos_2 - pos_1) + "}"
                                self._latex[pos_2][column] = "\\gate{H}"
                            elif nm == "swap":
                                self._latex[pos_1][column] = "\\qswap"
                                self._latex[pos_2][column] = \
                                    "\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
                            elif nm == "crz":
                                self._latex[pos_1][column] = \
                                    "\\ctrl{" + str(pos_2 - pos_1) + "}"
                                self._latex[pos_2][column] = \
                                    "\\gate{R_z(%s)}" % (op.op.params[0])
                            elif nm == "cu1":
                                self._latex[pos_1][
                                    column -
                                    1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
                                self._latex[pos_2][column -
                                                   1] = "\\control\\qw"
                                self._latex[min(pos_1, pos_2)][column] = \
                                    "\\dstick{%s}\\qw" % (op.op.params[0])
                                self._latex[max(pos_1, pos_2)][column] = "\\qw"
                            elif nm == "cu3":
                                self._latex[pos_1][column] = \
                                    "\\ctrl{" + str(pos_2 - pos_1) + "}"
                                self._latex[pos_2][column] = \
                                    "\\gate{U_3(%s,%s,%s)}" % (op.op.params[0],
                                                               op.op.params[1],
                                                               op.op.params[2])
                        else:
                            temp = [pos_1, pos_2]
                            temp.sort(key=int)

                            if nm == "cx":
                                self._latex[pos_1][column] = "\\ctrl{" + str(
                                    pos_2 - pos_1) + "}"
                                self._latex[pos_2][column] = "\\targ"
                            elif nm == "cz":
                                self._latex[pos_1][column] = "\\ctrl{" + str(
                                    pos_2 - pos_1) + "}"
                                self._latex[pos_2][column] = "\\control\\qw"
                            elif nm == "cy":
                                self._latex[pos_1][column] = "\\ctrl{" + str(
                                    pos_2 - pos_1) + "}"
                                self._latex[pos_2][column] = "\\gate{Y}"
                            elif nm == "ch":
                                self._latex[pos_1][column] = "\\ctrl{" + str(
                                    pos_2 - pos_1) + "}"
                                self._latex[pos_2][column] = "\\gate{H}"
                            elif nm == "swap":
                                self._latex[pos_1][column] = "\\qswap"
                                self._latex[pos_2][column] = \
                                    "\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
                            elif nm == "crz":
                                self._latex[pos_1][column] = "\\ctrl{" + str(
                                    pos_2 - pos_1) + "}"
                                self._latex[pos_2][column] = \
                                    "\\gate{R_z(%s)}" % (op.op.params[0])
                            elif nm == "cu1":
                                self._latex[pos_1][
                                    column -
                                    1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
                                self._latex[pos_2][column -
                                                   1] = "\\control\\qw"
                                self._latex[min(pos_1, pos_2)][column] = \
                                    "\\dstick{%s}\\qw" % (op.op.params[0])
                                self._latex[max(pos_1, pos_2)][column] = "\\qw"
                            elif nm == "cu3":
                                self._latex[pos_1][column] = "\\ctrl{" + str(
                                    pos_2 - pos_1) + "}"
                                self._latex[pos_2][column] = (
                                    "\\gate{U_3(%s,%s,%s)}" %
                                    (op.op.params[0], op.op.params[1],
                                     op.op.params[2]))
                            else:
                                start_pos = min([pos_1, pos_2])
                                stop_pos = max([pos_1, pos_2])
                                if stop_pos - start_pos >= 2:
                                    delta = stop_pos - start_pos
                                    self._latex[start_pos][column] = (
                                        "\\multigate{%s}{%s}" %
                                        (delta, utf8tolatex(nm)))
                                    for i_pos in range(start_pos + 1,
                                                       stop_pos + 1):
                                        self._latex[i_pos][column] = (
                                            "\\ghost{%s}" % utf8tolatex(nm))
                                else:
                                    self._latex[start_pos][column] = (
                                        "\\multigate{1}{%s}" % utf8tolatex(nm))
                                    self._latex[stop_pos][column] = (
                                        "\\ghost{%s}" % utf8tolatex(nm))

                    elif len(qarglist) == 3:
                        pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
                        pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
                        pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]

                        if op.condition:
                            pos_4 = self.img_regs[(if_reg, 0)]

                            temp = [pos_1, pos_2, pos_3, pos_4]
                            temp.sort(key=int)
                            bottom = temp[2]

                            prev_column = [x[column - 1] for x in self._latex]
                            for item, prev_entry in enumerate(prev_column):
                                if 'barrier' in prev_entry:
                                    span = re.search('barrier{(.*)}',
                                                     prev_entry)
                                    if span and any(i in temp for i in range(
                                            item, int(span.group(1)))):
                                        self._latex[item][column - 1] = \
                                            prev_entry.replace(
                                                '\\barrier{',
                                                '\\barrier[-0.65em]{')

                            gap = pos_4 - bottom
                            for i in range(self.cregs[if_reg]):
                                if if_value[i] == '1':
                                    self._latex[pos_4 + i][column] = \
                                        "\\control \\cw \\cwx[-" + str(gap) + "]"
                                    gap = 1
                                else:
                                    self._latex[pos_4 + i][column] = \
                                        "\\controlo \\cw \\cwx[-" + str(gap) + "]"
                                    gap = 1

                            if nm == "ccx":
                                self._latex[pos_1][column] = "\\ctrl{" + str(
                                    pos_2 - pos_1) + "}"
                                self._latex[pos_2][column] = "\\ctrl{" + str(
                                    pos_3 - pos_2) + "}"
                                self._latex[pos_3][column] = "\\targ"

                            if nm == "cswap":
                                self._latex[pos_1][column] = "\\ctrl{" + str(
                                    pos_2 - pos_1) + "}"
                                self._latex[pos_2][column] = "\\qswap"
                                self._latex[pos_3][column] = \
                                    "\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
                        else:
                            temp = [pos_1, pos_2, pos_3]
                            temp.sort(key=int)

                            prev_column = [x[column - 1] for x in self._latex]
                            for item, prev_entry in enumerate(prev_column):
                                if 'barrier' in prev_entry:
                                    span = re.search('barrier{(.*)}',
                                                     prev_entry)
                                    if span and any(i in temp for i in range(
                                            item, int(span.group(1)))):
                                        self._latex[item][column - 1] = \
                                            prev_entry.replace(
                                                '\\barrier{',
                                                '\\barrier[-0.65em]{')

                            if nm == "ccx":
                                self._latex[pos_1][column] = "\\ctrl{" + str(
                                    pos_2 - pos_1) + "}"
                                self._latex[pos_2][column] = "\\ctrl{" + str(
                                    pos_3 - pos_2) + "}"
                                self._latex[pos_3][column] = "\\targ"

                            elif nm == "cswap":
                                self._latex[pos_1][column] = "\\ctrl{" + str(
                                    pos_2 - pos_1) + "}"
                                self._latex[pos_2][column] = "\\qswap"
                                self._latex[pos_3][column] = \
                                    "\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
                            else:
                                start_pos = min([pos_1, pos_2, pos_3])
                                stop_pos = max([pos_1, pos_2, pos_3])
                                if stop_pos - start_pos >= 3:
                                    delta = stop_pos - start_pos
                                    self._latex[start_pos][column] = (
                                        "\\multigate{%s}{%s}" %
                                        (delta, utf8tolatex(nm)))
                                    for i_pos in range(start_pos + 1,
                                                       stop_pos + 1):
                                        self._latex[i_pos][column] = (
                                            "\\ghost{%s}" % utf8tolatex(nm))
                                else:
                                    self._latex[pos_1][column] = (
                                        "\\multigate{2}{%s}" % utf8tolatex(nm))
                                    self._latex[pos_2][column] = (
                                        "\\ghost{%s}" % utf8tolatex(nm))
                                    self._latex[pos_3][column] = (
                                        "\\ghost{%s}" % utf8tolatex(nm))

                    elif len(qarglist) > 3:
                        nbits = len(qarglist)
                        pos_array = [
                            self.img_regs[(qarglist[0][0], qarglist[0][1])]
                        ]
                        for i in range(1, nbits):
                            pos_array.append(self.img_regs[(qarglist[i][0],
                                                            qarglist[i][1])])
                        pos_start = min(pos_array)
                        pos_stop = max(pos_array)
                        delta = pos_stop - pos_start
                        self._latex[pos_start][column] = (
                            "\\multigate{%s}{%s}" %
                            (nbits - 1, utf8tolatex(nm)))
                        for pos in range(pos_start + 1, pos_stop + 1):
                            self._latex[pos][column] = ("\\ghost{%s}" %
                                                        utf8tolatex(nm))

                elif op.name == "measure":
                    if (len(op.cargs) != 1 or len(op.qargs) != 1
                            or op.op.params):
                        raise exceptions.VisualizationError(
                            "bad operation record")

                    if op.condition:
                        raise exceptions.VisualizationError(
                            "If controlled measures currently not supported.")

                    qname, qindex = op.qargs[0]
                    cname, cindex = op.cargs[0]
                    if aliases:
                        newq = aliases[(qname, qindex)]
                        qname = newq[0]
                        qindex = newq[1]

                    pos_1 = self.img_regs[(qname, qindex)]
                    pos_2 = self.img_regs[(cname, cindex)]

                    try:
                        self._latex[pos_1][column] = "\\meter"
                        prev_column = [x[column - 1] for x in self._latex]
                        for item, prev_entry in enumerate(prev_column):
                            if 'barrier' in prev_entry:
                                span = re.search('barrier{(.*)}', prev_entry)
                                if span and (item +
                                             int(span.group(1))) - pos_1 >= 0:
                                    self._latex[item][column - 1] = \
                                        prev_entry.replace(
                                            '\\barrier{',
                                            '\\barrier[-1.15em]{')

                        self._latex[pos_2][column] = \
                            "\\cw \\cwx[-" + str(pos_2 - pos_1) + "]"
                    except Exception as e:
                        raise exceptions.VisualizationError(
                            'Error during Latex building: %s' % str(e))

                elif op.name in [
                        'barrier', 'snapshot', 'load', 'save', 'noise'
                ]:
                    if self.plot_barriers:
                        qarglist = op.qargs
                        indexes = [self._get_qubit_index(x) for x in qarglist]
                        start_bit = self.qubit_list[min(indexes)]
                        if aliases is not None:
                            qarglist = map(lambda x: aliases[x], qarglist)
                        start = self.img_regs[start_bit]
                        span = len(op.qargs) - 1

                        self._latex[start][column] = "\\qw \\barrier{" + str(
                            span) + "}"
                else:
                    raise exceptions.VisualizationError("bad node data")
예제 #30
0
def parseMeta(metadict,basedir,folder,isfile,iszotero,iskeyword,verbose=True):
    '''Parse document meta-data

    metadict
    '''

    def getField(doc,field,default=''):
        return doc[field] or default
    
    page_re=re.compile('(.*?)-(.*)', re.UNICODE)
    def _subDash(match):
        return '%s--%s' %(match.group(1),match.group(2))

    #--------------------Get header--------------------
    doctype=getField(metadict,'type','article')
    if doctype==u'JournalArticle':
        doctype='article'  #Necessary?
    citekey=getField(metadict,'citationkey','citationkey')

    #-------------------Get authors-------------------
    first=metadict['firstnames']
    last=metadict['lastname']
    if first is None or last is None:
        authors=''
    if type(first) is not list and type(last) is not list:
        authors='%s, %s' %(last, first)
    else:
        authors=['%s, %s' %(ii[0],ii[1]) for ii in zip(last,first)]
        authors=' and '.join(authors)
    authors=latexencode.utf8tolatex(authors)
    
    string='@%s{%s,\n' %(doctype,citekey)
    entries=['author = {%s}' %authors,]

    #--------------Populate other fields--------------
    gotkeywords=False

    for kk,vv in metadict.items():
        if vv is None:
            continue
        if kk in ['type','firstnames','lastname','docid']:
            continue
        if kk in ['year','month','day']:
            # Convert float to int to str
            try:
                vv=str(int(vv))
            except:
                # vv is nan
                continue

        if kk=='publication' and doctype=='article':
            kk='journal'
        if kk=='pages':
            vv=page_re.sub(_subDash,vv)
        if kk=='path':
            if not isfile:
                continue
            if not isinstance(vv,list) and not isinstance(vv,tuple):
                vv=[vv,]
            vv=[parseFilePath(ii,basedir,folder,iszotero) for\
                    ii in vv]
            # proper way of joining multiple paths?
            #vv='}, {'.join(vv)
            vv='; '.join(vv)
            vv=u'%s' %vv

            if vv=='':
                continue
            else:
                kk='file'

        #--------------Parse unicode to latex--------------
        if type(vv) is list:
            fieldvv=[latexencode.utf8tolatex(ii) for ii in vv]
        else:
            # Leave file path alone
            if kk!='file':
                fieldvv=latexencode.utf8tolatex(vv)
            else:
                fieldvv=vv

        #----------Add tags to keywords if iszotero----------
        if iszotero and (kk=='tags' or kk=='keywords') and not gotkeywords:
            if iskeyword:
                keywords=getField(metadict,'keywords',[])
            else:
                keywords=[]
            if not isinstance(keywords, list):
                keywords=[keywords,]
            tags=getField(metadict,'tags',[])
            if not isinstance(tags, list):
                tags=[tags,]
            keywords.extend(tags)
	    keywords=list(set(keywords))
            fieldvv=[latexencode.utf8tolatex(ii) for ii in keywords]
            kk='keywords'
            gotkeywords=True

        #----------------Parse annotations----------------
        #if kk=='annote':
        if kk in ['notes', 'highlights']:
            #if type(fieldvv) is not list:
                #fieldvv=[fieldvv,]
            if len(fieldvv)==0:
                continue

            # For import to zotero, separate annotes
            if iszotero:
                for ii in fieldvv:
                    entrykk='%s = { %s }' %('annote',ii)
                    entries.append(entrykk)
            else:
                fieldvv=['{ %s }' %ii for ii in fieldvv]
                fieldvv=u', '.join(fieldvv)
                #entrykk='%s = {%s}' %(kk, fieldvv)
                entrykk='%s = {%s}' %('annote', fieldvv)
                entries.append(entrykk)

        #--------------------All others--------------------
        else:
            if type(fieldvv) is list:
                fieldvv=u', '.join(fieldvv)
            entrykk='%s = {%s}' %(kk, fieldvv)
            entries.append(entrykk)

    #entries=',\n'.join(entries)
    entries=',\n'.join([u'\t%s' %eii for eii in entries])
    string=string+entries+'\n}\n\n'
    string=string.encode('ascii','replace')

    return string
예제 #31
0
    def _build_latex_array(self, aliases=None):
        """Returns an array of strings containing \\LaTeX for this circuit.

        If aliases is not None, aliases contains a dict mapping
        the current qubits in the circuit to new qubit names.
        We will deduce the register names and sizes from aliases.
        """

        # Rename qregs if necessary
        if aliases:
            qregdata = {}
            for q in aliases.values():
                if q[0] not in qregdata:
                    qregdata[q[0]] = q[1] + 1
                elif qregdata[q[0]] < q[1] + 1:
                    qregdata[q[0]] = q[1] + 1
        else:
            qregdata = self.qregs

        column = 1
        for layer in self.ops:
            num_cols_used = 1

            for op in layer:
                if op.condition:
                    mask = self._get_mask(op.condition[0])
                    cl_reg = self.clbit_list[self._ffs(mask)]
                    if_reg = cl_reg.register
                    pos_2 = self.img_regs[cl_reg]
                    if_value = format(op.condition[1],
                                      'b').zfill(self.cregs[if_reg])[::-1]
                if op.name not in [
                        'measure', 'barrier', 'snapshot', 'load', 'save',
                        'noise'
                ]:
                    nm = utf8tolatex(op.name).replace(" ", "\\,")
                    qarglist = op.qargs
                    if aliases is not None:
                        qarglist = map(lambda x: aliases[x], qarglist)
                    if len(qarglist) == 1:
                        pos_1 = self.img_regs[qarglist[0]]

                        if op.condition:
                            mask = self._get_mask(op.condition[0])
                            cl_reg = self.clbit_list[self._ffs(mask)]
                            if_reg = cl_reg.register
                            pos_2 = self.img_regs[cl_reg]

                            if nm == "x":
                                self._latex[pos_1][column] = "\\gate{X}"
                            elif nm == "y":
                                self._latex[pos_1][column] = "\\gate{Y}"
                            elif nm == "z":
                                self._latex[pos_1][column] = "\\gate{Z}"
                            elif nm == "h":
                                self._latex[pos_1][column] = "\\gate{H}"
                            elif nm == "s":
                                self._latex[pos_1][column] = "\\gate{S}"
                            elif nm == "sdg":
                                self._latex[pos_1][column] = "\\gate{S^\\dag}"
                            elif nm == "t":
                                self._latex[pos_1][column] = "\\gate{T}"
                            elif nm == "tdg":
                                self._latex[pos_1][column] = "\\gate{T^\\dag}"
                            elif nm == "u0":
                                self._latex[pos_1][
                                    column] = "\\gate{U_0(%s)}" % (pi_check(
                                        op.op.params[0], output='latex'))
                            elif nm == "u1":
                                self._latex[pos_1][
                                    column] = "\\gate{U_1(%s)}" % (pi_check(
                                        op.op.params[0], output='latex'))
                            elif nm == "u2":
                                self._latex[pos_1][column] = \
                                    "\\gate{U_2\\left(%s,%s\\right)}" % (
                                        pi_check(op.op.params[0], output='latex'),
                                        pi_check(op.op.params[1], output='latex'))
                            elif nm == "u3":
                                self._latex[pos_1][column] = (
                                    "\\gate{U_3(%s,%s,%s)}" %
                                    (pi_check(op.op.params[0], output='latex'),
                                     pi_check(op.op.params[1], output='latex'),
                                     pi_check(op.op.params[2],
                                              output='latex')))
                            elif nm == "rx":
                                self._latex[pos_1][
                                    column] = "\\gate{R_x(%s)}" % (pi_check(
                                        op.op.params[0], output='latex'))
                            elif nm == "ry":
                                self._latex[pos_1][
                                    column] = "\\gate{R_y(%s)}" % (pi_check(
                                        op.op.params[0], output='latex'))
                            elif nm == "rz":
                                self._latex[pos_1][
                                    column] = "\\gate{R_z(%s)}" % (pi_check(
                                        op.op.params[0], output='latex'))
                            else:
                                self._latex[pos_1][column] = ("\\gate{%s}" %
                                                              nm)

                            gap = pos_2 - pos_1
                            for i in range(self.cregs[if_reg]):
                                if if_value[i] == '1':
                                    self._latex[pos_2 + i][column] = \
                                        "\\control \\cw \\cwx[-" + str(gap) + "]"
                                    gap = 1
                                else:
                                    self._latex[pos_2 + i][column] = \
                                        "\\controlo \\cw \\cwx[-" + str(gap) + "]"
                                    gap = 1

                        else:
                            if nm == "x":
                                self._latex[pos_1][column] = "\\gate{X}"
                            elif nm == "y":
                                self._latex[pos_1][column] = "\\gate{Y}"
                            elif nm == "z":
                                self._latex[pos_1][column] = "\\gate{Z}"
                            elif nm == "h":
                                self._latex[pos_1][column] = "\\gate{H}"
                            elif nm == "s":
                                self._latex[pos_1][column] = "\\gate{S}"
                            elif nm == "sdg":
                                self._latex[pos_1][column] = "\\gate{S^\\dag}"
                            elif nm == "t":
                                self._latex[pos_1][column] = "\\gate{T}"
                            elif nm == "tdg":
                                self._latex[pos_1][column] = "\\gate{T^\\dag}"
                            elif nm == "u0":
                                self._latex[pos_1][
                                    column] = "\\gate{U_0(%s)}" % (pi_check(
                                        op.op.params[0], output='latex'))
                            elif nm == "u1":
                                self._latex[pos_1][
                                    column] = "\\gate{U_1(%s)}" % (pi_check(
                                        op.op.params[0], output='latex'))
                            elif nm == "u2":
                                self._latex[pos_1][column] = \
                                    "\\gate{U_2\\left(%s,%s\\right)}" % (
                                        pi_check(op.op.params[0], output='latex'),
                                        pi_check(op.op.params[1], output='latex'))
                            elif nm == "u3":
                                self._latex[pos_1][column] = (
                                    "\\gate{U_3(%s,%s,%s)}" %
                                    (pi_check(op.op.params[0], output='latex'),
                                     pi_check(op.op.params[1], output='latex'),
                                     pi_check(op.op.params[2],
                                              output='latex')))
                            elif nm == "rx":
                                self._latex[pos_1][
                                    column] = "\\gate{R_x(%s)}" % (pi_check(
                                        op.op.params[0], output='latex'))
                            elif nm == "ry":
                                self._latex[pos_1][
                                    column] = "\\gate{R_y(%s)}" % (pi_check(
                                        op.op.params[0], output='latex'))
                            elif nm == "rz":
                                self._latex[pos_1][
                                    column] = "\\gate{R_z(%s)}" % (pi_check(
                                        op.op.params[0], output='latex'))
                            elif nm == "reset":
                                self._latex[pos_1][column] = (
                                    "\\push{\\rule{.6em}{0em}\\ket{0}\\"
                                    "rule{.2em}{0em}} \\qw")
                            else:
                                self._latex[pos_1][column] = ("\\gate{%s}" %
                                                              nm)

                    elif len(qarglist) == 2:
                        pos_1 = self.img_regs[qarglist[0]]
                        pos_2 = self.img_regs[qarglist[1]]

                        if op.condition:
                            pos_3 = self.img_regs[(if_reg, 0)]
                            temp = [pos_1, pos_2, pos_3]
                            temp.sort(key=int)
                            bottom = temp[1]

                            gap = pos_3 - bottom
                            for i in range(self.cregs[if_reg]):
                                if if_value[i] == '1':
                                    self._latex[pos_3 + i][column] = \
                                        "\\control \\cw \\cwx[-" + str(gap) + "]"
                                    gap = 1
                                else:
                                    self._latex[pos_3 + i][column] = \
                                        "\\controlo \\cw \\cwx[-" + str(gap) + "]"
                                    gap = 1

                            if nm == "cx":
                                self._latex[pos_1][column] = \
                                    "\\ctrl{" + str(pos_2 - pos_1) + "}"
                                self._latex[pos_2][column] = "\\targ"
                            elif nm == "cz":
                                self._latex[pos_1][column] = \
                                    "\\ctrl{" + str(pos_2 - pos_1) + "}"
                                self._latex[pos_2][column] = "\\control\\qw"
                            elif nm == "cy":
                                self._latex[pos_1][column] = \
                                    "\\ctrl{" + str(pos_2 - pos_1) + "}"
                                self._latex[pos_2][column] = "\\gate{Y}"
                            elif nm == "ch":
                                self._latex[pos_1][column] = \
                                    "\\ctrl{" + str(pos_2 - pos_1) + "}"
                                self._latex[pos_2][column] = "\\gate{H}"
                            elif nm == "swap":
                                self._latex[pos_1][column] = "\\qswap"
                                self._latex[pos_2][column] = \
                                    "\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
                            elif nm == "crz":
                                self._latex[pos_1][column] = \
                                    "\\ctrl{" + str(pos_2 - pos_1) + "}"
                                self._latex[pos_2][column] = \
                                    "\\gate{R_z(%s)}" % (pi_check(op.op.params[0], output='latex'))
                            elif nm == "cu1":
                                self._latex[pos_1][column] = "\\ctrl{" + str(
                                    pos_2 - pos_1) + "}"
                                self._latex[pos_2][column] = "\\control \\qw"
                                self._latex[min(pos_1, pos_2)][column + 1] = \
                                    "\\dstick{%s}\\qw" % (pi_check(op.op.params[0], output='latex'))
                                self._latex[max(pos_1,
                                                pos_2)][column + 1] = "\\qw"
                                # this is because this gate takes up 2 columns,
                                # and we have just written to the next column
                                num_cols_used = 2
                            elif nm == "cu3":
                                self._latex[pos_1][column] = \
                                    "\\ctrl{" + str(pos_2 - pos_1) + "}"
                                self._latex[pos_2][column] = \
                                    "\\gate{U_3(%s,%s,%s)}" % \
                                    (pi_check(op.op.params[0], output='latex'),
                                     pi_check(op.op.params[1], output='latex'),
                                     pi_check(op.op.params[2], output='latex'))
                            elif nm == "rzz":
                                self._latex[pos_1][column] = "\\ctrl{" + str(
                                    pos_2 - pos_1) + "}"
                                self._latex[pos_2][column] = "\\control \\qw"
                                # Based on the \cds command of the qcircuit package
                                self._latex[min(pos_1, pos_2)][column + 1] = \
                                    "*+<0em,0em>{\\hphantom{zz()}} \\POS [0,0].[%d,0]=" \
                                    "\"e\",!C *{zz(%s)};\"e\"+ R \\qw" %\
                                    (max(pos_1, pos_2), pi_check(op.op.params[0], output='latex'))
                                self._latex[max(pos_1,
                                                pos_2)][column + 1] = "\\qw"
                                num_cols_used = 2
                        else:
                            temp = [pos_1, pos_2]
                            temp.sort(key=int)

                            if nm == "cx":
                                self._latex[pos_1][column] = "\\ctrl{" + str(
                                    pos_2 - pos_1) + "}"
                                self._latex[pos_2][column] = "\\targ"
                            elif nm == "cz":
                                self._latex[pos_1][column] = "\\ctrl{" + str(
                                    pos_2 - pos_1) + "}"
                                self._latex[pos_2][column] = "\\control\\qw"
                            elif nm == "cy":
                                self._latex[pos_1][column] = "\\ctrl{" + str(
                                    pos_2 - pos_1) + "}"
                                self._latex[pos_2][column] = "\\gate{Y}"
                            elif nm == "ch":
                                self._latex[pos_1][column] = "\\ctrl{" + str(
                                    pos_2 - pos_1) + "}"
                                self._latex[pos_2][column] = "\\gate{H}"
                            elif nm == "swap":
                                self._latex[pos_1][column] = "\\qswap"
                                self._latex[pos_2][column] = \
                                    "\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
                            elif nm == "crz":
                                self._latex[pos_1][column] = "\\ctrl{" + str(
                                    pos_2 - pos_1) + "}"
                                self._latex[pos_2][column] = \
                                    "\\gate{R_z(%s)}" % (pi_check(op.op.params[0], output='latex'))
                            elif nm == "cu1":
                                self._latex[pos_1][column] = "\\ctrl{" + str(
                                    pos_2 - pos_1) + "}"
                                self._latex[pos_2][column] = "\\control \\qw"
                                self._latex[min(pos_1, pos_2)][column + 1] = \
                                    "\\dstick{%s}\\qw" % (pi_check(op.op.params[0], output='latex'))
                                self._latex[max(pos_1,
                                                pos_2)][column + 1] = "\\qw"
                                num_cols_used = 2
                            elif nm == "cu3":
                                self._latex[pos_1][column] = "\\ctrl{" + str(
                                    pos_2 - pos_1) + "}"
                                self._latex[pos_2][column] = \
                                    ("\\gate{U_3(%s,%s,%s)}" %
                                     (pi_check(op.op.params[0], output='latex'),
                                      pi_check(op.op.params[1], output='latex'),
                                      pi_check(op.op.params[2], output='latex')))
                            elif nm == "rzz":
                                self._latex[pos_1][column] = "\\ctrl{" + str(
                                    pos_2 - pos_1) + "}"
                                self._latex[pos_2][column] = "\\control \\qw"
                                # Based on the \cds command of the qcircuit package
                                self._latex[min(pos_1, pos_2)][column + 1] = \
                                    "*+<0em,0em>{\\hphantom{zz()}} \\POS [0,0].[%d,0]=" \
                                    "\"e\",!C *{zz(%s)};\"e\"+ R \\qw" %\
                                    (max(pos_1, pos_2), pi_check(op.op.params[0], output='latex'))
                                self._latex[max(pos_1,
                                                pos_2)][column + 1] = "\\qw"
                                num_cols_used = 2
                            else:
                                start_pos = min([pos_1, pos_2])
                                stop_pos = max([pos_1, pos_2])
                                if stop_pos - start_pos >= 2:
                                    delta = stop_pos - start_pos
                                    self._latex[start_pos][column] = (
                                        "\\multigate{%s}{%s}" % (delta, nm))
                                    for i_pos in range(start_pos + 1,
                                                       stop_pos + 1):
                                        self._latex[i_pos][column] = (
                                            "\\ghost{%s}" % nm)
                                else:
                                    self._latex[start_pos][column] = (
                                        "\\multigate{1}{%s}" % nm)
                                    self._latex[stop_pos][column] = (
                                        "\\ghost{%s}" % nm)

                    elif len(qarglist) == 3:
                        pos_1 = self.img_regs[qarglist[0]]
                        pos_2 = self.img_regs[qarglist[1]]
                        pos_3 = self.img_regs[qarglist[2]]

                        if op.condition:
                            pos_4 = self.img_regs[(if_reg, 0)]
                            temp = [pos_1, pos_2, pos_3, pos_4]
                            temp.sort(key=int)
                            bottom = temp[2]

                            gap = pos_4 - bottom
                            for i in range(self.cregs[if_reg]):
                                if if_value[i] == '1':
                                    self._latex[pos_4 + i][column] = \
                                        "\\control \\cw \\cwx[-" + str(gap) + "]"
                                    gap = 1
                                else:
                                    self._latex[pos_4 + i][column] = \
                                        "\\controlo \\cw \\cwx[-" + str(gap) + "]"
                                    gap = 1

                            if nm == "ccx":
                                self._latex[pos_1][column] = "\\ctrl{" + str(
                                    pos_2 - pos_1) + "}"
                                self._latex[pos_2][column] = "\\ctrl{" + str(
                                    pos_3 - pos_2) + "}"
                                self._latex[pos_3][column] = "\\targ"

                            if nm == "cswap":
                                self._latex[pos_1][column] = "\\ctrl{" + str(
                                    pos_2 - pos_1) + "}"
                                self._latex[pos_2][column] = "\\qswap"
                                self._latex[pos_3][column] = \
                                    "\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
                        else:
                            if nm == "ccx":
                                self._latex[pos_1][column] = "\\ctrl{" + str(
                                    pos_2 - pos_1) + "}"
                                self._latex[pos_2][column] = "\\ctrl{" + str(
                                    pos_3 - pos_2) + "}"
                                self._latex[pos_3][column] = "\\targ"

                            elif nm == "cswap":
                                self._latex[pos_1][column] = "\\ctrl{" + str(
                                    pos_2 - pos_1) + "}"
                                self._latex[pos_2][column] = "\\qswap"
                                self._latex[pos_3][column] = \
                                    "\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
                            else:
                                start_pos = min([pos_1, pos_2, pos_3])
                                stop_pos = max([pos_1, pos_2, pos_3])
                                if stop_pos - start_pos >= 3:
                                    delta = stop_pos - start_pos
                                    self._latex[start_pos][column] = (
                                        "\\multigate{%s}{%s}" % (delta, nm))
                                    for i_pos in range(start_pos + 1,
                                                       stop_pos + 1):
                                        self._latex[i_pos][column] = (
                                            "\\ghost{%s}" % nm)
                                else:
                                    self._latex[pos_1][column] = (
                                        "\\multigate{2}{%s}" % nm)
                                    self._latex[pos_2][column] = (
                                        "\\ghost{%s}" % nm)
                                    self._latex[pos_3][column] = (
                                        "\\ghost{%s}" % nm)

                    elif len(qarglist) > 3:
                        nbits = len(qarglist)
                        pos_array = [
                            self.img_regs[(qarglist[0].register,
                                           qarglist[0].index)]
                        ]
                        for i in range(1, nbits):
                            pos_array.append(
                                self.img_regs[(qarglist[i].register,
                                               qarglist[i].index)])
                        pos_start = min(pos_array)
                        pos_stop = max(pos_array)
                        self._latex[pos_start][column] = (
                            "\\multigate{%s}{%s}" % (nbits - 1, nm))
                        for pos in range(pos_start + 1, pos_stop + 1):
                            self._latex[pos][column] = ("\\ghost{%s}" % nm)

                elif op.name == "measure":
                    if (len(op.cargs) != 1 or len(op.qargs) != 1
                            or op.op.params):
                        raise exceptions.VisualizationError(
                            "bad operation record")

                    if op.condition:
                        raise exceptions.VisualizationError(
                            "If controlled measures currently not supported.")

                    if aliases:
                        newq = aliases[(qname, qindex)]
                        qname = newq[0]
                        qindex = newq[1]

                    pos_1 = self.img_regs[op.qargs[0]]
                    pos_2 = self.img_regs[op.cargs[0]]

                    try:
                        self._latex[pos_1][column] = "\\meter"
                        self._latex[pos_2][column] = \
                            "\\cw \\cwx[-" + str(pos_2 - pos_1) + "]"
                    except Exception as e:
                        raise exceptions.VisualizationError(
                            'Error during Latex building: %s' % str(e))

                elif op.name in [
                        'barrier', 'snapshot', 'load', 'save', 'noise'
                ]:
                    if self.plot_barriers:
                        qarglist = op.qargs
                        indexes = [self._get_qubit_index(x) for x in qarglist]
                        indexes.sort()
                        if aliases is not None:
                            qarglist = map(lambda x: aliases[x], qarglist)

                        first = last = indexes[0]
                        for index in indexes[1:]:
                            if index - 1 == last:
                                last = index
                            else:
                                pos = self.img_regs[self.qubit_list[first]]
                                self._latex[pos][
                                    column -
                                    1] += " \\barrier[0em]{" + str(last -
                                                                   first) + "}"
                                self._latex[pos][column] = "\\qw"
                                first = last = index
                        pos = self.img_regs[self.qubit_list[first]]
                        self._latex[pos][
                            column -
                            1] += " \\barrier[0em]{" + str(last - first) + "}"
                        self._latex[pos][column] = "\\qw"
                else:
                    raise exceptions.VisualizationError("bad node data")

            # increase the number of columns by the number of columns this layer used
            column += num_cols_used
예제 #32
0
def tex_escape(text):
    """
		:param text: a plain text message
		:return: the message escaped to appear correctly in LaTeX
	"""
    return utf8tolatex(text)
예제 #33
0
#!/usr/bin/env python3
from pylatexenc.latexencode import utf8tolatex

with open('../AUTHORS', 'r') as authors_file:
    authors = list([utf8tolatex(x.rstrip()) for x in authors_file])

with open('../Qiskit.bib', 'w') as fd:
    fd.write("@misc{ Qiskit,\n")
    fd.write('       author = {%s},\n' % ' and '.join(authors))
    fd.write('       title = {Qiskit: An Open-source Framework for Quantum Computing},\n')
    fd.write('       year = {2019},\n}')