From: Zbigniew Jędrzejewski-S. <zb...@in...> - 2014-04-01 21:12:16
|
Using the print function, instead of the print statement, is the first step to making the code simultaneously Python 2 and Python 3 compatible. print() also has slightly nicer semantics and is more readable, when end=..., sep=... are used, and when arguments span more than one line. --- gui/shell.py | 2 +- python/moose/alternate.py | 17 +++---- python/moose/hdfutil.py | 15 +++--- python/moose/moose.py | 25 +++++----- python/moose/moose_py3k.py | 1 + python/moose/mtypes.py | 3 +- python/moose/multiscale/core/mumbl.py | 2 + python/moose/multiscale/core/simulator.py | 2 + python/moose/multiscale/core/stimulus.py | 4 +- python/moose/multiscale/core/types.py | 2 +- python/moose/multiscale/helper/moose_methods.py | 4 +- .../neuroml/v1.8/GranuleCell/FvsI_Granule98.py | 5 +- .../models/neuroml/v1.8/GranuleCell/Granule98.py | 7 +-- .../neuroml/v1.8/GranuleCell/Granule98_hsolve.py | 9 ++-- .../moose/multiscale/multi_bhalla/diffusionOnly.py | 21 +++++---- python/moose/multiscale/multi_bhalla/lm2.py | 7 +-- python/moose/multiscale/multi_bhalla/loadMulti.py | 53 +++++++++++----------- python/moose/multiscale/multi_bhalla/minimal.py | 3 +- python/moose/multiscale/multi_bhalla/runcell18.py | 16 ++++--- python/moose/multiscale/multi_bhalla/x_compt.py | 3 +- python/moose/multiscale/parser/NetworkML.py | 3 +- python/moose/multiscale/parser/utils.py | 1 + python/moose/neuroml/ChannelML.py | 19 ++++---- python/moose/neuroml/MorphML.py | 23 +++++----- python/moose/neuroml/NetworkML.py | 17 +++---- python/moose/neuroml/NeuroML.py | 7 +-- python/moose/neuroml/utils.py | 11 +++-- python/moose/neuroml2/generated_neuroml.py | 3 +- python/moose/neuroml2/reader.py | 14 +++--- python/moose/neuroml2/test_converter.py | 5 +- python/moose/neuroml2/test_hhfit.py | 19 ++++---- python/moose/neuroml2/test_reader.py | 3 +- python/moose/neuroml2/units.py | 3 +- python/moose/recording.py | 5 +- python/moose/utils.py | 52 +++++++++++---------- python/moose/xmls_to_network/core/load_multi.py | 47 +++++++++---------- python/moose/xmls_to_network/core/multiscale.py | 5 +- .../moose/xmls_to_network/core/neuroml2_parser.py | 3 +- .../moose/xmls_to_network/core/neuroml_to_moose.py | 12 +++-- python/moose/xmls_to_network/parser/nml_parser.py | 3 +- .../generatedNEURON/NeuroMLUtils/NetworkMLNet.py | 5 +- .../NeuroMLUtils/NetworkMLSaxHandler.py | 3 +- .../generatedPyNN/NeuroMLUtils/NetworkMLNet.py | 5 +- .../NeuroMLUtils/NetworkMLSaxHandler.py | 3 +- .../twoNeurons/generatedPyNN/PyNNUtils/Pop.py | 13 +++--- .../generatedPyNN/PyNNUtils/PyNNUtils.py | 5 +- 46 files changed, 271 insertions(+), 219 deletions(-) diff --git a/gui/shell.py b/gui/shell.py index 2eeafb5..5790447 100644 --- a/gui/shell.py +++ b/gui/shell.py @@ -17,7 +17,7 @@ # http://obswww.unige.ch/~revaz/git/old.glups-4.0/glups/shell.py - # Subhasis Ray -__doc__=""" +""" This module implements a QT4 python interpreter widget. It is inspired bu PyCute : http://gerard.vermeulen.free.fr """ diff --git a/python/moose/alternate.py b/python/moose/alternate.py index e54b57f..24a0d41 100644 --- a/python/moose/alternate.py +++ b/python/moose/alternate.py @@ -280,6 +280,7 @@ le(obj) -- list element under object, if no parameter specified, list elements under current working element """ +from __future__ import print_function from functools import partial import warnings from collections import defaultdict @@ -825,7 +826,7 @@ def getCwe(): def pwe(): """Print present working element. Convenience function for GENESIS users.""" - print _moose.getCwe().getPath() + print(_moose.getCwe().getPath()) def connect(src, srcMsg, dest, destMsg, msgType='Single'): """Connect src object's source field specified by srcMsg to @@ -842,9 +843,9 @@ def le(element=None): element = getCwe()[0] elif isinstance(element, str): element = Neutral(element) - print 'Elements under', element.path + print('Elements under', element.path) for ch in element.children: - print ch + print(ch) ce = setCwe @@ -886,18 +887,18 @@ def showfield(element, field='*', showtype=False): value_field_dict = getFieldDict(element.className, 'valueFinfo') max_type_len = max([len(dtype) for dtype in value_field_dict.values()]) max_field_len = max([len(dtype) for dtype in value_field_dict.keys()]) - print - print '[', element.path, ']' + print() + print('[', element.path, ']') for key, dtype in value_field_dict.items(): if dtype == 'bad' or key == 'this' or key == 'dummy' or key == 'me' or dtype.startswith('vector') or 'ObjId' in dtype: continue value = element.oid_.getField(key) if showtype: - print dtype.ljust(max_type_len + 4), - print key.ljust(max_field_len + 4), '=', value + print(dtype.ljust(max_type_len + 4), end=' ') + print(key.ljust(max_field_len + 4), '=', value) else: try: - print field, '=', element.getField(field) + print(field, '=', element.getField(field)) except AttributeError: pass # Genesis silently ignores non existent fields diff --git a/python/moose/hdfutil.py b/python/moose/hdfutil.py index 0f114c3..a17ff5a 100644 --- a/python/moose/hdfutil.py +++ b/python/moose/hdfutil.py @@ -84,6 +84,7 @@ # Code: +from __future__ import print_function import moose as moose__ import numpy as np import h5py as h5 @@ -118,9 +119,9 @@ def get_rec_dtype(em): if em.className in dtype_table: dtype = dtype_table[em.className] else: - print 'Creating entries for class:', obj.className + print('Creating entries for class:', obj.className) fielddict = moose__.getFieldDict(obj.className, 'valueFinfo') - print fielddict + print(fielddict) keys = sorted(list(fielddict.keys())) fields = [] # [('path', 'S1024')] for fieldname in keys: @@ -244,7 +245,7 @@ def savestate(filename=None): for obj in moose__.wildcardFind("/##"): if obj.path.startswith('/Msg') or obj.path.startswith('/class') or obj.className == 'Table' or obj.className == 'TableEntry': continue - print 'Processing:', obj.path, obj.className + print('Processing:', obj.path, obj.className) typeinfo.append((obj.path, obj.className, str(obj.shape), obj[0].parent.path)) objcount += 1 if len(typeinfo) == size_step: @@ -253,9 +254,9 @@ def savestate(filename=None): typeinfo = [] # If we do not yet have dataset for this class, create one and keep it in dict if obj.className not in class_dataset_dict: - print 'Creating entries for class:', obj.className + print('Creating entries for class:', obj.className) fielddict = moose__.getFieldDict(obj.className, 'valueFinfo') - print fielddict + print(fielddict) keys = sorted(list(fielddict.keys())) fields = [] # [('path', 'S1024')] for fieldname in keys: @@ -273,9 +274,9 @@ def savestate(filename=None): ds = class_dataset_dict[obj.className] for entry in obj: fields = [] - print entry.path, + print(entry.path, end=' ') for f in ds.dtype.names: - print 'getting field:', f + print('getting field:', f) entry.getField(f) fields = [f.path if isinstance(f, moose__.ematrix) or isinstance(f, moose__.element) else f for f in fields] class_array_dict[obj.className].append(fields) diff --git a/python/moose/moose.py b/python/moose/moose.py index 92e87d5..af62d19 100644 --- a/python/moose/moose.py +++ b/python/moose/moose.py @@ -31,6 +31,7 @@ # Code: +from __future__ import print_function import cStringIO import warnings import platform @@ -76,7 +77,7 @@ def pwe(): """ pwe_ = _moose.getCwe() - print pwe_.getPath() + print(pwe_.getPath()) return pwe_ def le(el=None): @@ -102,9 +103,9 @@ def le(el=None): el = element(el) elif isinstance(el, ematrix): el = el[0] - print 'Elements under', el.path + print('Elements under', el.path) for ch in el.children: - print ch.path + print(ch.path) ce = setCwe # ce is a GENESIS shorthand for change element. @@ -163,7 +164,7 @@ def showfield(el, field='*', showtype=False): value_field_dict = getFieldDict(el.className, 'valueFinfo') max_type_len = max([len(dtype) for dtype in list(value_field_dict.values())]) max_field_len = max([len(dtype) for dtype in list(value_field_dict.keys())]) - print '\n[', el.path, ']' + print('\n[', el.path, ']') for key, dtype in list(value_field_dict.items()): if dtype == 'bad' or key == 'this' or key == 'dummy' or key == 'me' or dtype.startswith('vector') or 'ObjId' in dtype: continue @@ -173,11 +174,11 @@ def showfield(el, field='*', showtype=False): # The following hack is for handling both Python 2 and # 3. Directly putting the print command in the if/else # clause causes syntax error in both systems. - print typestr, - print key.ljust(max_field_len + 4), '=', value + print(typestr, end=' ') + print(key.ljust(max_field_len + 4), '=', value) else: try: - print field, '=', el.getField(field) + print(field, '=', el.getField(field)) except AttributeError: pass # Genesis silently ignores non existent fields @@ -233,12 +234,12 @@ def showmsg(el): """ obj = element(el) - print 'INCOMING:' + print('INCOMING:') for msg in obj.msgIn: - print msg.e2.path, msg.destFieldsOnE2, '<---', msg.e1.path, msg.srcFieldsOnE1 - print 'OUTGOING:' + print(msg.e2.path, msg.destFieldsOnE2, '<---', msg.e1.path, msg.srcFieldsOnE1) + print('OUTGOING:') for msg in obj.msgOut: - print msg.e1.path, msg.srcFieldsOnE1, '--->', msg.e2.path, msg.destFieldsOnE2 + print(msg.e1.path, msg.srcFieldsOnE1, '--->', msg.e2.path, msg.destFieldsOnE2) def getfielddoc(tokens, indent=''): """Return the documentation for field specified by `tokens`. @@ -390,7 +391,7 @@ def doc(arg, paged=False): if pager: pager(text) else: - print text + print(text) # diff --git a/python/moose/moose_py3k.py b/python/moose/moose_py3k.py index 43dd80b..f4c5302 100644 --- a/python/moose/moose_py3k.py +++ b/python/moose/moose_py3k.py @@ -30,6 +30,7 @@ # Code: +from __future__ import print_function import warnings import platform from collections import defaultdict diff --git a/python/moose/mtypes.py b/python/moose/mtypes.py index 6a3ae57..2f520ad 100644 --- a/python/moose/mtypes.py +++ b/python/moose/mtypes.py @@ -45,6 +45,7 @@ # Code: +from __future__ import print_function import re import moose @@ -142,7 +143,7 @@ def isNeuroML(filename): """ doc = md.parse(filename) for child in doc.childNodes: - print child.nodeName, child.nodeType == child.ELEMENT_NODE + print(child.nodeName, child.nodeType == child.ELEMENT_NODE) if child.nodeType == child.ELEMENT_NODE and \ (child.nodeName == 'networkml' or \ child.nodeName == 'morphml' or \ diff --git a/python/moose/multiscale/core/mumbl.py b/python/moose/multiscale/core/mumbl.py index e6ec650..32e5ca1 100644 --- a/python/moose/multiscale/core/mumbl.py +++ b/python/moose/multiscale/core/mumbl.py @@ -8,6 +8,8 @@ Last modified: Fri Jan 24, 2014 05:27PM """ +from __future__ import print_function + __author__ = "Dilawar Singh" __copyright__ = "Copyright 2013, NCBS Bangalore" __credits__ = ["NCBS Bangalore", "Bhalla Lab"] diff --git a/python/moose/multiscale/core/simulator.py b/python/moose/multiscale/core/simulator.py index bffb2cf..03f519b 100644 --- a/python/moose/multiscale/core/simulator.py +++ b/python/moose/multiscale/core/simulator.py @@ -7,6 +7,8 @@ Last modified: Sat Feb 01, 2014 04:01AM """ +from __future__ import print_function + __author__ = "Dilawar Singh" __copyright__ = "Copyright 2013, NCBS Bangalore" diff --git a/python/moose/multiscale/core/stimulus.py b/python/moose/multiscale/core/stimulus.py index 1cc63db..f144259 100644 --- a/python/moose/multiscale/core/stimulus.py +++ b/python/moose/multiscale/core/stimulus.py @@ -5,6 +5,8 @@ Created on: 2013-11-25 Description: generates stimuous """ +from __future__ import print_function + import random import numpy as np @@ -139,7 +141,7 @@ def timetable_file(filename='timetable.txt', simtime=100): def timetable_demo(): tt_array, sp_array = timetable_nparray() - print sp_array + print(sp_array) tt_file, sp_file = timetable_file() # Create a synchan inside a compartment to demonstrate how to use # TimeTable to send artificial spike events to a synapse. diff --git a/python/moose/multiscale/core/types.py b/python/moose/multiscale/core/types.py index ca3d31e..4ae60c1 100644 --- a/python/moose/multiscale/core/types.py +++ b/python/moose/multiscale/core/types.py @@ -75,4 +75,4 @@ if __name__ == "__main__": for s in b: a.insertUniqueVal(s) - print a + print(a) diff --git a/python/moose/multiscale/helper/moose_methods.py b/python/moose/multiscale/helper/moose_methods.py index f51e4e1..b99b4bd 100644 --- a/python/moose/multiscale/helper/moose_methods.py +++ b/python/moose/multiscale/helper/moose_methods.py @@ -7,6 +7,8 @@ Last modified: Tue Jan 28, 2014 10:31PM """ +from __future__ import print_function + __author__ = "Dilawar Singh" __copyright__ = "Copyright 2013, NCBS Bangalore" __credits__ = ["NCBS Bangalore", "Bhalla Lab"] @@ -135,7 +137,7 @@ def dumpMatchingPaths(path, pat='/##'): def dumpFieldName(path, whichInfo='valueF'): - print path.getFieldNames(whichInfo+'info') + print(path.getFieldNames(whichInfo+'info')) def writeGraphviz(pat='/##', filename=None, filterList=[]): '''This is a generic function. It takes the the pattern, search for paths diff --git a/python/moose/multiscale/models/neuroml/v1.8/GranuleCell/FvsI_Granule98.py b/python/moose/multiscale/models/neuroml/v1.8/GranuleCell/FvsI_Granule98.py index 8544793..5c0d2a4 100755 --- a/python/moose/multiscale/models/neuroml/v1.8/GranuleCell/FvsI_Granule98.py +++ b/python/moose/multiscale/models/neuroml/v1.8/GranuleCell/FvsI_Granule98.py @@ -8,6 +8,7 @@ ## Modification Date: 2012-07-12 ######################################################################################## +from __future__ import print_function import os os.environ['NUMPTHREADS'] = '1' import sys @@ -56,8 +57,8 @@ for currenti in currentvec: spikesList = spikesList[where(spikesList>0.0)[0]] spikesNow = len(spikesList) else: spikesNow = 0.0 - print "For injected current =",currenti,\ - "number of spikes in",RUNTIME,"seconds =",spikesNow + print("For injected current =", currenti, + "number of spikes in", RUNTIME, "seconds =", spikesNow) freqList.append( spikesNow/float(RUNTIME) ) ## plot the F vs I curve of the neuron diff --git a/python/moose/multiscale/models/neuroml/v1.8/GranuleCell/Granule98.py b/python/moose/multiscale/models/neuroml/v1.8/GranuleCell/Granule98.py index 6f4215d..4d3bb4b 100755 --- a/python/moose/multiscale/models/neuroml/v1.8/GranuleCell/Granule98.py +++ b/python/moose/multiscale/models/neuroml/v1.8/GranuleCell/Granule98.py @@ -6,6 +6,7 @@ python testNeuroML_Gran98.py (other channels and morph xml files are already present in this same directory). The soma name below is hard coded for gran98, else any other file can be used by modifying this script. """ +from __future__ import print_function import os os.environ['NUMPTHREADS'] = '1' import sys @@ -31,9 +32,9 @@ def loadGran98NeuroML_L123(filename): somaIKCa = setupTable('somaIKCa',moose.HHChannel(soma_path+'/Gran_KCa_98'),'Gk') #KDrX = setupTable('ChanX',moose.HHChannel(soma_path+'/Gran_KDr_98'),'X') soma = moose.Compartment(soma_path) - print "Reinit MOOSE ... " + print("Reinit MOOSE ... ") resetSim(['/elec','/cells'],simdt,plotdt,simmethod='ee') # from moose.utils - print "Running ... " + print("Running ... ") moose.start(runtime) tvec = arange(0.0,runtime,plotdt) plot(tvec,somaVm.vec[1:]) @@ -50,7 +51,7 @@ def loadGran98NeuroML_L123(filename): title('KCa current (A)') xlabel('time (s)') ylabel('') - print "Showing plots ..." + print("Showing plots ...") show() filename = "GranuleCell.net.xml" diff --git a/python/moose/multiscale/models/neuroml/v1.8/GranuleCell/Granule98_hsolve.py b/python/moose/multiscale/models/neuroml/v1.8/GranuleCell/Granule98_hsolve.py index c9b2172..3fae9ad 100755 --- a/python/moose/multiscale/models/neuroml/v1.8/GranuleCell/Granule98_hsolve.py +++ b/python/moose/multiscale/models/neuroml/v1.8/GranuleCell/Granule98_hsolve.py @@ -7,6 +7,7 @@ python testNeuroML_Gran98.py The soma name below is hard coded for gran98, else any other file can be used by modifying this script. """ +from __future__ import print_function import os os.environ['NUMPTHREADS'] = '1' import sys @@ -34,11 +35,11 @@ def loadGran98NeuroML_L123(filename): ## Am not able to plot KDr gating variable X when running under hsolve #KDrX = setupTable('ChanX',moose.HHChannel(soma_path+'/Gran_KDr_98'),'X') - print "Reinit MOOSE ... " - print cells_path + print("Reinit MOOSE ... ") + print(cells_path) resetSim(['/elec',cells_path], simdt, plotdt, simmethod='hsolve') - print "Running ... " + print("Running ... ") moose.start(runtime) tvec = arange(0.0,runtime*2.0,plotdt) tvec = tvec[ : somaVm.vec.size ] @@ -56,7 +57,7 @@ def loadGran98NeuroML_L123(filename): title('soma KCa current') xlabel('time (s)') ylabel('KCa current (A)') - print "Showing plots ..." + print("Showing plots ...") show() filename = "GranuleCell.net.xml" diff --git a/python/moose/multiscale/multi_bhalla/diffusionOnly.py b/python/moose/multiscale/multi_bhalla/diffusionOnly.py index 9965ce2..636f9de 100644 --- a/python/moose/multiscale/multi_bhalla/diffusionOnly.py +++ b/python/moose/multiscale/multi_bhalla/diffusionOnly.py @@ -30,6 +30,7 @@ # Code: +from __future__ import print_function import sys sys.path.append('../../python') import os @@ -95,7 +96,7 @@ def loadChem( neuroCompt, spineCompt, psdCompt ): assert( spineCompt.volume == 1.0 ) assert( psdCompt.volume == 1.0 ) assert( neuroCompt.mesh.num == 1 ) - print 'volume = ', neuroCompt.mesh[0].volume + print('volume = ', neuroCompt.mesh[0].volume) #assert( neuroCompt.mesh[0].volume == 1.0 ) #an unfortunate mismatch # So we'll have to resize the volumes of the current compartments to the @@ -114,7 +115,7 @@ def loadChem( neuroCompt, spineCompt, psdCompt ): pCaCaM.concInit = 0.001 dCaCaM = moose.element( '/model/model/kinetics/PSD/Ca_CaM' ) sCaCaM = moose.element( '/model/model/kinetics/SPINE/Ca_CaM' ) - print "CaCaM.concInit[p,s,d] = ", pCaCaM.concInit, sCaCaM.concInit, dCaCaM.concInit + print("CaCaM.concInit[p,s,d] = ", pCaCaM.concInit, sCaCaM.concInit, dCaCaM.concInit) #moose.delete( moose.ematrix( '/model/model/kinetics/SPINE/Ca_CaM' ) ) #CaCaM2 = moose.element( '/model/model/kinetics/SPINE/Ca_CaM' ) #CaCaM2.concInit = 0.001 @@ -123,20 +124,20 @@ def loadChem( neuroCompt, spineCompt, psdCompt ): oldS = moose.element( '/model/chem/compartment_1' ) oldP = moose.element( '/model/chem/compartment_2' ) oldN = moose.element( '/model/chem/kinetics' ) - print 'oldvols[p,s,d] = ', oldP.volume, oldS.volume, oldN.volume - print 'newvols[p,s,d] = ', psdCompt.mesh[0].volume, spineCompt.mesh[0].volume, neuroCompt.mesh[0].volume + print('oldvols[p,s,d] = ', oldP.volume, oldS.volume, oldN.volume) + print('newvols[p,s,d] = ', psdCompt.mesh[0].volume, spineCompt.mesh[0].volume, neuroCompt.mesh[0].volume) oldN.volume = neuroCompt.mesh[0].volume oldS.volume = spineCompt.mesh[0].volume oldP.volume = psdCompt.mesh[0].volume - print 'after redoing vols' - print "CaCaM.concInit[p,s,d] = ", pCaCaM.concInit, sCaCaM.concInit, dCaCaM.concInit + print('after redoing vols') + print("CaCaM.concInit[p,s,d] = ", pCaCaM.concInit, sCaCaM.concInit, dCaCaM.concInit) moveCompt( '/model/chem/kinetics/SPINE', oldS, spineCompt ) moveCompt( '/model/chem/kinetics/PSD', oldP, psdCompt ) # Need to do the DEND last because the oldN is /kinetics, # and it will be deleted. moveCompt( '/model/chem/kinetics/DEND', oldN, neuroCompt ) - print 'after moving to new compts' - print "CaCaM.concInit[p,s,d] = ", pCaCaM.concInit, sCaCaM.concInit, dCaCaM.concInit + print('after moving to new compts') + print("CaCaM.concInit[p,s,d] = ", pCaCaM.concInit, sCaCaM.concInit, dCaCaM.concInit) def makeNeuroMeshModel(): diffLength = 20e-6 # But we only want diffusion over part of the model. @@ -198,7 +199,7 @@ def makeNeuroMeshModel(): moose.connect( pm, 'remesh', pmksolve, 'remesh' ) #print "psd: nv=", pmksolve.numLocalVoxels, ", nav=", pmksolve.numAllVoxels, pmksolve.numVarPools, pmksolve.numAllPools # - print 'neuroMeshvolume = ', neuroCompt.mesh[0].volume + print('neuroMeshvolume = ', neuroCompt.mesh[0].volume) #print 'Assigning the cell model' # Now to set up the model. @@ -423,7 +424,7 @@ def testNeuroMeshMultiscale(): moose.start( 0.5 ) dumpPlots( plotName ) - print 'All done' + print('All done') def main(): diff --git a/python/moose/multiscale/multi_bhalla/lm2.py b/python/moose/multiscale/multi_bhalla/lm2.py index f27640e..d290d1b 100644 --- a/python/moose/multiscale/multi_bhalla/lm2.py +++ b/python/moose/multiscale/multi_bhalla/lm2.py @@ -25,6 +25,7 @@ # Code: +from __future__ import print_function import sys import os os.environ['NUMPTHREADS'] = '1' @@ -66,13 +67,13 @@ def addPlot( objpath, field, plot ): tab = moose.Table( '/graphs/' + plot ) obj = moose.element( objpath ) if obj.className == 'Neutral': - print "addPlot failed: object is a Neutral: ", objpath + print("addPlot failed: object is a Neutral: ", objpath) return moose.element( '/' ) else: moose.connect( tab, 'requestData', obj, field ) return tab else: - print "addPlot failed: object not found: ", objpath + print("addPlot failed: object not found: ", objpath) return moose.element( '/' ) def dumpPlots( fname ): @@ -298,7 +299,7 @@ def testNeuroMeshMultiscale(): moose.start( 0.5 ) dumpPlots( plotName ) - print 'All done' + print('All done') def main(): diff --git a/python/moose/multiscale/multi_bhalla/loadMulti.py b/python/moose/multiscale/multi_bhalla/loadMulti.py index 10a26cd..6b4a563 100644 --- a/python/moose/multiscale/multi_bhalla/loadMulti.py +++ b/python/moose/multiscale/multi_bhalla/loadMulti.py @@ -24,6 +24,7 @@ # Code: +from __future__ import print_function import sys sys.path.append('../../python') import os @@ -66,14 +67,14 @@ def addPlot( objpath, field, plot ): tab = moose.Table( '/graphs/' + plot ) obj = moose.element( objpath ) if obj.className == 'Neutral': - print "addPlot failed: object is a Neutral: ", objpath + print("addPlot failed: object is a Neutral: ", objpath) return moose.element( '/' ) else: #print "object was found: ", objpath, obj.className moose.connect( tab, 'requestData', obj, field ) return tab else: - print "addPlot failed: object not found: ", objpath + print("addPlot failed: object not found: ", objpath) return moose.element( '/' ) def dumpPlots( fname ): @@ -102,7 +103,7 @@ def loadChem( neuroCompt, spineCompt, psdCompt ): assert( spineCompt.volume == 1.0 ) assert( psdCompt.volume == 1.0 ) assert( neuroCompt.mesh.num == 1 ) - print 'volume = ', neuroCompt.mesh[0].volume + print('volume = ', neuroCompt.mesh[0].volume) #assert( neuroCompt.mesh[0].volume == 1.0 ) #an unfortunate mismatch # So we'll have to resize the volumes of the current compartments to the @@ -114,33 +115,33 @@ def loadChem( neuroCompt, spineCompt, psdCompt ): oldN = moose.element( '/model/chem/kinetics' ) oldS = moose.element( '/model/chem/compartment_1' ) oldP = moose.element( '/model/chem/compartment_2' ) - print 'old NSP vols = ', oldN.volume, oldS.volume, oldP.volume - print 'old NSP.mesh vols = ', oldN.mesh[0].volume, oldS.mesh[0].volume, oldP.mesh[0].volume - print 'new NSP vols = ', neuroCompt.volume, spineCompt.volume, psdCompt.volume - print 'new NSP.mesh vols = ', neuroCompt.mesh[0].volume, spineCompt.mesh[0].volume, psdCompt.mesh[0].volume + print('old NSP vols = ', oldN.volume, oldS.volume, oldP.volume) + print('old NSP.mesh vols = ', oldN.mesh[0].volume, oldS.mesh[0].volume, oldP.mesh[0].volume) + print('new NSP vols = ', neuroCompt.volume, spineCompt.volume, psdCompt.volume) + print('new NSP.mesh vols = ', neuroCompt.mesh[0].volume, spineCompt.mesh[0].volume, psdCompt.mesh[0].volume) for i in moose.wildcardFind( '/model/chem/#/#/#/transloc#' ): - print i[0].name, i[0].Kf, i[0].Kb, i[0].kf, i[0].kb + print(i[0].name, i[0].Kf, i[0].Kb, i[0].kf, i[0].kb) tr0 = moose.element( '/model/chem/kinetics/SPINE/CaMKII_BULK/tr0[6]' ) - print "tr0 rates = ", tr0.Kf, tr0.Kb, tr0.kf, tr0.kb + print("tr0 rates = ", tr0.Kf, tr0.Kb, tr0.kf, tr0.kb) oldN.volume = neuroCompt.mesh[0].volume oldS.volume = spineCompt.mesh[0].volume oldP.volume = psdCompt.mesh[0].volume #oldN.volume = neuroCompt.volume #oldS.volume = spineCompt.volume #oldP.volume = psdCompt.volume - print 'old NSP vols = ', oldN.volume, oldS.volume, oldP.volume - print 'old NSP.mesh vols = ', oldN.mesh[0].volume, oldS.mesh[0].volume, oldP.mesh[0].volume - print 'new NSP vols = ', neuroCompt.volume, spineCompt.volume, psdCompt.volume - print 'new NSP.mesh vols = ', neuroCompt.mesh[0].volume, spineCompt.mesh[0].volume, psdCompt.mesh[0].volume - print "tr0 rates = ", tr0.Kf, tr0.Kb, tr0.kf, tr0.kb + print('old NSP vols = ', oldN.volume, oldS.volume, oldP.volume) + print('old NSP.mesh vols = ', oldN.mesh[0].volume, oldS.mesh[0].volume, oldP.mesh[0].volume) + print('new NSP vols = ', neuroCompt.volume, spineCompt.volume, psdCompt.volume) + print('new NSP.mesh vols = ', neuroCompt.mesh[0].volume, spineCompt.mesh[0].volume, psdCompt.mesh[0].volume) + print("tr0 rates = ", tr0.Kf, tr0.Kb, tr0.kf, tr0.kb) for i in moose.wildcardFind( '/model/chem/#/#/#/transloc#' ): - print i[0].name, i[0].Kf, i[0].Kb, i[0].kf, i[0].kb + print(i[0].name, i[0].Kf, i[0].Kb, i[0].kf, i[0].kb) moveCompt( '/model/chem/kinetics/PSD', oldP, psdCompt ) moveCompt( '/model/chem/kinetics/SPINE', oldS, spineCompt ) moveCompt( '/model/chem/kinetics/DEND', oldN, neuroCompt ) - print "aftermove tr0 rates = ", tr0.Kf, tr0.Kb, tr0.kf, tr0.kb + print("aftermove tr0 rates = ", tr0.Kf, tr0.Kb, tr0.kf, tr0.kb) for i in moose.wildcardFind( '/model/chem/#/#/#/transloc#' ): - print i[0].name, i[0].Kf, i[0].Kb, i[0].kf, i[0].kb + print(i[0].name, i[0].Kf, i[0].Kb, i[0].kf, i[0].kb) def makeNeuroMeshModel(): diffLength = 20e-6 # But we only want diffusion over part of the model. @@ -256,14 +257,14 @@ def makeNeuroMeshModel(): path = '/model/elec/spine_head_14_' + str( i + 1 ) + '/NMDA_Ca_conc' elecCa = moose.element( path ) moose.connect( elecCa, 'concOut', adaptCa[i], 'input', 'Single' ) - print path + print(path) moose.connect( adaptCa, 'outputSrc', chemCa, 'set_conc', 'OneToOne' ) adaptCa.inputOffset = 0.0 # adaptCa.outputOffset = 0.00008 # 80 nM offset in chem. adaptCa.scale = 1e-5 # 520 to 0.0052 mM - print adaptCa.inputOffset - print adaptCa.outputOffset - print adaptCa.scale + print(adaptCa.inputOffset) + print(adaptCa.outputOffset) + print(adaptCa.scale) #print adaptCa.outputOffset #print adaptCa.scale @@ -348,9 +349,9 @@ def makeChemPlots(): addPlot( '/model/chem/spineMesh/SPINE/CaMKII_BULK/foo[6]', 'get_conc', 'spine_foo' ) bar = moose.element( '/model/chem/psdMesh/PSD/CaMKII_PSD/bar[6]' ) foo = moose.element( '/model/chem/spineMesh/SPINE/CaMKII_BULK/foo[6]' ) - print "bar,foo vols = ", bar.volume, foo.volume, bar.concInit, foo.concInit + print("bar,foo vols = ", bar.volume, foo.volume, bar.concInit, foo.concInit) tr0 = moose.element( '/model/chem/spineMesh/SPINE/CaMKII_BULK/tr0[6]' ) - print "tr0 rates = ", tr0.Kf, tr0.Kb, tr0.kf, tr0.kb + print("tr0 rates = ", tr0.Kf, tr0.Kb, tr0.kf, tr0.kb) signal.signal( signal.SIGUSR1, do_nothing) @@ -361,9 +362,9 @@ def testNeuroMeshMultiscale(): plotName = 'nm.plot' makeNeuroMeshModel() - print "after model is completely done" + print("after model is completely done") for i in moose.wildcardFind( '/model/chem/#/#/#/transloc#' ): - print i[0].name, i[0].Kf, i[0].Kb, i[0].kf, i[0].kb + print(i[0].name, i[0].Kf, i[0].Kb, i[0].kf, i[0].kb) """ for i in moose.wildcardFind( '/model/chem/##[ISA=PoolBase]' ): @@ -427,7 +428,7 @@ def testNeuroMeshMultiscale(): moose.start( 0.5 ) dumpPlots( plotName ) - print 'All done' + print('All done') def main(): diff --git a/python/moose/multiscale/multi_bhalla/minimal.py b/python/moose/multiscale/multi_bhalla/minimal.py index 278bc11..7eb1a7a 100644 --- a/python/moose/multiscale/multi_bhalla/minimal.py +++ b/python/moose/multiscale/multi_bhalla/minimal.py @@ -27,6 +27,7 @@ # Code: +from __future__ import print_function import sys sys.path.append('../../python') import os @@ -350,7 +351,7 @@ def testNeuroMeshMultiscale(): moose.start( 0.5 ) dumpPlots( plotName ) - print 'All done' + print('All done') def main(): diff --git a/python/moose/multiscale/multi_bhalla/runcell18.py b/python/moose/multiscale/multi_bhalla/runcell18.py index 3387680..387f2b3 100644 --- a/python/moose/multiscale/multi_bhalla/runcell18.py +++ b/python/moose/multiscale/multi_bhalla/runcell18.py @@ -1,3 +1,5 @@ +from __future__ import print_function + # First pass at loading and running a cell model import os os.environ['NUMPTHREADS'] = '1' @@ -38,7 +40,7 @@ soma.inject = 2e-10 moose.connect( tab, 'requestData', soma, 'get_Vm' ) capool = moose.element( '/cell/soma/Ca_conc' ) moose.connect( catab, 'requestData', capool, 'get_Ca' ) -print 1 +print(1) dt = 50e-6 moose.setClock( 0, dt ) moose.setClock( 1, dt ) @@ -49,12 +51,12 @@ moose.useClock( 1, '/cell/##[ISA=Compartment]', 'process' ) moose.useClock( 2, '/cell/##[ISA!=Compartment]', 'process' ) moose.useClock( 3, '/graphs/soma,/graphs/ca', 'process' ) -print 2 +print(2) moose.reinit() -print 3 +print(3) moose.start( 0.1 ) dumpPlots( '50usec.plot' ) -print 4 +print(4) moose.reinit() hsolve = moose.HSolve( '/cell/hsolve' ) moose.useClock( 1, '/cell/hsolve', 'process' ) @@ -62,10 +64,10 @@ hsolve.dt = dt hsolve.target = '/cell/soma' moose.reinit() moose.reinit() -print 5 +print(5) moose.start( 0.1 ) -print 6 +print(6) dumpPlots( 'h50usec.plot' ) -print 7 +print(7) diff --git a/python/moose/multiscale/multi_bhalla/x_compt.py b/python/moose/multiscale/multi_bhalla/x_compt.py index bd46996..a108545 100644 --- a/python/moose/multiscale/multi_bhalla/x_compt.py +++ b/python/moose/multiscale/multi_bhalla/x_compt.py @@ -31,6 +31,7 @@ # Code: +from __future__ import print_function import sys sys.path.append('../../python') import os @@ -362,7 +363,7 @@ def testNeuroMeshMultiscale(): moose.start( 0.5 ) dumpPlots( plotName ) - print 'All done' + print('All done') def main(): diff --git a/python/moose/multiscale/parser/NetworkML.py b/python/moose/multiscale/parser/NetworkML.py index eb60e28..9ec1562 100644 --- a/python/moose/multiscale/parser/NetworkML.py +++ b/python/moose/multiscale/parser/NetworkML.py @@ -22,6 +22,7 @@ """ +from __future__ import print_function from xml.etree import cElementTree as ET import string import os @@ -527,7 +528,7 @@ class NetworkML(object): except KeyError as e: debug.printDebug("ERR", "Failed find key {0}".format(e) , frame = inspect.currentframe()) - print self.projectionDict.keys() + print(self.projectionDict.keys()) sys.exit(0) properties = connection.findall('./{'+nmu.nml_ns+'}properties') diff --git a/python/moose/multiscale/parser/utils.py b/python/moose/multiscale/parser/utils.py index ad9f051..18e2ae2 100644 --- a/python/moose/multiscale/parser/utils.py +++ b/python/moose/multiscale/parser/utils.py @@ -11,6 +11,7 @@ while still including certain others. indent(...) is an in-place prettyprint formatter copied from http://effbot.org/zone/element-lib.htm """ +from __future__ import print_function from xml.etree import cElementTree as ET from xml.etree import ElementTree as slowET from math import * diff --git a/python/moose/neuroml/ChannelML.py b/python/moose/neuroml/ChannelML.py index c560aa3..79ca6f9 100644 --- a/python/moose/neuroml/ChannelML.py +++ b/python/moose/neuroml/ChannelML.py @@ -11,6 +11,7 @@ readChannelMLFromFile(...) to load a standalone ChannelML file (synapse/channel) readChannelML(...) / readSynapseML to load from an xml.etree xml element (could be part of a larger NeuroML file). """ +from __future__ import print_function from xml.etree import cElementTree as ET import string import os, sys @@ -49,10 +50,10 @@ class ChannelML(): Tfactor = 1.0 Gfactor = 1.0 else: - print "wrong units", units,": exiting ..." + print("wrong units", units,": exiting ...") sys.exit(1) moose.Neutral('/library') # creates /library in MOOSE tree; elif present, wraps - if utils.neuroml_debug: print "loading synapse :",synapseElement.attrib['name'],"into /library ." + if utils.neuroml_debug: print("loading synapse :",synapseElement.attrib['name'],"into /library .") moosesynapse = moose.SynChan('/library/'+synapseElement.attrib['name']) doub_exp_syn = synapseElement.find('./{'+self.cml+'}doub_exp_syn') moosesynapse.Ek = float(doub_exp_syn.attrib['reversal_potential'])*Vfactor @@ -81,11 +82,11 @@ class ChannelML(): Gfactor = 1.0 concfactor = 1.0 else: - print "wrong units", units,": exiting ..." + print("wrong units", units,": exiting ...") sys.exit(1) moose.Neutral('/library') # creates /library in MOOSE tree; elif present, wraps channel_name = channelElement.attrib['name'] - if utils.neuroml_debug: print "loading channel :", channel_name,"into /library ." + if utils.neuroml_debug: print("loading channel :", channel_name,"into /library .") IVrelation = channelElement.find('./{'+self.cml+'}current_voltage_relation') concdep = IVrelation.find('./{'+self.cml+'}conc_dependence') if concdep is None: @@ -113,7 +114,7 @@ class ChannelML(): gates = IVrelation.findall('./{'+self.cml+'}gate') if len(gates)>3: - print "Sorry! Maximum x, y, and z (three) gates are possible in MOOSE/Genesis" + print("Sorry! Maximum x, y, and z (three) gates are possible in MOOSE/Genesis") sys.exit() gate_full_name = [ 'gateX', 'gateY', 'gateZ' ] # These are the names that MOOSE uses to create gates. ## if impl_prefs tag is present change VMIN, VMAX and NDIVS @@ -195,7 +196,7 @@ class ChannelML(): if fn_name in ['alpha','beta']: self.make_cml_function(transition, fn_name, concdep) else: - print "Unsupported transition ", name + print("Unsupported transition ", name) sys.exit() time_course = gate.find('./{'+self.cml+'}time_course') @@ -326,10 +327,10 @@ class ChannelML(): ionSpecies = ionConcElement.find('./{'+self.cml+'}ion_species') if ionSpecies is not None: if not 'ca' in ionSpecies.attrib['name']: - print "Sorry, I cannot handle non-Ca-ion pools. Exiting ..." + print("Sorry, I cannot handle non-Ca-ion pools. Exiting ...") sys.exit(1) capoolName = ionConcElement.attrib['name'] - print "loading Ca pool :",capoolName,"into /library ." + print("loading Ca pool :",capoolName,"into /library .") caPool = moose.CaConc('/library/'+capoolName) poolModel = ionConcElement.find('./{'+self.cml+'}decaying_pool_model') caPool.CaBasal = float(poolModel.attrib['resting_conc']) * concfactor @@ -370,7 +371,7 @@ class ChannelML(): expr_string = self.replace(expr_string, 'beta', 'self.beta(v'+ca_name+')') fn = self.make_function( fn_name, fn_type, expr_string=expr_string, concdep=concdep ) else: - print "Unsupported function type ", fn_type + print("Unsupported function type ", fn_type) sys.exit() def make_function(self, fn_name, fn_type, **kwargs): diff --git a/python/moose/neuroml/MorphML.py b/python/moose/neuroml/MorphML.py index 14282c9..6982c87 100644 --- a/python/moose/neuroml/MorphML.py +++ b/python/moose/neuroml/MorphML.py @@ -13,6 +13,7 @@ It is assumed that any channels and synapses referred to by above MorphML have already been loaded under that same name in /library in MOOSE (use ChannelML loader). """ +from __future__ import print_function from xml.etree import cElementTree as ET # cELementTree is mostly API-compatible but faster than ElementTree import string import sys @@ -43,7 +44,7 @@ class MorphML(): returns { cellname1 : segDict, ... } see readMorphML(...) for segDict """ - print filename + print(filename) tree = ET.parse(filename) neuroml_element = tree.getroot() cellsDict = {} @@ -66,7 +67,7 @@ class MorphML(): self.length_factor = 1.0 cellname = cell.attrib["name"] moose.Neutral('/library') # creates /library in MOOSE tree; elif present, wraps - print "loading cell :", cellname,"into /library ." + print("loading cell :", cellname,"into /library .") if 'IF' in cellname: # if integrate & fire -- hackjob -- rectify moosecell = moose.LeakyIaF('/library/'+cellname) @@ -186,7 +187,7 @@ class MorphML(): ## with the potential synapses on this segment, in function set_compartment_param(..) self.segDict[running_segid] = [running_comp.name,(running_comp.x0,running_comp.y0,running_comp.z0),\ (running_comp.x,running_comp.y,running_comp.z),running_comp.diameter,running_comp.length,[]] - if neuroml_utils.neuroml_debug: print 'Set up compartment/section', running_comp.name + if neuroml_utils.neuroml_debug: print('Set up compartment/section', running_comp.name) ############################################### #### load cablegroups into a dictionary @@ -284,7 +285,7 @@ class MorphML(): if mechanism.attrib.has_key("passive_conductance"): if mechanism.attrib['passive_conductance'] in ["true",'True','TRUE']: passive = True - print "Loading mechanism ", mechanismname + print("Loading mechanism ", mechanismname) ## ONLY creates channel if at least one parameter (like gmax) is specified in the xml ## Neuroml does not allow you to specify all default values. ## However, granule cell example in neuroconstruct has Ca ion pool without @@ -308,8 +309,8 @@ class MorphML(): self.set_group_compartment_param(cell, cellname, parameter,\ 'inject', Ifactor*float(parameter.attrib["value"]), self.bio) else: - print "WARNING: Yo programmer of MorphML! You didn't implement parameter ",\ - parametername, " in mechanism ",mechanismname + print("WARNING: Yo programmer of MorphML! You didn't implement parameter ",\ + parametername, " in mechanism ",mechanismname) else: if parametername in ['gmax']: gmaxval = float(eval(parameter.attrib["value"],{"__builtins__":None},{})) @@ -323,8 +324,8 @@ class MorphML(): 'thick', self.length_factor*float(parameter.attrib["value"]),\ self.bio, mechanismname) else: - print "WARNING: Yo programmer of MorphML import! You didn't implement parameter ",\ - parametername, " in mechanism ",mechanismname + print("WARNING: Yo programmer of MorphML import! You didn't implement parameter ",\ + parametername, " in mechanism ",mechanismname) #### Connect the Ca pools and channels #### Am connecting these at the very end so that all channels and pools have been created #### Note: this function is in moose.utils not moose.neuroml.utils ! @@ -344,7 +345,7 @@ class MorphML(): self.set_group_compartment_param(cell, cellname, potential_syn_loc,\ 'spikegen_type', potential_syn_loc.attrib['synapse_type'], self.nml, mechanismname='spikegen') - print "Finished loading into library, cell: ",cellname + print("Finished loading into library, cell: ",cellname) return {cellname:self.segDict} def set_group_compartment_param(self, cell, cellname, parameter, name, value, grouptype, mechanismname=None): @@ -375,7 +376,7 @@ class MorphML(): elif name == 'initVm': compartment.initVm = value elif name == 'inject': - print compartment.name, 'inject', value, 'A.' + print(compartment.name, 'inject', value, 'A.') compartment.inject = value elif mechanismname is 'synapse': # synapse being added to the compartment ## these are potential locations, we do not actually make synapses. @@ -465,4 +466,4 @@ class MorphML(): ## Later, when calling connect_CaConc, ## B is set for caconc based on thickness of Ca shell and compartment l and dia. ## OR based on the Mstring phi under CaConc path. - if neuroml_utils.neuroml_debug: print "Setting ",name," for ",compartment.path," value ",value + if neuroml_utils.neuroml_debug: print("Setting ",name," for ",compartment.path," value ",value) diff --git a/python/moose/neuroml/NetworkML.py b/python/moose/neuroml/NetworkML.py index ccce65a..a521ed9 100644 --- a/python/moose/neuroml/NetworkML.py +++ b/python/moose/neuroml/NetworkML.py @@ -11,6 +11,7 @@ readNetworkMLFromFile(...) to load a standalone NetworkML file, OR readNetworkML(...) to load from an xml.etree xml element (could be part of a larger NeuroML file). """ +from __future__ import print_function from xml.etree import cElementTree as ET import string import os @@ -47,12 +48,12 @@ class NetworkML(): these synapses receive file based pre-synaptic events, not presynaptically connected to a cell. """ - print "reading file ... ", filename + print("reading file ... ", filename) tree = ET.parse(filename) root_element = tree.getroot() - print "Tweaking model ... " + print("Tweaking model ... ") tweak_model(root_element, params) - print "Loading model into MOOSE ... " + print("Loading model into MOOSE ... ") return self.readNetworkML(root_element,cellSegmentDict,params,root_element.attrib['lengthUnits']) def readNetworkML(self,network,cellSegmentDict,params={},lengthUnits="micrometer"): @@ -67,11 +68,11 @@ class NetworkML(): self.network = network self.cellSegmentDict = cellSegmentDict self.params = params - print "creating populations ... " + print("creating populations ... ") self.createPopulations() # create cells - print "creating connections ... " + print("creating connections ... ") self.createProjections() # create connections - print "creating inputs in /elec ... " + print("creating inputs in /elec ... ") self.createInputs() # create inputs (only current pulse supported) return (self.populationDict,self.projectionDict) @@ -132,7 +133,7 @@ class NetworkML(): for population in self.network.findall(".//{"+nml_ns+"}population"): cellname = population.attrib["cell_type"] populationname = population.attrib["name"] - print "loading", populationname + print("loading", populationname) ## if cell does not exist in library load it from xml file if not moose.exists('/library/'+cellname): mmlR = MorphML(self.nml_params) @@ -218,7 +219,7 @@ class NetworkML(): Tfactor = 1.0 for projection in self.network.findall(".//{"+nml_ns+"}projection"): projectionname = projection.attrib["name"] - print "setting",projectionname + print("setting",projectionname) source = projection.attrib["source"] target = projection.attrib["target"] self.projectionDict[projectionname] = (source,target,[]) diff --git a/python/moose/neuroml/NeuroML.py b/python/moose/neuroml/NeuroML.py index 3712c9b..4594c0a 100644 --- a/python/moose/neuroml/NeuroML.py +++ b/python/moose/neuroml/NeuroML.py @@ -21,6 +21,7 @@ use the separate Channel, Morph and NetworkML loaders in moose.neuroml.<...> . For testing, you can also call this from the command line with a neuroML file as argument. """ +from __future__ import print_function import moose from moose.utils import * from xml.etree import cElementTree as ET @@ -44,7 +45,7 @@ class NeuroML(): Returns (populationDict,projectionDict), see doc string of NetworkML.readNetworkML() for details. """ - print "Loading neuroml file ... ", filename + print("Loading neuroml file ... ", filename) moose.Neutral('/library') # creates /library in MOOSE tree; elif present, wraps tree = ET.parse(filename) root_element = tree.getroot() @@ -58,7 +59,7 @@ class NeuroML(): self.temperature = float(meta_property.attrib['value']) self.temperature_default = False if self.temperature_default: - print "Using default temperature of", self.temperature,"degrees Celsius." + print("Using default temperature of", self.temperature,"degrees Celsius.") self.nml_params = { 'temperature':self.temperature, 'model_dir':self.model_dir, @@ -96,7 +97,7 @@ def loadNeuroML_L123(filename): if __name__ == "__main__": if len(sys.argv)<2: - print "You need to specify the neuroml filename." + print("You need to specify the neuroml filename.") sys.exit(1) loadNeuroML_L123(sys.argv[1]) diff --git a/python/moose/neuroml/utils.py b/python/moose/neuroml/utils.py index 39ab789..3a1e3c0 100644 --- a/python/moose/neuroml/utils.py +++ b/python/moose/neuroml/utils.py @@ -11,6 +11,7 @@ while still including certain others. indent(...) is an in-place prettyprint formatter copied from http://effbot.org/zone/element-lib.htm """ +from __future__ import print_function from xml.etree import cElementTree as ET from xml.etree import ElementTree as slowET from math import * @@ -139,7 +140,7 @@ def keepOnlyInclude(network, onlyInclude): includeCellsDict = {includepopname:includecellids} ## projections 'includeProjs' will be pruned later, keeping connections to second order cells. includeProjs = [] - print "removing obviously extra connections in ... " + print("removing obviously extra connections in ... ") for projection in network.findall(".//{"+nml_ns+"}projection"): projname = projection.attrib['name'] includeProj = False @@ -153,7 +154,7 @@ def keepOnlyInclude(network, onlyInclude): includeProjs.append(projection) source = projection.attrib["source"] target = projection.attrib["target"] - print projname, source, target + print(projname, source, target) connections = projection.find(".//{"+nml_ns+"}connections") if connections is not None: for connection in connections.findall(".//{"+nml_ns+"}connection"): @@ -190,7 +191,7 @@ def keepOnlyInclude(network, onlyInclude): for key in includeCellsDict: includeCellsDict[key] = set(includeCellsDict[key]) - print "removing extra cells ... " + print("removing extra cells ... ") ### remove the cells that are not in includeCellsDict populations = network.find(".//{"+nml_ns+"}populations") for population in network.findall(".//{"+nml_ns+"}population"): @@ -208,8 +209,8 @@ def keepOnlyInclude(network, onlyInclude): ### Prune the 'includeProjections' that we skipped pruning before, ### while keeping connections to second order cells! for projection in includeProjs: - print "removing projection",projection.attrib['name'],\ - "keeping second-order connections." + print("removing projection",projection.attrib['name'],\ + "keeping second-order connections.") source = projection.attrib["source"] target = projection.attrib["target"] ## boolean: True if includeCellsDict has key source diff --git a/python/moose/neuroml2/generated_neuroml.py b/python/moose/neuroml2/generated_neuroml.py index b319f6c..f03fa42 100644 --- a/python/moose/neuroml2/generated_neuroml.py +++ b/python/moose/neuroml2/generated_neuroml.py @@ -5,6 +5,7 @@ # Generated Sun Jul 28 10:18:38 2013 by generateDS.py version 2.10a. # +from __future__ import print_function import sys import getopt import re as re_ @@ -14143,7 +14144,7 @@ Usage: python <Parser>.py [ -s ] <in_xml_file> def usage(): - print USAGE_TEXT + print(USAGE_TEXT) sys.exit(1) diff --git a/python/moose/neuroml2/reader.py b/python/moose/neuroml2/reader.py index fa0596e..28d7d5e 100644 --- a/python/moose/neuroml2/reader.py +++ b/python/moose/neuroml2/reader.py @@ -51,6 +51,8 @@ TODO: handle include statements (start with simple ion channel prototype includes. """ + +from __future__ import print_function import sys, os from itertools import izip from urllib2 import urlopen @@ -235,7 +237,7 @@ class NML2Reader(object): according to NeuroML2 cell `nmlcell`.""" bp = nmlcell.biophysicalProperties if bp is None: - print 'Warning: %s in %s has no biophysical properties' % (nmlcell.id, self.filename) + print('Warning: %s in %s has no biophysical properties' % (nmlcell.id, self.filename)) return self.importMembraneProperties(nmlcell, moosecell, bp.membraneProperties) self.importIntracellularProperties(nmlcell, moosecell, bp.intracellularProperties) @@ -302,7 +304,7 @@ class NML2Reader(object): try: ionChannel = self.id_to_ionChannel[chdens.ionChannel] except KeyError: - print 'No channel with id', chdens.ionChannel + print('No channel with id', chdens.ionChannel) continue if ionChannel.type_ == 'ionChannelPassive': for seg in segments: @@ -351,7 +353,7 @@ class NML2Reader(object): error = None break if error: - print 'Last exception:', error + print('Last exception:', error) raise IOError('Could not read any of the locations: %s' % (paths)) def importIonChannels(self, doc, vmin=-120e-3, vmax=40e-3, vdivs=3000): @@ -411,9 +413,9 @@ class NML2Reader(object): else: name = concModel.id ca = moose.CaConc('%s/%s' % (self.lib.path, id)) - print '11111', concModel.restingConc - print '2222', concModel.decayConstant - print '33333', concModel.shellThickness + print('11111', concModel.restingConc) + print('2222', concModel.decayConstant) + print('33333', concModel.shellThickness) ca.CaBasal = SI(concModel.restingConc) ca.tau = SI(concModel.decayConstant) diff --git a/python/moose/neuroml2/test_converter.py b/python/moose/neuroml2/test_converter.py index 4a56dcb..3145551 100644 --- a/python/moose/neuroml2/test_converter.py +++ b/python/moose/neuroml2/test_converter.py @@ -47,6 +47,7 @@ # Code: +from __future__ import print_function import os import numpy as np import uuid @@ -59,7 +60,7 @@ from neuroml.writers import NeuroMLWriter outdir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tmp') if not os.access(outdir, os.F_OK): - print 'Creating output directory', outdir + print('Creating output directory', outdir) os.mkdir(outdir) class TestConvertMorphology(unittest.TestCase): @@ -91,7 +92,7 @@ class TestConvertMorphology(unittest.TestCase): doc.id = 'TestNeuroMLDocument' fname = os.path.join(outdir, 'test_morphology_conversion.nml') NeuroMLWriter.write(doc, fname) - print 'Wrote', fname + print('Wrote', fname) if __name__ == '__main__': unittest.main() diff --git a/python/moose/neuroml2/test_hhfit.py b/python/moose/neuroml2/test_hhfit.py index 1e72fde..31156ff 100644 --- a/python/moose/neuroml2/test_hhfit.py +++ b/python/moose/neuroml2/test_hhfit.py @@ -47,6 +47,7 @@ # Code: +from __future__ import print_function import os import numpy as np import uuid @@ -82,9 +83,9 @@ class TestFindRateFn(unittest.TestCase): self.p_dblexp = p_dblexp def test_sigmoid(self): - print 'Testing sigmoid' + print('Testing sigmoid') fn, params = hhfit.find_ratefn(self.v_array, self.sigmoid) - print 'Sigmoid params original:', self.p_sigmoid, 'detected:', params + print('Sigmoid params original:', self.p_sigmoid, 'detected:', params) pylab.plot(self.v_array, self.sigmoid, 'y-', self.v_array, hhfit.sigmoid(self.v_array, *self.p_sigmoid), 'b--', self.v_array, fn(self.v_array, *params), 'r-.') @@ -95,9 +96,9 @@ class TestFindRateFn(unittest.TestCase): self.assertAlmostEqual(rms_error/max(abs(self.sigmoid)), 0.0, places=3) def test_exponential(self): - print 'Testing exponential' + print('Testing exponential') fn, params = hhfit.find_ratefn(self.v_array, self.exp) - print 'Exponential params original:', self.p_exp, 'detected:', params + print('Exponential params original:', self.p_exp, 'detected:', params) fnval = hhfit.exponential(self.v_array, *params) pylab.plot(self.v_array, self.exp, 'y-', self.v_array, hhfit.exponential(self.v_array, *self.p_exp), 'b--', @@ -112,13 +113,13 @@ class TestFindRateFn(unittest.TestCase): # pylab.plot(self.v_array, self.exp, 'b-') # pylab.plot(self.v_array, fnval, 'r-.') # pylab.show() - print rms_error, rms_error/max(self.exp) + print(rms_error, rms_error/max(self.exp)) self.assertAlmostEqual(rms_error/max(self.exp), 0.0, places=3) def test_linoid(self): - print 'Testing linoid' + print('Testing linoid') fn, params = hhfit.find_ratefn(self.v_array, self.linoid) - print 'Linoid params original:', self.p_linoid, 'detected:', params + print('Linoid params original:', self.p_linoid, 'detected:', params) pylab.plot(self.v_array, self.linoid, 'y-', self.v_array, hhfit.linoid(self.v_array, *self.p_linoid), 'b--', self.v_array, fn(self.v_array, *params), 'r-.') @@ -133,7 +134,7 @@ class TestFindRateFn(unittest.TestCase): # self.assertAlmostEqual(abs(err/orig), 0.0, places=2) def test_dblexponential(self): - print 'Testing double exponential' + print('Testing double exponential') fn, params = hhfit.find_ratefn(self.v_array, self.dblexp) fnval = fn(self.v_array, *params) pylab.plot(self.v_array, self.dblexp, 'y-', @@ -143,7 +144,7 @@ class TestFindRateFn(unittest.TestCase): pylab.show() self.assertEqual(hhfit.double_exp, fn) rms_error = np.sqrt(np.mean((self.dblexp - fnval)**2)) - print params, rms_error + print(params, rms_error) self.assertAlmostEqual(rms_error/max(self.dblexp), 0.0, places=3) diff --git a/python/moose/neuroml2/test_reader.py b/python/moose/neuroml2/test_reader.py index 8e68525..7afb232 100644 --- a/python/moose/neuroml2/test_reader.py +++ b/python/moose/neuroml2/test_reader.py @@ -45,6 +45,7 @@ # Code: +from __future__ import print_function import unittest import numpy as np import moose @@ -110,7 +111,7 @@ class TestFullCell(unittest.TestCase): def test_protochans(self): """TODO: verify the prototype cahnnel.""" for chan_id in moose.wildcardFind('/library/##[ISA=HHChannel]'): - print moose.element(chan_id) + print(moose.element(chan_id)) def test_HHChannels(self): """Verify copied channel in membrane properties.""" diff --git a/python/moose/neuroml2/units.py b/python/moose/neuroml2/units.py index 5e4a66d..cd89edf 100644 --- a/python/moose/neuroml2/units.py +++ b/python/moose/neuroml2/units.py @@ -49,6 +49,7 @@ in NeuroMLCoreDimensions.xml) to SI """ +from __future__ import print_function import numpy as np import re from xml.etree import ElementTree @@ -67,7 +68,7 @@ def SI(expression): try: match = magnitude_regex.match(expression) except Exception, e: - print 'Error %s with expression: %s' % (e, expression) + print('Error %s with expression: %s' % (e, expression)) raise(e) magnitude = float(match.group(0)) unitstr = re.split(magnitude_regex, expression)[-1] diff --git a/python/moose/recording.py b/python/moose/recording.py index 1cba449..312d1d9 100644 --- a/python/moose/recording.py +++ b/python/moose/recording.py @@ -1,3 +1,4 @@ +from __future__ import print_function import moose as _moose _tick = 8 @@ -218,7 +219,7 @@ def show( try: from matplotlib import pyplot as plt except ImportError: - print "Warning: recording.show(): Cannot find 'matplotlib'. Not showing plots." + print("Warning: recording.show(): Cannot find 'matplotlib'. Not showing plots.") return plots = _selectedPlots( selected ) @@ -230,7 +231,7 @@ def show( if not combine: plt.figure() - print _label( plot ) + print(_label( plot )) plt.plot( plot.time, plot.values, label = _label( plot ) ) plt.legend() diff --git a/python/moose/utils.py b/python/moose/utils.py index 15e86d9..61d5a2e 100644 --- a/python/moose/utils.py +++ b/python/moose/utils.py @@ -1,6 +1,8 @@ #!/usr/bin/env python """Utility functions for MOOSE """ +from __future__ import print_function + __author__ = 'Subhasis Ray and Aditya Gilra, NCBS' __date__ = '21 November 2012' @@ -61,7 +63,7 @@ def readtable(table, filename, separ... [truncated message content] |