files: # -*- coding: utf-8 -*-
  #
  # Copyright Â© Spyder Project Contributors
  # Licensed under the terms of the MIT License
  # (see spyder/__init__.py for details)
  
  """
  Spyder configuration options.
  
  Note: Leave this file free of Qt related imports, so that it can be used to
  quickly load a user config file.
  """
  
  import os
  import sys
  
  # Local import
  from spyder.config.base import CHECK_ALL, EXCLUDED_NAMES
  from spyder.config.fonts import MEDIUM, SANS_SERIF
  from spyder.config.utils import IMPORT_EXT
  from spyder.config.appearance import APPEARANCE
  from spyder.plugins.editor.utils.findtasks import TASKS_PATTERN
  from spyder.utils.introspection.module_completion import PREFERRED_MODULES
  
  
  # =============================================================================
  # Main constants
  # =============================================================================
  # Find in files exclude patterns
  EXCLUDE_PATTERNS = ['*.csv, *.dat, *.log, *.tmp, *.bak, *.orig']
  
  # Extensions that should be visible in Spyder's file/project explorers
  SHOW_EXT = ['.py', '.ipynb', '.dat', '.pdf', '.png', '.svg', '.md', '.yml',
              '.yaml']
  
  # Extensions supported by Spyder (Editor or Variable explorer)
  USEFUL_EXT = IMPORT_EXT + SHOW_EXT
  
  # Name filters for file/project explorers (excluding files without extension)
  NAME_FILTERS = ['README', 'INSTALL', 'LICENSE', 'CHANGELOG']
  NAME_FILTERS += ['*' + _ext for _ext in USEFUL_EXT if _ext not in NAME_FILTERS]
  
  # Port used to detect if there is a running instance and to communicate with
  # it to open external files
  OPEN_FILES_PORT = 21128
  
  # OS Specific
  WIN = os.name == 'nt'
  MAC = sys.platform == 'darwin'
  LINUX = sys.platform.startswith('linux')
  CTRL = "Meta" if MAC else "Ctrl"
  
  # Modules to be preloaded for Rope and Jedi
  PRELOAD_MDOULES = ', '.join(PREFERRED_MODULES)
  
  
  # =============================================================================
  #  Defaults
  # =============================================================================
  DEFAULTS = [
              ('main',
               {
                'opengl': 'software',
                'single_instance': True,
                'open_files_port': OPEN_FILES_PORT,
                'mac_open_file': False,
                'normal_screen_resolution': True,
                'high_dpi_scaling': False,
                'high_dpi_custom_scale_factor': False,
                'high_dpi_custom_scale_factors': '1.5',
                'vertical_tabs': False,
                'prompt_on_exit': False,
                'panes_locked': True,
                'window/size': (1260, 740),
                'window/position': (10, 10),
                'window/is_maximized': True,
                'window/is_fullscreen': False,
                'window/prefs_dialog_size': (1050, 530),
                'use_custom_margin': True,
                'custom_margin': 0,
                'use_custom_cursor_blinking': False,
                'show_internal_errors': True,
                'check_updates_on_startup': True,
                'cursor/width': 2,
                'completion/size': (300, 180),
                'report_error/remember_token': False,
                'show_dpi_message': True,
                }),
              ('toolbar',
               {
                'enable': True,
                'toolbars_visible': True,
                'last_visible_toolbars': [],
               }),
              ('statusbar',
               {
                'show_status_bar': True,
                'memory_usage/enable': True,
                'memory_usage/timeout': 2000,
                'cpu_usage/enable': False,
                'cpu_usage/timeout': 2000,
                'clock/enable': False,
                'clock/timeout': 1000,
                'check_updates_on_startup': False,
                }),
              ('quick_layouts',
               {
                'place_holder': '',
                'names': [],
                'order': [],
                'active': [],
                'ui_names': []
                }),
              ('internal_console',
               {
                'max_line_count': 300,
                'working_dir_history': 30,
                'working_dir_adjusttocontents': False,
                'wrap': True,
                'codecompletion/auto': False,
                'external_editor/path': 'SciTE',
                'external_editor/gotoline': '-goto:',
                }),
              ('main_interpreter',
               {
                'default': True,
                'custom': False,
                'umr/enabled': True,
                'umr/verbose': True,
                'umr/namelist': [],
                'custom_interpreters_list': [],
                'custom_interpreter': '',
                }),
              ('ipython_console',
               {
                'show_banner': True,
                'completion_type': 0,
                'show_calltips': True,
                'ask_before_closing': False,
                'show_reset_namespace_warning': True,
                'buffer_size': 500,
                'pylab': True,
                'pylab/autoload': False,
                'pylab/backend': 0,
                'pylab/inline/figure_format': 0,
                'pylab/inline/resolution': 72,
                'pylab/inline/width': 6,
                'pylab/inline/height': 4,
                'pylab/inline/bbox_inches': True,
                'startup/run_lines': 'import antimony; import rrplugins; import numpy; import scipy; import matplotlib; import roadrunner; import tellurium as te',
                'startup/use_run_file': False,
                'startup/run_file': '',
                'greedy_completer': False,
                'jedi_completer': False,
                'autocall': 0,
                '
  
  [... the rest is omitted ...]
files: spyder_mod/Spyder 5.1.5/site-packages/spyder/config/main.py
files: # -*- coding: utf-8 -*-
  #
  # Copyright Â© Spyder Project Contributors
  # Licensed under the terms of the MIT License
  # (see spyder/__init__.py for details)
  
  """
  Spyder configuration options.
  
  Note: Leave this file free of Qt related imports, so that it can be used to
  quickly load a user config file.
  """
  
  import os
  import sys
  
  # Local import
  from spyder.config.base import CHECK_ALL, EXCLUDED_NAMES
  from spyder.config.fonts import MEDIUM, SANS_SERIF
  from spyder.config.utils import IMPORT_EXT
  from spyder.config.appearance import APPEARANCE
  from spyder.plugins.editor.utils.findtasks import TASKS_PATTERN
  from spyder.utils.introspection.module_completion import PREFERRED_MODULES
  
  
  # =============================================================================
  # Main constants
  # =============================================================================
  # Find in files exclude patterns
  EXCLUDE_PATTERNS = ['*.csv, *.dat, *.log, *.tmp, *.bak, *.orig']
  
  # Extensions that should be visible in Spyder's file/project explorers
  SHOW_EXT = ['.py', '.ipynb', '.dat', '.pdf', '.png', '.svg', '.md', '.yml',
              '.yaml']
  
  # Extensions supported by Spyder (Editor or Variable explorer)
  USEFUL_EXT = IMPORT_EXT + SHOW_EXT
  
  # Name filters for file/project explorers (excluding files without extension)
  NAME_FILTERS = ['README', 'INSTALL', 'LICENSE', 'CHANGELOG']
  NAME_FILTERS += ['*' + _ext for _ext in USEFUL_EXT if _ext not in NAME_FILTERS]
  
  # Port used to detect if there is a running instance and to communicate with
  # it to open external files
  OPEN_FILES_PORT = 21128
  
  # OS Specific
  WIN = os.name == 'nt'
  MAC = sys.platform == 'darwin'
  LINUX = sys.platform.startswith('linux')
  CTRL = "Meta" if MAC else "Ctrl"
  
  # Modules to be preloaded for Rope and Jedi
  PRELOAD_MDOULES = ', '.join(PREFERRED_MODULES)
  
  
  # =============================================================================
  #  Defaults
  # =============================================================================
  DEFAULTS = [
              ('main',
               {
                'opengl': 'software',
                'single_instance': True,
                'open_files_port': OPEN_FILES_PORT,
                'mac_open_file': False,
                'normal_screen_resolution': True,
                'high_dpi_scaling': False,
                'high_dpi_custom_scale_factor': False,
                'high_dpi_custom_scale_factors': '1.5',
                'vertical_tabs': False,
                'prompt_on_exit': False,
                'panes_locked': True,
                'window/size': (1260, 740),
                'window/position': (10, 10),
                'window/is_maximized': True,
                'window/is_fullscreen': False,
                'window/prefs_dialog_size': (1050, 530),
                'use_custom_margin': True,
                'custom_margin': 0,
                'use_custom_cursor_blinking': False,
                'show_internal_errors': True,
                'check_updates_on_startup': True,
                'cursor/width': 2,
                'completion/size': (300, 180),
                'report_error/remember_token': False,
                'show_dpi_message': True,
                }),
              ('toolbar',
               {
                'enable': True,
                'toolbars_visible': True,
                'last_visible_toolbars': [],
               }),
              ('statusbar',
               {
                'show_status_bar': True,
                'memory_usage/enable': True,
                'memory_usage/timeout': 2000,
                'cpu_usage/enable': False,
                'cpu_usage/timeout': 2000,
                'clock/enable': False,
                'clock/timeout': 1000,
                'check_updates_on_startup': False,
                }),
              ('quick_layouts',
               {
                'place_holder': '',
                'names': [],
                'order': [],
                'active': [],
                'ui_names': []
                }),
              ('internal_console',
               {
                'max_line_count': 300,
                'working_dir_history': 30,
                'working_dir_adjusttocontents': False,
                'wrap': True,
                'codecompletion/auto': False,
                'external_editor/path': 'SciTE',
                'external_editor/gotoline': '-goto:',
                }),
              ('main_interpreter',
               {
                'default': True,
                'custom': False,
                'umr/enabled': True,
                'umr/verbose': True,
                'umr/namelist': [],
                'custom_interpreters_list': [],
                'custom_interpreter': '',
                }),
              ('ipython_console',
               {
                'show_banner': True,
                'completion_type': 0,
                'show_calltips': True,
                'ask_before_closing': False,
                'show_reset_namespace_warning': True,
                'buffer_size': 500,
                'pylab': True,
                'pylab/autoload': False,
                'pylab/backend': 0,
                'pylab/inline/figure_format': 0,
                'pylab/inline/resolution': 72,
                'pylab/inline/width': 6,
                'pylab/inline/height': 4,
                'pylab/inline/bbox_inches': True,
                'startup/run_lines': 'import antimony; import sbml2matlab; import rrplugins; import numpy; import scipy; import matplotlib; import roadrunner; import tellurium as te',
                'startup/use_run_file': False,
                'startup/run_file': '',
                'greedy_completer': False,
                'jedi_completer': False,
                'autoc
  
  [... the rest is omitted ...]
files: spyder_mod/Spyder 5.1.5/site-packages/spyder/config/main.py
files: """
  Class for working with omex files.
  """
  from __future__ import print_function, division, absolute_import
  import os
  import re
  import tempfile
  import json
  import getpass
  
  
  import imp  # reloads because numl is overwriting symbols
  try:
      import libcombine
  except ImportError:
      import tecombine as libcombine
  
  try:
      from .convert_phrasedml import phrasedmlImporter
  except:
      pass
  from .convert_antimony import antimonyConverter
  
  class OmexFormatDetector:
      def __init__(self, omex):
          self.omex = omex
          # match sbml, any level/ver
          self.sbml_fmt_expr = re.compile(r'^http[s]?://identifiers\.org/combine\.specifications/sbml.*$')
          # match sedml, any level/ver
          self.sedml_fmt_expr = re.compile(r'^http[s]?://identifiers\.org/combine\.specifications/sed-ml.*$')
  
      def isSEDMLEntry(self, entry):
          return self.sedml_fmt_expr.match(entry.getFormat()) != None
  
      def isSBMLEntry(self, entry):
          """ Return true if this entry is SBML. """
          if self.sbml_fmt_expr.match(entry.getFormat()) != None:
              return True
          elif entry.getFormat() == 'application/xml':
              # try to guess if it is SBML
              content = self.omex.extractEntryToString(entry.getLocation())
              if content.startswith('<?xml') and '<sbml xmlns="http://www.sbml.org/sbml' in content:
                  return True
              else:
                  return False
          else:
              return False
  
  def readCreator(file=None):
      from .. import getAppDir
      if file is None:
          file = os.path.join(getAppDir(), 'telocal', getpass.getuser() + '.vcard')
          if not os.path.exists(file) or not os.path.isfile(file):
              return None
      with open(file, 'rb') as f:
          return json.load(f)
  
  
  class OmexAsset(object):
      def getLocation(self):
          return self.location
  
      def getFileName(self):
          return os.path.split(self.getLocation())[-1]
  
      def getContent(self):
          return self.content
  
      def getMaster(self):
          master = False
          if self.master is not None:
              master = self.master
          return master
  
  
  class SbmlAsset(OmexAsset):
      def __init__(self, location, content, master=False):
          self.location = location
          self.content = content
          self.master = master
  
      def getModuleName(self):
          return os.path.splitext(self.getFileName())[0]
  
      def __repr__(self):
          return 'SbmlAsset(location={}, master={})'.format(self.getLocation(), self.getMaster())
  
  
  class SedmlAsset(OmexAsset):
      def __init__(self, location, content, master=False):
          self.location = location
          self.content = content
          self.master = master
  
      def __repr__(self):
          return 'SedmlAsset(location={}, master={})'.format(self.getLocation(), self.getMaster())
  
  
  class Omex(object):
      """ Wrapper for Combine archives. """
      def __init__(self,
                   description='',
                   creator=None):
  
          self.about = '.'
          self.description = description
          self.creator = creator
  
          self.sbml_assets = []
          self.sedml_assets = []
  
      def addSbmlAsset(self, asset):
          self.sbml_assets.append(asset)
  
      def addSedmlAsset(self, asset):
          self.sedml_assets.append(asset)
  
      def getSbmlAssets(self):
          return self.sbml_assets
  
      def getSedmlAssets(self):
          return self.sedml_assets
  
      def writeFiles(self, dir):
          filenames = []
          for t in self.getSedmlAssets():
              fname = os.path.join(dir, os.path.normpath(t.getLocation()))
              dname = os.path.dirname(fname)
              if not os.path.exists(dname):
                  os.makedirs(dname)
              filenames.append(fname)
              with open(fname, 'w') as f:
                  f.write(t.getContent())
  
          for t in self.getSbmlAssets():
              fname = os.path.join(dir, os.path.normpath(t.getLocation()))
              dname = os.path.dirname(fname)
              if not os.path.exists(dname):
                  os.makedirs(dname)
              filenames.append(fname)
              with open(fname, 'w') as f:
                  f.write(t.getContent())
          return filenames
  
      def executeOmex(self):
          """ Executes this Omex instance.
  
          :return:
          """
          try:
              import phrasedml
              phrasedml.clearReferencedSBML()
          except:
              pass
  
          workingDir = tempfile.mkdtemp(suffix="_sedml")
          self.writeFiles(workingDir)
          from tellurium import executeSEDML
          for sedml_asset in self.getSedmlAssets():
              if sedml_asset.getMaster():
                  sedml_path = os.path.join(workingDir, sedml_asset.getLocation())
                  executeSEDML(sedml_path,
                               workingDir=os.path.dirname(sedml_path))
                  # shutil.rmtree(workingDir)
  
      def exportToCombine(self, outfile):
          """ Export Omex instance as combine archive.
  
          :param outfile: A path to the output file"""
          try:
              import phrasedml
              phrasedml.clearReferencedSBML()
          except:
              pass
  
          archive = libcombine.CombineArchive()
          description = libcombine.OmexDescription()
          description.setAbout(self.about)
          description.setDescription(self.description)
          time_now = libcombine.OmexDescription.getCurrentDateAndTime()
          description.setCreated(time_now)
  
          # TODO:
  
  [... the rest is omitted ...]
files: tellurium/teconverters/convert_omex.py
files: """
  Class for working with omex files.
  """
  from __future__ import print_function, division, absolute_import
  import os
  import re
  import shutil
  import tempfile
  import json
  import getpass
  
  
  import imp  # reloads because numl is overwriting symbols
  try:
      import libcombine
  except ImportError:
      import tecombine as libcombine
  
  
  from .convert_phrasedml import phrasedmlImporter
  from .convert_antimony import antimonyConverter
  
  class OmexFormatDetector:
      def __init__(self, omex):
          self.omex = omex
          # match sbml, any level/ver
          self.sbml_fmt_expr = re.compile(r'^http[s]?://identifiers\.org/combine\.specifications/sbml.*$')
          # match sedml, any level/ver
          self.sedml_fmt_expr = re.compile(r'^http[s]?://identifiers\.org/combine\.specifications/sed-ml.*$')
  
      def isSEDMLEntry(self, entry):
          return self.sedml_fmt_expr.match(entry.getFormat()) != None
  
      def isSBMLEntry(self, entry):
          """ Return true if this entry is SBML. """
          if self.sbml_fmt_expr.match(entry.getFormat()) != None:
              return True
          elif entry.getFormat() == 'application/xml':
              # try to guess if it is SBML
              content = self.omex.extractEntryToString(entry.getLocation())
              if content.startswith('<?xml') and '<sbml xmlns="http://www.sbml.org/sbml' in content:
                  return True
              else:
                  return False
          else:
              return False
  
  def readCreator(file=None):
      from .. import getAppDir
      if file is None:
          file = os.path.join(getAppDir(), 'telocal', getpass.getuser() + '.vcard')
          if not os.path.exists(file) or not os.path.isfile(file):
              return None
      with open(file, 'rb') as f:
          return json.load(f)
  
  
  class OmexAsset(object):
      def getLocation(self):
          return self.location
  
      def getFileName(self):
          return os.path.split(self.getLocation())[-1]
  
      def getContent(self):
          return self.content
  
      def getMaster(self):
          master = False
          if self.master is not None:
              master = self.master
          return master
  
  
  class SbmlAsset(OmexAsset):
      def __init__(self, location, content, master=False):
          self.location = location
          self.content = content
          self.master = master
  
      def getModuleName(self):
          return os.path.splitext(self.getFileName())[0]
  
      def __repr__(self):
          return 'SbmlAsset(location={}, master={})'.format(self.getLocation(), self.getMaster())
  
  
  class SedmlAsset(OmexAsset):
      def __init__(self, location, content, master=False):
          self.location = location
          self.content = content
          self.master = master
  
      def __repr__(self):
          return 'SedmlAsset(location={}, master={})'.format(self.getLocation(), self.getMaster())
  
  
  class Omex(object):
      """ Wrapper for Combine archives. """
      def __init__(self,
                   description='',
                   creator=None):
  
          self.about = '.'
          self.description = description
          self.creator = creator
  
          self.sbml_assets = []
          self.sedml_assets = []
  
      def addSbmlAsset(self, asset):
          self.sbml_assets.append(asset)
  
      def addSedmlAsset(self, asset):
          self.sedml_assets.append(asset)
  
      def getSbmlAssets(self):
          return self.sbml_assets
  
      def getSedmlAssets(self):
          return self.sedml_assets
  
      def writeFiles(self, dir):
          filenames = []
          for t in self.getSedmlAssets():
              fname = os.path.join(dir, os.path.normpath(t.getLocation()))
              dname = os.path.dirname(fname)
              if not os.path.exists(dname):
                  os.makedirs(dname)
              filenames.append(fname)
              with open(fname, 'w') as f:
                  f.write(t.getContent())
  
          for t in self.getSbmlAssets():
              fname = os.path.join(dir, os.path.normpath(t.getLocation()))
              dname = os.path.dirname(fname)
              if not os.path.exists(dname):
                  os.makedirs(dname)
              filenames.append(fname)
              with open(fname, 'w') as f:
                  f.write(t.getContent())
          return filenames
  
      def executeOmex(self):
          """ Executes this Omex instance.
  
          :return:
          """
          import phrasedml
          phrasedml.clearReferencedSBML()
  
          workingDir = tempfile.mkdtemp(suffix="_sedml")
          self.writeFiles(workingDir)
          from tellurium import executeSEDML
          for sedml_asset in self.getSedmlAssets():
              if sedml_asset.getMaster():
                  sedml_path = os.path.join(workingDir, sedml_asset.getLocation())
                  executeSEDML(sedml_path,
                               workingDir=os.path.dirname(sedml_path))
                  # shutil.rmtree(workingDir)
  
      def exportToCombine(self, outfile):
          """ Export Omex instance as combine archive.
  
          :param outfile: A path to the output file"""
          import phrasedml
          phrasedml.clearReferencedSBML()
  
          archive = libcombine.CombineArchive()
          description = libcombine.OmexDescription()
          description.setAbout(self.about)
          description.setDescription(self.description)
          time_now = libcombine.OmexDescription.getCurrentDateAndTime()
          description.setCreated(time_now)
  
          # TODO: pass in creator
          if self.creator is not None:
              creator = libcombine.VCard()
  
  
  [... the rest is omitted ...]
files: tellurium/teconverters/convert_omex.py
files: from __future__ import print_function, division, absolute_import
  
  import os
  import re
  try:
      import tesedml as libsedml
  except ImportError:
      import libsedml
  
  #Only load this class if phrasedml exists
  try:
      import phrasedml
  
      class phrasedmlImporter(object):
      
          def __init__(self, sbml_map={}):
              """ Constructor. """
              self.sedml_str = None
              self.sedml_path = None
              self.sbml_map = sbml_map
      
      
          @classmethod
          def fromContent(cls, sedml_str, sbml_map={}):
      
              # FIXME: bad hack for https://github.com/fbergmann/libSEDML/issues/47
              # test for JWS quirks
              if 'xmlns="http://sed-ml.org/sed-ml/level1/version3"' in sedml_str:
                  # import xml.etree.ElementTree as ElementTree
                  # root = ElementTree.fromstring(sedml_str)
                  # for p in root.findall('{http://sed-ml.org/sed-ml/level1/version3}plot2D'):
                  #     if not 'logX' in p.attrib or not 'logY' in p.attrib:
                  #         logX = False
                  #         logY = False
                  #         for l in p.findall('{http://sed-ml.org/sed-ml/level1/version3}listOfCurves'):
                  #             for c in l.findall('{http://sed-ml.org/sed-ml/level1/version3}curve'):
                  #                 if 'logX' in c.attrib and c.attrib['logX'].lower() == 'true':
                  #                     logX = True
                  #                 if 'logY' in c.attrib and c.attrib['logY'].lower() == 'true':
                  #                     logY = True
                  #         p.set('logX', logX)
                  #         p.set('logY', logY)
                  # sedml_str = (ElementTree.tostring(root, encoding='utf8', method='xml')).decode('utf8')
                  while True:
                      p = sedml_str.find('plot2D')
                      if p < 0:
                          break
                      b = sedml_str.find('>', p)
                      if b < 0:
                          break
                      l = sedml_str.find('logX', p)
                      if l < 0 or b < l:
                          sedml_str = sedml_str[:p] + 'plot2D logX="false" logY="false" ' + sedml_str[p+len('plot2D'):]
                      else:
                          break
                  print(sedml_str)
      
      
              importer = phrasedmlImporter(sbml_map)
              importer.sedml_str = sedml_str
              # test for errors
              result = importer.toPhrasedml()
              if result is None:
                  # get errors from libsedml
                  doc = libsedml.SedReader().readSedMLFromString(sedml_str)
                  if doc.getNumErrors():
                      max_len = 100
                      message = doc.getError(doc.getNumErrors()-1).getMessage()
                      message = message[:max_len] + '...' if len(message) > max_len else message
                      raise RuntimeError('Errors reading SED-ML: {}'.format(message))
                  else:
                      raise RuntimeError('Unable to read SED-ML.')
              return importer
      
      
          def isInRootDir(self, file):
              d = os.path.split(file)[0]
              return d == '' or d == '.'
      
          def removeFileExt(self, filename):
              return os.path.splitext(filename)[0]
      
          def formatResource(self, filename):
              """ Normalizes and also strips xml extension."""
              return self.removeFileExt(os.path.normpath(filename))
      
          def fixModelRefs(self, phrasedml_str):
              ''' Changes all references of type myModel.xml to myModel.'''
              model_ref = re.compile(r'^.*\s*model\s*"([^"]*)"\s*$')
              out_str = ''
              for line in phrasedml_str.splitlines():
                  match = model_ref.match(line)
                  if match:
                      filename = match.group(1)
                      if self.isInRootDir(filename):
                          line = line.replace(filename,self.formatResource(filename))
                  out_str += line+'\n'
              return out_str
      
          def toPhrasedml(self):
              # assign sbml resources
              # print('toPhrasedml sbml resources:')
              phrasedml.clearReferencedSBML()
              for sbml_resource in self.sbml_map:
                  # print('  {} -> {}'.format(sbml_resource, self.sbml_map[sbml_resource][:30]))
                  phrasedml.setReferencedSBML(sbml_resource, self.sbml_map[sbml_resource])
              # convert to phrasedml
              if self.sedml_str:
                  result = phrasedml.convertString(self.sedml_str)
                  if result is None:
                      raise RuntimeError(phrasedml.getLastError())
                  return self.fixModelRefs(phrasedml.getLastPhraSEDML())
              elif self.sedml_path:
                  result = phrasedml.convertFile(self.sedml_str)
                  if result is None:
                      raise RuntimeError(phrasedml.getLastError())
                  return self.fixModelRefs(phrasedml.getLastPhraSEDML())
  
  except:
      pass
  
  [... the rest is omitted ...]
files: tellurium/teconverters/convert_phrasedml.py
files: from __future__ import print_function, division, absolute_import
  
  import os
  import re
  import phrasedml
  try:
      import tesedml as libsedml
  except ImportError:
      import libsedml
  
  
  class phrasedmlImporter(object):
  
      def __init__(self, sbml_map={}):
          """ Constructor. """
          self.sedml_str = None
          self.sedml_path = None
          self.sbml_map = sbml_map
  
  
      @classmethod
      def fromContent(cls, sedml_str, sbml_map={}):
  
          # FIXME: bad hack for https://github.com/fbergmann/libSEDML/issues/47
          # test for JWS quirks
          if 'xmlns="http://sed-ml.org/sed-ml/level1/version3"' in sedml_str:
              # import xml.etree.ElementTree as ElementTree
              # root = ElementTree.fromstring(sedml_str)
              # for p in root.findall('{http://sed-ml.org/sed-ml/level1/version3}plot2D'):
              #     if not 'logX' in p.attrib or not 'logY' in p.attrib:
              #         logX = False
              #         logY = False
              #         for l in p.findall('{http://sed-ml.org/sed-ml/level1/version3}listOfCurves'):
              #             for c in l.findall('{http://sed-ml.org/sed-ml/level1/version3}curve'):
              #                 if 'logX' in c.attrib and c.attrib['logX'].lower() == 'true':
              #                     logX = True
              #                 if 'logY' in c.attrib and c.attrib['logY'].lower() == 'true':
              #                     logY = True
              #         p.set('logX', logX)
              #         p.set('logY', logY)
              # sedml_str = (ElementTree.tostring(root, encoding='utf8', method='xml')).decode('utf8')
              while True:
                  p = sedml_str.find('plot2D')
                  if p < 0:
                      break
                  b = sedml_str.find('>', p)
                  if b < 0:
                      break
                  l = sedml_str.find('logX', p)
                  if l < 0 or b < l:
                      sedml_str = sedml_str[:p] + 'plot2D logX="false" logY="false" ' + sedml_str[p+len('plot2D'):]
                  else:
                      break
              print(sedml_str)
  
  
          importer = phrasedmlImporter(sbml_map)
          importer.sedml_str = sedml_str
          # test for errors
          result = importer.toPhrasedml()
          if result is None:
              # get errors from libsedml
              doc = libsedml.SedReader().readSedMLFromString(sedml_str)
              if doc.getNumErrors():
                  max_len = 100
                  message = doc.getError(doc.getNumErrors()-1).getMessage()
                  message = message[:max_len] + '...' if len(message) > max_len else message
                  raise RuntimeError('Errors reading SED-ML: {}'.format(message))
              else:
                  raise RuntimeError('Unable to read SED-ML.')
          return importer
  
  
      def isInRootDir(self, file):
          d = os.path.split(file)[0]
          return d == '' or d == '.'
  
      def removeFileExt(self, filename):
          return os.path.splitext(filename)[0]
  
      def formatResource(self, filename):
          """ Normalizes and also strips xml extension."""
          return self.removeFileExt(os.path.normpath(filename))
  
      def fixModelRefs(self, phrasedml_str):
          ''' Changes all references of type myModel.xml to myModel.'''
          model_ref = re.compile(r'^.*\s*model\s*"([^"]*)"\s*$')
          out_str = ''
          for line in phrasedml_str.splitlines():
              match = model_ref.match(line)
              if match:
                  filename = match.group(1)
                  if self.isInRootDir(filename):
                      line = line.replace(filename,self.formatResource(filename))
              out_str += line+'\n'
          return out_str
  
      def toPhrasedml(self):
          # assign sbml resources
          # print('toPhrasedml sbml resources:')
          phrasedml.clearReferencedSBML()
          for sbml_resource in self.sbml_map:
              # print('  {} -> {}'.format(sbml_resource, self.sbml_map[sbml_resource][:30]))
              phrasedml.setReferencedSBML(sbml_resource, self.sbml_map[sbml_resource])
          # convert to phrasedml
          if self.sedml_str:
              result = phrasedml.convertString(self.sedml_str)
              if result is None:
                  raise RuntimeError(phrasedml.getLastError())
              return self.fixModelRefs(phrasedml.getLastPhraSEDML())
          elif self.sedml_path:
              result = phrasedml.convertFile(self.sedml_str)
              if result is None:
                  raise RuntimeError(phrasedml.getLastError())
              return self.fixModelRefs(phrasedml.getLastPhraSEDML())
  
  
  [... the rest is omitted ...]
files: tellurium/teconverters/convert_phrasedml.py