__init__.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. """Module with some functions for MathML, like transforming MathML
  2. content in MathML presentation.
  3. To use this module, you will need lxml.
  4. """
  5. from sympy.utilities.pkgdata import get_resource
  6. from sympy.utilities.decorator import doctest_depends_on
  7. __doctest_requires__ = {('apply_xsl', 'c2p'): ['lxml']}
  8. def add_mathml_headers(s):
  9. return """<math xmlns:mml="http://www.w3.org/1998/Math/MathML"
  10. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  11. xsi:schemaLocation="http://www.w3.org/1998/Math/MathML
  12. http://www.w3.org/Math/XMLSchema/mathml2/mathml2.xsd">""" + s + "</math>"
  13. @doctest_depends_on(modules=('lxml',))
  14. def apply_xsl(mml, xsl):
  15. """Apply a xsl to a MathML string.
  16. Parameters
  17. ==========
  18. mml
  19. A string with MathML code.
  20. xsl
  21. A string representing a path to a xsl (xml stylesheet) file.
  22. This file name is relative to the PYTHONPATH.
  23. Examples
  24. ========
  25. >>> from sympy.utilities.mathml import apply_xsl
  26. >>> xsl = 'mathml/data/simple_mmlctop.xsl'
  27. >>> mml = '<apply> <plus/> <ci>a</ci> <ci>b</ci> </apply>'
  28. >>> res = apply_xsl(mml,xsl)
  29. >>> ''.join(res.splitlines())
  30. '<?xml version="1.0"?><mrow xmlns="http://www.w3.org/1998/Math/MathML"> <mi>a</mi> <mo> + </mo> <mi>b</mi></mrow>'
  31. """
  32. from lxml import etree
  33. parser = etree.XMLParser(resolve_entities=False)
  34. ac = etree.XSLTAccessControl.DENY_ALL
  35. s = etree.XML(get_resource(xsl).read(), parser=parser)
  36. transform = etree.XSLT(s, access_control=ac)
  37. doc = etree.XML(mml, parser=parser)
  38. result = transform(doc)
  39. s = str(result)
  40. return s
  41. @doctest_depends_on(modules=('lxml',))
  42. def c2p(mml, simple=False):
  43. """Transforms a document in MathML content (like the one that sympy produces)
  44. in one document in MathML presentation, more suitable for printing, and more
  45. widely accepted
  46. Examples
  47. ========
  48. >>> from sympy.utilities.mathml import c2p
  49. >>> mml = '<apply> <exp/> <cn>2</cn> </apply>'
  50. >>> c2p(mml,simple=True) != c2p(mml,simple=False)
  51. True
  52. """
  53. if not mml.startswith('<math'):
  54. mml = add_mathml_headers(mml)
  55. if simple:
  56. return apply_xsl(mml, 'mathml/data/simple_mmlctop.xsl')
  57. return apply_xsl(mml, 'mathml/data/mmlctop.xsl')