Пример #1
0
    def load_pymathics_module(self, module, remove_on_quit=True):
        '''
        loads Mathics builtin objects and their definitions
        from an external python module
        '''
        import importlib
        from mathics.builtin import is_builtin, builtins, builtins_by_module, Builtin
        loaded_module = importlib.import_module(module)
        builtins_by_module[loaded_module.__name__] = []
        vars = dir(loaded_module)
        newsymbols = {}
        if not ('pymathics_version_data' in vars):
            raise PyMathicsLoadException(module)
        for name in vars:
            var = getattr(loaded_module, name)
            if (hasattr(var, '__module__')
                    and var.__module__ != 'mathics.builtin.base'
                    and is_builtin(var) and not name.startswith('_')
                    and var.__module__[:len(loaded_module.__name__)]
                    == loaded_module.__name__):  # nopep8
                instance = var(expression=False)
                if isinstance(instance, Builtin):
                    builtins[instance.get_name()] = instance
                    builtins_by_module[loaded_module.__name__].append(instance)
                    newsymbols[instance.get_name()] = instance

        for name in newsymbols:
            if remove_on_quit and name not in self.pymathics:
                self.pymathics[name] = self.builtin.get(name, None)
        self.builtin.update(newsymbols)
        for name, item in newsymbols.items():
            if name != 'System`MakeBoxes':
                item.contribute(self)
        return loaded_module
Пример #2
0
    def load_pymathics_module(self, module, remove_on_quit=True):
        """
        Loads Mathics builtin objects and their definitions
        from an external Python module in the pymathics module namespace.
        """
        import importlib
        from mathics.builtin import is_builtin, builtins_by_module, Builtin

        # Ensures that the pymathics module be reloaded
        import sys

        if module in sys.modules:
            loaded_module = importlib.reload(sys.modules[module])
        else:
            loaded_module = importlib.import_module(module)

        builtins_by_module[loaded_module.__name__] = []
        vars = set(
            loaded_module.__all__
            if hasattr(loaded_module, "__all__")
            else dir(loaded_module)
        )

        newsymbols = {}
        if not ("pymathics_version_data" in vars):
            raise PyMathicsLoadException(module)
        for name in vars - set(("pymathics_version_data", "__version__")):
            var = getattr(loaded_module, name)
            if (
                hasattr(var, "__module__")
                and is_builtin(var)
                and not name.startswith("_")
                and var.__module__[: len(loaded_module.__name__)]
                == loaded_module.__name__
            ):  # nopep8
                instance = var(expression=False)
                if isinstance(instance, Builtin):
                    if not var.context:
                        var.context = "Pymathics`"
                    symbol_name = instance.get_name()
                    builtins_by_module[loaded_module.__name__].append(instance)
                    newsymbols[symbol_name] = instance

        for name in newsymbols:
            luname = self.lookup_name(name)
            self.user.pop(name, None)

        for name, item in newsymbols.items():
            if name != "System`MakeBoxes":
                item.contribute(self, is_pymodule=True)

        onload = loaded_module.pymathics_version_data.get("onload", None)
        if onload:
            onload(self)

        return loaded_module
Пример #3
0
    def load_pymathics_module(self, module, remove_on_quit=True):
        """
        Loads Mathics builtin objects and their definitions
        from an external Python module in the pymathics module namespace.
        """
        import importlib
        from mathics.builtin import is_builtin, builtins, builtins_by_module, Builtin

        loaded_module = importlib.import_module(module)
        builtins_by_module[loaded_module.__name__] = []
        vars = set(
            loaded_module.__all__
            if hasattr(loaded_module, "__all__")
            else dir(loaded_module)
        )
        context = "PyMathics`"
        newsymbols = {}
        if not ("pymathics_version_data" in vars):
            raise PyMathicsLoadException(module)
        for name in vars - set(("pymathics_version_data", "__version__")):
            var = getattr(loaded_module, name)
            if (
                hasattr(var, "__module__")
                and is_builtin(var)
                and not name.startswith("_")
                and var.__module__[: len(loaded_module.__name__)]
                == loaded_module.__name__
            ):  # nopep8
                instance = var(expression=False)
                if isinstance(instance, Builtin):
                    symbol_name = context + instance.get_name(short=True)
                    builtins[symbol_name] = instance
                    builtins_by_module[loaded_module.__name__].append(instance)
                    newsymbols[symbol_name] = instance

        for name in newsymbols:
            if remove_on_quit and name not in self.pymathics:
                self.pymathics[name] = self.builtin.get(name, None)
        self.builtin.update(newsymbols)
        for name, item in newsymbols.items():
            if name != "System`MakeBoxes":
                item.contribute(self, is_pymodule=True)
        return loaded_module
Пример #4
0
    from sage import all as sage
    from mathics.optional import calculus, numerical_optimization
    
    modules += [calculus, numerical_optimization]
    
    sage_version = sage.version()
except ImportError:
    # silently ignore when Sage cannot be imported
    sage_version = None

from mathics.builtin import add_builtins, builtins_by_module, is_builtin
from mathics.builtin.base import Builtin

optional_builtins = []
optional_builtins_by_module = {}

for module in modules:
    optional_builtins_by_module[module.__name__] = []
    vars = dir(module)
    for name in vars:
        var = getattr(module, name)
        if hasattr(var, '__module__') and var.__module__.startswith('mathics.optional.') and \
            var.__module__ != 'mathics.optional.base' and is_builtin(var) and not name.startswith('_'):
            instance = var(expression=False)
            if isinstance(instance, Builtin):
                optional_builtins.append((instance.get_name(), instance))
                optional_builtins_by_module[module.__name__].append(instance)

# update existing builtins
add_builtins(optional_builtins)
builtins_by_module.update(optional_builtins_by_module)
Пример #5
0
    def __init__(self, module=None):
        self.title = "Overview"
        self.parts = []
        self.parts_by_slug = {}
        self.doc_dir = None
        self.xml_data_file = None
        self.tex_data_file = None
        self.latex_file = None
        self.symbols = {}
        if module is None:
            return

        import importlib

        # Load the module and verifies it is a pymathics module
        try:
            self.pymathicsmodule = importlib.import_module(module)
        except ImportError:
            print("Module does not exist")
            mainfolder = ""
            self.pymathicsmodule = None
            self.parts = []
            return

        try:
            mainfolder = self.pymathicsmodule.__path__[0]
            if "name" in self.pymathicsmodule.pymathics_version_data:
                self.name = self.version = self.pymathicsmodule.pymathics_version_data[
                    'name']
            else:
                self.name = (self.pymathicsmodule.__package__)[10:]
            self.version = self.pymathicsmodule.pymathics_version_data[
                'version']
            self.author = self.pymathicsmodule.pymathics_version_data['author']
        except (AttributeError, KeyError, IndexError):
            print(module + " is not a pymathics module.")
            mainfolder = ""
            self.pymathicsmodule = None
            self.parts = []
            return

        # Paths
        self.doc_dir = self.pymathicsmodule.__path__[0] + "/doc/"
        self.xml_data_file = self.doc_dir + "xml/data"
        self.tex_data_file = self.doc_dir + "tex/data"
        self.latex_file = self.doc_dir + "tex/documentation.tex"

        # Load the dictionary of mathics symbols defined in the module
        self.symbols = {}
        from mathics.builtin import is_builtin, Builtin
        print("loading symbols")
        for name in dir(self.pymathicsmodule):
            var = getattr(self.pymathicsmodule, name)
            if (hasattr(var, '__module__')
                    and var.__module__ != 'mathics.builtin.base'
                    and is_builtin(var) and not name.startswith('_')
                    and var.__module__[:len(self.pymathicsmodule.__name__)]
                    == self.pymathicsmodule.__name__):  # nopep8
                instance = var(expression=False)
                if isinstance(instance, Builtin):
                    self.symbols[instance.get_name()] = instance
        # Defines de default first part, in case we are building an independent documentation module.
        self.title = "Overview"
        self.parts = []
        self.parts_by_slug = {}
        try:
            files = listdir(self.doc_dir)
            files.sort()
        except FileNotFoundError:
            self.doc_dir = ""
            self.xml_data_file = ""
            self.tex_data_file = ""
            self.latex_file = ""
            files = []
        appendix = []
        for file in files:
            part_title = file[2:]
            if part_title.endswith('.mdoc'):
                part_title = part_title[:-len('.mdoc')]
                part = DocPart(self, part_title)
                text = open(self.doc_dir + file, 'rb').read().decode('utf8')
                text = filter_comments(text)
                chapters = CHAPTER_RE.findall(text)
                for title, text in chapters:
                    chapter = DocChapter(part, title)
                    text += '<section title=""></section>'
                    sections = SECTION_RE.findall(text)
                    for pre_text, title, text in sections:
                        if not chapter.doc:
                            chapter.doc = Doc(pre_text)
                        if title:
                            section = DocSection(chapter, title, text)
                            chapter.sections.append(section)
                    part.chapters.append(chapter)
                if file[0].isdigit():
                    self.parts.append(part)
                else:
                    part.is_appendix = True
                    appendix.append(part)

        # Builds the automatic documentation
        builtin_part = DocPart(self, "Pymathics Modules", is_reference=True)
        title, text = get_module_doc(self.pymathicsmodule)
        chapter = DocChapter(builtin_part, title, Doc(text))
        for name in self.symbols:
            instance = self.symbols[name]
            installed = True
            for package in getattr(instance, 'requires', []):
                try:
                    importlib.import_module(package)
                except ImportError:
                    installed = False
                    break
            section = DocSection(chapter,
                                 strip_system_prefix(name),
                                 instance.__doc__ or '',
                                 operator=instance.get_operator(),
                                 installed=installed)
            chapter.sections.append(section)
        builtin_part.chapters.append(chapter)
        self.parts.append(builtin_part)
        # Adds possible appendices
        for part in appendix:
            self.parts.append(part)

        # set keys of tests
        for tests in self.get_tests():
            for test in tests.tests:
                test.key = (tests.part, tests.chapter, tests.section,
                            test.index)
Пример #6
0
    def __init__(self, module=None):
        self.title = "Overview"
        self.parts = []
        self.parts_by_slug = {}
        self.doc_dir = None
        self.doc_data_file = None
        self.symbols = {}
        if module is None:
            return

        import importlib

        # Load the module and verifies it is a pymathics module
        try:
            self.pymathicsmodule = importlib.import_module(module)
        except ImportError:
            print("Module does not exist")
            self.pymathicsmodule = None
            self.parts = []
            return

        try:
            if "name" in self.pymathicsmodule.pymathics_version_data:
                self.name = self.version = self.pymathicsmodule.pymathics_version_data[
                    "name"]
            else:
                self.name = (self.pymathicsmodule.__package__)[10:]
            self.version = self.pymathicsmodule.pymathics_version_data[
                "version"]
            self.author = self.pymathicsmodule.pymathics_version_data["author"]
        except (AttributeError, KeyError, IndexError):
            print(module + " is not a pymathics module.")
            self.pymathicsmodule = None
            self.parts = []
            return

        # Paths
        self.doc_dir = self.pymathicsmodule.__path__[0] + "/doc/"
        self.doc_data_file = self.doc_dir + "xml/data"

        # Load the dictionary of mathics symbols defined in the module
        self.symbols = {}
        from mathics.builtin import is_builtin, Builtin

        for name in dir(self.pymathicsmodule):
            var = getattr(self.pymathicsmodule, name)
            if (hasattr(var, "__module__")
                    and var.__module__ != "mathics.builtin.base"
                    and is_builtin(var) and not name.startswith("_")
                    and var.__module__[:len(self.pymathicsmodule.__name__)]
                    == self.pymathicsmodule.__name__):  # nopep8
                instance = var(expression=False)
                if isinstance(instance, Builtin):
                    self.symbols[instance.get_name()] = instance
        # Defines de default first part, in case we are building an independent documentation module.
        self.title = "Overview"
        self.parts = []
        self.parts_by_slug = {}
        try:
            files = listdir(self.doc_dir)
            files.sort()
        except FileNotFoundError:
            self.doc_dir = ""
            self.doc_data_file = ""
            files = []
        appendix = []
        for file in files:
            part_title = file[2:]
            if part_title.endswith(".mdoc"):
                part_title = part_title[:-len(".mdoc")]
                part = DjangoDocPart(self, part_title)
                text = open(self.doc_dir + file, "rb").read().decode("utf8")
                text = filter_comments(text)
                chapters = CHAPTER_RE.findall(text)
                for title, text in chapters:
                    chapter = DjangoDocChapter(part, title)
                    text += '<section title=""></section>'
                    sections = SECTION_RE.findall(text)
                    for pre_text, title, text in sections:
                        if not chapter.doc:
                            chapter.doc = DjangoDoc(pre_text)
                        if title:
                            section = DjangoDocSection(chapter, title, text)
                            chapter.sections.append(section)
                    part.chapters.append(chapter)
                if file[0].isdigit():
                    self.parts.append(part)
                else:
                    part.is_appendix = True
                    appendix.append(part)

        # Adds possible appendices
        for part in appendix:
            self.parts.append(part)

        # set keys of tests
        for tests in self.get_tests():
            for test in tests.tests:
                test.key = (tests.part, tests.chapter, tests.section,
                            test.index)