INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
scan an ABF directory and subdirectory. Try to do this just once. Returns ABF files SWHLab files and groups. | def scanABFfolder(abfFolder):
"""
scan an ABF directory and subdirectory. Try to do this just once.
Returns ABF files, SWHLab files, and groups.
"""
assert os.path.isdir(abfFolder)
filesABF=forwardSlash(sorted(glob.glob(abfFolder+"/*.*")))
filesSWH=[]
if os.path.exists(abfFolder+"/swhlab... |
given an ABF file name return the ABF of its parent. | def getParent(abfFname):
"""given an ABF file name, return the ABF of its parent."""
child=os.path.abspath(abfFname)
files=sorted(glob.glob(os.path.dirname(child)+"/*.*"))
parentID=abfFname #its own parent
for fname in files:
if fname.endswith(".abf") and fname.replace(".abf",".TIF") in file... |
given an ABF and the groups dict return the ID of its parent. | def getParent2(abfFname,groups):
"""given an ABF and the groups dict, return the ID of its parent."""
if ".abf" in abfFname:
abfFname=os.path.basename(abfFname).replace(".abf","")
for parentID in groups.keys():
if abfFname in groups[parentID]:
return parentID
return abfFname |
given an ABF find the parent return that line of experiments. txt | def getNotesForABF(abfFile):
"""given an ABF, find the parent, return that line of experiments.txt"""
parent=getParent(abfFile)
parent=os.path.basename(parent).replace(".abf","")
expFile=os.path.dirname(abfFile)+"/experiment.txt"
if not os.path.exists(expFile):
return "no experiment file"
... |
given a list of ALL files ( not just ABFs ) return a dict [ ID ] = [ ID ID ID ]. Parents are determined if a. abf matches a. TIF. This is made to assign children files to parent ABF IDs. | def getABFgroups(files):
"""
given a list of ALL files (not just ABFs), return a dict[ID]=[ID,ID,ID].
Parents are determined if a .abf matches a .TIF.
This is made to assign children files to parent ABF IDs.
"""
children=[]
groups={}
for fname in sorted(files):
if fname.endswith(... |
given a list of files return a dict [ ID ] = [ files ]. This is made to assign children files to parent ABF IDs. | def getIDfileDict(files):
"""
given a list of files, return a dict[ID]=[files].
This is made to assign children files to parent ABF IDs.
"""
d={}
orphans=[]
for fname in files:
if fname.endswith(".abf"):
d[os.path.basename(fname)[:-4]]=[]
for fname in files:
i... |
given a path or list of files return ABF IDs. | def getIDsFromFiles(files):
"""given a path or list of files, return ABF IDs."""
if type(files) is str:
files=glob.glob(files+"/*.*")
IDs=[]
for fname in files:
if fname[-4:].lower()=='.abf':
ext=fname.split('.')[-1]
IDs.append(os.path.basename(fname).replace('.'+... |
May be given an ABF object or filename. | def inspectABF(abf=exampleABF,saveToo=False,justPlot=False):
"""May be given an ABF object or filename."""
pylab.close('all')
print(" ~~ inspectABF()")
if type(abf) is str:
abf=swhlab.ABF(abf)
swhlab.plot.new(abf,forceNewFigure=True)
if abf.sweepInterval*abf.sweeps<60*5: #shorter than 5 ... |
return an FTP object after logging in. | def ftp_login(folder=None):
"""return an "FTP" object after logging in."""
pwDir=os.path.realpath(__file__)
for i in range(3):
pwDir=os.path.dirname(pwDir)
pwFile = os.path.join(pwDir,"passwd.txt")
print(" -- looking for login information in:\n [%s]"%pwFile)
try:
with open(pwFi... |
upload everything from localFolder into the current FTP folder. | def ftp_folder_match(ftp,localFolder,deleteStuff=True):
"""upload everything from localFolder into the current FTP folder."""
for fname in glob.glob(localFolder+"/*.*"):
ftp_upload(ftp,fname)
return |
Only scott should do this. Upload new version to site. | def version_upload(fname,username="nibjb"):
"""Only scott should do this. Upload new version to site."""
print("popping up pasword window...")
password=TK_askPassword("FTP LOGIN","enter password for %s"%username)
if not password:
return
print("username:",username)
print("password:","*"*(... |
use the GUI to ask for a string. | def TK_askPassword(title="input",msg="type here:"):
"""use the GUI to ask for a string."""
root = tkinter.Tk()
root.withdraw() #hide tk window
root.attributes("-topmost", True) #always on top
root.lift() #bring to top
value=tkinter.simpledialog.askstring(title,msg)
root.destroy()
return ... |
use the GUI to pop up a message. | def TK_message(title,msg):
"""use the GUI to pop up a message."""
root = tkinter.Tk()
root.withdraw() #hide tk window
root.attributes("-topmost", True) #always on top
root.lift() #bring to top
tkinter.messagebox.showwarning(title, msg)
root.destroy() |
use the GUI to ask YES or NO. | def TK_ask(title,msg):
"""use the GUI to ask YES or NO."""
root = tkinter.Tk()
root.attributes("-topmost", True) #always on top
root.withdraw() #hide tk window
result=tkinter.messagebox.askyesno(title,msg)
root.destroy()
return result |
Convert weird TIF files into web - friendly versions. Auto contrast is applied ( saturating lower and upper 0. 1% ). make saveAs True to save as. TIF. png make saveAs False and it won t save at all make saveAs someFile. jpg to save it as a different path/ format | def image_convert(fname,saveAs=True,showToo=False):
"""
Convert weird TIF files into web-friendly versions.
Auto contrast is applied (saturating lower and upper 0.1%).
make saveAs True to save as .TIF.png
make saveAs False and it won't save at all
make saveAs "someFile.jpg" to save i... |
check out the arguments and figure out what to do. | def processArgs():
"""check out the arguments and figure out what to do."""
if len(sys.argv)<2:
print("\n\nERROR:")
print("this script requires arguments!")
print('try "python command.py info"')
return
if sys.argv[1]=='info':
print("import paths:\n ","\n ".join(sys.p... |
An AP will be detected by a upslope that exceeds 50V/ s. Analyzed too. if type ( sweep ) is int graph int ( sweep ) if sweep == None process all sweeps sweep. | def detect(abf,sweep=None,threshold_upslope=50,dT=.1,saveToo=True):
"""
An AP will be detected by a upslope that exceeds 50V/s. Analyzed too.
if type(sweep) is int, graph int(sweep)
if sweep==None, process all sweeps sweep.
"""
if type(sweep) is int:
sweeps=[sweep]
else:
... |
On the current ( setSweep () ) sweep calculate things like accomodation. Only call directly just for demonstrating how it works by making a graph. Or call this if you want really custom T1 and T2 ( multiple per sweep ) This is called by default with default T1 and T2. Manually call it again for custom. | def analyzeAPgroup(abf=exampleABF,T1=None,T2=None,plotToo=False):
"""
On the current (setSweep()) sweep, calculate things like accomodation.
Only call directly just for demonstrating how it works by making a graph.
Or call this if you want really custom T1 and T2 (multiple per sweep)
This is calle... |
after running detect () and abf. SAP is populated this checks it. | def check_AP_group(abf=exampleABF,sweep=0):
"""
after running detect() and abf.SAP is populated, this checks it.
"""
abf.setSweep(sweep)
swhlab.plot.new(abf,title="sweep %d (%d pA)"%(abf.currentSweep,abf.protoSeqY[1]))
swhlab.plot.sweep(abf)
SAP=cm.matrixToDicts(abf.SAP[sweep])
if "T1" i... |
given a sweep and a time point return the AP array for that AP. APs will be centered in time by their maximum upslope. | def analyzeAP(Y,dY,I,rate,verbose=False):
"""
given a sweep and a time point, return the AP array for that AP.
APs will be centered in time by their maximum upslope.
"""
Ims = int(rate/1000) #Is per MS
IsToLook=5*Ims #TODO: clarify this, ms until downslope is over
upslope=np.max(dY[I:I+IsToL... |
Plotting for an eyeball check of AP detection in the given sweep. | def check_sweep(abf,sweep=None,dT=.1):
"""Plotting for an eyeball check of AP detection in the given sweep."""
if abf.APs is None:
APs=[]
else:
APs=cm.matrixToDicts(abf.APs)
if sweep is None or len(sweep)==0: #find the first sweep with >5APs in it
for sweepNum in range(abf.sweep... |
return list of time points ( sec ) of all AP events in experiment. | def get_AP_timepoints(abf):
"""return list of time points (sec) of all AP events in experiment."""
col=abf.APs.dtype.names.index("expT")
timePoints=[]
for i in range(len(abf.APs)):
timePoints.append(abf.APs[i][col])
return timePoints |
X | def check_AP_raw(abf,n=10):
"""X"""
timePoints=get_AP_timepoints(abf)[:n] #first 10
if len(timePoints)==0:
return
swhlab.plot.new(abf,True,title="AP shape (n=%d)"%n,xlabel="ms")
Ys=abf.get_data_around(timePoints,padding=.2)
Xs=(np.arange(len(Ys[0]))-len(Ys[0])/2)*1000/abf.rate
for i ... |
X | def check_AP_deriv(abf,n=10):
"""X"""
timePoints=get_AP_timepoints(abf)[:10] #first 10
if len(timePoints)==0:
return
swhlab.plot.new(abf,True,title="AP velocity (n=%d)"%n,xlabel="ms",ylabel="V/S")
pylab.axhline(-50,color='r',lw=2,ls="--",alpha=.2)
pylab.axhline(-100,color='r',lw=2,ls="--... |
X | def check_AP_phase(abf,n=10):
"""X"""
timePoints=get_AP_timepoints(abf)[:10] #first 10
if len(timePoints)==0:
return
swhlab.plot.new(abf,True,title="AP phase (n=%d)"%n,xlabel="mV",ylabel="V/S")
Ys=abf.get_data_around(timePoints,msDeriv=.1,padding=.005)
Xs=abf.get_data_around(timePoints,p... |
provide all stats on the first AP. | def stats_first(abf):
"""provide all stats on the first AP."""
msg=""
for sweep in range(abf.sweeps):
for AP in abf.APs[sweep]:
for key in sorted(AP.keys()):
if key[-1] is "I" or key[-2:] in ["I1","I2"]:
continue
msg+="%s = %s\n"%(key,A... |
returns Xs Ys ( the key ) and sweep #s for every AP found. | def get_values(abf,key="freq",continuous=False):
"""returns Xs, Ys (the key), and sweep #s for every AP found."""
Xs,Ys,Ss=[],[],[]
for sweep in range(abf.sweeps):
for AP in cm.matrixToDicts(abf.APs):
if not AP["sweep"]==sweep:
continue
Ys.append(AP[key])
... |
return average of a feature divided by sweep. | def getAvgBySweep(abf,feature,T0=None,T1=None):
"""return average of a feature divided by sweep."""
if T1 is None:
T1=abf.sweepLength
if T0 is None:
T0=0
data = [np.empty((0))]*abf.sweeps
for AP in cm.dictFlat(cm.matrixToDicts(abf.APs)):
if T0<AP['sweepT']<T1:
val... |
return a list of [ stamp project ] elements. | def readLog(fname="workdays.csv",onlyAfter=datetime.datetime(year=2017,month=1,day=1)):
"""return a list of [stamp, project] elements."""
with open(fname) as f:
raw=f.read().split("\n")
efforts=[] #date,nickname
for line in raw[1:]:
line=line.strip().split(",")
date=dateti... |
sometimes a huge file takes several seconds to copy over. This will hang until the file is copied ( file size is stable ). | def waitTillCopied(fname):
"""
sometimes a huge file takes several seconds to copy over.
This will hang until the file is copied (file size is stable).
"""
lastSize=0
while True:
thisSize=os.path.getsize(fname)
print("size:",thisSize)
if lastSize==thisSize:
pr... |
continuously monitor a folder for new abfs and try to analyze them. This is intended to watch only one folder but can run multiple copies. | def lazygo(watchFolder='../abfs/',reAnalyze=False,rebuildSite=False,
keepGoing=True,matching=False):
"""
continuously monitor a folder for new abfs and try to analyze them.
This is intended to watch only one folder, but can run multiple copies.
"""
abfsKnown=[]
while True:
pr... |
chunkMs should be ~50 ms or greater. bin sizes must be equal to or multiples of the data resolution. transients smaller than the expected RMS will be silenced. | def phasicTonic(self,m1=None,m2=None,chunkMs=50,quietPercentile=10,
histResolution=.5,plotToo=False,rmsExpected=5):
"""
chunkMs should be ~50 ms or greater.
bin sizes must be equal to or multiples of the data resolution.
transients smaller than the expected RMS will ... |
To make plots like AP frequency over original trace. dataI = [ i ] #the i of the sweep dataY = [ 1. 234 ] #something like inst freq | def values_above_sweep(abf,dataI,dataY,ylabel="",useFigure=None):
"""
To make plots like AP frequency over original trace.
dataI=[i] #the i of the sweep
dataY=[1.234] #something like inst freq
"""
xOffset = abf.currentSweep*abf.sweepInterval
if not useFigure: #just passing the figure makes i... |
easy way to plot a gain function. | def gain(abf):
"""easy way to plot a gain function."""
Ys=np.nan_to_num(swhlab.ap.getAvgBySweep(abf,'freq'))
Xs=abf.clampValues(abf.dataX[int(abf.protoSeqX[1]+.01)])
swhlab.plot.new(abf,title="gain function",xlabel="command current (pA)",
ylabel="average inst. freq. (Hz)")
pylab.... |
Given two time points ( seconds ) return IV data. Optionally plots a fancy graph ( with errorbars ) Returns [[ AV ] [ SD ]] for the given range. | def IV(abf,T1,T2,plotToo=True,color='b'):
"""
Given two time points (seconds) return IV data.
Optionally plots a fancy graph (with errorbars)
Returns [[AV],[SD]] for the given range.
"""
rangeData=abf.average_data([[T1,T2]]) #get the average data per sweep
AV,SD=rangeData[:,0,0],rangeData[:,... |
draw vertical lines at comment points. Defaults to seconds. | def comments(abf,minutes=False):
"""draw vertical lines at comment points. Defaults to seconds."""
if not len(abf.commentTimes):
return
for i in range(len(abf.commentTimes)):
t,c = abf.commentTimes[i],abf.commentTags[i]
if minutes:
t=t/60
pylab.axvline(t,lw=1,colo... |
Plot two channels of current sweep ( top/ bottom ). | def dual(ABF):
"""Plot two channels of current sweep (top/bottom)."""
new(ABF)
pylab.subplot(211)
pylab.title("Input A (channel 0)")
ABF.channel=0
sweep(ABF)
pylab.subplot(212)
pylab.title("Input B (channel 1)")
ABF.channel=1
sweep(ABF) |
Load a particular sweep then plot it. If sweep is None or False just plot current dataX/ dataY. If rainbow it ll make it color coded prettily. | def sweep(ABF,sweep=None,rainbow=True,alpha=None,protocol=False,color='b',
continuous=False,offsetX=0,offsetY=0,minutes=False,
decimate=None,newFigure=False):
"""
Load a particular sweep then plot it.
If sweep is None or False, just plot current dataX/dataY.
If rainbow, it'... |
stamp the bottom with file info. | def annotate(abf):
"""stamp the bottom with file info."""
msg="SWHLab %s "%str(swhlab.VERSION)
msg+="ID:%s "%abf.ID
msg+="CH:%d "%abf.channel
msg+="PROTOCOL:%s "%abf.protoComment
msg+="COMMAND: %d%s "%(abf.holding,abf.units)
msg+="GENERATED:%s "%'{0:%Y-%m-%d %H:%M:%S}'.format(datetime.dateti... |
makes a new matplotlib figure with default dims and DPI. Also labels it with pA or mV depending on ABF. | def new(ABF,forceNewFigure=False,title=None,xlabel=None,ylabel=None):
"""
makes a new matplotlib figure with default dims and DPI.
Also labels it with pA or mV depending on ABF.
"""
if len(pylab.get_fignums()) and forceNewFigure==False:
#print("adding to existing figure")
return
... |
Save the pylab figure somewhere. If fname == False show it instead. Height force > dpi force if a tag is given instead of a filename save it alongside the ABF | def save(abf,fname=None,tag=None,width=700,close=True,facecolor='w',
resize=True):
"""
Save the pylab figure somewhere.
If fname==False, show it instead.
Height force > dpi force
if a tag is given instead of a filename, save it alongside the ABF
"""
if len(pylab.gca().get_lines... |
if the module is in this path load it from the local folder. | def tryLoadingFrom(tryPath,moduleName='swhlab'):
"""if the module is in this path, load it from the local folder."""
if not 'site-packages' in swhlab.__file__:
print("loaded custom swhlab module from",
os.path.dirname(swhlab.__file__))
return # no need to warn if it's already outsi... |
Called to update the state of the iterator. This methods receives the set of task ids from the previous set of tasks together with the launch information to allow the output values to be parsed using the output_extractor. This data is then used to determine the next desired point in the parameter space by calling the _... | def update(self, tids, info):
"""
Called to update the state of the iterator. This methods
receives the set of task ids from the previous set of tasks
together with the launch information to allow the output
values to be parsed using the output_extractor. This data is then
... |
When dynamic not all argument values may be available. | def show(self):
"""
When dynamic, not all argument values may be available.
"""
copied = self.copy()
enumerated = [el for el in enumerate(copied)]
for (group_ind, specs) in enumerated:
if len(enumerated) > 1: print("Group %d" % group_ind)
ordering ... |
Summarizes the trace of values used to update the DynamicArgs and the arguments subsequently returned. May be used to implement the summary method. | def _trace_summary(self):
"""
Summarizes the trace of values used to update the DynamicArgs
and the arguments subsequently returned. May be used to
implement the summary method.
"""
for (i, (val, args)) in enumerate(self.trace):
if args is StopIteration:
... |
Takes as input a list or tuple of two elements. First the value returned by incrementing by stepsize followed by the value returned after a stepsize decrement. | def _update_state(self, vals):
"""
Takes as input a list or tuple of two elements. First the
value returned by incrementing by 'stepsize' followed by the
value returned after a 'stepsize' decrement.
"""
self._steps_complete += 1
if self._steps_complete == self.max... |
protocol: unknown. | def proto_unknown(theABF):
"""protocol: unknown."""
abf=ABF(theABF)
abf.log.info("analyzing as an unknown protocol")
plot=ABFplot(abf)
plot.rainbow=False
plot.title=None
plot.figure_height,plot.figure_width=SQUARESIZE,SQUARESIZE
plot.kwargs["lw"]=.5
plot.figure_chronological()
pl... |
protocol: IC ramp for AP shape analysis. | def proto_0111(theABF):
"""protocol: IC ramp for AP shape analysis."""
abf=ABF(theABF)
abf.log.info("analyzing as an IC ramp")
# AP detection
ap=AP(abf)
ap.detect()
# also calculate derivative for each sweep
abf.derivative=True
# create the multi-plot figure
plt.figure(figsize... |
protocol: gain function of some sort. step size and start at are pA. | def proto_gain(theABF,stepSize=25,startAt=-100):
"""protocol: gain function of some sort. step size and start at are pA."""
abf=ABF(theABF)
abf.log.info("analyzing as an IC ramp")
plot=ABFplot(abf)
plot.kwargs["lw"]=.5
plot.title=""
currents=np.arange(abf.sweeps)*stepSize-startAt
# AP d... |
protocol: membrane test. | def proto_0201(theABF):
"""protocol: membrane test."""
abf=ABF(theABF)
abf.log.info("analyzing as a membrane test")
plot=ABFplot(abf)
plot.figure_height,plot.figure_width=SQUARESIZE/2,SQUARESIZE/2
plot.figure_sweeps()
# save it
plt.tight_layout()
frameAndSave(abf,"membrane test")
... |
protocol: MTIV. | def proto_0202(theABF):
"""protocol: MTIV."""
abf=ABF(theABF)
abf.log.info("analyzing as MTIV")
plot=ABFplot(abf)
plot.figure_height,plot.figure_width=SQUARESIZE,SQUARESIZE
plot.title=""
plot.kwargs["alpha"]=.6
plot.figure_sweeps()
# frame to uppwer/lower bounds, ignoring peaks from... |
protocol: vast IV. | def proto_0203(theABF):
"""protocol: vast IV."""
abf=ABF(theABF)
abf.log.info("analyzing as a fast IV")
plot=ABFplot(abf)
plot.title=""
m1,m2=.7,1
plt.figure(figsize=(SQUARESIZE,SQUARESIZE/2))
plt.subplot(121)
plot.figure_sweeps()
plt.axvspan(m1,m2,color='r',ec=None,alpha=.1)
... |
protocol: repeated IC ramps. | def proto_0303(theABF):
"""protocol: repeated IC ramps."""
abf=ABF(theABF)
abf.log.info("analyzing as a halorhodopsin (2s pulse)")
# show average voltage
proto_avgRange(theABF,0.2,1.2)
plt.close('all')
# show stacked sweeps
plt.figure(figsize=(8,8))
for sweep in abf.setsweeps():
... |
protocol: repeated IC steps. | def proto_0304(theABF):
"""protocol: repeated IC steps."""
abf=ABF(theABF)
abf.log.info("analyzing as repeated current-clamp step")
# prepare for AP analysis
ap=AP(abf)
# calculate rest potential
avgVoltagePerSweep = [];
times = []
for sweep in abf.setsweeps():
avgVoltageP... |
experiment: generic VC time course experiment. | def proto_avgRange(theABF,m1=None,m2=None):
"""experiment: generic VC time course experiment."""
abf=ABF(theABF)
abf.log.info("analyzing as a fast IV")
if m1 is None:
m1=abf.sweepLength
if m2 is None:
m2=abf.sweepLength
I1=int(abf.pointsPerSec*m1)
I2=int(abf.pointsPerSec*m2... |
given a filename or ABF object try to analyze it. | def analyze(fname=False,save=True,show=None):
"""given a filename or ABF object, try to analyze it."""
if fname and os.path.exists(fname.replace(".abf",".rst")):
print("SKIPPING DUE TO RST FILE")
return
swhlab.plotting.core.IMAGE_SAVE=save
if show is None:
if cm.isIpython():
... |
call processAbf () for every ABF in a folder. | def processFolder(abfFolder):
"""call processAbf() for every ABF in a folder."""
if not type(abfFolder) is str or not len(abfFolder)>3:
return
files=sorted(glob.glob(abfFolder+"/*.abf"))
for i,fname in enumerate(files):
print("\n\n\n### PROCESSING {} of {}:".format(i,len(files)),os.path.... |
automatically generate a single representative image for an ABF. If saveAs is given ( full path of a jpg of png file ) the image will be saved. Otherwise the image will pop up in a matplotlib window. | def processAbf(abfFname,saveAs=False,dpi=100,show=True):
"""
automatically generate a single representative image for an ABF.
If saveAs is given (full path of a jpg of png file), the image will be saved.
Otherwise, the image will pop up in a matplotlib window.
"""
if not type(abfFname) is str or... |
frame the current matplotlib plot with ABF info and optionally save it. Note that this is entirely independent of the ABFplot class object. if saveImage is False show it instead. | def frameAndSave(abf,tag="",dataType="plot",saveAsFname=False,closeWhenDone=True):
"""
frame the current matplotlib plot with ABF info, and optionally save it.
Note that this is entirely independent of the ABFplot class object.
if saveImage is False, show it instead.
Datatype should be:
* p... |
make sure a figure is ready. | def figure(self,forceNew=False):
"""make sure a figure is ready."""
if plt._pylab_helpers.Gcf.get_num_fig_managers()>0 and forceNew is False:
self.log.debug("figure already seen, not creating one.")
return
if self.subplot:
self.log.debug("subplot mode enabled... |
save the existing figure. does not close it. | def save(self,callit="misc",closeToo=True,fullpath=False):
"""save the existing figure. does not close it."""
if fullpath is False:
fname=self.abf.outPre+"plot_"+callit+".jpg"
else:
fname=callit
if not os.path.exists(os.path.dirname(fname)):
os.mkdir(o... |
Add comment lines/ text to an existing plot. Defaults to seconds. Call after a plot has been made and after margins have been set. | def comments(self,minutes=False):
"""
Add comment lines/text to an existing plot. Defaults to seconds.
Call after a plot has been made, and after margins have been set.
"""
if self.comments==0:
return
self.log.debug("adding comments to plot")
for i,t i... |
plot every sweep of an ABF file ( with comments ). | def figure_chronological(self):
"""plot every sweep of an ABF file (with comments)."""
self.log.debug("creating chronological plot")
self.figure()
for sweep in range(self.abf.sweeps):
self.abf.setsweep(sweep)
self.setColorBySweep()
if self.abf.derivati... |
plot every sweep of an ABF file. | def figure_sweeps(self, offsetX=0, offsetY=0):
"""plot every sweep of an ABF file."""
self.log.debug("creating overlayed sweeps plot")
self.figure()
for sweep in range(self.abf.sweeps):
self.abf.setsweep(sweep)
self.setColorBySweep()
plt.plot(self.abf.... |
plot the current sweep protocol. | def figure_protocol(self):
"""plot the current sweep protocol."""
self.log.debug("creating overlayed protocols plot")
self.figure()
plt.plot(self.abf.protoX,self.abf.protoY,color='r')
self.marginX=0
self.decorate(protocol=True) |
plot the protocol of all sweeps. | def figure_protocols(self):
"""plot the protocol of all sweeps."""
self.log.debug("creating overlayed protocols plot")
self.figure()
for sweep in range(self.abf.sweeps):
self.abf.setsweep(sweep)
plt.plot(self.abf.protoX,self.abf.protoY,color='r')
self.marg... |
Given an already - open ( rb mode ) file object return a certain number of bytes at a specific location. If a struct format is given calculate the number of bytes required and return the object it represents. | def fread(f,byteLocation,structFormat=None,nBytes=1):
"""
Given an already-open (rb mode) file object, return a certain number of bytes at a specific location.
If a struct format is given, calculate the number of bytes required and return the object it represents.
"""
f.seek(byteLocation)
if str... |
Practice pulling data straight out of an ABF s binary header. Support only ABF2 ( ClampEx an ClampFit 10 ). Use only native python libraries. Strive for simplicity and readability ( to promote language portability ). This was made by Scott Harden after a line - by - line analysis of axonrawio. py from the neo io librar... | def abf_read_header(fname, saveHeader=True):
"""
Practice pulling data straight out of an ABF's binary header. Support only ABF2 (ClampEx an ClampFit 10).
Use only native python libraries. Strive for simplicity and readability (to promote language portability).
This was made by Scott Harden after a line... |
create and save a two column frames HTML file. | def frames(fname=None,menuWidth=200,launch=False):
"""create and save a two column frames HTML file."""
html="""
<frameset cols="%dpx,*%%">
<frame name="menu" src="index_menu.html">
<frame name="content" src="index_splash.html">
</frameset>"""%(menuWidth)
with open(fname,'w') as f:
f... |
wrap HTML in a top and bottom ( with css ) and save to disk. | def save(html,fname=None,launch=False):
"""wrap HTML in a top and bottom (with css) and save to disk."""
html=html_top+html+html_bot
html=html.replace("~GENAT~",swhlab.common.datetimeToString())
if fname is None:
fname = tempfile.gettempdir()+"/temp.html"
launch=True
fname=os.path.ab... |
Given ABFs and TIFs formatted long style rename each of them to prefix their number with a different number. | def clampfit_rename(path,char):
"""
Given ABFs and TIFs formatted long style, rename each of them to prefix their number with a different number.
Example: 2017_10_11_0011.abf
Becomes: 2017_10_11_?011.abf
where ? can be any character.
"""
assert len(char)==1 and type(char)==str, "replacement... |
return a 1d gassuan array of a given size and sigma. If sigma isn t given it will be 1/ 10 of the size which is usually good. | def kernel_gaussian(size=100, sigma=None, forwardOnly=False):
"""
return a 1d gassuan array of a given size and sigma.
If sigma isn't given, it will be 1/10 of the size, which is usually good.
"""
if sigma is None:sigma=size/10
points=np.exp(-np.power(np.arange(size)-size/2,2)/(2*np.power(sigma,... |
m1 and m2 if given are in seconds. returns [ # EPSCs # IPSCs ] | def analyzeSweep(abf,sweep,m1=None,m2=None,plotToo=False):
"""
m1 and m2, if given, are in seconds.
returns [# EPSCs, # IPSCs]
"""
abf.setsweep(sweep)
if m1 is None: m1=0
else: m1=m1*abf.pointsPerSec
if m2 is None: m2=-1
else: m2=m2*abf.pointsPerSec
# obtain X and Y
Yorig=ab... |
given a list of files return a dict organized by extension. | def filesByExtension(fnames):
"""given a list of files, return a dict organized by extension."""
byExt={"abf":[],"jpg":[],"tif":[]} # prime it with empties
for fname in fnames:
ext = os.path.splitext(fname)[1].replace(".",'').lower()
if not ext in byExt.keys():
byExt[ext]=[]
... |
given a list of files return a list of cells by their ID. A cell is indicated when an ABF name matches the start of another file. Example: 123456. abf 123456 - whatever. tif | def findCells(fnames):
"""
given a list of files, return a list of cells by their ID.
A cell is indicated when an ABF name matches the start of another file.
Example:
123456.abf
123456-whatever.tif
"""
IDs=[]
filesByExt = filesByExtension(fnames)
for abfFname in fil... |
given files and cells return a dict of files grouped by cell. | def filesByCell(fnames,cells):
"""given files and cells, return a dict of files grouped by cell."""
byCell={}
fnames=smartSort(fnames)
days = list(set([elem[:5] for elem in fnames if elem.endswith(".abf")])) # so pythonic!
for day in smartSort(days):
parent=None
for i,fname in enumer... |
populate class properties relating to files in the folder. | def folderScan(self,abfFolder=None):
"""populate class properties relating to files in the folder."""
if abfFolder is None and 'abfFolder' in dir(self):
abfFolder=self.abfFolder
else:
self.abfFolder=abfFolder
self.abfFolder=os.path.abspath(self.abfFolder)
... |
generate list of cells with links. keep this simple. automatically generates splash page and regnerates frames. | def html_index(self,launch=False,showChildren=False):
"""
generate list of cells with links. keep this simple.
automatically generates splash page and regnerates frames.
"""
self.makePics() # ensure all pics are converted
# generate menu
html='<a href="index_splas... |
generate landing page. | def html_index_splash(self):
"""generate landing page."""
html="""<h1 style="background-color: #EEEEFF; padding: 10px; border: 1px solid #CCCCFF;">
SWHLab <span style="font-size: 35%%;">%s<?span></h1>
"""%version.__version__
#html+='<code>%s</code><br><br>'%self.abfFolder
... |
generate./ swhlab/ xxyxxzzz. html for a single given abf. Input can be an ABF file path of ABF ID. | def html_single_basic(self,ID):
"""
generate ./swhlab/xxyxxzzz.html for a single given abf.
Input can be an ABF file path of ABF ID.
"""
if not ID in self.cells:
self.log.error("ID [%s] not seen!",ID)
return
htmlFname=os.path.abspath(self.abfFolder... |
generate a data view for every ABF in the project folder. | def html_singleAll(self,template="basic"):
"""generate a data view for every ABF in the project folder."""
for fname in smartSort(self.cells):
if template=="fixed":
self.html_single_fixed(fname)
else:
self.html_single_basic(fname) |
convert every. image we find to a./ swhlab/ image | def makePics(self):
"""convert every .image we find to a ./swhlab/ image"""
rescanNeeded=False
for fname in smartSort(self.fnames):
if fname in self.fnames2:
continue
ext=os.path.splitext(fname)[1].lower()
if ext in [".jpg",".png"]:
... |
hyperpolarization step. Use to calculate tau and stuff. | def proto_01_01_HP010(abf=exampleABF):
"""hyperpolarization step. Use to calculate tau and stuff."""
swhlab.memtest.memtest(abf) #knows how to do IC memtest
swhlab.memtest.checkSweep(abf) #lets you eyeball check how it did
swhlab.plot.save(abf,tag="tau") |
each sweep is a ramp ( of set size ) which builds on the last sweep. Used for detection of AP properties from first few APs. | def proto_01_11_rampStep(abf=exampleABF):
"""each sweep is a ramp (of set size) which builds on the last sweep.
Used for detection of AP properties from first few APs."""
standard_inspect(abf)
swhlab.ap.detect(abf)
swhlab.ap.check_sweep(abf) #eyeball how well event detection worked
swhlab.plot.s... |
IC steps. Use to determine gain function. | def proto_01_12_steps025(abf=exampleABF):
"""IC steps. Use to determine gain function."""
swhlab.ap.detect(abf)
standard_groupingForInj(abf,200)
for feature in ['freq','downslope']:
swhlab.ap.plot_values(abf,feature,continuous=False) #plot AP info
swhlab.plot.save(abf,tag='A_'+feature)
... |
IC steps. See how hyperpol. step affects things. | def proto_01_13_steps025dual(abf=exampleABF):
"""IC steps. See how hyperpol. step affects things."""
swhlab.ap.detect(abf)
standard_groupingForInj(abf,200)
for feature in ['freq','downslope']:
swhlab.ap.plot_values(abf,feature,continuous=False) #plot AP info
swhlab.plot.save(abf,tag='A_... |
repeated membrane tests. | def proto_02_01_MT70(abf=exampleABF):
"""repeated membrane tests."""
standard_overlayWithAverage(abf)
swhlab.memtest.memtest(abf)
swhlab.memtest.checkSweep(abf)
swhlab.plot.save(abf,tag='check',resize=False) |
dual I/ V steps in VC mode one from - 70 and one - 50. | def proto_02_02_IVdual(abf=exampleABF):
"""dual I/V steps in VC mode, one from -70 and one -50."""
av1,sd1=swhlab.plot.IV(abf,.7,1,True,'b')
swhlab.plot.save(abf,tag='iv1')
a2v,sd2=swhlab.plot.IV(abf,2.2,2.5,True,'r')
swhlab.plot.save(abf,tag='iv2')
swhlab.plot.sweep(abf,'all')
pylab.axis(... |
fast sweeps 1 step per sweep for clean IV without fast currents. | def proto_02_03_IVfast(abf=exampleABF):
"""fast sweeps, 1 step per sweep, for clean IV without fast currents."""
av1,sd1=swhlab.plot.IV(abf,.6,.9,True)
swhlab.plot.save(abf,tag='iv1')
Xs=abf.clampValues(.6) #generate IV clamp values
abf.saveThing([Xs,av1],'iv') |
repeated membrane tests likely with drug added. Maybe IPSCs. | def proto_04_01_MTmon70s2(abf=exampleABF):
"""repeated membrane tests, likely with drug added. Maybe IPSCs."""
standard_inspect(abf)
swhlab.memtest.memtest(abf)
swhlab.memtest.checkSweep(abf)
swhlab.plot.save(abf,tag='check',resize=False)
swhlab.memtest.plot_standard4(abf)
swhlab.plot.save(a... |
combination of membrane test and IV steps. | def proto_VC_50_MT_IV(abf=exampleABF):
"""combination of membrane test and IV steps."""
swhlab.memtest.memtest(abf) #do membrane test on every sweep
swhlab.memtest.checkSweep(abf) #see all MT values
swhlab.plot.save(abf,tag='02-check',resize=False)
av1,sd1=swhlab.plot.IV(abf,1.2,1.4,True,'b')
s... |
increasing ramps in ( ? ) pA steps. | def proto_IC_ramp_gain(abf=exampleABF):
"""increasing ramps in (?) pA steps."""
standard_inspect(abf)
swhlab.ap.detect(abf)
swhlab.ap.check_AP_raw(abf) #show overlayed first few APs
swhlab.plot.save(abf,tag="01-raw",resize=False)
swhlab.ap.check_AP_deriv(abf) #show overlayed first few APs
s... |
OBSOLETE WAY TO INDEX A FOLDER. | def indexImages(folder,fname="index.html"):
"""OBSOLETE WAY TO INDEX A FOLDER.""" #TODO: REMOVE
html="<html><body>"
for item in glob.glob(folder+"/*.*"):
if item.split(".")[-1] in ['jpg','png']:
html+="<h3>%s</h3>"%os.path.basename(item)
html+='<img src="%s">'%os.path.basenam... |
A custom save method that handles figuring out when something is activated or deactivated. | def save(self, *args, **kwargs):
"""
A custom save method that handles figuring out when something is activated or deactivated.
"""
current_activable_value = getattr(self, self.ACTIVATABLE_FIELD_NAME)
is_active_changed = self.id is None or self.__original_activatable_value != cur... |
It is impossible to delete an activatable model unless force is True. This function instead sets it to inactive. | def delete(self, force=False, **kwargs):
"""
It is impossible to delete an activatable model unless force is True. This function instead sets it to inactive.
"""
if force:
return super(BaseActivatableModel, self).delete(**kwargs)
else:
setattr(self, self.A... |
Write to file_handle if supplied othewise print output | def show(self, args, file_handle=None, **kwargs):
"Write to file_handle if supplied, othewise print output"
full_string = ''
info = {'root_directory': '<root_directory>',
'batch_name': '<batch_name>',
'batch_tag': '<batch_tag>',
... |
Update the launch information -- use if additional launches were made. | def update(self):
"""Update the launch information -- use if additional launches were
made.
"""
launches = []
for path in os.listdir(self.output_dir):
full_path = os.path.join(self.output_dir, path)
if os.path.isdir(full_path):
launches.app... |
A helper method that supplies the root directory name given a timestamp. | def get_root_directory(self, timestamp=None):
"""
A helper method that supplies the root directory name given a
timestamp.
"""
if timestamp is None: timestamp = self.timestamp
if self.timestamp_format is not None:
root_name = (time.strftime(self.timestamp_for... |
The log contains the tids and corresponding specifications used during launch with the specifications in JSON format. | def _append_log(self, specs):
"""
The log contains the tids and corresponding specifications
used during launch with the specifications in JSON format.
"""
self._spec_log += specs # This should be removed
log_path = os.path.join(self.root_directory, ("%s.log" % self.batch... |
All launchers should call this method to write the info file at the end of the launch. The. info file is saved given setup_info supplied by _setup_launch into the root_directory. When called without setup_info the existing info file is updated with the end - time. | def _record_info(self, setup_info=None):
"""
All launchers should call this method to write the info file
at the end of the launch. The .info file is saved given
setup_info supplied by _setup_launch into the
root_directory. When called without setup_info, the existing
inf... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.