libSBML Python API  5.11.0
flattenModel.py

Model flattening example.

1 #!/usr/bin/env python
2 ##
3 ## @file flattenModel.py
4 ## @brief Flattens the comp code from the given SBML file.
5 ## @author Frank T. Bergmann
6 ## @author Michael Hucka
7 ##
8 ## <!--------------------------------------------------------------------------
9 ## This sample program is distributed under a different license than the rest
10 ## of libSBML. This program uses the open-source MIT license, as follows:
11 ##
12 ## Copyright (c) 2013-2014 by the California Institute of Technology
13 ## (California, USA), the European Bioinformatics Institute (EMBL-EBI, UK)
14 ## and the University of Heidelberg (Germany), with support from the National
15 ## Institutes of Health (USA) under grant R01GM070923. All rights reserved.
16 ##
17 ## Permission is hereby granted, free of charge, to any person obtaining a
18 ## copy of this software and associated documentation files (the "Software"),
19 ## to deal in the Software without restriction, including without limitation
20 ## the rights to use, copy, modify, merge, publish, distribute, sublicense,
21 ## and/or sell copies of the Software, and to permit persons to whom the
22 ## Software is furnished to do so, subject to the following conditions:
23 ##
24 ## The above copyright notice and this permission notice shall be included in
25 ## all copies or substantial portions of the Software.
26 ##
27 ## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
28 ## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
29 ## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
30 ## THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
31 ## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
32 ## FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
33 ## DEALINGS IN THE SOFTWARE.
34 ##
35 ## Neither the name of the California Institute of Technology (Caltech), nor
36 ## of the European Bioinformatics Institute (EMBL-EBI), nor of the University
37 ## of Heidelberg, nor the names of any contributors, may be used to endorse
38 ## or promote products derived from this software without specific prior
39 ## written permission.
40 ## ------------------------------------------------------------------------ -->
41 
42 import sys, getopt, os.path
43 from libsbml import *
44 
45 
46 # Utility function to make it easier to check the return values from
47 # libSBML calls.
48 
49 def check(value, message):
50  """If 'value' is None, prints an error message constructed using
51  'message' and then exits with status code 1. If 'value' is an integer,
52  it assumes it is a libSBML return status code. If the code value is
53  LIBSBML_OPERATION_SUCCESS, returns without further action; if it is not,
54  prints an error message constructed using 'message' along with text from
55  libSBML explaining the meaning of the code, and exits with status code 1.
56  """
57  if value == None:
58  raise SystemExit('LibSBML returned a null value trying to ' + message + '.')
59  elif type(value) is int:
60  if value == LIBSBML_OPERATION_SUCCESS:
61  return
62  else:
63  err_msg = 'Error encountered trying to ' + message + '.' \
64  + 'LibSBML returned error code ' + str(value) + ': "' \
65  + OperationReturnValue_toString(value).strip() + '"'
66  raise SystemExit(err_msg)
67  else:
68  return
69 
70 
71 # The actual program.
72 
73 def main (argv):
74  """Usage: flattenModel.py [-p] MODEL_FILE OUTPUT_FILE
75 Arguments:
76  -p (Optional) list unused ports
77  """
78 
79  # Before we begin, check that this copy of libSBML has the 'comp' package
80  # extension compiled in.
81 
82  if not SBMLExtensionRegistry.isPackageEnabled("comp"):
83  err_msg = 'This copy of libSBML does not contain the "comp" extension.' \
84  + 'Unable to proceed with flattening the model.'
85  raise SystemExit(err_msg)
86 
87  # Read and verify command line arguments.
88 
89  try:
90  opts, args = getopt.getopt(argv[1:], "p")
91  except:
92  raise SystemExit(main.__doc__)
93 
94  if len(args) < 2:
95  raise SystemExit(main.__doc__)
96 
97  leave_ports = '-p' in opts
98  input_file = args[0]
99  output_file = args[1]
100 
101  if not os.path.exists(input_file):
102  raise SystemExit('%s : No such file.' % (input_file))
103 
104  # Read the SBML input file.
105 
106  reader = SBMLReader()
107  check(reader, 'create an SBMLReader object.')
108  sbmldoc = reader.readSBML(input_file)
109  check(sbmldoc, 'create an SBMLDocument object from file input')
110 
111  if sbmldoc.getNumErrors() > 0:
112  if sbmldoc.getError(0).getErrorId() == XMLFileUnreadable:
113  # Handle case of unreadable file here.
114  sbmldoc.printErrors()
115  elif sbmldoc.getError(0).getErrorId() == XMLFileOperationError:
116  # Handle case of other file error here.
117  sbmldoc.printErrors()
118  else:
119  # Handle other error cases here.
120  sbmldoc.printErrors()
121 
122  raise SystemExit(2)
123 
124  # Create the converter options
125 
126  props = ConversionProperties()
127  props.addOption("flatten comp", True) # Invokes CompFlatteningConverter
128  props.addOption("leave_ports", leave_ports) # Indicates whether to leave ports
129 
130  # Do the conversion.
131 
132  result = sbmldoc.convert(props)
133  if (result != LIBSBML_OPERATION_SUCCESS):
134  sbmldoc.printErrors()
135  raise SystemExit("Conversion failed... ("+ str(result) + ")")
136 
137  # Write the results to the output file.
138 
139  writer = SBMLWriter()
140  check(writer, 'create an SBMLWriter object.')
141  writer.writeSBML(sbmldoc, output_file)
142  print("Flattened model written to %s" % (output_file))
143 
144 if __name__ == '__main__':
145  main(sys.argv)