Example #1
0
def do_insert(config="default.conf", logging=False):
    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)
    try:
        w = P.Worm()
        net = P.Network()
        w.neuron_network(net)
        w.save()

        upload_neurons()
        upload_muscles()
        upload_lineage_and_descriptions()
        upload_synapses()
        upload_receptors_and_innexins()
        upload_types()
        serialize_as_n3()
        #infer()
    except:
        traceback.print_exc()
    finally:
        P.disconnect()
 def setUp(self):
     PyOpenWorm.connect(conf=Configure(
         **{
             'rdf.store_conf': 'tests/test.db',
             'rdf.source': 'ZODB'
         }))
     self.g = PyOpenWorm.config("rdf.graph")
    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()
Example #4
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})
Example #5
0
    def __init__(self, cw_obj):
        self.channelworm_object = cw_obj
        self.map_properties()

        P.connect()
        self.pyopenworm_object.set_data(cw_obj.asarray())
        P.disconnect()
Example #6
0
def do_insert(config="default.conf", logging=False):
    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)
    try:
        w = P.Worm()
        net = P.Network()
        w.neuron_network(net)
        w.save()

        upload_neurons()
        upload_muscles()
        upload_lineage_and_descriptions()
        upload_synapses()
        upload_receptors_and_innexins()
        upload_types()
        serialize_as_n3()
        #infer()
    except:
        traceback.print_exc()
    finally:
        P.disconnect()
    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()
Example #8
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_reference(data_pool):
    """Test that we can map a Reference object to a PyOpenWorm
    Experiment object."""
    r = data_pool.get_reference()

    reference_adapter = Adapter.create(r)

    experiment = reference_adapter.get_pow()
    reference = reference_adapter.get_cw()

    PyOpenWorm.connect()

    pyow_dict = {
        'authors': experiment.author(),
        'doi': experiment.doi(),
        'pmid': experiment.pmid(),
        'title': experiment.title(),
        'url': experiment.uri(),
        'year': experiment.year(),
    }

    cw_dict = {
        'authors': set([reference.authors]),
        'doi': reference.doi,
        'pmid': reference.PMID,
        'title': reference.title,
        'url': set([reference.url]),
        'year': reference.year
    }

    PyOpenWorm.disconnect()

    assert pyow_dict == cw_dict
Example #10
0
    def setUpClass(cls):
        import csv

        cls.neurons = [
        ]  #array that holds the names of the 302 neurons at class-level scope

        if not USE_BINARY_DB:
            PyOpenWorm.connect(conf=Data(
            ))  # Connect for integrity tests that use PyOpenWorm functions
            cls.g = PyOpenWorm.config(
                'rdf.graph')  # declare class-level scope for the database
            cls.g.parse("OpenWormData/WormData.n3",
                        format="n3")  # load in the database
        else:
            conf = Configure(**{
                "rdf.source": "ZODB",
                "rdf.store_conf": BINARY_DB
            })
            PyOpenWorm.connect(conf=conf)
            cls.g = PyOpenWorm.config('rdf.graph')

        #grab the list of the names of the 302 neurons

        csvfile = open('OpenWormData/aux_data/neurons.csv', 'r')
        reader = csv.reader(csvfile, delimiter=';', quotechar='|')

        for row in reader:
            if len(row[0]) > 0:  # Only saves valid neuron names
                cls.neurons.append(row[0])
Example #11
0
 def __init__(self):
     logger.info("Initialising OpenWormReader")
     P.connect()
     self.net = P.Worm().get_neuron_network()
     self.all_connections = self.net.synapses()
     self.neuron_connections = set(filter(lambda x: x.termination() == u'neuron', self.all_connections))
     self.muscle_connections = set(filter(lambda x: x.termination() == u'muscle', self.all_connections))
     logger.info("Finished initialising OpenWormReader")
Example #12
0
    def __enter__(self):
        # if P.connected:
        #     raise RuntimeError("Already connected")
        P.connect(POW_CONF_PATH)
        self.ctx = Context(ident=WORM_IDENT)
        self.worm = self.ctx.stored(Worm)()
        self.net = self.worm.neuron_network()

        return self
Example #13
0
 def setUp(self):
     # Set do_logging to True if you like walls of text
     self.TestConfig = Configure.open(TEST_CONFIG)
     td = '__tempdir__'
     z = self.TestConfig['rdf.store_conf']
     if z.startswith(td):
         x = z[len(td):]
         h=tempfile.mkdtemp()
         self.TestConfig['rdf.store_conf'] = h + x
     self.delete_dir()
     PyOpenWorm.connect(conf=self.TestConfig, do_logging=False)
Example #14
0
 def setUp(self):
     # Set do_logging to True if you like walls of text
     self.TestConfig = Configure.open(TEST_CONFIG)
     td = '__tempdir__'
     z = self.TestConfig['rdf.store_conf']
     if z.startswith(td):
         x = z[len(td):]
         h = tempfile.mkdtemp()
         self.TestConfig['rdf.store_conf'] = h + x
     self.delete_dir()
     PyOpenWorm.connect(conf=self.TestConfig, do_logging=False)
Example #15
0
def _get_cell_info(cells):

    import PyOpenWorm as P
    print("Connecting to the PyOpenWorm database...")
    P.connect()

    #Get the worm object.
    worm = P.Worm()

    #Extract the network object from the worm object.
    net = worm.neuron_network()

    #Go through our list and get the neuron object associated with each name.
    #Store these in another list.
    some_neurons = [P.Neuron(name) for name in cells]
    all_neuron_info = collections.OrderedDict()
    all_muscle_info = collections.OrderedDict()
    
    for neuron in some_neurons: 
        print("=====Checking properties of: %s"%neuron)
        print neuron.triples()
        print neuron.__class__
        short = ') %s'%neuron.name()
        if 'motor' in neuron.type():
            short = 'Mo%s'%short
        if 'sensory' in neuron.type():
            short = 'Se%s'%short
        if 'interneuron' in neuron.type():
            short = 'In%s'%short
        if _is_muscle(neuron.name()):
            short = 'Mu%s'%short
            
            
        short = '(%s'%short
        
        
        if 'GABA' in neuron.neurotransmitter():
            short = '- %s'%short
        elif len(neuron.neurotransmitter())==0:
            short = '? %s'%short
        else:
            short = '+ %s'%short
            
        info = (neuron, neuron.type(), neuron.receptor(), neuron.neurotransmitter(), short)
        #print dir(neuron)
        
        if _is_muscle(neuron.name()):
            all_muscle_info[neuron.name()] = info
        else:
            all_neuron_info[neuron.name()] = info
        
    return all_neuron_info, all_muscle_info
 def handle(self, *args, **options):
     P.connect()
     print 'clearing data'
     self.Del_Neuron()
     self.Del_Muscle()
     self.Del_IonChannel()
     print 'done'
     print "calculating scores"
     self.scoring_ionchannels()
     self.scoring_neurons()
     self.scoring_muscles()
     P.disconnect()
     print "scores calculated"
def Channels(request):
    P.connect()

    try:
        CHANNEL_DICT = {}
        for channel in P.Channel().load():
            CHANNEL_DICT[str(channel)] = {
                'name': str(channel),
                'completeness': '#2B7558'
            }
    finally:
        P.disconnect()

    return render_to_response('pyopenworm/channels.html',
                              {'channels': CHANNEL_DICT})
def Muscles(request):
    P.connect()

    try:
        MUSCLE_DICT = {}
        for muscle in P.Muscle().load():
            MUSCLE_DICT[str(muscle)] = {
                'name': str(muscle),
                'completeness': '#2B7558'
            }
    finally:
        P.disconnect()

    return render_to_response('pyopenworm/muscles.html',
                              {'muscles': MUSCLE_DICT})
def Neurons(request):
    P.connect()

    try:
        NEURON_DICT = {}
        for neuron in P.Neuron().load():
            NEURON_DICT[str(neuron)] = {
                'name': str(neuron),
                'completeness': '#2B7558'
            }
    finally:
        P.disconnect()

    return render_to_response('pyopenworm/neurons.html',
                              {'neurons': NEURON_DICT})
def Channel(request, channel_id):
    P.connect()

    try:
        channel_dict = {}
        for channel in P.Channel().load():
            channel_dict[str(channel)] = {
                'name': str(channel),
                'completeness': '#2B7558'
            }
    finally:
        P.disconnect()

    return render_to_response('pyopenworm/channel.html',
                              {'channel': channel_dict[channel_id]})
 def setUp(self):
     xfail_without_db()
     self.conn = PyOpenWorm.connect(
         configFile='tests/data_integrity_test.conf')
     self.g = self.conn.conf["rdf.graph"]
     self.context = Context()
     self.qctx = self.context.stored
Example #22
0
def test_adapt_GraphData(data_pool):
    """
    Test that we can map some GraphData to a PyOpenWorm 
    data object.
    """
    graph_data = data_pool.get_graph_data()
    gda = Adapter.create(graph_data)

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

    PyOpenWorm.connect()

    assert cw_obj.asarray() == pow_obj.data

    PyOpenWorm.disconnect()
 def setUp(self):
     self.conn = PyOpenWorm.connect(
         configFile='tests/data_integrity_test.conf')
     self.conf = self.conn.conf
     self.g = self.conf["rdf.graph"]
     self.context = Context(ident="http://openworm.org/data",
                            conf=self.conf)
     self.qctx = self.context.stored
Example #24
0
    def map_properties(self):
        """
        Map between the properties defined in the subclass.
        """

        # initialize PyOpenWorm connection so we can access its API
        P.connect()

        # initialize pyopenworm object
        self.pyopenworm_object = self.pyopenworm_class()

        for p, c in self.pyow_to_cw.items():
            cw_value = getattr(self.channelworm_object, c)
            pow_property = getattr(self.pyopenworm_object, p)
            map(pow_property, [cw_value])

        P.disconnect()
Example #25
0
    def setUpClass(cls):
        import csv
        PyOpenWorm.connect(
            conf=Configure(
                **{'rdf.store_conf': 'tests/test.db', 'rdf.source': 'ZODB'}))
        PyOpenWorm.loadData(skipIfNewer=False)
        PyOpenWorm.disconnect()
        # grab the list of the names of the 302 neurons

        csvfile = open('OpenWormData/aux_data/neurons.csv', 'r')
        reader = csv.reader(csvfile, delimiter=';', quotechar='|')

        # array that holds the names of the 302 neurons at class-level scope
        cls.neurons = []
        for row in reader:
            if len(row[0]) > 0:  # Only saves valid neuron names
                cls.neurons.append(row[0])
Example #26
0
    def setUpClass(cls):
        import csv
        PyOpenWorm.connect(conf=Configure(
            **{
                'rdf.store_conf': 'tests/test.db',
                'rdf.source': 'ZODB'
            }))
        PyOpenWorm.loadData(skipIfNewer=False)
        PyOpenWorm.disconnect()
        # grab the list of the names of the 302 neurons

        csvfile = open('OpenWormData/aux_data/neurons.csv', 'r')
        reader = csv.reader(csvfile, delimiter=';', quotechar='|')

        # array that holds the names of the 302 neurons at class-level scope
        cls.neurons = []
        for row in reader:
            if len(row[0]) > 0:  # Only saves valid neuron names
                cls.neurons.append(row[0])
def Muscle(request, muscle_id):
    P.connect()

    try:
        muscle_dict = {}
        for muscle in P.Muscle(muscle_id).load():
            '''
                'neurons': list(muscle.neurons.get()),
                'receptors': list(muscle.receptors.get()),
            '''
            muscle_dict[str(muscle)] = {
                'name': str(muscle),
                'completeness': '#2B7558'
            }
    finally:
        P.disconnect()

    return render_to_response('pyopenworm/muscle.html',
                              {'muscle': muscle_dict[muscle_id]})
Example #28
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()
def Neuron(request, neuron_id):
    P.connect()

    try:
        neuron_dict = {}
        for neuron in P.Neuron(neuron_id).load():
            neuron_dict[str(neuron)] = {
                'name': str(neuron),
                'type': list(neuron.type.get()),
                'receptor': list(neuron.receptor.get()),
                'innexin': list(neuron.innexin.get()),
                'neurotransmitter': list(neuron.neurotransmitter.get()),
                'neuropeptide': list(neuron.neuropeptide.get()),
                'completeness': '#2B7558'
            }
    finally:
        P.disconnect()

    return render_to_response('pyopenworm/neuron.html',
                              {'neuron': neuron_dict[neuron_id]})
Example #30
0
 def setUp(self):
     # Set do_logging to True if you like walls of text
     self.TestConfig = Data.open(TEST_CONFIG)
     td = '__tempdir__'
     z = self.TestConfig['rdf.store_conf']
     if z.startswith(td):
         x = z[len(td):]
         h = tempfile.mkdtemp()
         self.TestConfig['rdf.store_conf'] = h + x
     self.delete_dir()
     PyOpenWorm.connect(conf=self.TestConfig, do_logging=False)
     self.context = Context(ident='http://example.org/test-context',
                            conf=self.TestConfig)
     typ = type(self)
     if hasattr(typ, 'ctx_classes'):
         if isinstance(dict, typ.ctx_classes):
             self.ctx = self.context(typ.ctx_classes)
         else:
             self.ctx = self.context(
                 {x.__name__: x
                  for x in typ.ctx_classes})
Example #31
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()

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

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

    except:
        traceback.print_exc()
    finally:
        P.disconnect()
Example #32
0
def read_data(include_nonconnected_cells=False):

    print_("Initialising OpenWormReader")
    P.connect()
    net = P.Worm().get_neuron_network()
    all_connections = net.synapses()
    print_("Finished initialising OpenWormReader")

    conns = []
    cells = []

    cell_names = get_cells_in_model(net)

    for s in all_connections:
        pre = str(s.pre_cell().name())
        post = str(s.post_cell().name())

        if isinstance(s.post_cell(),
                      P.Neuron) and pre in cell_names and post in cell_names:
            syntype = str(s.syntype())
            syntype = syntype[0].upper() + syntype[1:]
            num = int(s.number())
            synclass = str(s.synclass())
            ci = ConnectionInfo(pre, post, num, syntype, synclass)
            conns.append(ci)
            if pre not in cells:
                cells.append(pre)
            if post not in cells:
                cells.append(post)

    print_("Total cells %i (%i with connections)" %
           (len(cell_names), len(cells)))
    print_("Total connections found %i " % len(conns))
    P.disconnect()

    if include_nonconnected_cells:
        return cell_names, conns
    else:
        return cells, conns
Example #33
0
    def setUpClass(cls):
        import csv

        cls.neurons = [] #array that holds the names of the 302 neurons at class-level scope

        if not USE_BINARY_DB:
            PyOpenWorm.connect(conf=Data()) # Connect for integrity tests that use PyOpenWorm functions
            cls.g = PyOpenWorm.config('rdf.graph') # declare class-level scope for the database
            cls.g.parse("OpenWormData/WormData.n3", format="n3") # load in the database
        else:
            conf = Configure(**{ "rdf.source" : "ZODB", "rdf.store_conf" : BINARY_DB })
            PyOpenWorm.connect(conf=conf)
            cls.g = PyOpenWorm.config('rdf.graph')

        #grab the list of the names of the 302 neurons

        csvfile = open('OpenWormData/aux_data/neurons.csv', 'r')
        reader = csv.reader(csvfile, delimiter=';', quotechar='|')

        for row in reader:
            if len(row[0]) > 0: # Only saves valid neuron names
                cls.neurons.append(row[0])
Example #34
0
def test_adapt_PatchClamp(data_pool):
    """
    Test that we can map a PatchClamp object to a PyOpenWorm
    PatchClamp object.
    """
    pc = data_pool.get_patch_clamp()

    pca = Adapter.create(pc)

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

    PyOpenWorm.connect()

    pow_dict = {
        'delta_t': pow_obj.delta_t(),
        'duration': pow_obj.duration(),
        'end_time': pow_obj.end_time(),
        'ion_channel': pow_obj.ion_channel(),
        'protocol_end': pow_obj.protocol_end(),
        'protocol_start': pow_obj.protocol_start(),
        'protocol_step': pow_obj.protocol_step(),
        'start_time': pow_obj.start_time(),
    }

    cw_dict = {
        'delta_t': cw_obj.deltat,
        'duration': cw_obj.duration,
        'end_time': cw_obj.end_time,
        'ion_channel': cw_obj.ion_channel,
        'protocol_end': cw_obj.protocol_end,
        'protocol_start': cw_obj.protocol_start,
        'protocol_step': cw_obj.protocol_step,
        'start_time': cw_obj.start_time,
    }

    PyOpenWorm.disconnect()

    assert cw_dict == pow_dict
Example #35
0
def do_insert():
    import sys
    logging = False
    if len(sys.argv) > 1 and sys.argv[1] == '-l':
        logging = True
    P.connect(configFile='default.conf', do_logging=logging)
    try:
        upload_neurons()
        print ("uploaded neurons")
        #upload_muscles()
        print ("uploaded muscles")
        upload_lineage_and_descriptions()
        print ("uploaded lineage and descriptions")
        #upload_synapses()
        print ("uploaded synapses")
        #upload_receptors_and_innexins()
        print ("uploaded receptors and innexins")
        #infer()
        print ("filled in with inferred data")
    except:
        traceback.print_exc()
    finally:
        P.disconnect()
Example #36
0
def do_insert():
    import sys
    logging = False
    if len(sys.argv) > 1 and sys.argv[1] == '-l':
        logging = True
    P.connect(configFile='default.conf', do_logging=logging)
    try:
        upload_muscles()
        print ("uploaded muscles")
        upload_lineage_and_descriptions()
        print ("uploaded lineage and descriptions")
        upload_synapses()
        print ("uploaded synapses")
        upload_receptors_and_innexins()
        print ("uploaded receptors and innexins")
        update_neurons_and_muscles_with_lineage_and_descriptions()
        print ("updated muscles and neurons with cell data")
        infer()
        print ("filled in with inferred data")
    except:
        traceback.print_exc()
    finally:
        P.disconnect()
Example #37
0
 def setUp(self):
     # Set do_logging to True if you like walls of text
     self.TestConfig = Data.open(TEST_CONFIG)
     td = '__tempdir__'
     z = self.TestConfig['rdf.store_conf']
     if z.startswith(td):
         x = z[len(td):]
         h = tempfile.mkdtemp()
         self.TestConfig['rdf.store_conf'] = h + x
     self.delete_dir()
     self.connection = PyOpenWorm.connect(conf=self.TestConfig, do_logging=False)
     self.context = Context(ident='http://example.org/test-context',
                            conf=self.TestConfig)
     typ = type(self)
     if hasattr(typ, 'ctx_classes'):
         if isinstance(dict, typ.ctx_classes):
             self.ctx = self.context(typ.ctx_classes)
         else:
             self.ctx = self.context({x.__name__: x for x in typ.ctx_classes})
Example #38
0
Try running this script and see what it prints out. It takes a while to run
because there are so many connections, so feel free to comment out some of the
neuron names in the arbitrary list declared further below.
"""
from __future__ import absolute_import
from __future__ import print_function
import PyOpenWorm as P
from PyOpenWorm.worm import Worm
from PyOpenWorm.neuron import Neuron
from PyOpenWorm.context import Context
from OpenWormData import BIO_ENT_NS


print("Connecting to the database...")
conn = P.connect('default.conf')

ctx = Context(ident=BIO_ENT_NS['worm0'], conf=conn.conf).stored

#Get the worm object.
worm = ctx(Worm)()

#Extract the network object from the worm object.
net = worm.neuron_network()

#Make a list of some arbitrary neuron names.
some_neuron_names = ["ADAL", "AIBL", "I1R", "PVCR", "DD5"]

#Go through our list and get the neuron object associated with each name.
#Store these in another list.
some_neurons = [ctx(Neuron)(name) for name in some_neuron_names]
Example #39
0
"""
How to get a particular Neuron's gap junctions from the database.
"""

import PyOpenWorm as P
#Connect to existing database.
P.connect()
#Put the Worm's Network object in a variable.
net = P.Worm().get_neuron_network()

#Put a particular Neuron object in a variable ('AVAL' in this example).
aval = net.aneuron('AVAL')

print("Getting all Connections to/from AVAL, and printing the gap junctions")
#We could also put them into an array or do other things with them other than print.
num_gjs = 0
for c in aval.connection():
    #the `one()` returns a string like "gapJunction" instead of "syntype=gapJunction"
    if c.syntype.one() == 'gapJunction':
        num_gjs += 1
        print num_gjs, c
Example #40
0
 def setUp(self):
     PyOpenWorm.connect(configFile='tests/data_integrity_test.conf')
     self.g = PyOpenWorm.config("rdf.graph")
     self.context = Context()
     self.qctx = self.context.stored
Example #41
0
"""

from __future__ import absolute_import
from __future__ import print_function
import PyOpenWorm as P
from PyOpenWorm.evidence import Evidence
from PyOpenWorm.neuron import Neuron
from PyOpenWorm.document import Document
from PyOpenWorm.data import Data
from PyOpenWorm.context import Context

# Create dummy database configuration.
d = Data()

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

ctx = Context(ident='http://example.org/data', conf=conn.conf)
evctx = Context(ident='http://example.org/meta', conf=conn.conf)

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

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

# 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
Example #42
0
 def setUpClass(self):
     PyOpenWorm.connect()
     PyOpenWorm.loadData(skipIfNewer=False)
     PyOpenWorm.disconnect()
     os.chdir('examples')
Example #43
0
 def setUp(self):
     PyOpenWorm.connect(
         conf=Configure(
             **{'rdf.store_conf': 'tests/test.db', 'rdf.source': 'ZODB'}))
     self.g = PyOpenWorm.config("rdf.graph")
def fetch_ma_mapping():
    """Fetch associations between monoamines and their receptors from Bentley data.

    :return: dict from full monoamine names (title case) to cognate receptor gene names (upper case).
    """
    url = BASE_URL + "monoamine_receptor_expression.tsv"
    mapping = defaultdict(set)
    for row in csv.DictReader(decode_lines(urlopen(url)), delimiter='\t'):
        if int(row.get("excluded", 0)):
            continue
        mapping[row["monoamine"].title()].add(row["receptor"].upper())
    return mapping


with P.connect('default.conf') as conn:
    ctx = Context(ident=BIO_ENT_NS['worm0'], conf=conn.conf).stored
    #Get the worm object.
    worm = ctx(Worm)()
    #Extract the network object from the worm object.
    net = worm.neuron_network()

    cell_transmitter_mapping, receptor_cell_mapping = get_mappings()

    ma_t_r_mapping = fetch_ma_mapping()
    ma_edges = list(get_possible_extrasynaptic_edges(cell_transmitter_mapping, ma_t_r_mapping, receptor_cell_mapping))

    np_t_r_mapping = fetch_np_mapping()
    np_edges = list(get_possible_extrasynaptic_edges(cell_transmitter_mapping, np_t_r_mapping, receptor_cell_mapping))

    print('Monamine edges: count={}'.format(len(ma_edges)))
 def setUp(self):
     xfail_without_db()
     self.conn = PyOpenWorm.connect(configFile='tests/data_integrity_test.conf')
     self.g = self.conn.conf["rdf.graph"]
     self.context = Context()
     self.qctx = self.context.stored
 def __init__(self):
     P.connect()
     self.net = P.Worm().get_neuron_network()
     self.all_connections = self.net.synapses()
Example #47
0
 def setUp(self):
     PyOpenWorm.connect(configFile='tests/data_integrity_test.conf')
     self.g = PyOpenWorm.config("rdf.graph")
     self.context = Context()
     self.qctx = self.context.stored
Example #48
0
import PyOpenWorm as P
import rdflib as R
import unittest
import os

P.connect("default.conf")

#create new muscle object
m = P.Muscle()

#save muscle to graph (and infer new triples to it, based on rules)
m.save()

#get the graph associated with th muscle cell
graph = m.rdf.serialize(format="n3")

P.disconnect()

#remove unnecessary files from directory
os.remove("worm.db")
os.remove("worm.db.tmp")
os.remove("worm.db.lock")
os.remove("worm.db.index")

class InferenceTest(unittest.TestCase):

    def testIfInferred(self):
        #this will fail unless "TestClass" is in the graph
        self.failUnless("<http://openworm.org/entities/TestClass>" in graph)

def main():
Example #49
0
 def __init__(self):
     logger.info("Initialising OpenWormReader")
     P.connect()
     self.net = P.Worm().get_neuron_network()
     self.all_connections = self.net.synapses()
     logger.info("Finished initialising OpenWormReader")
import PyOpenWorm
from time import time
from PyOpenWorm.neuron import Neuron
PyOpenWorm.connect(configFile='PyOpenWorm/default.conf')
t0 = time()

print("Neurons:")
print(", ".join(sorted(Neuron().name.get())))

print("Receptors:")
print(", ".join(sorted(Neuron().receptor.get())))
tot = time() - t0
print ("Took {} seconds".format(tot))
Example #51
0
def do_insert(ident, config="default.conf", logging=False, imports_context_ident=None, basedir=aux_data()):

    sources = init_sources()
    extras = init_extra_sources(basedir)
    data_sources_by_key = {x.key: x for x in sources + extras}
    trans_map = init_translators() + init_extra_neuron_data_translators(extras)
    P.connect(configFile=config, do_logging=logging)
    P.config()

    CTX = Context(ident=ident + '-data', imported=(P.CONTEXT,), conf=P.config())

    EVCTX = Context(ident=ident + '-evidence', imported=(P.CONTEXT,), conf=P.config())

    IWCTX = Context(ident=ident, imported=(CTX, EVCTX), conf=P.config())

    imports_context = Context(ident=imports_context_ident, conf=P.config())

    try:
        t0 = time()
        translators = dict()
        remaining = list(trans_map)
        last_remaining = None
        saved_contexts = set([])
        while remaining != last_remaining:
            next_remaining = []
            for t in remaining:
                if not isinstance(t[0], (list, tuple)):
                    source_keys = (t[0],)
                else:
                    source_keys = t[0]

                sources = tuple(data_sources_by_key.get(s) for s in source_keys)
                if None in sources:
                    next_remaining.append(t)
                    continue
                translator_class = t[1]
                if len(t) > 2:
                    output_key = t[2]
                else:
                    output_key = None
                translator = translators.get(translator_class, None)
                if not translator:
                    translator = translator_class()
                    translators[translator_class] = translator

                print('\n'.join('Input({}/{}): {}'.format(i + 1, len(sources), s) for i, s in enumerate(sources)))
                print('Translating with {}'.format(translator))
                orig_wd = os.getcwd()
                os.chdir(basedir)
                try:
                    res = translator(*sources, output_key=output_key)
                finally:
                    os.chdir(orig_wd)

                print('Result: {}'.format(res))
                if isinstance(res, DataWithEvidenceDataSource):
                    res.data_context.save_context(inline_imports=True, saved_contexts=saved_contexts)
                    res.data_context.save_imports(imports_context)
                    res.evidence_context.save_context(inline_imports=True, saved_contexts=saved_contexts)
                    res.evidence_context.save_imports(imports_context)
                    for ctx in res.contexts:
                        raise Exception()

                if res:
                    if res.key:
                        data_sources_by_key[res.key] = res
                    else:
                        data_sources_by_key[res.identifier] = res
            last_remaining = list(remaining)
            remaining = next_remaining
        for x in remaining:
            warn("Failed to process: {}".format(x))

        # attach_neuromlfiles_to_channel()

        t1 = time()
        print("Saving data...")
        graph = P.config('rdf.graph')
        for src in data_sources_by_key.values():
            if isinstance(src, DataWithEvidenceDataSource):
                print('saving', src)
                CTX.add_import(src.data_context)
                EVCTX.add_import(src.evidence_context)
                for ctx in src.contexts:
                    IWCTX.add_import(ctx)
        IWCTX.save_context(graph, saved_contexts=saved_contexts)
        IWCTX.save_imports(imports_context)
        print('imports context size', len(imports_context))
        print("Saved %d triples." % IWCTX.triples_saved)
        t2 = time()

        print("Serializing...")
        serialize_as_nquads()
        t3 = time()
        print("generating objects took", t1 - t0, "seconds")
        print("saving objects took", t2 - t1, "seconds")
        print("serializing objects took", t3 - t2, "seconds")

    except Exception:
        traceback.print_exc()
    finally:
        P.disconnect()
Example #52
0
"""

from __future__ import absolute_import
from __future__ import print_function
import PyOpenWorm as P
from PyOpenWorm.evidence import Evidence
from PyOpenWorm.neuron import Neuron
from PyOpenWorm.document import Document
from PyOpenWorm.data import Data
from PyOpenWorm.context import Context

# Create dummy database configuration.
d = Data({'rdf.source': 'ZODB'})

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

ctx = Context(ident='http://example.org/data')
evctx = Context(ident='http://example.org/meta')

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

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

# 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
Example #53
0
 def setUp(self):
     self.conn = PyOpenWorm.connect(configFile='tests/data_integrity_test.conf')
     self.conf = self.conn.conf
     self.g = self.conf["rdf.graph"]
     self.context = Context(ident="http://openworm.org/data", conf=self.conf)
     self.qctx = self.context.stored