Write the given MetabolicModel to YAML files in dest folder.

    The parameter ``convert_exchange`` indicates whether the exchange reactions
    should be converted automatically to an exchange file.
19177
def write_yaml_model(model, dest='.', convert_exchange=True,
                     split_subsystem=True):
    
    yaml.SafeDumper.add_representer(OrderedDict, _dict_representer)
    yaml.SafeDumper.add_representer(set, _set_representer)
    yaml.SafeDumper.add_representer(frozenset, _set_representer)
    yaml.SafeDumper.add_representer(
        boolean.Expression, _boolean_expression_representer)
    yaml.SafeDumper.add_representer(Decimal, _decimal_representer)

    yaml.SafeDumper.ignore_aliases = lambda *args: True

    yaml.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
                         _dict_constructor)

    yaml_args = {'default_flow_style': False,
                 'encoding': 'utf-8',
                 'allow_unicode': True,
                 'width': 79}

    # The ModelWriter from PSAMM is not yet able to write the full model but
    # only reactions and compounds.
    writer = ModelWriter()

    with open(os.path.join(dest, 'compounds.yaml'), 'w+') as f:
        writer.write_compounds(f, sorted(model.compounds, key=lambda c: c.id))

    if model.default_flux_limit is None:
        model.default_flux_limit = detect_best_flux_limit(model)

    if model.extracellular_compartment is None:
        model.extracellular_compartment = (
            sbml.detect_extracellular_compartment(model))

    if model.default_compartment is None:
        model.default_compartment = get_default_compartment(model)

    if model.default_flux_limit is not None:
        logger.info('Using default flux limit of {}'.format(
            model.default_flux_limit))

    if convert_exchange:
        logger.info('Converting exchange reactions to exchange file')
        sbml.convert_exchange_to_compounds(model)

    if len(model.compartments) == 0:
        infer_compartment_entries(model)
        logger.info('Inferred {} compartments: {}'.format(
            len(model.compartments),
            ', '.join(c.id for c in model.compartments)))

    if len(model.compartments) != 0 and len(model.compartment_boundaries) == 0:
        infer_compartment_adjacency(model)

    reaction_files = reactions_to_files(model, dest, writer, split_subsystem)

    if len(model.exchange) > 0:
        with open(os.path.join(dest, 'exchange.yaml'), 'w+') as f:
            yaml.safe_dump(model_exchange(model), f, **yaml_args)

    reaction_limits = list(model_reaction_limits(model))
    if len(reaction_limits) > 0:
        with open(os.path.join(dest, 'limits.yaml'), 'w+') as f:
            yaml.safe_dump(reaction_limits, f, **yaml_args)

    model_d = OrderedDict()
    if model.name is not None:
        model_d['name'] = model.name

    if model.biomass_reaction is not None:
        model_d['biomass'] = model.biomass_reaction
    if model.default_flux_limit is not None:
        model_d['default_flux_limit'] = model.default_flux_limit
    if model.extracellular_compartment != 'e':
        model_d['extracellular'] = model.extracellular_compartment
    if model.default_compartment != 'c':
        model_d['default_compartment'] = model.default_compartment

    if len(model.compartments) > 0:
        adjacency = {}
        for c1, c2 in model.compartment_boundaries:
            adjacency.setdefault(c1, set()).add(c2)
            adjacency.setdefault(c2, set()).add(c1)

        compartment_list = []
        for compartment in sorted(model.compartments, key=lambda c: c.id):
            adjacent = adjacency.get(compartment.id)
            if adjacent is not None and len(adjacent) == 1:
                adjacent = next(iter(adjacent))
            compartment_list.append(writer.convert_compartment_entry(
                compartment, adjacent))

        model_d['compartments'] = compartment_list

    model_d['compounds'] = [{'include': 'compounds.yaml'}]
    model_d['reactions'] = []
    for reaction_file in reaction_files:
        model_d['reactions'].append({'include': reaction_file})

    if len(model.exchange) > 0:
        model_d['exchange'] = [{'include': 'exchange.yaml'}]

    if len(reaction_limits) > 0:
        model_d['limits'] = [{'include': 'limits.yaml'}]

    with open(os.path.join(dest, 'model.yaml'), 'w+') as f:
        yaml.safe_dump(model_d, f, **yaml_args)
234304
def exchange_partition(self, partitionSpecs, source_db, source_table_name, dest_db, dest_table_name):
    
    self.send_exchange_partition(partitionSpecs, source_db, source_table_name, dest_db, dest_table_name)
    return self.recv_exchange_partition()
702366
def exchange_partitions(self, partitionSpecs, source_db, source_table_name, dest_db, dest_table_name):
    
    self.send_exchange_partitions(partitionSpecs, source_db, source_table_name, dest_db, dest_table_name)
    return self.recv_exchange_partitions()
688581
def write_transforms_to_file(self, fname='ace_transforms.txt'):
        """"""
        self._write_columns(fname, self.x_transforms, self.y_transform)
266934
def Convert(self, metadata, yara_match, token=None):
    """"""

    conv = ProcessToExportedProcessConverter(options=self.options)
    process = list(
        conv.Convert(ExportedMetadata(), yara_match.process, token=token))[0]

    seen_rules = set()
    for m in yara_match.match:
      if m.rule_name in seen_rules:
        continue

      seen_rules.add(m.rule_name)
      yield ExportedYaraProcessScanMatch(
          metadata=metadata,
          process=process,
          rule_name=m.rule_name,
          scan_time_us=yara_match.scan_time_us)
1179428
def respth2ck(argv=None):
    
    parser = ArgumentParser(
        description='Convert a ReSpecTh XML file to a ChemKED YAML file.'
        )
    parser.add_argument('-i', '--input',
                        type=str,
                        required=True,
                        help='Input filename (e.g., "file1.yaml")'
                        )
    parser.add_argument('-o', '--output',
                        type=str,
                        required=False,
                        default='',
                        help='Output filename (e.g., "file1.xml")'
                        )
    parser.add_argument('-fa', '--file-author',
                        dest='file_author',
                        type=str,
                        required=False,
                        default='',
                        help='File author name to override original'
                        )
    parser.add_argument('-fo', '--file-author-orcid',
                        dest='file_author_orcid',
                        type=str,
                        required=False,
                        default='',
                        help='File author ORCID'
                        )

    args = parser.parse_args(argv)

    filename_ck = args.output
    filename_xml = args.input

    properties = ReSpecTh_to_ChemKED(filename_xml, args.file_author, args.file_author_orcid,
                                     validate=True)

    # set output filename and path
    if not filename_ck:
        filename_ck = os.path.join(os.path.dirname(filename_xml),
                                   os.path.splitext(os.path.basename(filename_xml))[0] + '.yaml'
                                   )

    with open(filename_ck, 'w') as outfile:
        yaml.dump(properties, outfile, default_flow_style=False)
    print('Converted to ' + filename_ck)
184858
def to_yaml(opts = {}) #:nodoc:
        if YAML.const_defined?(:ENGINE) && !YAML::ENGINE.syck?
          super
        else
          coder = {}
          encode_with(coder)
          YAML.quick_emit(self, opts) do |out|
            out.map(taguri, to_yaml_style) do |map|
              coder.each { |k, v| map.add(k, v) }
            end
          end
        end
      end
545249
def read_source_models(fnames, converter, monitor):
    
    for fname in fnames:
        if fname.endswith(('.xml', '.nrml')):
            sm = to_python(fname, converter)
        elif fname.endswith('.hdf5'):
            sm = sourceconverter.to_python(fname, converter)
        else:
            raise ValueError('Unrecognized extension in %s' % fname)
        sm.fname = fname
        yield sm
1097712
function transpileDerivedExchangeClass (contents) {

    let exchangeClassDeclarationMatches = contents.match (/^module\.exports\s*=\s*class\s+([\S]+)\s+extends\s+([\S]+)\s+{([\s\S]+?)^};*/m)

    // log.green (file, exchangeClassDeclarationMatches[3])

    let className = exchangeClassDeclarationMatches[1]
    let baseClass = exchangeClassDeclarationMatches[2]

    let methods = exchangeClassDeclarationMatches[3].trim ().split (/\n\s*\n/)

    let python2 = []
    let python3 = []
    let php = []

    let methodNames = []

    // run through all methods
    for (let i = 0; i < methods.length; i++) {
        // parse the method signature
        let part = methods[i].trim ()
        let lines = part.split ("\n")
        let signature = lines[0].trim ()
        let methodSignatureRegex = /(async |)([\S]+)\s\(([^)]*)\)\s*{/ // signature line
        let matches = methodSignatureRegex.exec (signature)

        if (!matches) {
            log.red (methods[i])
            log.yellow.bright ("\nMake sure your methods don't have empty lines!\n")
        }

        // async or not
        let keyword = matches[1]
        // try {
        //     keyword = matches[1]
        // } catch (e) {
        //     log.red (e)
        //     log.green (methods[i])
        //     log.yellow (exchangeClassDeclarationMatches[3].trim ().split (/\n\s*\n/))
        //     process.exit ()
        // }

        // method name
        let method = matches[2]

        methodNames.push (method)

        method = unCamelCase (method)

        // method arguments
        let args = matches[3].trim ()

        // extract argument names and local variables
        args = args.length ? args.split (',').map (x => x.trim ()) : []

        // get names of all method arguments for later substitutions
        let variables = args.map (arg => arg.split ('=').map (x => x.trim ()) [0])

        // add $ to each argument name in PHP method signature
        let phpArgs = args.join (', $').trim ().replace (/undefined/g, 'null').replace ('{}', 'array ()')
        phpArgs = phpArgs.length ? ('$' + phpArgs) : ''

        // remove excessive spacing from argument defaults in Python method signature
        let pythonArgs = args.map (x => x.replace (' = ', '='))
                                .join (', ')
                                .replace (/undefined/g, 'None')
                                .replace (/false/g, 'False')
                                .replace (/true/g, 'True')

        // method body without the signature (first line)
        // and without the closing bracket (last line)
        let js = lines.slice (1, -1).join ("\n")

        // transpile everything
        let { python3Body, python2Body, phpBody } = transpileJavaScriptToPythonAndPHP ({ js, className, variables, removeEmptyLines: true })

        // compile the final Python code for the method signature
        let pythonString = 'def ' + method + '(self' + (pythonArgs.length ? ', ' + pythonArgs : '') + '):'

        // compile signature + body for Python 2
        python2.push ('');
        python2.push ('    ' + pythonString);
        python2.push (python2Body);

        // compile signature + body for Python 3
        python3.push ('');
        python3.push ('    ' + keyword + pythonString);
        python3.push (python3Body);

        // compile signature + body for PHP
        php.push ('');
        php.push ('    public function ' + method + ' (' + phpArgs + ') {');
        php.push (phpBody);
        php.push ('    }')

    }

    return {

        // altogether in PHP, Python 2 and 3
        python2: createPythonClass (className, baseClass, python2, methodNames),
        python3: createPythonClass (className, baseClass, python3, methodNames, true),
        php:     createPHPClass    (className, baseClass, php,     methodNames),

        className,
        baseClass,
    }
}
719555
def parse_exchange(self):
        

        if 'media' in self._model:
            if 'exchange' in self._model:
                raise ParseError('Both "media" and "exchange" are specified')
            logger.warning(
                'The "media" key is deprecated! Please use "exchange" instead:'
                ' https://psamm.readthedocs.io/en/stable/file_format.html')
            exchange_list = self._model['media']
        else:
            exchange_list = self._model.get('exchange')

        extracellular = self.extracellular_compartment
        if exchange_list is not None:
            if not isinstance(exchange_list, list):
                raise ParseError('Expected "exchange" to be a list')

            for exchange_compound in parse_exchange_list(
                    self._context, exchange_list, extracellular):
                compound, reaction_id, lower, upper = exchange_compound
                if compound.compartment is None:
                    compound = compound.in_compartment(extracellular)
                yield compound, reaction_id, lower, upper
524324
def write_mps(filename)
      # Make a new model and ensure everything is added
      old_ptr = @ptr
      @ptr = new_model
      parent_update

      Cbc.Cbc_writeMps @ptr, filename.chomp('.mps')
      contents = Zlib::GzipReader.open(filename + '.gz').read
      File.delete(filename + '.gz')
      File.open(filename, 'w').write contents

      # Reset to the original model
      @ptr = old_ptr
      reset_model
    end
717073
def parse_exchange_file(path, default_compartment):
    

    context = FilePathContext(path)

    format = resolve_format(None, context.filepath)
    if format == 'tsv':
        logger.debug('Parsing exchange file {} as TSV'.format(
            context.filepath))
        with context.open('r') as f:
            for entry in parse_exchange_table_file(f):
                yield entry
    elif format == 'yaml':
        logger.debug('Parsing exchange file {} as YAML'.format(
            context.filepath))
        with context.open('r') as f:
            for entry in parse_exchange_yaml_file(
                    context, f, default_compartment):
                yield entry
    else:
        raise ParseError('Unable to detect format of exchange file {}'.format(
            context.filepath))
1334937
function saveNameToExportMap(index, def, exportsMap) {
    if (exportsMap) {
        if (def.exportAs)
            exportsMap[def.exportAs] = index;
        if (def.template)
            exportsMap[''] = index;
    }
}
150843
def create_metabolic_model(self):
        """"""

        def _translate_compartments(reaction, compartment):
            """Translate compound with missing compartments.

            These compounds will have the specified compartment in the output.
            """
            left = (((c.in_compartment(compartment), v)
                     if c.compartment is None else (c, v))
                    for c, v in reaction.left)
            right = (((c.in_compartment(compartment), v)
                      if c.compartment is None else (c, v))
                     for c, v in reaction.right)
            return Reaction(reaction.direction, left, right)

        # Create metabolic model
        database = DictDatabase()
        for reaction in self.reactions:
            if reaction.equation is not None:
                equation = _translate_compartments(
                    reaction.equation, self.default_compartment)
                database.set_reaction(reaction.id, equation)

        undefined_compartments = set()
        undefined_compounds = set()
        extracellular_compounds = set()
        extracellular = self.extracellular_compartment
        for reaction in database.reactions:
            for compound, _ in database.get_reaction_values(reaction):
                if compound.name not in self.compounds:
                    undefined_compounds.add(compound.name)
                if compound.compartment == extracellular:
                    extracellular_compounds.add(compound.name)
                if compound.compartment not in self.compartments:
                    undefined_compartments.add(compound.compartment)

        for compartment in sorted(undefined_compartments):
            logger.warning(
                'The compartment {} was not defined in the list'
                ' of compartments'.format(compartment))

        for compound in sorted(undefined_compounds):
            logger.warning(
                'The compound {} was not defined in the list'
                ' of compounds'.format(compound))

        exchange_compounds = set()
        for exchange_compound in self.exchange:
            if exchange_compound.compartment == extracellular:
                exchange_compounds.add(exchange_compound.name)

        for compound in sorted(extracellular_compounds - exchange_compounds):
            logger.warning(
                'The compound {} was in the extracellular compartment'
                ' but not defined in the exchange compounds'.format(compound))
        for compound in sorted(exchange_compounds - extracellular_compounds):
            logger.warning(
                'The compound {} was defined in the exchange compounds but'
                ' is not in the extracellular compartment'.format(compound))

        model_definition = None
        if len(self.model) > 0:
            model_definition = self.model

        return MetabolicModel.load_model(
            database, model_definition, itervalues(self.exchange),
            itervalues(self.limits), v_max=self.default_flux_limit)
964447
function transpileDerivedExchangeFiles (folder, pattern = '.js') {

    // exchanges.json accounts for ids included in exchanges.cfg
    const ids = require ('../exchanges.json').ids;

    const classNames = fs.readdirSync (folder)
        .filter (file => file.includes (pattern) && ids.includes (path.basename (file, pattern)))
        .map (file => transpileDerivedExchangeFile (folder, file))

    if (classNames.length === 0)
        return null

    let classes = {}
    classNames.forEach (({ className, baseClass }) => {
        classes[className] = baseClass
    })

    return classes
}
21452
def write_model_to_file(self, mdl, fn):
        
        # Write the model to file
        output = ''.join(self.post_process_model(mdl, self.add_line_refs))
        if fn:
            fqfn = self.dst_dir + '/' + fn
            if os.path.isfile(fqfn):
                self.error("File '%s' exists" % fqfn)
                return
            with open(fqfn, 'w') as of:
                of.write(output)
                of.close()
                self.extracted_models.append(fn)
        else:
            self.error("Output file name can not be determined; YANG file not created")
207409
function yamlTransform (filename) {
  if (!/\.yml|\.yaml$/i.test(filename)) {
    return through()
  }

  return through(function (buf, enc, next) {
    this.push(
      'module.exports=' + JSON.stringify(YAML.parse(buf.toString('utf8')))
    )
    next()
  })
}