Beispiel #1
0
    def __init__(self, cw_obj):
        self.channelworm_object = cw_obj
        self.map_properties()

        P.connect()
        # mapping evidence to Assertions
        pmids = cw_obj.expression_evidences.split(', ')
        for pmid in pmids:
            e = P.Evidence()
            e.pmid(pmid)
            e.asserts(self.pyopenworm_object.expression_pattern)
            e.save()

        pmids = cw_obj.description_evidences.split(', ')
        for pmid in pmids:
            e = P.Evidence()
            e.pmid(pmid)
            e.asserts(self.pyopenworm_object.description)
            e.save()

        # proteins in CW are ;-delimited, but should be 
        #multiple values in PyOpenWorm
        pros = cw_obj.proteins.split('; ')
        for p in pros:
            self.pyopenworm_object.proteins(p)
def test_adapt_IonChannel(data_pool):
    """
    Test that we can map a IonChannel object to a PyOpenWorm
    Channel object.
    """
    ic = data_pool.get_ion_channel()
    ica = Adapter.create(ic)

    cw_obj = ica.get_cw()
    pow_obj = ica.get_pow()

    # parse PMIDs for expression_patterns,
    # then for descriptions
    # and finally proteins
    exp_strings = cw_obj.expression_evidences.split(', ')
    cw_expression_pmids = set(int(s) for s in exp_strings)

    desc_strings = cw_obj.description_evidences.split(', ')
    cw_description_pmids = set(int(s) for s in desc_strings)

    cw_proteins = set(cw_obj.proteins.split('; '))

    cw_dict = {
        'channel_name': cw_obj.channel_name,
        'description': cw_obj.description,
        'description_evidences': cw_obj.description_evidences,
        'gene_name': cw_obj.gene_name,
        'gene_WB_ID': cw_obj.gene_WB_ID,
        'gene_class': cw_obj.gene_class,
        'proteins': cw_proteins,
        'expression_pattern': cw_obj.expression_pattern,
        'expression_evidences': cw_obj.expression_evidences,
    }

    # retrieve PMIDs for expression_patterns,
    # then for descriptions
    ev = PyOpenWorm.Evidence()
    ev.asserts(pow_obj.expression_pattern)
    pow_expression_pmids = set(e.pmid() for e in ev.load())

    ev = PyOpenWorm.Evidence()
    ev.asserts(pow_obj.description)
    pow_description_pmids = set(e.pmid() for e in ev.load())

    pow_dict = {
        'channel_name': pow_obj.name(),
        'description': pow_obj.description(),
        'description_evidences': pow_description_pmids,
        'gene_name': pow_obj.gene_name(),
        'gene_WB_ID': pow_obj.gene_WB_ID(),
        'gene_class': pow_obj.gene_class(),
        'proteins': pow_obj.proteins(),
        'expression_pattern': pow_obj.expression_pattern(),
        'expression_evidences': pow_expression_pmids,
    }

    assert pow_dict == cw_dict
Beispiel #3
0
def Evidences(request):
    P.connect()

    try:
        EVIDENCE_DICT = {}
        count = 0
        for evidence in P.Evidence().load():
            EVIDENCE_DICT[str(count)] = {
                'index': count,
                'doi': list(evidence.doi.get()),
                'pmid': list(evidence.pmid.get()),
                'wormbaseid': list(evidence.wbid.get()),
                'author': list(evidence.author.get()),
                'title': list(evidence.title.get()),
                'year': list(evidence.year.get()),
                'uri': list(evidence.uri.get()),
                'completeness': '#2B7558'
            }

            count += 1
    finally:
        P.disconnect()

    return render_to_response('pyopenworm/evidences.html',
                              {'evidences': EVIDENCE_DICT})
Beispiel #4
0
def upload_neurons():
    try:
        #TODO: Improve this evidence marker
        ev = P.Evidence(title="C. elegans Cell List - WormBase.csv")
        w = WORM
        n = NETWORK
        w.neuron_network(n)
        # insert neurons.
        i = 0
        with open(CELL_NAMES_SOURCE) as csvfile:
            csvreader = csv.reader(csvfile)

            for num, line in enumerate(csvreader):
                if num < 4:  # skip rows with no data
                    continue

                if line[5] == '1':  # neurons marked in this column
                    neuron_name = normalize(line[0]).upper()
                    n.neuron(P.Neuron(name=neuron_name))
                    i = i + 1

        ev.asserts(n)
        #second step, get the relationships between them and add them to the graph
        print("uploaded " + str(i) + " neurons")
    except Exception:
        traceback.print_exc()
    def __init__(self, cw_obj):
        # initialize PyOpenWorm connection so we can access its API
        P.connect()

        self.channelworm_object = cw_obj
        cw_dict = model_to_dict(self.channelworm_object)

        experiment_id = cw_dict.pop('experiment')
        patch_clamp_id = cw_dict.pop('id')

        self.pyopenworm_object = P.Experiment()

        # get the CW model's experiment
        cw_evidence = C.Experiment.objects.get(id=experiment_id)

        # make a PyOW evidence object with it
        pow_evidence = P.Evidence(doi=cw_evidence.doi)

        # add it to the PyOW experiment model
        self.pyopenworm_object.reference(pow_evidence)

        for key, value in cw_dict.iteritems():
            self.pyopenworm_object.conditions.set(key, value)

        # we not longer need PyOW API so we can kill the connection
        P.disconnect()
Beispiel #6
0
def upload_types():
    import csv
    ev = P.Evidence(title="neurons.csv")
    w = P.Worm()
    net = w.neuron_network.one()

    data = dict()
    for x in csv.reader(open('../aux_data/neurons.csv'), delimiter=';'):
        types = []
        name = x[0]
        types_string = x[1]
        if 'sensory' in (types_string.lower()):
            types.append('sensory')
        if 'interneuron' in (types_string.lower()):
            types.append('interneuron')
        if 'motor' in (types_string.lower()):
            types.append('motor')
        data[name] = types

    for name in data:
        n = P.Neuron(name=name)
        types = data[name]
        for t in types:
            n.type(t)
        net.neuron(n)
    ev.asserts(net)
    ev.save()
    print("uploaded types")
Beispiel #7
0
def parse_bibtex_into_evidence(file_name):
    import bibtexparser
    e = P.Evidence()
    with open(file_name) as bibtex_file:
        bib_database = bibtexparser.load(bibtex_file)
        key = bib_database.entries[0]['ID']
        e.setKey(key)
        try:
            doi = bib_database.entries[0]['doi']
            if doi:
                e.doi(doi)
        except KeyError:
            pass

        try:
            author = bib_database.entries[0]['author']
            if author:
                e.author(author)
        except KeyError:
            pass

        try:
            title = bib_database.entries[0]['title']
            if title:
                e.title(title)
        except KeyError:
            pass
        try:
            year = bib_database.entries[0]['year']
            if year:
                e.year(year)
        except KeyError:
            pass
    return e
Beispiel #8
0
def upload_muscles():
    """ Upload muscles and the neurons that connect to them
    """
    try:
        ev = P.Evidence(title="C. elegans sqlite database")
        conn = sqlite3.connect(SQLITE_DB_LOC)
        cur = conn.cursor()
        w = P.Worm()
        cur.execute("""
        SELECT DISTINCT a.Entity, b.Entity
        FROM tblrelationship innervatedBy, tblentity b, tblentity a, tblrelationship type_b
        WHERE innervatedBy.EnID1=a.id and innervatedBy.Relation = '1516' and innervatedBy.EnID2=b.id
        and type_b.EnID1 = b.id and type_b.Relation='1515' and type_b.EnID2='1519'
        """)  # 1519 is the
        for r in cur.fetchall():
            neuron_name = str(r[0])
            muscle_name = str(r[1])
            m = P.Muscle(muscle_name)
            n = P.Neuron(neuron_name)
            w.muscle(m)
            m.innervatedBy(n)

        ev.asserts(w)
        ev.save()
        #second step, get the relationships between them and add them to the graph
        print("uploaded muscles")
    except Exception:
        traceback.print_exc()
    finally:
        conn.close()
Beispiel #9
0
def upload_neurons():
    try:
        conn = sqlite3.connect(SQLITE_DB_LOC)
        cur = conn.cursor()
        ev = P.Evidence(title="C. elegans sqlite database")
        w = P.Worm()
        n = P.Network()
        w.neuron_network(n)
        # insert neurons.
        # save
        cur.execute("""
        SELECT DISTINCT a.Entity FROM tblrelationship, tblentity a, tblentity b
        where EnID1=a.id and Relation = '1515' and EnID2='1'
        """)
        for r in cur.fetchall():
            neuron_name = str(r[0])
            n.neuron(P.Neuron(name=neuron_name))
        ev.asserts(n)
        ev.save()
        #second step, get the relationships between them and add them to the graph
        print("uploaded neurons")
    except Exception:
        traceback.print_exc()
    finally:
        conn.close()
Beispiel #10
0
def do_insert(config="default.conf", logging=False):
    global SQLITE_EVIDENCE
    global WORM
    global NETWORK

    if config:
        if isinstance(config, P.Configure):
            pass
        elif isinstance(config, str):
            config = P.Configure.open(config)
        elif isinstance(config, dict):
            config = P.Configure().copy(config)
        else:
            raise Exception("Invalid configuration object " + str(config))

    P.connect(conf=config, do_logging=logging)
    SQLITE_EVIDENCE = P.Evidence(key="C_elegans_SQLite_DB",
                                 title="C. elegans sqlite database")
    try:
        WORM = P.Worm()
        NETWORK = P.Network()
        WORM.neuron_network(NETWORK)
        NETWORK.worm(WORM)

        upload_neurons()
        upload_muscles()
        upload_lineage_and_descriptions()
        upload_connections()
        upload_receptors_types_neurotransmitters_neuropeptides_innexins()
        upload_additional_receptors_neurotransmitters_neuropeptides_innexins()

        print("Saving...")
        WORM.save()

        #infer()
        print("Serializing...")
        serialize_as_n3()

    except Exception:
        traceback.print_exc()
    finally:
        P.disconnect()
Beispiel #11
0
def upload_synapses():
    try:
        conn = sqlite3.connect(SQLITE_DB_LOC)
        cur = conn.cursor()
        w = P.Worm()
        n = P.Network()
        w.neuron_network(n)
        #second step, get the relationships between them and add them to the graph
        cur.execute("SELECT DISTINCT a.Entity, b.Entity, Weight, Relation FROM tblrelationship, tblentity a, tblentity b where EnID1=a.id and EnID2=b.id and (Relation = '356' OR Relation = '357')")

        for r in cur.fetchall():
            #all items are numbers -- need to be converted to a string
            first = str(r[0])
            second = str(r[1])
            third = str(r[2])
            syntype = str(r[3])
            if syntype == '356':
                syntype = 'send'
            else:
                syntype = 'gapjunction'
            try:
                weight = int(third)
                # NMJs have negative weights. we only want the synaptic connections
                if weight < 0:
                    syntype = 'gapjunction'
                    weight = -1 * weight

            except:
                weight = None

            if weight:
                c = P.Connection(pre_cell=first, post_cell=second, number=weight, syntype=syntype)
                n.synapse(c)
        e = P.Evidence(author='*****@*****.**')
        e.asserts(w)
        e.save()
    except Exception, e:
        traceback.print_exc()
Beispiel #12
0
def upload_muscles():
    """ Upload muscles and the neurons that connect to them
    """
    try:
        with open(CELL_NAMES_SOURCE) as csvfile:
            csvreader = csv.reader(csvfile)

            ev = P.Evidence(title="C. elegans Cell List - WormBase.csv")
            w = WORM
            for num, line in enumerate(csvreader):
                if num < 4:  # skip rows with no data
                    continue

                if line[7] or line[8] or line[
                        9] == '1':  # muscle's marked in these columns
                    muscle_name = normalize(line[0]).upper()
                    m = P.Muscle(name=muscle_name)
                    w.muscle(m)
            ev.asserts(w)
        #second step, get the relationships between them and add them to the graph
        print("uploaded muscles")
    except Exception:
        traceback.print_exc()
Beispiel #13
0
import sys
import PyOpenWorm as P

#Create dummy database configuration.
d = P.Data({})

#Connect to database with dummy configuration
P.connect(conf=d)

#Create a new Neuron object to work with
n = P.Neuron(name='AVAL')

#Create a new Evidence object with `doi` and `pmid` fields populated.
#See `PyOpenWorm/evidence.py` for other available fields.
e = P.Evidence(doi='125.41.3/ploscompbiol', pmid='57182010')

#Evidence object asserts something about the enclosed dataObject.
#Here we add a receptor to the Neuron we made earlier, and "assert it".
#As the discussion (see top) reads, this might be asserting the existence of
#receptor UNC-8 on neuron AVAL.
e.asserts(n.receptor('UNC-8'))

#Save the Neuron and Evidence objects to the database.
n.save()
e.save()

#What does my evidence object contain?
print e

#Disconnect from the database.
Beispiel #14
0
def upload_lineage_and_descriptions():
    """ Upload lineage names and descriptions pulled from the WormAtlas master cell list

    Assumes that Neurons and Muscles have already been added
    """
    # XXX: This wants a way to insert cells, then later, to insert neurons from the same set
    # and have the later recoginzed as the former. Identifier matching limits us here. It would
    # be best to establish owl:sameAs links to the super class (Cell) from the subclass (Neuron)
    # at the sub-class insert and have a reasoner relate
    # the two sets of inserts.
    try:
        w = WORM
        net = NETWORK
        #TODO: Improve this evidence marker
        ev = P.Evidence(uri="http://www.wormatlas.org/celllist.htm")
        cell_data = open(LINEAGE_LIST_LOC, "r")

        # Skip headers
        next(cell_data)

        cell_name_counters = dict()
        data = dict()
        for x in cell_data:
            j = [x.strip().strip("\"") for x in x.split("\t")]
            name = j[0]
            lineageName = j[1]
            desc = j[2]

            # XXX: These renaming choices are arbitrary and may be inappropriate
            if name == "DB1/3":
                name = "DB1"
            elif name == "DB3/1":
                name = "DB3"
            elif name == "AVFL/R":
                if lineageName[0] == "W":
                    name = "AVFL"
                elif lineageName[0] == "P":
                    name = "AVFR"

            if name in cell_name_counters:
                while (name in cell_name_counters):
                    cell_name_counters[name] += 1
                    name = name + "(" + str(cell_name_counters[name]) + ")"
            else:
                cell_name_counters[name] = 0

            data[name] = {"lineageName": lineageName, "desc": desc}

        def add_data_to_cell(n):
            name = n.name.one()
            cell_data = data[str(name)]
            n.lineageName(cell_data['lineageName'])
            n.description(cell_data['desc'])
            w.cell(n)

        for n in net.neurons():
            add_data_to_cell(n)

        # TODO: Add data for other cells here. Requires relating named
        # muscle cells to their counterparts in the cell list (e.g. mu_bod(#))
        # Also requires removing neurons and muscles from the list once
        # they've been identified so they aren't stored twice

        ev.asserts(w)
        print("uploaded lineage and descriptions")
    except Exception:
        traceback.print_exc()
Beispiel #15
0
def upload_connections():

    print(
        "uploading statements about connections.  Buckle up; this will take a while!"
    )

    # to normalize certian body wall muscle cell names
    search_string_muscle = re.compile(r'\w+[BWM]+\w+')
    replace_string_muscle = re.compile(r'[BWM]+')

    def normalize_muscle(name):
        # normalize names of Body Wall Muscles
        # if there is 'BWM' in the name, remove it
        if re.match(search_string_muscle, name):
            name = replace_string_muscle.sub('', name)
        return name

    # connectome specific definitions

    # cells that are generically definited in source. These will not be added to PyOpenWorm
    #unwanted = ['HYP', 'INTESTINE']

    # muscle cells that are generically defined in source and need to be broken into pair of L and R before being added to PyOpenWorm
    to_expand_muscles = ['PM1D', 'PM2D', 'PM3D', 'PM4D', 'PM5D']

    # muscle cells that have different names in connectome source and cell list. Their wormbase cell list names will be used in PyOpenWorm
    changed_muscles = ['ANAL', 'INTR', 'INTL', 'SPH']

    def changed_muscle(x):
        return {
            'ANAL': 'MU_ANAL',
            'INTR': 'MU_INT_R',
            'INTL': 'MU_INT_L',
            'SPH': 'MU_SPH'
        }[x]

    # cells that are neither neurons or muscles. These are marked as 'Other Cells' in the wormbase cell list but are still part of the new connectome. In future work these should be uploaded seperately to PyOpenWorm in a new upload function and should be referred from there instead of this list.
    other_cells = [
        'MC1DL', 'MC1DR', 'MC1V', 'MC2DL', 'MC2DR', 'MC2V', 'MC3DL', 'MC3DR',
        'MC3V'
    ]

    # counters for terminal printing
    neuron_connections = [0]
    muscle_connections = [0]
    other_connections = [0]
    #unwanted_connections = 0

    try:
        w = WORM
        n = NETWORK

        neuron_objs = list(set(n.neurons()))
        muscle_objs = list(w.muscles())

        w.neuron_network(n)

        # get lists of neuron and muscles names
        neurons = [neuron.name() for neuron in neuron_objs]
        muscles = [muscle.name() for muscle in muscle_objs]

        # Evidence object to assert each connection
        e = P.Evidence(title='herm_full_edgelist.csv')

        with open(CONNECTOME_SOURCE) as csvfile:
            edge_reader = csv.reader(csvfile)
            edge_reader.next()  # skip header row
            for row in edge_reader:
                source, target, weight, syn_type = map(str.strip, row)

                # set synapse type to something the Connection object
                # expects, and normalize the source and target names
                if syn_type == 'electrical':
                    syn_type = 'gapJunction'
                elif syn_type == 'chemical':
                    syn_type = 'send'

                source = normalize(source).upper()
                target = normalize(target).upper()

                weight = int(weight)

                # remove BMW from Body Wall Muscle cells
                if 'BWM' in source:
                    source = normalize_muscle(source)
                if 'BWM' in target:
                    target = normalize_muscle(target)

                # change certain muscle names to names in wormbase
                if source in changed_muscles:
                    source = changed_muscle(source)
                if target in changed_muscles:
                    target = changed_muscle(target)

                def marshall(name):
                    ret = []
                    res = None
                    res2 = None
                    if name in neurons:
                        res = P.Neuron(name)
                    elif name in muscles:
                        res = P.Muscle(name)
                    elif name in to_expand_muscles:
                        name_l = name + 'L'
                        name_r = name + 'R'
                        res = P.Muscle(name_l)
                        res2 = P.Muscle(name_r)
                    elif name in other_cells:
                        res = P.Cell(name)

                    if res is not None:
                        ret.append(res)
                    if res2 is not None:
                        ret.append(res2)

                    return ret

                def add_synapse(source, target):
                    c = P.Connection(pre_cell=source,
                                     post_cell=target,
                                     number=weight,
                                     syntype=syn_type)
                    n.synapse(c)
                    e.asserts(c)

                    if isinstance(source, P.Neuron) and isinstance(
                            target, P.Neuron):
                        c.termination('neuron')
                        neuron_connections[0] += 1
                    elif isinstance(source, P.Neuron) and isinstance(
                            target, P.Muscle):
                        c.termination('muscle')
                        muscle_connections[0] += 1
                    elif isinstance(source, P.Muscle) and isinstance(
                            target, P.Neuron):
                        c.termination('muscle')
                        muscle_connections[0] += 1
                    else:
                        other_connections[0] += 1

                    return c

                sources = marshall(source)
                targets = marshall(target)

                for s in sources:
                    for t in targets:
                        add_synapse(s, t)

        e.asserts(n)  # assert the whole connectome too
        print('Total neuron to neuron connections added = %i' %
              neuron_connections[0])
        print('Total neuron to muscle connections added = %i' %
              muscle_connections[0])
        print('Total other connections added = %i' % other_connections[0])
        #print('Total connections discarded = %i' %unwanted_connections)
        print('uploaded connections')

    except Exception:
        traceback.print_exc()
Beispiel #16
0
# ------------------------------------[implies]-------
# n.p(a) # Any property except name, connection, and neighbor is the same as in nc
# n.neighbor(d) # For neighbors, if the neighbor is a neuron, then just the connection
#               # holds for all members of the class
# n.neighbor(b) # Otherwise, the neuron (b) in the connected class on the same side as
#               # n (i.e., the one for which the last character in its name matches the
#               # last in n's name) in the neighbor
# n.name()[:-1] == nc.name()

#
# Setting up the data
#

ev = P.Evidence(
    title=
    "A Hub-and-Spoke Circuit Drives Pheromone Attraction and Social Behavior in C. elegans",
    uri="http://www.ncbi.nlm.nih.gov/pmc/articles/PMC2760495/",
    year=2009)
w = P.Worm("C. elegans")
net = P.Network()
w.neuron_network(net)

ev.asserts(w)


def setup(name, type):
    n = NeuronClass(name)
    n.type(type)
    n.member(P.Neuron(name + "R"))
    n.member(P.Neuron(name + "L"))
    net.neuron(n)
Beispiel #17
0
def upload_synapses():

    import re
    search_string = re.compile(r'\w+[0]+[1-9]+')
    replace_string = re.compile(r'[0]+')

    def normalize(name):
        # normalize neuron names to match those used at other points
        # see #137 for elaboration
        # if there are zeroes in the middle of a name, remove them
        if re.match(search_string, name):
            name = replace_string.sub('', name)
        return name

    import xlrd

    try:
        w = P.Worm()
        n = P.Network()
        w.neuron_network(n)
        combining_dict = {}
        # Get synapses and gap junctions and add them to the graph
        s = xlrd.open_workbook('../aux_data/NeuronConnect.xls').sheets()[0]
        for row in range(1, s.nrows):
            if s.cell(row, 2).value in ('S', 'Sp', 'EJ'):
                #We're not going to include 'receives' ('R', 'Rp') since they're just the inverse of 'sends'
                #Also omitting 'NMJ' for the time being (no model in db)
                pre = normalize(s.cell(row, 0).value)
                post = normalize(s.cell(row, 1).value)
                num = int(s.cell(row, 3).value)
                if s.cell(row, 2).value == 'EJ':
                    syntype = 'gapJunction'
                elif s.cell(row, 2).value in ('S', 'Sp'):
                    syntype = 'send'

                # Add them to a dict to make sure Sends ('S') and Send-polys ('Sp') are summed.
                # keying by connection pairs as a string (e.g. 'SDQL,AVAL,send').
                # values are lists of the form [pre, post, number, syntype].
                string_key = '{},{},{}'.format(pre, post, syntype)
                if string_key in combining_dict.keys():
                    # if key already there, add to number
                    num += combining_dict[string_key][2]

                combining_dict[string_key] = [pre, post, num, syntype]

        for entry in combining_dict:
            pre, post, num, syntype = combining_dict[entry]
            c = P.Connection(pre_cell=pre,
                             post_cell=post,
                             number=num,
                             syntype=syntype)
            n.synapse(c)

        e = P.Evidence(
            uri='http://www.wormatlas.org/neuronalwiring.html#Connectivitydata'
        )
        e.asserts(n)
        e.save()
        print('uploaded synapses')
    except Exception, e:
        traceback.print_exc()
Beispiel #18
0
from __future__ import print_function
import PyOpenWorm as P

#Create dummy database configuration.
d = P.Data({})

#Connect to database with dummy configuration
P.connect(conf=d)

#Create a new Neuron object to work with
n = P.Neuron(name='AVAL')

#Create a new Evidence object with `doi` and `pmid` fields populated.
#See `PyOpenWorm/evidence.py` for other available fields.
e = P.Evidence(key='Anonymous2011',
               doi='125.41.3/ploscompbiol',
               pmid='12345678')

#Evidence object asserts something about the enclosed dataObject.
#Here we add a receptor to the Neuron we made earlier, and "assert it".
#As the discussion (see top) reads, this might be asserting the existence of
#receptor UNC-8 on neuron AVAL.
e.asserts(n.receptor('UNC-8'))

#Save the Neuron and Evidence objects to the database.
n.save()
e.save()

#What does my evidence object contain?
print(e)
Beispiel #19
0
def upload_lineage_and_descriptions():
    """ Upload lineage names and descriptions pulled from the WormAtlas master cell list

    Assumes that Neurons and Muscles have already been added
    """
    # XXX: This wants a way to insert cells, then later, to insert neurons from the same set
    # and have the later recoginzed as the former. Identifier matching limits us here. It would
    # be best to establish owl:sameAs links to the super class (Cell) from the subclass (Neuron)
    # at the sub-class insert and have a reasoner relate
    # the two sets of inserts.
    cells = dict()
    try:
        w = P.Worm()
        net = w.neuron_network.one()
        ev = P.Evidence(uri="http://www.wormatlas.org/celllist.htm")
        # insert neurons.
        # save
        cell_data = open(LINEAGE_LIST_LOC, "r")

        # Skip headers
        next(cell_data)

        cell_name_counters = dict()
        data = dict()
        for x in cell_data:
             j = [x.strip().strip("\"") for x in x.split("\t")]
             name = j[0]
             lineageName = j[1]
             desc = j[2]

             # XXX: These renaming choices are arbitrary and may be inappropriate
             if name == "DB1/3":
                 name = "DB1"
             elif name == "DB3/1":
                 name = "DB3"
             elif name == "AVFL/R":
                 if lineageName[0] == "W":
                     name = "AVFL"
                 elif lineageName[0] == "P":
                     name = "AVFR"

             if name in cell_name_counters:
                 while (name in cell_name_counters):
                     cell_name_counters[name] += 1
                     name = name + "("+ str(cell_name_counters[name]) +")"
             else:
                 cell_name_counters[name] = 0

             data[name] = {"lineageName" : lineageName, "desc": desc}

        for n in net.neuron():
             name = n.name.one()
             neuron_data = data[str(name)]
             n.lineageName(neuron_data['lineageName'])
             n.description(neuron_data['desc'])
             w.cell(n)

        ev.asserts(w)
        ev.save()
    except Exception, e:
        traceback.print_exc()
Beispiel #20
0
def upload_receptors_types_neurotransmitters_neuropeptides_innexins():
    """ Augment the metadata about neurons with information about receptors,
        neuron types, neurotransmitters, neuropeptides and innexins.
        As we go, add evidence objects to each statement."""
    print(
        "uploading statements about types, receptors, innexins, neurotransmitters and neuropeptides"
    )

    #set up evidence objects in advance
    altun_ev = get_altun_evidence()
    wormatlas_ev = get_wormatlas_evidence()

    import csv
    f = open(RECEPTORS_TYPES_NEUROPEPTIDES_NEUROTRANSMITTERS_INNEXINS_SOURCE)
    reader = csv.reader(f)
    reader.next()  #skip the header row

    i = 0

    neurons = set()
    uris = dict()

    for row in reader:
        neuron_name = row[0]
        relation = row[1].lower()
        data = row[2]
        evidence = row[3]
        evidenceURL = row[4]

        #prepare evidence
        e = P.Evidence()

        #pick correct evidence given the row
        if 'altun' in evidence.lower():
            e = altun_ev

        elif 'wormatlas' in evidence.lower():
            e = wormatlas_ev

        e2 = []
        try:
            e2 = uris[evidenceURL]
        except KeyError:
            e2 = P.Evidence(uri=evidenceURL)
            uris[evidenceURL] = e2

        #grab the neuron object
        n = NETWORK.aneuron(neuron_name)
        neurons.add(n)

        if relation == 'neurotransmitter':
            # assign the data, grab the relation into r
            r = n.neurotransmitter(data)
            #assert the evidence on the relationship
            e.asserts(r)
            e2.asserts(r)
        elif relation == 'innexin':
            # assign the data, grab the relation into r
            r = n.innexin(data)
            #assert the evidence on the relationship
            e.asserts(r)
            e2.asserts(r)
        elif relation == 'neuropeptide':
            # assign the data, grab the relation into r
            r = n.neuropeptide(data)
            #assert the evidence on the relationship
            e.asserts(r)
            e2.asserts(r)
        elif relation == 'receptor':
            # assign the data, grab the relation into r
            r = n.receptor(data)
            #assert the evidence on the relationship
            e.asserts(r)
            e2.asserts(r)

        if relation == 'type':
            types = []
            if 'sensory' in (data.lower()):
                types.append('sensory')
            if 'interneuron' in (data.lower()):
                types.append('interneuron')
            if 'motor' in (data.lower()):
                types.append('motor')
            if 'unknown' in (data.lower()):
                types.append('unknown')
            # assign the data, grab the relation into r
            for t in types:
                r = n.type(t)
                #assert the evidence on the relationship
                e.asserts(r)
                e2.asserts(r)

        i = i + 1

    for neur in neurons:
        n = NETWORK.neuron(neur)
    print(
        "uploaded " + str(i) +
        " statements about types, receptors, innexins, neurotransmitters and neuropeptides"
    )
Beispiel #21
0
def _upload_receptors_types_neurotransmitters_neuropeptides_innexins_from_file(
        file_path):
    # set up evidence objects in advance
    altun_ev = get_altun_evidence()
    wormatlas_ev = get_wormatlas_evidence()

    i = 0

    neurons = []
    uris = dict()

    with open(file_path) as f:
        reader = csv.reader(f)
        next(reader)  # skip the header row

        for row in reader:
            neuron_name = row[0]
            relation = row[1].lower()
            data = row[2]
            evidence = row[3]
            evidenceURL = row[4]

            # prepare evidence
            e = P.Evidence()

            # pick correct evidence given the row
            if 'altun' in evidence.lower():
                e = altun_ev
            elif 'wormatlas' in evidence.lower():
                e = wormatlas_ev

            e2 = []
            try:
                e2 = uris[evidenceURL]
            except KeyError:
                e2 = P.Evidence(uri=evidenceURL)
                uris[evidenceURL] = e2

            # grab the neuron object
            n = NETWORK.aneuron(neuron_name)
            neurons.append(n)

            if relation == 'neurotransmitter':
                if data in n.neurotransmitter():
                    continue
                # assign the data, grab the relation into r
                r = n.neurotransmitter(data)
                # assert the evidence on the relationship
                e.asserts(r)
                e2.asserts(r)

            elif relation == 'innexin':
                if data in n.innexin():
                    continue
                # assign the data, grab the relation into r
                r = n.innexin(data)
                # assert the evidence on the relationship
                e.asserts(r)
                e2.asserts(r)

            elif relation == 'neuropeptide':
                if data in n.neuropeptide():
                    continue
                # assign the data, grab the relation into r
                r = n.neuropeptide(data)
                # assert the evidence on the relationship
                e.asserts(r)
                e2.asserts(r)

            elif relation == 'receptor':
                if data in n.receptor():
                    continue
                # assign the data, grab the relation into r
                r = n.receptor(data)
                # assert the evidence on the relationship
                e.asserts(r)
                e2.asserts(r)

            elif relation == 'type':
                if data.lower() in n.type():
                    continue
                types = []
                if 'sensory' in (data.lower()):
                    types.append('sensory')
                if 'interneuron' in (data.lower()):
                    types.append('interneuron')
                if 'motor' in (data.lower()):
                    types.append('motor')
                if 'unknown' in (data.lower()):
                    types.append('unknown')
                # assign the data, grab the relation into r
                for t in types:
                    r = n.type(t)
                    # assert the evidence on the relationship
                    e.asserts(r)
                    e2.asserts(r)

            i += 1

    for neur in neurons:
        NETWORK.neuron(neur)
    print(
        'uploaded {} statements about types, receptors, innexins, neurotransmitters and neuropeptides from {}'
        .format(i, file_path))
Beispiel #22
0
 def get_supporting_evidence(fact):
     """ Helper function for checking amount of Evidence.
     Returns list of Evidence supporting fact. """
     ev = P.Evidence()
     ev.asserts(fact)
     return list(ev.load())