Coverage for /usr/lib/python3/dist-packages/sympy/utilities/mathml/__init__.py: 35%

23 statements  

« prev     ^ index     » next       coverage.py v7.9.1, created at 2025-06-14 15:55 +0200

1"""Module with some functions for MathML, like transforming MathML 

2content in MathML presentation. 

3 

4To use this module, you will need lxml. 

5""" 

6 

7from sympy.utilities.pkgdata import get_resource 

8from sympy.utilities.decorator import doctest_depends_on 

9 

10 

11__doctest_requires__ = {('apply_xsl', 'c2p'): ['lxml']} 

12 

13 

14def add_mathml_headers(s): 

15 return """<math xmlns:mml="http://www.w3.org/1998/Math/MathML" 

16 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 

17 xsi:schemaLocation="http://www.w3.org/1998/Math/MathML 

18 http://www.w3.org/Math/XMLSchema/mathml2/mathml2.xsd">""" + s + "</math>" 

19 

20 

21@doctest_depends_on(modules=('lxml',)) 

22def apply_xsl(mml, xsl): 

23 """Apply a xsl to a MathML string. 

24 

25 Parameters 

26 ========== 

27 

28 mml 

29 A string with MathML code. 

30 xsl 

31 A string representing a path to a xsl (xml stylesheet) file. 

32 This file name is relative to the PYTHONPATH. 

33 

34 Examples 

35 ======== 

36 

37 >>> from sympy.utilities.mathml import apply_xsl 

38 >>> xsl = 'mathml/data/simple_mmlctop.xsl' 

39 >>> mml = '<apply> <plus/> <ci>a</ci> <ci>b</ci> </apply>' 

40 >>> res = apply_xsl(mml,xsl) 

41 >>> ''.join(res.splitlines()) 

42 '<?xml version="1.0"?><mrow xmlns="http://www.w3.org/1998/Math/MathML"> <mi>a</mi> <mo> + </mo> <mi>b</mi></mrow>' 

43 """ 

44 from lxml import etree 

45 

46 parser = etree.XMLParser(resolve_entities=False) 

47 ac = etree.XSLTAccessControl.DENY_ALL 

48 

49 s = etree.XML(get_resource(xsl).read(), parser=parser) 

50 transform = etree.XSLT(s, access_control=ac) 

51 doc = etree.XML(mml, parser=parser) 

52 result = transform(doc) 

53 s = str(result) 

54 return s 

55 

56 

57@doctest_depends_on(modules=('lxml',)) 

58def c2p(mml, simple=False): 

59 """Transforms a document in MathML content (like the one that sympy produces) 

60 in one document in MathML presentation, more suitable for printing, and more 

61 widely accepted 

62 

63 Examples 

64 ======== 

65 

66 >>> from sympy.utilities.mathml import c2p 

67 >>> mml = '<apply> <exp/> <cn>2</cn> </apply>' 

68 >>> c2p(mml,simple=True) != c2p(mml,simple=False) 

69 True 

70 

71 """ 

72 

73 if not mml.startswith('<math'): 

74 mml = add_mathml_headers(mml) 

75 

76 if simple: 

77 return apply_xsl(mml, 'mathml/data/simple_mmlctop.xsl') 

78 

79 return apply_xsl(mml, 'mathml/data/mmlctop.xsl')