Create model from reader.

        Returns:
            :class:`psamm.datasource.native.NativeModel`.
773567
def create_model(self):
        
        properties = {
            'name': self.name,
            'default_flux_limit': 1000
        }

        # Load objective as biomass reaction
        objective = self.get_active_objective()
        if objective is not None:
            reactions = dict(objective.reactions)
            if len(reactions) == 1:
                reaction, value = next(iteritems(reactions))
                if ((value < 0 and objective.type == 'minimize') or
                        (value > 0 and objective.type == 'maximize')):
                    properties['biomass'] = reaction

        model = NativeModel(properties)

        # Load compartments into model
        for compartment in self.compartments:
            model.compartments.add_entry(compartment)

        # Load compounds into model
        for compound in self.species:
            model.compounds.add_entry(compound)

        # Load reactions into model
        for reaction in self.reactions:
            model.reactions.add_entry(reaction)

        # Create model reaction set
        for reaction in model.reactions:
            model.model[reaction.id] = None

        # Convert reaction limits properties to proper limits
        for reaction in model.reactions:
            props = reaction.properties
            if 'lower_flux' in props or 'upper_flux' in props:
                lower = props.get('lower_flux')
                upper = props.get('upper_flux')
                model.limits[reaction.id] = reaction.id, lower, upper

        # Load model limits from FBC V1 bounds if present, i.e. if FBC V1 is
        # used instead of V2.
        limits_lower = {}
        limits_upper = {}
        for bounds in self.flux_bounds:
            reaction = bounds.reaction
            if reaction in model.limits:
                continue

            if bounds.operation == SBMLFluxBoundEntry.LESS_EQUAL:
                if reaction not in limits_upper:
                    limits_upper[reaction] = bounds.value
                else:
                    raise ParseError(
                        'Conflicting bounds for {}'.format(reaction))
            elif bounds.operation == SBMLFluxBoundEntry.GREATER_EQUAL:
                if reaction not in limits_lower:
                    limits_lower[reaction] = bounds.value
                else:
                    raise ParseError(
                        'Conflicting bounds for {}'.format(reaction))
            elif bounds.operation == SBMLFluxBoundEntry.EQUAL:
                if (reaction not in limits_lower and
                        reaction not in limits_upper):
                    limits_lower[reaction] = bounds.value
                    limits_upper[reaction] = bounds.value
                else:
                    raise ParseError(
                        'Conflicting bounds for {}'.format(reaction))

        for reaction in model.reactions:
            if reaction.id in limits_lower or reaction.id in limits_upper:
                lower = limits_lower.get(reaction.id, None)
                upper = limits_upper.get(reaction.id, None)
                model.limits[reaction.id] = reaction.id, lower, upper

        return model
1363201
def internal_model_from_file(
            self, file_name, encoding='utf-8', debug=None,
            pre_ref_resolution_callback=None, is_main_model=True):
        
        model = None
        callback = pre_ref_resolution_callback

        if hasattr(self, "_tx_model_repository"):
            # metamodel has a global repo
            if not callback:
                def _pre_ref_resolution_callback(other_model):
                    from textx.scoping import GlobalModelRepository
                    filename = other_model._tx_filename
                    assert filename
                    # print("METAMODEL PRE-CALLBACK{}".format(filename))
                    other_model._tx_model_repository = GlobalModelRepository(
                        self._tx_model_repository.all_models)
                    self._tx_model_repository.all_models\
                        .filename_to_model[filename] = other_model

                callback = _pre_ref_resolution_callback
            if self._tx_model_repository.all_models.has_model(file_name):
                model = self._tx_model_repository.all_models\
                    .filename_to_model[file_name]

        if not model:
            # model not present (from global repo) -> load it
            model = self._parser_blueprint.clone().get_model_from_file(
                file_name, encoding, debug=debug,
                pre_ref_resolution_callback=callback,
                is_main_model=is_main_model)

        for p in self._model_processors:
            p(model, self)
        return model
83580
async def create(self, **kwargs):
        '''
        
        '''
        try:
            # create model
            obj = self._meta.object_class()
            # deserialize data from request body
            self.data.update(kwargs)
            await obj.deserialize(self.data)
            # create document in DB
            await obj.insert(db=self.db)
            # serialize object for response
            return await obj.serialize()
        except Exception as ex:
            logger.exception(ex)
            raise BadRequest(ex)
1084837
private Model initModel() {
        OntModel m = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, ModelFactory.createDefaultModel());
        try {
            schemaReader.read(m);
        } catch (RdfReaderException e) {
            log.error("Cannot load ontology: {} ", getSchema(), e);
        }
        return m;
    }
569499
def get_model(self, sm_id):
        
        sm = self.source_models[sm_id]
        if self.source_model_lt.num_samples:
            self.source_model_lt.num_samples = sm.samples
        new = self.__class__(self.gsim_lt, self.source_model_lt, [sm],
                             self.optimize_same_id)
        new.sm_id = sm_id
        return new
594625
def create(self, data, fields=[], models={}):
        '''
        
        '''
        if not fields: fields = self.fields
        if not models and hasattr(self, 'models'): models = self.models
        for field in fields:
            setattr(self,field,None)
        if not data: return None
        for k, v in data.iteritems():
            if type(v) in (str, unicode):
                v = v.strip()
            if models and k in models:
                if type(v) == dict:
                    lists = []
                    for k2, v2 in v.iteritems():
                        if type(v2) == list:
                            for d in v2:
                                model = models[k]()
                                lists.append(model.create(d))
                    if not lists:
                        model = models[k]()
                        v = model.create(v)
                    else:
                        v = lists
                else:
                    model = models[k]()
                    v = model.create(v)
            setattr(self,k,v)
        return self
159151
def from_dict(self, data):
        
        if "model" in data:
            model = data["model"]
            self.description = model["description"] if "description" in model else None
            self.package = model["package"] if "package" in model else None
            self.extends = model["extends"] if "extends" in model else []
            self.entity_name = model["entity_name"] if "entity_name" in model else None
            self.rest_name = model["rest_name"] if "rest_name" in model else None
            self.resource_name = model["resource_name"] if "resource_name" in model else None
            self.allows_get = model["get"] if "get" in model else False
            self.allows_create = model["create"] if "create" in model else False
            self.allows_update = model["update"] if "update" in model else False
            self.allows_delete = model["delete"] if "delete" in model else False
            self.is_root = model["root"] if "root" in model else False
            self.userlabel = model["userlabel"] if "userlabel" in model else None
            self.template = model["template"] if "template" in model else False
            self.allowed_job_commands = model["allowed_job_commands"] if "allowed_job_commands" in model else None

        if "attributes" in data:
            self.attributes = self._get_attributes(data["attributes"])

        if "children" in data:
            self.child_apis = self._get_apis(data["children"])
1150502
def create_model(self, parent, name, multiplicity=Multiplicity.ZERO_MANY):
        
        return self._client.create_model(parent, name, multiplicity=multiplicity)
862630
def model(self, model, create=True):
        ''''''
        manager = self.manager(model)
        sm = self._models.get(manager)
        if sm is None and create:
            sm = SessionModel(manager)
            self._models[manager] = sm
        return sm
861296
def create_reader(name, *args, format=None, registry=default_registry, **kwargs):
    
    return registry.get_reader_factory_for(name, format=format)(name, *args, **kwargs)
1065310
public ISimpleChemObjectReader createReader(Reader input) throws IOException {
        if (!(input instanceof BufferedReader)) {
            input = new BufferedReader(input);
        }
        IChemFormat chemFormat = formatFactory.guessFormat((BufferedReader) input);
        ISimpleChemObjectReader coReader = createReader(chemFormat);
        try {
            coReader.setReader(input);
        } catch (Exception exception) {
            logger.error("Could not set the Reader source: ", exception.getMessage());
            logger.debug(exception);
        }
        return coReader;
    }
390774
def model_factory(schema, resolver=None, base_class=model.Model, name=None):
    
    schema = copy.deepcopy(schema)
    resolver = resolver

    class Model(base_class):
        def __init__(self, *args, **kwargs):
            self.__dict__['schema'] = schema
            self.__dict__['resolver'] = resolver
            base_class.__init__(self, *args, **kwargs)

    if resolver is not None:
        Model.resolver = resolver

    if name is not None:
        Model.__name__ = name
    elif 'name' in schema:
        Model.__name__ = str(schema['name'])
    return Model
704130
def build_model_input(cls, name='input'):
        
        return cls(name, PortDirection.INPUT, type=PortType.MODEL)
8477
def create(self, **kwargs):
        
        obj = self.model(**kwargs)
        meta = obj.get_meta()
        meta.connection = get_es_connection(self.es_url, self.es_kwargs)
        meta.index=self.index
        meta.type=self.type
        obj.save(force=True)
        return obj
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
1170216
def create_modelo(self):
        """"""
        return Modelo(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)
1064628
def _reader_factory(name, filetype, descr):
    """"""
    def basic_reader(filename, last = None, first = 0):
        """Common "template" to all read functions."""
        hdl = Sndfile(filename, 'r')
        try:
            if not hdl.format.file_format == filetype:
                raise ValueError, "%s is not a %s file (is %s)" \
                      % (filename, filetype, hdl.format.file_format)

            fs = hdl.samplerate
            enc = hdl.encoding
            # Set the pointer to start position
            nf  = hdl.seek(first, 1)
            if not nf == first:
                raise IOError("Error while seeking at starting position")

            if last is None:
                nframes = hdl.nframes - first
                data    = hdl.read_frames(nframes)
            else:
                data    = hdl.read_frames(last)
        finally:
            hdl.close()

        return data, fs, enc
    doc = \
    """Simple reader for %(format)s audio files.

    Parameters
    ----------
    filename : str
        Name of the file to read
    last : int
        Last frame to read. If None, this is equal to the number of frames in
        the file.
    first : int
        First frame to read. If 0, means starting from the beginning of the
        file.

    Returns
    -------
    data : array
        the read data (one column per channel)
    fs : int
        the sampling rate
    enc : str
        the encoding of the file, such as 'pcm16', 'float32', etc...

    Notes
    -----
    For total control over options, such as output's dtype, etc...,
    you should use Sndfile class instances instead""" % {'format': str(descr)}
    basic_reader.__doc__    = doc
    basic_reader.__name__   = name
    return basic_reader