Пример #1
0
class ExpressionPattern(BiologyType):

    class_context = BiologyType.class_context

    wormbaseid = DatatypeProperty()
    ''' The ID for the expression pattern in Wormbase '''

    wormbaseID = Alias(wormbaseid)
    ''' Alias to :py:attr:`wormbaseid` '''

    wormbaseURL = DatatypeProperty()
    ''' The URL for the expression pattern in Wormbase '''

    description = DatatypeProperty()
    ''' Natural language description of the expression pattern '''
    def __init__(self, wormbaseid=None, **kwargs):
        super(ExpressionPattern, self).__init__(**kwargs)

        if wormbaseid:
            self.wormbaseid(wormbaseid)
            self.wormbaseURL(
                R.URIRef("http://www.wormbase.org/species/all/expr_pattern/" +
                         wormbaseid))

    def defined_augment(self):
        return self.wormbaseid.has_defined_value()

    def identifier_augment(self):
        return self.make_identifier(self.wormbaseid.defined_values[0])
 class Widget(DataObject):
     class_context = 'http://example.org/test_adding_data'
     rdf_type = 'http://example.org/BDW/schema/Widget'
     rdf_namespace = 'http://example.org/BDW/entities/Widget#'
     hardiness = DatatypeProperty()
     fullness = DatatypeProperty()
     part_number = DatatypeProperty()
     key_property = {'name': 'part_number', 'type': 'direct'}
Пример #3
0
class Muscle(Cell):
    """
    A single muscle cell.

    See what neurons innervate a muscle:

    Example::

        >>> mdr21 = Muscle('MDR21')
        >>> innervates_mdr21 = mdr21.innervatedBy()
        >>> len(innervates_mdr21)
        4
    """

    class_context = Cell.class_context

    innervatedBy = ObjectProperty(value_type=Neuron, multiple=True)
    ''' Neurons synapsing with this muscle '''

    neurons = Alias(innervatedBy)
    ''' Alias to `innervatedBy` '''

    receptors = DatatypeProperty(multiple=True)
    ''' Receptor types expressed by this type of muscle '''

    receptor = Alias(receptors)
    ''' Alias to `receptors` '''
Пример #4
0
class Monkey(DataObject):
    class_context = 'http://example.org/primate/monkey'

    bananas = DatatypeProperty()

    def identifier_augment(self):
        return type(self).rdf_namespace['paul']

    def defined_augment(self):
        return True
Пример #5
0
class ModelDBPropertyClassDescription(ModelDB, PythonClassDescription):
    '''
    Description of a `ModelDBDataSource` property
    '''

    local_id = DatatypeProperty(__doc__='ID used on the page')
    display_name = DatatypeProperty(__doc__='Display name')

    key_properties = ('name', 'module', 'local_id')

    def resolve_class(self):
        local_id = self.local_id()
        if not local_id:
            raise ClassResolutionFailed('Missing local_id')

        display_name = self.display_name()
        if not display_name:
            raise ClassResolutionFailed('Missing display_name')
        return create_property_class(local_id, display_name)
Пример #6
0
class ChannelModel(DataObject):
    """
    A model for an ion channel.

    There may be multiple models for a single channel.

    Example usage::

        >>> from owmeta_core.quantity import Quantity

        # Create a ChannelModel
        >>> cm = PatchClampChannelModel(key='ca_boyle',
        ...     gating='voltage',
        ...     ion='Ca',
        ...     conductance=Quantity.parse('10pS'))

    """
    class_context = CONTEXT

    modelType = DatatypeProperty()
    ''' The type of model employed to describe a channel '''

    ion = DatatypeProperty(multiple=True)
    ''' The type of ion this channel selects for '''

    gating = DatatypeProperty(multiple=True)
    ''' The gating mechanism for this channel ("voltage" or name of ligand(s) ) '''

    conductance = DatatypeProperty()
    ''' The conductance of this ion channel. This is the initial value, and should be entered as a Quantity object. '''

    neuroML = CPThunk(NeuroMLProperty)

    def __init__(self, modelType=None, *args, **kwargs):
        super(ChannelModel, self).__init__(*args, **kwargs)

        #Change modelType value to something from ChannelModelType class on init
        if isinstance(modelType, six.string_types):
            modelType = modelType.lower()
            if modelType in ('homology', ChannelModelType.homologyEstimate):
                self.modelType(ChannelModelType.homologyEstimate)
            elif modelType in ('patch-clamp', ChannelModelType.patchClamp):
                self.modelType(ChannelModelType.patchClamp)
Пример #7
0
class Website(BaseDocument):
    """ A representation of a website """

    class_context = SCI_CTX

    url = DatatypeProperty()
    ''' A URL for the website '''

    title = DatatypeProperty()
    ''' The official name for the website '''
    def __init__(self, title=None, **kwargs):
        super(Website, self).__init__(rdfs_comment=title,
                                      title=title,
                                      **kwargs)

    def defined_augment(self):
        return self.url.has_defined_value()

    def identifier_augment(self):
        return URIRef(self.url.defined_values[0].identifier)
Пример #8
0
class Donkey(DataObject):
    base_namespace = 'http://example.org/schema/'
    class_context = 'http://example.org/ungulate/donkey'

    bananas = DatatypeProperty()

    def identifier_augment(self):
        return type(self).rdf_namespace['danny']

    def defined_augment(self):
        return True
Пример #9
0
class NeuroMLDocument(DataObject):
    '''
    Represents a NeuroML document

    The document may be represented literally in the RDF graph using `xml_content` or
    stored elsewhere and included by reference with `document_url`.

    Example::

        >>> embedded_nml = NeuroMLDocument(key='embedded_ex', content="""\\
        ... <?xml version="1.0" encoding="UTF-8"?>
        ... <neuroml xmlns="http://www.neuroml.org/schema/neuroml2"
        ...     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        ...     xsi:schemaLocation="http://www.neuroml.org/schema/neuroml2
        ...     https://raw.github.com/NeuroML/NeuroML2/master/Schemas/NeuroML2/NeuroML_v2beta.xsd"
        ...     id="k_slow">
        ...     <ionChannel id="k_slow" conductance="10pS" type="ionChannelHH" species="k">
        ...         <notes>K slow channel from Boyle and Cohen 2008</notes>
        ...         <gateHHtauInf id="n" instances="1">
        ...             <timeCourse type="fixedTimeCourse" tau="25.0007 ms"/>
        ...             <steadyState type="HHSigmoidVariable" rate="1" scale="15.8512 mV" midpoint="19.8741 mV"/>
        ...         </gateHHtauInf>
        ...     </ionChannel>
        ... </neuroml>""")

        >>> external_nml = NeuroMLDocument(ident='external_ex',
        ...     document_url='')

    '''

    class_context = CONTEXT

    content = DatatypeProperty()
    '''
    XML content for the document. Should be a complete NeuroML document rather than a
    fragment.
    '''

    document_url = DatatypeProperty(multiple=True)
    '''
Пример #10
0
class Channel(BiologyType):
    """
    A biological ion channel.
    """

    class_context = BiologyType.class_context

    rdf_type = CHANNEL_RDF_TYPE

    subfamily = DatatypeProperty()
    ''' Ion channel's subfamily '''

    name = DatatypeProperty()
    ''' Ion channel's name '''

    description = DatatypeProperty()
    ''' A description of the ion channel '''

    gene_name = DatatypeProperty()
    ''' Name of the gene that codes for this ion channel '''

    gene_class = DatatypeProperty()
    ''' Classification of the encoding gene '''

    gene_WB_ID = DatatypeProperty()
    ''' Wormbase ID of the encoding gene '''

    expression_pattern = ObjectProperty(multiple=True,
                                        value_type=ExpressionPattern)
    ''' A pattern of expression of this cell within an organism '''

    proteins = DatatypeProperty(multiple=True)
    ''' Proteins associated with this channel '''

    appearsIn = ObjectProperty(multiple=True, value_rdf_type=CELL_RDF_TYPE)
    ''' Cell types in which the ion channel has been expressed '''

    model = ObjectProperty(value_type=ChannelModel)
    ''' Get experimental models of this ion channel '''

    models = Alias(model)
    ''' Alias to :py:attr:`model` '''
    def __init__(self, name=None, **kwargs):
        super(Channel, self).__init__(name=name, **kwargs)

    def defined_augment(self):
        return self.name.has_defined_value()

    def identifier_augment(self):
        return self.make_identifier(self.name.defined_values[0])
Пример #11
0
 class A(DataObject):
     a = ObjectProperty()
     b = DatatypeProperty()
     key_properties = ('a', 'b')
Пример #12
0
 class B(DataObject):
     prop = DatatypeProperty()
     key_properties = (prop, A.cookie)
Пример #13
0
 class A(DataObject):
     cookie = DatatypeProperty()
Пример #14
0
 class B(DataObject):
     a = DatatypeProperty()
     key_properties = (a, DatatypeProperty(name="cookie"))
Пример #15
0
 class A(B):
     a = DatatypeProperty()
     key_properties = (a, B.prop)
Пример #16
0
class Document(BaseDocument):
    """
    A representation of some document.

    Possible keys include::

        pmid, pubmed: a pubmed id or url (e.g., 24098140)
        wbid, wormbase: a wormbase id or url (e.g., WBPaper00044287)
        doi: a Digitial Object id or url (e.g., s00454-010-9273-0)
        uri: a URI specific to the document, preferably usable for accessing
             the document
    """

    class_context = SCI_CTX

    author = DatatypeProperty(multiple=True)
    ''' An author of the document '''

    doi = DatatypeProperty()
    ''' A Digital Object Identifier (DOI), optional '''

    uri = DatatypeProperty(multiple=True)
    ''' A non-standard URI for the document '''

    wbid = DatatypeProperty()
    ''' An ID from WormBase.org that points to a record, optional '''

    wormbaseid = Alias(wbid)
    ''' An alias to `wbid` '''

    pmid = DatatypeProperty()
    ''' A PubMed ID (PMID) that points to a paper '''

    year = DatatypeProperty()
    ''' The year (e.g., publication year) of the document '''

    date = Alias(year)
    ''' Alias to year '''

    title = DatatypeProperty()
    ''' The title of the document '''

    def __init__(
            self,
            bibtex=None,
            doi=None,
            pubmed=None,
            wormbase=None,
            **kwargs):
        """
        Parameters
        ----------
        bibtex : string
            A string containing a single BibTeX entry. Parsed during initialization, but not saved thereafter. optional
        doi : string
            A Digital Object Identifier (DOI). optional
        pubmed : string
            A PubMed ID (PMID) or URL that points to a paper. Ignored if 'pmid' is provided. optional
        wormbase : string
            An ID or URL from WormBase that points to a record. Ignored if `wbid` or `wormbaseid` are provided. optional
        """
        super(Document, self).__init__(**kwargs)

        self.id_precedence = ('doi', 'pmid', 'wbid', 'uri')

        if bibtex is not None:
            self.update_with_bibtex(bibtex)

        if pubmed is not None and not self.pmid.has_defined_value():
            if pubmed[:4] == 'http':
                _tmp = _pubmed_uri_to_pmid(pubmed)
                if _tmp is None:
                    raise ValueError("Couldn't convert Pubmed URL to a PubMed ID")
                pmid = _tmp
            else:
                pmid = pubmed
            self.pmid.set(pmid)

        if wormbase is not None and not self.wbid.has_defined_value():
            if wormbase[:4] == 'http':
                _tmp = _wormbase_uri_to_wbid(wormbase)
                if _tmp is None:
                    raise ValueError("Couldn't convert Wormbase URL to a Wormbase ID")
                wbid = _tmp
            else:
                wbid = wormbase
            self.wbid.set(wbid)

        if doi is not None:
            if doi[:4] == 'http':
                _tmp = _doi_uri_to_doi(doi)
                if _tmp is not None:
                    doi = _tmp
            self.doi.set(doi)

    def update_with_bibtex(self, bibtex):
        bib_db = BIB.loads(bibtex)
        if len(bib_db.entries) > 1:
            raise ValueError('The given BibTex string has %d entries.'
                             ' Cannot determine which entry to use for the document' % len(bib_db))
        BIB.update_document_with_bibtex(self, bib_db.entries[0])

    def defined_augment(self):
        for x in self.id_precedence:
            if getattr(self, x).has_defined_value():
                return True
        return False

    def identifier_augment(self):
        for idKind in self.id_precedence:
            idprop = getattr(self, idKind)
            if idprop.has_defined_value():
                s = str(idKind) + ":" + idprop.defined_values[0].identifier.n3()
                return self.make_identifier(s)
        raise IdentifierMissingException(self)

    # TODO: Provide a way to override modification of already set values.
    def update_from_wormbase(self, replace_existing=False):
        """ Queries wormbase for additional data to fill in the Document.

        If replace_existing is set to `True`, then existing values will be cleared.
        """

        # XXX: wormbase's REST API is pretty sparse in terms of data provided.
        #     Would be better off using AQL or the perl interface
        # _Very_ few of these have these fields filled in
        wbid = self.wbid.defined_values
        if len(wbid) == 1:
            wbid = wbid[0].identifier.toPython()

            # get the author
            try:
                root = self.conf.get('wormbase_api_root_url', 'http://rest.wormbase.org')
                url = root + '/rest/widget/paper/' + str(wbid) + '/overview?content-type=application%2Fjson'
                j = _json_request(url)
                if 'fields' in j:
                    f = j['fields']
                    if 'authors' in f:
                        dat = f['authors']['data']
                        if dat is not None:
                            if replace_existing and self.author.has_defined_value:
                                self.author.clear()
                            for x in dat:
                                self.author.set(x['label'])

                    for fname in ('pmid', 'year', 'title', 'doi'):
                        if fname in f and f[fname]['data'] is not None:
                            attr = getattr(self, fname)
                            if replace_existing and attr.has_defined_value:
                                attr.clear()
                            attr.set(f[fname]['data'])
            except Exception:
                logger.warning("Couldn't retrieve Wormbase data", exc_info=True)
        elif len(wbid) == 0:
            raise WormbaseRetrievalException("There is no Wormbase ID attached to this Document."
                                             " So no data can be retrieved")
        else:
            raise WormbaseRetrievalException("There is more than one Wormbase ID attached to this Document."
                                             " Please try with just one Wormbase ID")

    def _crossref_doi_extract(self):
        # Extract data from crossref
        def crRequest(doi):
            data = {'q': doi}
            data_encoded = urlencode(data)
            return _json_request(
                'http://search.labs.crossref.org/dois?%s' %
                data_encoded)

        doi = self.doi()
        if doi[:4] == 'http':
            doi = _doi_uri_to_doi(doi)
        try:
            r = crRequest(doi)
        except Exception:
            logger.warning("Couldn't retrieve Crossref info", exc_info=True)
            return
        # XXX: I don't think coins is meant to be used, but it has structured
        # data...
        if len(r) > 0:
            extra_data = r[0]['coins'].split('&amp;')
            fields = (x.split("=") for x in extra_data)
            fields = [[y.replace('+', ' ').strip() for y in x] for x in fields]
            authors = [x[1] for x in fields if x[0] == 'rft.au']
            for a in authors:
                self.author(a)
            # no error for bad ids, just an empty list
            if len(r) > 0:
                # Crossref can process multiple doi's at one go and return the
                # metadata. we just need the first one
                r = r[0]
                if 'title' in r:
                    self.title(r['title'])
                if 'year' in r:
                    self.year(r['year'])

    def update_from_pubmed(self):
        def pmRequest(pmid):
            import xml.etree.ElementTree as ET  # Python 2.5 and up
            url = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=pubmed&id=' + str(pmid)
            key = self.get('pubmed.api_key', None)
            if key:
                url += '&api_key=' + key
            else:
                logger.warning("PubMed API key not defined. API calls will be limited.")
            s = _url_request(url)
            if hasattr(s, 'charset'):
                parser = ET.XMLParser(encoding=s.charset)
            else:
                parser = None

            return ET.parse(s, parser)

        pmid = self.pmid.defined_values
        if len(pmid) == 1:
            pmid = pmid[0].identifier.toPython()
            try:
                tree = pmRequest(pmid)
            except Exception:
                logger.warning("Couldn't retrieve Pubmed info", exc_info=True)
                return
            for x in tree.findall('./DocSum/Item[@Name="AuthorList"]/Item'):
                self.author(x.text)

            for x in tree.findall('./DocSum/Item[@Name="Title"]'):
                self.title(x.text)

            for x in tree.findall('./DocSum/Item[@Name="DOI"]'):
                self.doi(x.text)

            for x in tree.findall('./DocSum/Item[@Name="PubDate"]'):
                self.year(x.text)

        elif len(pmid) == 0:
            raise PubmedRetrievalException('No Pubmed ID is attached to this document. Cannot retrieve Pubmed data')
        else:
            raise PubmedRetrievalException('More than one Pubmed ID is attached to this document.'
                                           ' Please try with just one Pubmed ID')
Пример #17
0
class TDO(DataObject):
    rdf_type = 'http://openworm.org/entities/TDO'
    a = DatatypeProperty()
Пример #18
0
 class A(DataObject):
     a = DatatypeProperty()
Пример #19
0
class Worm(BiologyType):
    """ A representation of the whole worm """

    class_context = BiologyType.class_context

    rdf_type = WORM_RDF_TYPE

    scientific_name = DatatypeProperty()
    ''' Scientific name for the organism '''

    name = Alias(scientific_name)
    ''' Alias to `scientific_name` '''

    muscle = ObjectProperty(value_type=Muscle, multiple=True)
    ''' A type of muscle which is in the worm '''

    cell = ObjectProperty(value_type=Cell)
    ''' A type of cell in the worm '''

    neuron_network = ObjectProperty(value_type=Network,
                                    inverse_of=(Network, 'worm'))
    ''' The neuron network of the worm '''
    def __init__(self, scientific_name=None, **kwargs):
        super(Worm, self).__init__(**kwargs)

        if scientific_name:
            self.scientific_name(scientific_name)
        else:
            self.scientific_name("C. elegans")

    def get_neuron_network(self):
        """
        Return the neuron network of the worm.

        Example::

            # Grabs the representation of the neuronal network
            >>> net = P.Worm().get_neuron_network()

            # Grab a specific neuron
            >>> aval = net.aneuron('AVAL')

            >>> aval.type()
            set([u'interneuron'])

            #show how many connections go out of AVAL
            >>> aval.connection.count('pre')
            77

        :returns: An object to work with the network of the worm
        :rtype: owmeta.Network
        """
        return self.neuron_network()

    def muscles(self):
        """
        Get all Muscle objects attached to the Worm.

        Example::

            >>> muscles = P.Worm().muscles()
            >>> len(muscles)
            96

        :returns: A set of all muscles
        :rtype: :py:class:`set`
         """
        return set(x for x in self._muscles_helper())

    def _muscles_helper(self):
        for x in self.muscle.get():
            yield x

    def get_semantic_net(self):
        """
         Get the underlying semantic network as an RDFLib Graph

        :returns: A semantic network containing information about the worm
        :rtype: rdflib.ConjunctiveGraph
         """

        return self.rdf

    def defined_augment(self):
        ''' True if the name is defined '''
        return self.name.has_defined_value()

    def identifier_augment(self, *args, **kwargs):
        ''' Result is derived from the name property '''
        return self.make_identifier(self.name.defined_values[0])
Пример #20
0
class A(DataObject):
    class_context = 'https://example.org/types'
    redness = DatatypeProperty()
    blueness = DatatypeProperty()
Пример #21
0
class PatchClampExperiment(Experiment):
    """
    Store experimental conditions for a patch clamp experiment.
    """

    class_context = CONTEXT

    Ca_concentration = DatatypeProperty()
    '''Calcium concentration'''

    Cl_concentration = DatatypeProperty()
    '''Chlorine concentration'''

    blockers = DatatypeProperty()
    '''Channel blockers used for this experiment'''

    cell = DatatypeProperty()
    '''The cell this experiment was performed on'''

    cell_age = DatatypeProperty()
    '''Age of the cell'''

    delta_t = DatatypeProperty()

    duration = DatatypeProperty()

    end_time = DatatypeProperty()

    extra_solution = DatatypeProperty()

    initial_voltage = DatatypeProperty()
    '''Starting voltage of the patch clamp'''

    ion_channel = DatatypeProperty()
    '''The ion channel being clamped'''

    membrane_capacitance = DatatypeProperty()
    '''Initial membrane capacitance'''

    mutants = DatatypeProperty()
    '''Type(s) of mutants being used in this experiment'''

    patch_type = DatatypeProperty()
    '''Type of patch clamp being used ('voltage' or 'current')'''

    pipette_solution = DatatypeProperty()
    '''Type of solution in the pipette'''

    protocol_end = DatatypeProperty()

    protocol_start = DatatypeProperty()

    protocol_step = DatatypeProperty()

    start_time = DatatypeProperty()

    temperature = DatatypeProperty()

    type = DatatypeProperty()
Пример #22
0
class Person(DataObject):
    class_context = 'http://example.org/Person'
    first_name = DatatypeProperty()
    last_name = DatatypeProperty()
Пример #23
0
class Plot(DataObject):
    """
    Object for storing plot data in owmeta.

    Parameters
    ----------

    data : 2D list (list of lists)
        List of XY coordinates for this Plot.

    Example usage ::
        >>> pl = Plot([[1, 2], [3, 4]])
        >>> pl.get_data()
        # [[1, 2], [3, 4]]
    """

    class_context = SCI_CTX

    _data_string = DatatypeProperty()

    def __init__(self, data=None, *args, **kwargs):
        super(Plot, self).__init__(*args, **kwargs)

        if data:
            self.set_data(data)

    def _to_string(self, input_list):
        """
        Converts input_list to a string
        for serialized storage in owmeta.
        """
        return '|'.join([str(item) for item in input_list])

    def _to_list(self, input_string):
        """
        Converts from internal serlialized string
        to a 2D list.
        """
        if input_string is None:
            return None

        out_list = []
        for pair_string in input_string.split('|'):
            pair_as_list = pair_string \
                .replace('[', '') \
                .replace(']', '') \
                .split(',')
            out_list.append([float(x) for x in pair_as_list])
        return out_list

    def set_data(self, data):
        """
        Set the data attribute, which is user-facing,
        as well as the serialized _data_string
        attribute, which is used for db storage.
        """
        try:
            # make sure we're dealing with a 2D list
            assert isinstance(data, list)
            assert isinstance(data[0], list)
            self._data_string(self._to_string(data))
            self.data = data
        except (AssertionError, IndexError):
            raise ValueError('Attribute "data" must be a 2D list of numbers.')

    def get_data(self):
        """
        Get the data stored for this plot.
        """
        return self._to_list(self._data_string())
Пример #24
0
 class A(DataObject):
     a = DatatypeProperty()
     properties_are_init_args = True
Пример #25
0
 class B(A):
     b = DatatypeProperty()
     properties_are_init_args = False
Пример #26
0
 class A(DataObject):
     a = DatatypeProperty()
     b = DatatypeProperty()
     key_properties = (a, b)
Пример #27
0
class Connection(BiologyType):

    class_context = BiologyType.class_context

    post_cell = ObjectProperty(value_type=Cell)
    ''' The post-synaptic cell '''

    pre_cell = ObjectProperty(value_type=Cell)
    ''' The pre-synaptic cell '''

    number = DatatypeProperty()
    ''' The weight of the connection '''

    synclass = DatatypeProperty()
    ''' The kind of Neurotransmitter (if any) sent between `pre_cell` and `post_cell` '''

    syntype = DatatypeProperty()
    ''' The kind of synaptic connection. 'gapJunction' indicates a gap junction and 'send' a chemical synapse '''

    termination = DatatypeProperty()
    ''' Where the connection terminates. Inferred from type of post_cell at initialization '''

    key_properties = (pre_cell, post_cell, syntype)

    # Arguments are given explicitly here to support positional arguments
    def __init__(self,
                 pre_cell=None,
                 post_cell=None,
                 number=None,
                 syntype=None,
                 synclass=None,
                 termination=None,
                 **kwargs):
        super(Connection, self).__init__(pre_cell=pre_cell,
                                         post_cell=post_cell,
                                         number=number,
                                         syntype=syntype,
                                         synclass=synclass,
                                         **kwargs)

        if isinstance(termination, six.string_types):
            termination = termination.lower()
            if termination in ('neuron', Termination.Neuron):
                self.termination(Termination.Neuron)
            elif termination in ('muscle', Termination.Muscle):
                self.termination(Termination.Muscle)

        if isinstance(syntype, six.string_types):
            syntype = syntype.lower()
            if syntype in ('send', SynapseType.Chemical):
                self.syntype(SynapseType.Chemical)
            elif syntype in ('gapjunction', SynapseType.GapJunction):
                self.syntype(SynapseType.GapJunction)

    def __str__(self):
        nom = []
        props = (
            'pre_cell',
            'post_cell',
            'syntype',
            'termination',
            'number',
            'synclass',
        )
        for p in props:
            if getattr(self, p).has_defined_value():
                nom.append((p, getattr(self, p).defined_values[0]))
        if len(nom) == 0:
            return super(Connection, self).__str__()
        else:
            return 'Connection(' + \
                   ', '.join('{}={}'.format(n[0], n[1]) for n in nom) + \
                   ')'
Пример #28
0
 class B(DataObject):
     prop = DatatypeProperty()
Пример #29
0
class Neuron(Cell):
    """
    A neuron.

    See what neurons express some neuropeptide

    Example::

        # Grabs the representation of the neuronal network
        >>> net = P.Worm().get_neuron_network()

        # Grab a specific neuron
        >>> aval = net.aneuron('AVAL')

        >>> aval.type()
        set([u'interneuron'])

        #show how many connections go out of AVAL
        >>> aval.connection.count('pre')
        77

        >>> aval.name()
        u'AVAL'

        #list all known receptors
        >>> sorted(aval.receptors())
        [u'GGR-3', u'GLR-1', u'GLR-2', u'GLR-4', u'GLR-5', u'NMR-1', u'NMR-2', u'UNC-8']

        #show how many chemical synapses go in and out of AVAL
        >>> aval.Syn_degree()
        90

    Parameters
    ----------
    name : string
        The name of the neuron.

    Attributes
    ----------
    neighbor : CustomProperty
        Get neurons connected to this neuron if called with no arguments, or
        with arguments, state that neuronName is a neighbor of this Neuron
    connection : CustomProperty
        Get a set of Connection objects describing chemical synapses or gap
        junctions between this neuron and others

    """

    class_context = Cell.class_context

    type = DatatypeProperty(multiple=True)
    ''' The neuron type (i.e., sensory, interneuron, motor) '''

    receptor = DatatypeProperty(multiple=True)
    ''' The receptor types associated with this neuron '''

    innexin = DatatypeProperty(multiple=True)
    ''' Innexin types associated with this neuron '''

    neurotransmitter = DatatypeProperty(multiple=True)
    ''' Neurotransmitters associated with this neuron '''

    neuropeptide = DatatypeProperty(multiple=True)
    ''' Name of the gene corresponding to the neuropeptide produced by this neuron '''

    receptors = Alias(receptor)
    ''' Alias to :py:attr:`receptor` '''

    def __init__(self, name=None, **kwargs):
        super(Neuron, self).__init__(name=name, **kwargs)

        # Get neurons connected to this neuron
        Neighbor(owner=self)

        # Get connections from this neuron
        ConnectionProperty(owner=self)

        self.get_neighbors = self.neighbor

    def contextualize(self, context):
        res = super(Neuron, self).contextualize(context)
        if hasattr(self, 'neighbor'):
            res = NeuronProxy(self.neighbor.contextualize(context),
                              self.connection.contextualize(context),
                              res)
        return res

    def GJ_degree(self):
        """Get the degree of this neuron for gap junction edges only

        :returns: total number of incoming and outgoing gap junctions
        :rtype: int
        """
        count = 0
        for c in self.connection():
            if c.syntype.one() == 'gapJunction':
                count += 1
        return count

    def Syn_degree(self):
        """Get the degree of this neuron for chemical synapse edges only

        :returns: total number of incoming and outgoing chemical synapses
        :rtype: int
        """
        count = 0
        for c in self.connection.get('either'):
            if c.syntype.one() == 'send':
                count += 1
        return count

    def get_incidents(self, type=0):
        """ Get neurons which synapse at this neuron """
        # Directed graph. Getting accessible _from_ this node
        for item in self['nx'].in_edges_iter(self.name(), data=True):
            if 'GapJunction' in item[2]['synapse']:
                yield item[0]
Пример #30
0
class Cell(BiologyType):
    """
    A biological cell.

    All cells with the same `name` are considered to be the same object.

    Parameters
    -----------
    name : str
        The name of the cell
    lineageName : str
        The lineageName of the cell

    Examples
    --------
    >>> from owmeta_core.quantity import Quantity
    >>> c = Cell(lineageName="AB plapaaaap",
    ...     divisionVolume=Quantity("600","(um)^3"))
    """

    class_context = BiologyType.class_context

    rdf_type = CELL_RDF_TYPE

    divisionVolume = DatatypeProperty()
    ''' The volume of the cell at division '''

    name = DatatypeProperty()
    ''' The 'adult' name of the cell typically used by biologists when discussing C. elegans '''

    wormbaseID = DatatypeProperty()

    description = DatatypeProperty()
    ''' A description of the cell '''

    channel = ObjectProperty(value_type=Channel,
                             multiple=True,
                             inverse_of=(Channel, 'appearsIn'))

    lineageName = DatatypeProperty()
    ''' The lineageName of the cell '''

    synonym = DatatypeProperty(multiple=True)

    daughterOf = ObjectProperty(value_type=This, inverse_of=(This, 'parentOf'))

    parentOf = ObjectProperty(value_type=This, multiple=True)

    key_property = {'property': name, 'type': 'direct'}

    def __init__(self, name=None, lineageName=None, **kwargs):
        # NOTE: We name the `name` and `lineageName` as positional parameters for
        # convenience
        super(Cell, self).__init__(name=name,
                                   lineageName=lineageName,
                                   **kwargs)

    def blast(self):
        """
        Return the blast name.

        Example::

            >>> c = Cell(name="ADAL", lineageName='AB ')
            >>> c.blast()
            'AB'

        Note that this isn't a `~dataobject_property.Property`. It returns the blast cell
        part of a `lineageName` value.
        """
        import re
        try:
            ln = self.lineageName()
            x = re.split("[. ]", ln)
            return x[0]
        except Exception:
            return ""

    def __str__(self):
        if self.name.has_defined_value():
            return str(self.name.defined_values[0].idl)
        else:
            return super(Cell, self).__str__()