Search is not available for this dataset
text
stringlengths 75
104k
|
---|
def _setup_launch(self):
"""
Method to be used by all launchers that prepares the root
directory and generate basic launch information for command
templates to use (including a registered timestamp).
"""
self.root_directory = self.get_root_directory()
if not os.path.isdir(self.root_directory):
os.makedirs(self.root_directory)
platform_dict = {}
python_version = (platform.python_implementation()
+ platform.python_version())
platform_dict['platform'] = platform.platform()
platform_dict['python_version'] = python_version
platform_dict['lancet_version'] = str(lancet_version)
return {'root_directory': self.root_directory,
'batch_name': self.batch_name,
'batch_tag': self.tag,
'batch_description': self.description,
'launcher': repr(self),
'platform' : platform_dict,
'timestamp': self.timestamp,
'timestamp_format': self.timestamp_format,
'varying_keys': self.args.varying_keys,
'constant_keys': self.args.constant_keys,
'constant_items': self.args.constant_items} |
def _launch_process_group(self, process_commands, streams_path):
"""
Launches processes defined by process_commands, but only
executes max_concurrency processes at a time; if a process
completes and there are still outstanding processes to be
executed, the next processes are run until max_concurrency is
reached again.
"""
processes = {}
def check_complete_processes(wait=False):
"""
Returns True if a process completed, False otherwise.
Optionally allows waiting for better performance (avoids
sleep-poll cycle if possible).
"""
result = False
# list creates copy of keys, as dict is modified in loop
for proc in list(processes):
if wait: proc.wait()
if proc.poll() is not None:
# process is done, free up slot
self.debug("Process %d exited with code %d."
% (processes[proc]['tid'], proc.poll()))
processes[proc]['stdout'].close()
processes[proc]['stderr'].close()
del processes[proc]
result = True
return result
for cmd, tid in process_commands:
self.debug("Starting process %d..." % tid)
job_timestamp = time.strftime('%H%M%S')
basename = "%s_%s_tid_%d" % (self.batch_name, job_timestamp, tid)
stdout_handle = open(os.path.join(streams_path, "%s.o.%d"
% (basename, tid)), "wb")
stderr_handle = open(os.path.join(streams_path, "%s.e.%d"
% (basename, tid)), "wb")
proc = subprocess.Popen(cmd, stdout=stdout_handle, stderr=stderr_handle)
processes[proc] = { 'tid' : tid,
'stdout' : stdout_handle,
'stderr' : stderr_handle }
if self.max_concurrency:
# max_concurrency reached, wait until more slots available
while len(processes) >= self.max_concurrency:
if not check_complete_processes(len(processes)==1):
time.sleep(0.1)
# Wait for all processes to complete
while len(processes) > 0:
if not check_complete_processes(True):
time.sleep(0.1) |
def summary(self):
"""
A succinct summary of the Launcher configuration. Unlike the
repr, a summary does not have to be complete but must supply
key information relevant to the user.
"""
print("Type: %s" % self.__class__.__name__)
print("Batch Name: %r" % self.batch_name)
if self.tag:
print("Tag: %s" % self.tag)
print("Root directory: %r" % self.get_root_directory())
print("Maximum concurrency: %s" % self.max_concurrency)
if self.description:
print("Description: %s" % self.description) |
def _qsub_args(self, override_options, cmd_args, append_options=[]):
"""
Method to generate Popen style argument list for qsub using
the qsub_switches and qsub_flag_options parameters. Switches
are returned first. The qsub_flag_options follow in keys()
ordered if not a vanilla Python dictionary (ie. a Python 2.7+
or param.external OrderedDict). Otherwise the keys are sorted
alphanumerically. Note that override_options is a list of
key-value pairs.
"""
opt_dict = type(self.qsub_flag_options)()
opt_dict.update(self.qsub_flag_options)
opt_dict.update(override_options)
if type(self.qsub_flag_options) == dict: # Alphanumeric sort if vanilla Python dictionary
ordered_options = [(k, opt_dict[k]) for k in sorted(opt_dict)]
else:
ordered_options = list(opt_dict.items())
ordered_options += append_options
unpacked_groups = [[(k,v) for v in val] if type(val)==list else [(k,val)]
for (k,val) in ordered_options]
unpacked_kvs = [el for group in unpacked_groups for el in group]
# Adds '-' if missing (eg, keywords in dict constructor) and flattens lists.
ordered_pairs = [(k,v) if (k[0]=='-') else ('-%s' % (k), v)
for (k,v) in unpacked_kvs]
ordered_options = [[k]+([v] if type(v) == str else list(v)) for (k,v) in ordered_pairs]
flattened_options = [el for kvs in ordered_options for el in kvs]
return (['qsub'] + self.qsub_switches
+ flattened_options + [pipes.quote(c) for c in cmd_args]) |
def collate_and_launch(self):
"""
Method that collates the previous jobs and launches the next
block of concurrent jobs when using DynamicArgs. This method
is invoked on initial launch and then subsequently via a
commandline call (to Python via qsub) to collate the
previously run jobs and launch the next block of jobs.
"""
try: specs = next(self.spec_iter)
except StopIteration:
self.qdel_batch()
if self.reduction_fn is not None:
self.reduction_fn(self._spec_log, self.root_directory)
self._record_info()
return
tid_specs = [(self.last_tid + i, spec) for (i,spec) in enumerate(specs)]
self.last_tid += len(specs)
self._append_log(tid_specs)
# Updating the argument specifier
if self.dynamic:
self.args.update(self.last_tids, self._launchinfo)
self.last_tids = [tid for (tid,_) in tid_specs]
output_dir = self.qsub_flag_options['-o']
error_dir = self.qsub_flag_options['-e']
self._qsub_block(output_dir, error_dir, tid_specs)
# Pickle launcher before exit if necessary.
if self.dynamic or (self.reduction_fn is not None):
pickle_path = os.path.join(self.root_directory, 'qlauncher.pkl')
pickle.dump(self, open(pickle_path,'wb'), protocol=2) |
def _qsub_collate_and_launch(self, output_dir, error_dir, job_names):
"""
The method that actually runs qsub to invoke the python
process with the necessary commands to trigger the next
collation step and next block of jobs.
"""
job_name = "%s_%s_collate_%d" % (self.batch_name,
self.job_timestamp,
self.collate_count)
overrides = [("-e",error_dir), ('-N',job_name), ("-o",output_dir),
('-hold_jid',','.join(job_names))]
resume_cmds =["import os, pickle, lancet",
("pickle_path = os.path.join(%r, 'qlauncher.pkl')"
% self.root_directory),
"launcher = pickle.load(open(pickle_path,'rb'))",
"launcher.collate_and_launch()"]
cmd_args = [self.command.executable,
'-c', ';'.join(resume_cmds)]
popen_args = self._qsub_args(overrides, cmd_args)
p = subprocess.Popen(popen_args, stdout=subprocess.PIPE)
(stdout, stderr) = p.communicate()
self.debug(stdout)
if p.poll() != 0:
raise EnvironmentError("qsub command exit with code: %d" % p.poll())
self.collate_count += 1
self.message("Invoked qsub for next batch.")
return job_name |
def _qsub_block(self, output_dir, error_dir, tid_specs):
"""
This method handles static argument specifiers and cases where
the dynamic specifiers cannot be queued before the arguments
are known.
"""
processes = []
job_names = []
for (tid, spec) in tid_specs:
job_name = "%s_%s_tid_%d" % (self.batch_name, self.job_timestamp, tid)
job_names.append(job_name)
cmd_args = self.command(
self.command._formatter(spec),
tid, self._launchinfo)
popen_args = self._qsub_args([("-e",error_dir), ('-N',job_name), ("-o",output_dir)],
cmd_args)
p = subprocess.Popen(popen_args, stdout=subprocess.PIPE)
(stdout, stderr) = p.communicate()
self.debug(stdout)
if p.poll() != 0:
raise EnvironmentError("qsub command exit with code: %d" % p.poll())
processes.append(p)
self.message("Invoked qsub for %d commands" % len(processes))
if (self.reduction_fn is not None) or self.dynamic:
self._qsub_collate_and_launch(output_dir, error_dir, job_names) |
def qdel_batch(self):
"""
Runs qdel command to remove all remaining queued jobs using
the <batch_name>* pattern . Necessary when StopIteration is
raised with scheduled jobs left on the queue.
Returns exit-code of qdel.
"""
p = subprocess.Popen(['qdel', '%s_%s*' % (self.batch_name,
self.job_timestamp)],
stdout=subprocess.PIPE)
(stdout, stderr) = p.communicate()
return p.poll() |
def _launch_process_group(self, process_commands, streams_path):
"""
Aggregates all process_commands and the designated output files into a
list, and outputs it as JSON, after which the wrapper script is called.
"""
processes = []
for cmd, tid in process_commands:
job_timestamp = time.strftime('%H%M%S')
basename = "%s_%s_tid_%d" % (self.batch_name, job_timestamp, tid)
stdout_path = os.path.join(streams_path, "%s.o.%d" % (basename, tid))
stderr_path = os.path.join(streams_path, "%s.e.%d" % (basename, tid))
process = { 'tid' : tid,
'cmd' : cmd,
'stdout' : stdout_path,
'stderr' : stderr_path }
processes.append(process)
# To make the JSON filename unique per group, we use the last tid in
# this group.
json_path = os.path.join(self.root_directory, self.json_name % (tid))
with open(json_path, 'w') as json_file:
json.dump(processes, json_file, sort_keys=True, indent=4)
p = subprocess.Popen([self.script_path, json_path, self.batch_name,
str(len(processes)), str(self.max_concurrency)])
if p.wait() != 0:
raise EnvironmentError("Script command exit with code: %d" % p.poll()) |
def cross_check_launchers(self, launchers):
"""
Performs consistency checks across all the launchers.
"""
if len(launchers) == 0: raise Exception('Empty launcher list')
timestamps = [launcher.timestamp for launcher in launchers]
if not all(timestamps[0] == tstamp for tstamp in timestamps):
raise Exception("Launcher timestamps not all equal. "
"Consider setting timestamp explicitly.")
root_directories = []
for launcher in launchers:
command = launcher.command
args = launcher.args
command.verify(args)
root_directory = launcher.get_root_directory()
if os.path.isdir(root_directory):
raise Exception("Root directory already exists: %r" % root_directory)
if root_directory in root_directories:
raise Exception("Each launcher requires a unique root directory")
root_directories.append(root_directory) |
def _launch_all(self, launchers):
"""
Launches all available launchers.
"""
for launcher in launchers:
print("== Launching %s ==" % launcher.batch_name)
launcher()
return True |
def _review_all(self, launchers):
"""
Runs the review process for all the launchers.
"""
# Run review of launch args if necessary
if self.launch_args is not None:
proceed = self.review_args(self.launch_args,
show_repr=True,
heading='Meta Arguments')
if not proceed: return False
reviewers = [self.review_args,
self.review_command,
self.review_launcher]
for (count, launcher) in enumerate(launchers):
# Run reviews for all launchers if desired...
if not all(reviewer(launcher) for reviewer in reviewers):
print("\n == Aborting launch ==")
return False
# But allow the user to skip these extra reviews
if len(launchers)!= 1 and count < len(launchers)-1:
skip_remaining = self.input_options(['Y', 'n','quit'],
'\nSkip remaining reviews?', default='y')
if skip_remaining == 'y': break
elif skip_remaining == 'quit': return False
if self.input_options(['y','N'], 'Execute?', default='n') != 'y':
return False
else:
return self._launch_all(launchers) |
def review_args(self, obj, show_repr=False, heading='Arguments'):
"""
Reviews the given argument specification. Can review the
meta-arguments (launch_args) or the arguments themselves.
"""
args = obj.args if isinstance(obj, Launcher) else obj
print('\n%s\n' % self.summary_heading(heading))
args.summary()
if show_repr: print("\n%s\n" % args)
response = self.input_options(['y', 'N','quit'],
'\nShow available argument specifier entries?', default='n')
if response == 'quit': return False
if response == 'y': args.show()
print('')
return True |
def input_options(self, options, prompt='Select option', default=None):
"""
Helper to prompt the user for input on the commandline.
"""
check_options = [x.lower() for x in options]
while True:
response = input('%s [%s]: ' % (prompt, ', '.join(options))).lower()
if response in check_options: return response.strip()
elif response == '' and default is not None:
return default.lower().strip() |
def save(self, filename, metadata={}, **data):
"""
The implementation in the base class simply checks there is no
clash between the metadata and data keys.
"""
intersection = set(metadata.keys()) & set(data.keys())
if intersection:
msg = 'Key(s) overlap between data and metadata: %s'
raise Exception(msg % ','.join(intersection)) |
def _savepath(self, filename):
"""
Returns the full path for saving the file, adding an extension
and making the filename unique as necessary.
"""
(basename, ext) = os.path.splitext(filename)
basename = basename if (ext in self.extensions) else filename
ext = ext if (ext in self.extensions) else self.extensions[0]
savepath = os.path.abspath(os.path.join(self.directory,
'%s%s' % (basename, ext)))
return (tempfile.mkstemp(ext, basename + "_", self.directory)[1]
if self.hash_suffix else savepath) |
def file_supported(cls, filename):
"""
Returns a boolean indicating whether the filename has an
appropriate extension for this class.
"""
if not isinstance(filename, str):
return False
(_, ext) = os.path.splitext(filename)
if ext not in cls.extensions:
return False
else:
return True |
def save(self, filename, imdata, **data):
"""
Data may be either a PIL Image object or a Numpy array.
"""
if isinstance(imdata, numpy.ndarray):
imdata = Image.fromarray(numpy.uint8(imdata))
elif isinstance(imdata, Image.Image):
imdata.save(self._savepath(filename)) |
def fileModifiedTimestamp(fname):
"""return "YYYY-MM-DD" when the file was modified."""
modifiedTime=os.path.getmtime(fname)
stamp=time.strftime('%Y-%m-%d', time.localtime(modifiedTime))
return stamp |
def loadResults(resultsFile):
"""returns a dict of active folders with days as keys."""
with open(resultsFile) as f:
raw=f.read().split("\n")
foldersByDay={}
for line in raw:
folder=line.split('"')[1]+"\\"
line=[]+line.split('"')[2].split(", ")
for day in line[1:]:
if not day in foldersByDay:
foldersByDay[day]=[]
foldersByDay[day]=foldersByDay[day]+[folder]
nActiveDays=len(foldersByDay)
dayFirst=sorted(foldersByDay.keys())[0]
dayLast=sorted(foldersByDay.keys())[-1]
dayFirst=datetime.datetime.strptime(dayFirst, "%Y-%m-%d" )
dayLast=datetime.datetime.strptime(dayLast, "%Y-%m-%d" )
nDays = (dayLast - dayFirst).days + 1
emptyDays=0
for deltaDays in range(nDays):
day=dayFirst+datetime.timedelta(days=deltaDays)
stamp=datetime.datetime.strftime(day, "%Y-%m-%d" )
if not stamp in foldersByDay:
foldersByDay[stamp]=[]
emptyDays+=1
percActive=nActiveDays/nDays*100
print("%d of %d days were active (%.02f%%)"%(nActiveDays,nDays,percActive))
return foldersByDay |
def HTML_results(resultsFile):
"""generates HTML report of active folders/days."""
foldersByDay=loadResults(resultsFile)
# optionally skip dates before a certain date
# for day in sorted(list(foldersByDay.keys())):
# if time.strptime(day,"%Y-%m-%d")<time.strptime("2016-05-01","%Y-%m-%d"):
# del foldersByDay[day]
# Create a header
html="<div class='heading'>Active Folder Report (updated TIMESTAMP)</div>"
html+="<li>When a file is created (or modified) its parent folder is marked active for that day."
html+="<li>This page reports all folders which were active in the last several years. "
html+="<li>A single folder can be active for more than one date."
html=html.replace("TIMESTAMP",(time.strftime('%Y-%m-%d', time.localtime())))
html+="<br>"*5
# create menu at the top of the page
html+="<div class='heading'>Active Folder Dates</div>"
html+="<code>"
lastMonth=""
lastYear=""
for day in sorted(list(foldersByDay.keys())):
month=day[:7]
year=day[:4]
if year!=lastYear:
html+="<br><br><b style='font-size: 200%%;'>%s</b> "%year
lastYear=year
if month!=lastMonth:
html+="<br><b>%s:</b> "%month
lastMonth=month
html+="<a href='#%s'>%s</a>, "%(day,day[8:])
html+="<br>"*5
html=html.replace(", <br>","<br>")
html+="</code>"
# create the full list of folders organized by active date
html+="<div class='heading'>Active Folders</div>"
for day in sorted(list(foldersByDay.keys())):
dt=datetime.datetime.strptime(day, "%Y-%m-%d" )
classPrefix="weekday"
if int(dt.weekday())>4:
classPrefix="weekend"
html+="<a name='%s' href='#%s' style='color: black;'>"%(day,day)
title="%s (%s)"%(day,DAYSOFWEEK[dt.weekday()])
html+="<div class='%s_datecode'>%s</div></a>"%(classPrefix,title)
html+="<div class='%s_folders'>"%(classPrefix)
# define folders to skip
for folder in foldersByDay[day]:
if "\\References\\" in folder:
continue
if "\\MIP\\" in folder:
continue
if "LineScan-" and "\\analysis\\" in folder:
continue
if "trakem2" in folder:
continue
if "SWHlab-" in folder:
continue
if "\\swhlab" in folder:
continue
html+="%s<br>"%folder
html+="</div>"
fnameSave=resultsFile+".html"
html=html.replace("D:\\X_Drive\\","X:\\")
with open(fnameSave,'w') as f:
f.write(HTML_TEMPLATE.replace("<body>","<body>"+html))
print("saved",fnameSave) |
def quietParts(data,percentile=10):
"""
Given some data (Y) break it into chunks and return just the quiet ones.
Returns data where the variance for its chunk size is below the given percentile.
CHUNK_POINTS should be adjusted so it's about 10ms of data.
"""
nChunks=int(len(Y)/CHUNK_POINTS)
chunks=np.reshape(Y[:nChunks*CHUNK_POINTS],(nChunks,CHUNK_POINTS))
variances=np.var(chunks,axis=1)
percentiles=np.empty(len(variances))
for i,variance in enumerate(variances):
percentiles[i]=sorted(variances).index(variance)/len(variances)*100
selected=chunks[np.where(percentiles<=percentile)[0]].flatten()
return selected |
def ndist(data,Xs):
"""
given some data and a list of X posistions, return the normal
distribution curve as a Y point at each of those Xs.
"""
sigma=np.sqrt(np.var(data))
center=np.average(data)
curve=mlab.normpdf(Xs,center,sigma)
curve*=len(data)*HIST_RESOLUTION
return curve |
def abfinfo(self,printToo=False,returnDict=False):
"""show basic info about ABF class variables."""
info="\n### ABF INFO ###\n"
d={}
for thingName in sorted(dir(self)):
if thingName in ['cm','evIs','colormap','dataX','dataY',
'protoX','protoY']:
continue
if "_" in thingName:
continue
thing=getattr(self,thingName)
if type(thing) is list and len(thing)>5:
continue
thingType=str(type(thing)).split("'")[1]
if "method" in thingType or "neo." in thingType:
continue
if thingName in ["header","MT"]:
continue
info+="%s <%s> %s\n"%(thingName,thingType,thing)
d[thingName]=thing
if printToo:
print()
for line in info.split("\n"):
if len(line)<3:
continue
print(" ",line)
print()
if returnDict:
return d
return info |
def headerHTML(self,fname=None):
"""read the ABF header and save it HTML formatted."""
if fname is None:
fname = self.fname.replace(".abf","_header.html")
html="<html><body><code>"
html+="<h2>abfinfo() for %s.abf</h2>"%self.ID
html+=self.abfinfo().replace("<","<").replace(">",">").replace("\n","<br>")
html+="<h2>Header for %s.abf</h2>"%self.ID
html+=pprint.pformat(self.header, indent=1)
html=html.replace("\n",'<br>').replace(" "," ")
html=html.replace(r"\x00","")
html+="</code></body></html>"
print("WRITING HEADER TO:")
print(fname)
f=open(fname,'w')
f.write(html)
f.close() |
def generate_colormap(self,colormap=None,reverse=False):
"""use 1 colormap for the whole abf. You can change it!."""
if colormap is None:
colormap = pylab.cm.Dark2
self.cm=colormap
self.colormap=[]
for i in range(self.sweeps): #TODO: make this the only colormap
self.colormap.append(colormap(i/self.sweeps))
if reverse:
self.colormap.reverse() |
def setSweep(self,sweep=0,force=False):
"""Load X/Y data for a particular sweep.
determines if forced reload is needed, updates currentSweep,
regenerates dataX (if not None),decimates,returns X/Y.
Note that setSweep() takes 0.17ms to complete, so go for it!
"""
if sweep is None or sweep is False:
sweep=0
if sweep<0:
sweep=self.sweeps-sweep #-1 means last sweep
if sweep<0: #still!
sweep=0 #first sweep
if sweep>(self.sweeps-1):
print(" !! there aren't %d sweeps. Reverting to last (%d) sweep."%(sweep,self.sweeps-1))
sweep=self.sweeps-1
sweep=int(sweep)
try:
if self.currentSweep==sweep and force==False:
return
self.currentSweep=sweep
self.dataY = self.block.segments[sweep].analogsignals[self.channel]
self.dataY = np.array(self.dataY)
B1,B2=self.baseline
if B1==None:
B1=0
else:
B1=B1*self.rate
if B2==None:
B2==self.sweepSize
else:
B2=B2*self.rate
self.dataY-=np.average(self.dataY[self.baseline[0]*self.rate:self.baseline[1]*self.rate])
self.sweep_genXs()
self.sweep_decimate()
self.generate_protocol(sweep=sweep)
self.dataStart = self.sweepInterval*self.currentSweep
except Exception:
print("#"*400,"\n",traceback.format_exc(),'\n',"#"*400)
return self.dataX,self.dataY |
def sweep_genXs(self):
"""generate sweepX (in seconds) to match sweepY"""
if self.decimateMethod:
self.dataX=np.arange(len(self.dataY))/self.rate
self.dataX*=self.decimateBy
return
if self.dataX is None or len(self.dataX)!=len(self.dataY):
self.dataX=np.arange(len(self.dataY))/self.rate |
def sweep_decimate(self):
"""
decimate data using one of the following methods:
'avg','max','min','fast'
They're self explainatory. 'fast' just plucks the n'th data point.
"""
if len(self.dataY)<self.decimateBy:
return
if self.decimateMethod:
points = int(len(self.dataY)/self.decimateBy)
self.dataY=self.dataY[:points*self.decimateBy]
self.dataY = np.reshape(self.dataY,(points,self.decimateBy))
if self.decimateMethod=='avg':
self.dataY = np.average(self.dataY,1)
elif self.decimateMethod=='max':
self.dataY = np.max(self.dataY,1)
elif self.decimateMethod=='min':
self.dataY = np.min(self.dataY,1)
elif self.decimateMethod=='fast':
self.dataY = self.dataY[:,0]
else:
print("!!! METHOD NOT IMPLIMENTED YET!!!",self.decimateMethod)
self.dataX = np.arange(len(self.dataY))/self.rate*self.decimateBy |
def get_data_around(self,timePoints,thisSweep=False,padding=0.02,msDeriv=0):
"""
return self.dataY around a time point. All units are seconds.
if thisSweep==False, the time point is considered to be experiment time
and an appropriate sweep may be selected. i.e., with 10 second
sweeps and timePint=35, will select the 5s mark of the third sweep
"""
if not np.array(timePoints).shape:
timePoints=[float(timePoints)]
data=None
for timePoint in timePoints:
if thisSweep:
sweep=self.currentSweep
else:
sweep=int(timePoint/self.sweepInterval)
timePoint=timePoint-sweep*self.sweepInterval
self.setSweep(sweep)
if msDeriv:
dx=int(msDeriv*self.rate/1000) #points per ms
newData=(self.dataY[dx:]-self.dataY[:-dx])*self.rate/1000/dx
else:
newData=self.dataY
padPoints=int(padding*self.rate)
pad=np.empty(padPoints)*np.nan
Ic=timePoint*self.rate #center point (I)
newData=np.concatenate((pad,pad,newData,pad,pad))
Ic+=padPoints*2
newData=newData[Ic-padPoints:Ic+padPoints]
newData=newData[:int(padPoints*2)] #TODO: omg so much trouble with this!
if data is None:
data=[newData]
else:
data=np.vstack((data,newData))#TODO: omg so much trouble with this!
return data |
def generate_protocol(self,sweep=None):
"""
Create (x,y) points necessary to graph protocol for the current sweep.
"""
#TODO: make a line protocol that's plottable
if sweep is None:
sweep = self.currentSweep
if sweep is None:
sweep = 0
if not self.channel in self.header['dictEpochInfoPerDAC'].keys():
self.protoX=[0,self.sweepSize]
self.protoY=[self.holding,self.holding]
self.protoSeqX=self.protoX
self.protoSeqY=self.protoY
return
proto=self.header['dictEpochInfoPerDAC'][self.channel]
self.protoX=[] #plottable Xs
self.protoY=[] #plottable Ys
self.protoX.append(0)
self.protoY.append(self.holding)
for step in proto:
dX = proto[step]['lEpochInitDuration']
Y = proto[step]['fEpochInitLevel']+proto[step]['fEpochLevelInc']*sweep
self.protoX.append(self.protoX[-1])
self.protoY.append(Y) #go to new Y
self.protoX.append(self.protoX[-1]+dX) #take it to the new X
self.protoY.append(Y) #update the new Y #TODO: fix for ramps
if self.header['listDACInfo'][0]['nInterEpisodeLevel']: #nInterEpisodeLevel
finalVal=self.protoY[-1] #last holding
else:
finalVal=self.holding #regular holding
self.protoX.append(self.protoX[-1])
self.protoY.append(finalVal)
self.protoX.append(self.sweepSize)
self.protoY.append(finalVal)
for i in range(1,len(self.protoX)-1): #correct for weird ABF offset issue.
self.protoX[i]=self.protoX[i]+self.offsetX
self.protoSeqY=[self.protoY[0]]
self.protoSeqX=[self.protoX[0]]
for i in range(1,len(self.protoY)):
if not self.protoY[i]==self.protoY[i-1]:
self.protoSeqY.append(self.protoY[i])
self.protoSeqX.append(self.protoX[i])
if self.protoY[0]!=self.protoY[1]:
self.protoY.insert(1,self.protoY[0])
self.protoX.insert(1,self.protoX[1])
self.protoY.insert(1,self.protoY[0])
self.protoX.insert(1,self.protoX[0]+self.offsetX/2)
self.protoSeqY.append(finalVal)
self.protoSeqX.append(self.sweepSize)
self.protoX=np.array(self.protoX)
self.protoY=np.array(self.protoY) |
def clampValues(self,timePoint=0):
"""
return an array of command values at a time point (in sec).
Useful for things like generating I/V curves.
"""
Cs=np.zeros(self.sweeps)
for i in range(self.sweeps):
self.setSweep(i) #TODO: protocol only = True
for j in range(len(self.protoSeqX)):
if self.protoSeqX[j]<=timePoint*self.rate:
Cs[i]=self.protoSeqY[j]
return Cs |
def guess_protocol(self):
"""
This just generates a string to define the nature of the ABF.
The ultimate goal is to use info about the abf to guess what to do with it.
[vc/ic]-[steps/fixed]-[notag/drugs]-[2ch/1ch]
This represents 2^4 (18) combinations, but is easily expanded.
"""
clamp="ic"
if self.units=="pA":
clamp="vc"
command="fixed"
if self.sweeps>1:
self.setSweep(0)
P0=str(self.protoX)+str(self.protoY)
self.setSweep(1)
P1=str(self.protoX)+str(self.protoY)
if not P0==P1:
command="steps"
tags="notag"
if len(self.commentSweeps):
tags="drugs"
ch="1ch"
if self.nADC>1:
ch="2ch"
guess="-".join([clamp,command,tags,ch])
return guess |
def average_sweep(self,T1=0,T2=None,sweeps=None,stdErr=False):
"""
given an array of sweeps, return X,Y,Err average.
This returns *SWEEPS* of data, not just 1 data point.
"""
T1=T1*self.rate
if T2 is None:
T2 = self.sweepSize-1
else:
T2 = T2*self.rate
if sweeps is None:
sweeps = range(self.sweeps)
Ys=np.empty((len(sweeps),(T2-T1)))
for i in range(len(sweeps)):
self.setSweep(sweeps[i])
Ys[i]=self.dataY[T1:T2]
Av = np.average(Ys,0)
Es = np.std(Ys,0)
Xs = self.dataX[T1:T2]
if stdErr: #otherwise return stdev
Es = Es/np.sqrt(len(sweeps))
return Xs,Av,Es |
def average_data(self,ranges=[[None,None]],percentile=None):
"""
given a list of ranges, return single point averages for every sweep.
Units are in seconds. Expects something like:
ranges=[[1,2],[4,5],[7,7.5]]
None values will be replaced with maximum/minimum bounds.
For baseline subtraction, make a range baseline then sub it youtself.
returns datas[iSweep][iRange][AVorSD]
if a percentile is given, return that percentile rather than average.
percentile=50 is the median, but requires sorting, and is slower.
"""
ranges=copy.deepcopy(ranges) #TODO: make this cleaner. Why needed?
# clean up ranges, make them indexes
for i in range(len(ranges)):
if ranges[i][0] is None:
ranges[i][0] = 0
else:
ranges[i][0] = int(ranges[i][0]*self.rate)
if ranges[i][1] is None:
ranges[i][1] = -1
else:
ranges[i][1] = int(ranges[i][1]*self.rate)
# do the math
datas=np.empty((self.sweeps,len(ranges),2)) #[sweep][range]=[Av,Er]
for iSweep in range(self.sweeps):
self.setSweep(iSweep)
for iRange in range(len(ranges)):
I1=ranges[iRange][0]
I2=ranges[iRange][1]
if percentile:
datas[iSweep][iRange][0]=np.percentile(self.dataY[I1:I2],percentile)
else:
datas[iSweep][iRange][0]=np.average(self.dataY[I1:I2])
datas[iSweep][iRange][1]=np.std(self.dataY[I1:I2])
return datas |
def filter_gaussian(self,sigmaMs=100,applyFiltered=False,applyBaseline=False):
"""RETURNS filtered trace. Desn't filter it in place."""
if sigmaMs==0:
return self.dataY
filtered=cm.filter_gaussian(self.dataY,sigmaMs)
if applyBaseline:
self.dataY=self.dataY-filtered
elif applyFiltered:
self.dataY=filtered
else:
return filtered |
def saveThing(self,thing,fname,overwrite=True,ext=".pkl"):
"""save any object as /swhlab4/ID_[fname].pkl"""
if not os.path.exists(os.path.dirname(self.outpre)):
os.mkdir(os.path.dirname(self.outpre))
if ext and not ext in fname:
fname+=ext
fname=self.outpre+fname
if overwrite is False:
if os.path.exists(fname):
print(" o- not overwriting [%s]"%os.path.basename(fname))
return
time1=cm.timethis()
pickle.dump(thing, open(fname,"wb"),pickle.HIGHEST_PROTOCOL)
print(" <- saving [%s] %s (%.01f kB) took %.02f ms"%(\
os.path.basename(fname),str(type(thing)),
sys.getsizeof(pickle.dumps(thing, -1))/1e3,
cm.timethis(time1))) |
def loadThing(self,fname,ext=".pkl"):
"""save any object from /swhlab4/ID_[fname].pkl"""
if ext and not ext in fname:
fname+=ext
fname=self.outpre+fname
time1=cm.timethis()
thing = pickle.load(open(fname,"rb"))
print(" -> loading [%s] (%.01f kB) took %.02f ms"%(\
os.path.basename(fname),
sys.getsizeof(pickle.dumps(thing, -1))/1e3,
cm.timethis(time1)))
return thing |
def deleteStuff(self,ext="*",spareInfo=True,spare=["_info.pkl"]):
"""delete /swhlab4/ID_*"""
print(" -- deleting /swhlab4/"+ext)
for fname in sorted(glob.glob(self.outpre+ext)):
reallyDelete=True
for item in spare:
if item in fname:
reallyDelete=False
if reallyDelete:
os.remove(fname) |
def validate_activatable_models():
"""
Raises a ValidationError for any ActivatableModel that has ForeignKeys or OneToOneFields that will
cause cascading deletions to occur. This function also raises a ValidationError if the activatable
model has not defined a Boolean field with the field name defined by the ACTIVATABLE_FIELD_NAME variable
on the model.
"""
for model in get_activatable_models():
# Verify the activatable model has an activatable boolean field
activatable_field = next((
f for f in model._meta.fields
if f.__class__ == models.BooleanField and f.name == model.ACTIVATABLE_FIELD_NAME
), None)
if activatable_field is None:
raise ValidationError((
'Model {0} is an activatable model. It must define an activatable BooleanField that '
'has a field name of model.ACTIVATABLE_FIELD_NAME (which defaults to is_active)'.format(model)
))
# Ensure all foreign keys and onetoone fields will not result in cascade deletions if not cascade deletable
if not model.ALLOW_CASCADE_DELETE:
for field in model._meta.fields:
if field.__class__ in (models.ForeignKey, models.OneToOneField):
if field.remote_field.on_delete == models.CASCADE:
raise ValidationError((
'Model {0} is an activatable model. All ForeignKey and OneToOneFields '
'must set on_delete methods to something other than CASCADE (the default). '
'If you want to explicitely allow cascade deletes, then you must set the '
'ALLOW_CASCADE_DELETE=True class variable on your model.'
).format(model)) |
def to_table(args, vdims=[]):
"Helper function to convet an Args object to a HoloViews Table"
if not Table:
return "HoloViews Table not available"
kdims = [dim for dim in args.constant_keys + args.varying_keys
if dim not in vdims]
items = [tuple([spec[k] for k in kdims+vdims])
for spec in args.specs]
return Table(items, kdims=kdims, vdims=vdims) |
def pprint_args(self, pos_args, keyword_args, infix_operator=None, extra_params={}):
"""
Method to define the positional arguments and keyword order
for pretty printing.
"""
if infix_operator and not (len(pos_args)==2 and keyword_args==[]):
raise Exception('Infix format requires exactly two'
' positional arguments and no keywords')
(kwargs,_,_,_) = self._pprint_args
self._pprint_args = (keyword_args + kwargs, pos_args, infix_operator, extra_params) |
def _pprint(self, cycle=False, flat=False, annotate=False, onlychanged=True, level=1, tab = ' '):
"""
Pretty printer that prints only the modified keywords and
generates flat representations (for repr) and optionally
annotates the top of the repr with a comment.
"""
(kwargs, pos_args, infix_operator, extra_params) = self._pprint_args
(br, indent) = ('' if flat else '\n', '' if flat else tab * level)
prettify = lambda x: isinstance(x, PrettyPrinted) and not flat
pretty = lambda x: x._pprint(flat=flat, level=level+1) if prettify(x) else repr(x)
params = dict(self.get_param_values())
show_lexsort = getattr(self, '_lexorder', None) is not None
modified = [k for (k,v) in self.get_param_values(onlychanged=onlychanged)]
pkwargs = [(k, params[k]) for k in kwargs if (k in modified)] + list(extra_params.items())
arg_list = [(k,params[k]) for k in pos_args] + pkwargs
lines = []
if annotate: # Optional annotating comment
len_ckeys, len_vkeys = len(self.constant_keys), len(self.varying_keys)
info_triple = (len(self),
', %d constant key(s)' % len_ckeys if len_ckeys else '',
', %d varying key(s)' % len_vkeys if len_vkeys else '')
annotation = '# == %d items%s%s ==\n' % info_triple
lines = [annotation]
if show_lexsort: lines.append('(')
if cycle:
lines.append('%s(...)' % self.__class__.__name__)
elif infix_operator:
level = level - 1
triple = (pretty(params[pos_args[0]]), infix_operator, pretty(params[pos_args[1]]))
lines.append('%s %s %s' % triple)
else:
lines.append('%s(' % self.__class__.__name__)
for (k,v) in arg_list:
lines.append('%s%s=%s' % (br+indent, k, pretty(v)))
lines.append(',')
lines = lines[:-1] +[br+(tab*(level-1))+')'] # Remove trailing comma
if show_lexsort:
lines.append(').lexsort(%s)' % ', '.join(repr(el) for el in self._lexorder))
return ''.join(lines) |
def spec_formatter(cls, spec):
" Formats the elements of an argument set appropriately"
return type(spec)((k, str(v)) for (k,v) in spec.items()) |
def _collect_by_key(self,specs):
"""
Returns a dictionary like object with the lists of values
collapsed by their respective key. Useful to find varying vs
constant keys and to find how fast keys vary.
"""
# Collect (key, value) tuples as list of lists, flatten with chain
allkeys = itertools.chain.from_iterable(
[[(k, run[k]) for k in run] for run in specs])
collection = defaultdict(list)
for (k,v) in allkeys: collection[k].append(v)
return collection |
def _cartesian_product(self, first_specs, second_specs):
"""
Takes the Cartesian product of the specifications. Result will
contain N specifications where N = len(first_specs) *
len(second_specs) and keys are merged.
Example: [{'a':1},{'b':2}] * [{'c':3},{'d':4}] =
[{'a':1,'c':3},{'a':1,'d':4},{'b':2,'c':3},{'b':2,'d':4}]
"""
return [ dict(zip(
list(s1.keys()) + list(s2.keys()),
list(s1.values()) + list(s2.values())
))
for s1 in first_specs for s2 in second_specs ] |
def summary(self):
"""
A succinct summary of the argument specifier. Unlike the repr,
a summary does not have to be complete but must supply the
most relevant information about the object to the user.
"""
print("Items: %s" % len(self))
varying_keys = ', '.join('%r' % k for k in self.varying_keys)
print("Varying Keys: %s" % varying_keys)
items = ', '.join(['%s=%r' % (k,v)
for (k,v) in self.constant_items])
if self.constant_items:
print("Constant Items: %s" % items) |
def _build_specs(self, specs, kwargs, fp_precision):
"""
Returns the specs, the remaining kwargs and whether or not the
constructor was called with kwarg or explicit specs.
"""
if specs is None:
overrides = param.ParamOverrides(self, kwargs,
allow_extra_keywords=True)
extra_kwargs = overrides.extra_keywords()
kwargs = dict([(k,v) for (k,v) in kwargs.items()
if k not in extra_kwargs])
rounded_specs = list(self.round_floats([extra_kwargs],
fp_precision))
if extra_kwargs=={}: return [], kwargs, True
else: return rounded_specs, kwargs, False
return list(self.round_floats(specs, fp_precision)), kwargs, True |
def _unique(self, sequence, idfun=repr):
"""
Note: repr() must be implemented properly on all objects. This
is implicitly assumed by Lancet when Python objects need to be
formatted to string representation.
"""
seen = {}
return [seen.setdefault(idfun(e),e) for e in sequence
if idfun(e) not in seen] |
def show(self, exclude=[]):
"""
Convenience method to inspect the available argument values in
human-readable format. The ordering of keys is determined by
how quickly they vary.
The exclude list allows specific keys to be excluded for
readability (e.g. to hide long, absolute filenames).
"""
ordering = self.constant_keys + self.varying_keys
spec_lines = [', '.join(['%s=%s' % (k, s[k]) for k in ordering
if (k in s) and (k not in exclude)])
for s in self.specs]
print('\n'.join(['%d: %s' % (i,l) for (i,l) in enumerate(spec_lines)])) |
def lexsort(self, *order):
"""
The lexical sort order is specified by a list of string
arguments. Each string is a key name prefixed by '+' or '-'
for ascending and descending sort respectively. If the key is
not found in the operand's set of varying keys, it is ignored.
"""
if order == []:
raise Exception("Please specify the keys for sorting, use"
"'+' prefix for ascending,"
"'-' for descending.)")
if not set(el[1:] for el in order).issubset(set(self.varying_keys)):
raise Exception("Key(s) specified not in the set of varying keys.")
sorted_args = copy.deepcopy(self)
specs_param = sorted_args.params('specs')
specs_param.constant = False
sorted_args.specs = self._lexsorted_specs(order)
specs_param.constant = True
sorted_args._lexorder = order
return sorted_args |
def _lexsorted_specs(self, order):
"""
A lexsort is specified using normal key string prefixed by '+'
(for ascending) or '-' for (for descending).
Note that in Python 2, if a key is missing, None is returned
(smallest Python value). In Python 3, an Exception will be
raised regarding comparison of heterogenous types.
"""
specs = self.specs[:]
if not all(el[0] in ['+', '-'] for el in order):
raise Exception("Please specify the keys for sorting, use"
"'+' prefix for ascending,"
"'-' for descending.)")
sort_cycles = [(el[1:], True if el[0]=='+' else False)
for el in reversed(order)
if el[1:] in self.varying_keys]
for (key, ascending) in sort_cycles:
specs = sorted(specs, key=lambda s: s.get(key, None),
reverse=(not ascending))
return specs |
def linspace(self, start, stop, n):
""" Simple replacement for numpy linspace"""
if n == 1: return [start]
L = [0.0] * n
nm1 = n - 1
nm1inv = 1.0 / nm1
for i in range(n):
L[i] = nm1inv * (start*(nm1 - i) + stop*i)
return L |
def extract_log(log_path, dict_type=dict):
"""
Parses the log file generated by a launcher and returns
dictionary with tid keys and specification values.
Ordering can be maintained by setting dict_type to the
appropriate constructor (i.e. OrderedDict). Keys are converted
from unicode to strings for kwarg use.
"""
log_path = (log_path if os.path.isfile(log_path)
else os.path.join(os.getcwd(), log_path))
with open(log_path,'r') as log:
splits = (line.split() for line in log)
uzipped = ((int(split[0]), json.loads(" ".join(split[1:]))) for split in splits)
szipped = [(i, dict((str(k),v) for (k,v) in d.items())) for (i,d) in uzipped]
return dict_type(szipped) |
def write_log(log_path, data, allow_append=True):
"""
Writes the supplied specifications to the log path. The data
may be supplied as either as a an Args or as a list of
dictionaries.
By default, specifications will be appropriately appended to
an existing log file. This can be disabled by setting
allow_append to False.
"""
append = os.path.isfile(log_path)
islist = isinstance(data, list)
if append and not allow_append:
raise Exception('Appending has been disabled'
' and file %s exists' % log_path)
if not (islist or isinstance(data, Args)):
raise Exception('Can only write Args objects or dictionary'
' lists to log file.')
specs = data if islist else data.specs
if not all(isinstance(el,dict) for el in specs):
raise Exception('List elements must be dictionaries.')
log_file = open(log_path, 'r+') if append else open(log_path, 'w')
start = int(log_file.readlines()[-1].split()[0])+1 if append else 0
ascending_indices = range(start, start+len(data))
log_str = '\n'.join(['%d %s' % (tid, json.dumps(el))
for (tid, el) in zip(ascending_indices,specs)])
log_file.write("\n"+log_str if append else log_str)
log_file.close() |
def directory(cls, directory, root=None, extension=None, **kwargs):
"""
Load all the files in a given directory selecting only files
with the given extension if specified. The given kwargs are
passed through to the normal constructor.
"""
root = os.getcwd() if root is None else root
suffix = '' if extension is None else '.' + extension.rsplit('.')[-1]
pattern = directory + os.sep + '*' + suffix
key = os.path.join(root, directory,'*').rsplit(os.sep)[-2]
format_parse = list(string.Formatter().parse(key))
if not all([el is None for el in zip(*format_parse)[1]]):
raise Exception('Directory cannot contain format field specifications')
return cls(key, pattern, root, **kwargs) |
def fields(self):
"""
Return the fields specified in the pattern using Python's
formatting mini-language.
"""
parse = list(string.Formatter().parse(self.pattern))
return [f for f in zip(*parse)[1] if f is not None] |
def _load_expansion(self, key, root, pattern):
"""
Loads the files that match the given pattern.
"""
path_pattern = os.path.join(root, pattern)
expanded_paths = self._expand_pattern(path_pattern)
specs=[]
for (path, tags) in expanded_paths:
filelist = [os.path.join(path,f) for f in os.listdir(path)] if os.path.isdir(path) else [path]
for filepath in filelist:
specs.append(dict(tags,**{key:os.path.abspath(filepath)}))
return sorted(specs, key=lambda s: s[key]) |
def _expand_pattern(self, pattern):
"""
From the pattern decomposition, finds the absolute paths
matching the pattern.
"""
(globpattern, regexp, fields, types) = self._decompose_pattern(pattern)
filelist = glob.glob(globpattern)
expansion = []
for fname in filelist:
if fields == []:
expansion.append((fname, {}))
continue
match = re.match(regexp, fname)
if match is None: continue
match_items = match.groupdict().items()
tags = dict((k,types.get(k, str)(v)) for (k,v) in match_items)
expansion.append((fname, tags))
return expansion |
def _decompose_pattern(self, pattern):
"""
Given a path pattern with format declaration, generates a
four-tuple (glob_pattern, regexp pattern, fields, type map)
"""
sep = '~lancet~sep~'
float_codes = ['e','E','f', 'F','g', 'G', 'n']
typecodes = dict([(k,float) for k in float_codes]
+ [('b',bin), ('d',int), ('o',oct), ('x',hex)])
parse = list(string.Formatter().parse(pattern))
text, fields, codes, _ = zip(*parse)
# Finding the field types from format string
types = []
for (field, code) in zip(fields, codes):
if code in ['', None]: continue
constructor = typecodes.get(code[-1], None)
if constructor: types += [(field, constructor)]
stars = ['' if not f else '*' for f in fields]
globpat = ''.join(text+star for (text,star) in zip(text,stars))
refields = ['' if not f else sep+('(?P<%s>.*?)'% f)+sep for f in fields]
parts = ''.join(text+group for (text,group) in zip(text, refields)).split(sep)
for i in range(0, len(parts), 2): parts[i] = re.escape(parts[i])
regexp_pattern = ''.join(parts).replace('\\*','.*')
fields = list(f for f in fields if f)
return globpat, regexp_pattern , fields, dict(types) |
def from_pattern(cls, pattern, filetype=None, key='filename', root=None, ignore=[]):
"""
Convenience method to directly chain a pattern processed by
FilePattern into a FileInfo instance.
Note that if a default filetype has been set on FileInfo, the
filetype argument may be omitted.
"""
filepattern = FilePattern(key, pattern, root=root)
if FileInfo.filetype and filetype is None:
filetype = FileInfo.filetype
elif filetype is None:
raise Exception("The filetype argument must be supplied unless "
"an appropriate default has been specified as "
"FileInfo.filetype")
return FileInfo(filepattern, key, filetype, ignore=ignore) |
def load(self, val, **kwargs):
"""
Load the file contents into the supplied pandas dataframe or
HoloViews Table. This allows a selection to be made over the
metadata before loading the file contents (may be slow).
"""
if Table and isinstance(val, Table):
return self.load_table(val, **kwargs)
elif DataFrame and isinstance(val, DataFrame):
return self.load_dframe(val, **kwargs)
else:
raise Exception("Type %s not a DataFrame or Table." % type(val)) |
def load_table(self, table):
"""
Load the file contents into the supplied Table using the
specified key and filetype. The input table should have the
filenames as values which will be replaced by the loaded
data. If data_key is specified, this key will be used to index
the loaded data to retrive the specified item.
"""
items, data_keys = [], None
for key, filename in table.items():
data_dict = self.filetype.data(filename[0])
current_keys = tuple(sorted(data_dict.keys()))
values = [data_dict[k] for k in current_keys]
if data_keys is None:
data_keys = current_keys
elif data_keys != current_keys:
raise Exception("Data keys are inconsistent")
items.append((key, values))
return Table(items, kdims=table.kdims, vdims=data_keys) |
def load_dframe(self, dframe):
"""
Load the file contents into the supplied dataframe using the
specified key and filetype.
"""
filename_series = dframe[self.key]
loaded_data = filename_series.map(self.filetype.data)
keys = [list(el.keys()) for el in loaded_data.values]
for key in set().union(*keys):
key_exists = key in dframe.columns
if key_exists:
self.warning("Appending '_data' suffix to data key %r to avoid"
"overwriting existing metadata with the same name." % key)
suffix = '_data' if key_exists else ''
dframe[key+suffix] = loaded_data.map(lambda x: x.get(key, np.nan))
return dframe |
def _info(self, source, key, filetype, ignore):
"""
Generates the union of the source.specs and the metadata
dictionary loaded by the filetype object.
"""
specs, mdata = [], {}
mdata_clashes = set()
for spec in source.specs:
if key not in spec:
raise Exception("Key %r not available in 'source'." % key)
mdata = dict((k,v) for (k,v) in filetype.metadata(spec[key]).items()
if k not in ignore)
mdata_spec = {}
mdata_spec.update(spec)
mdata_spec.update(mdata)
specs.append(mdata_spec)
mdata_clashes = mdata_clashes | (set(spec.keys()) & set(mdata.keys()))
# Metadata clashes can be avoided by using the ignore list.
if mdata_clashes:
self.warning("Loaded metadata keys overriding source keys.")
return specs |
async def _push(self, *args, **kwargs):
"""Push new data into the buffer. Resume looping if paused."""
self._data.append((args, kwargs))
if self._future is not None:
future, self._future = self._future, None
future.set_result(True) |
def newVersion():
"""increments version counter in swhlab/version.py"""
version=None
fname='../swhlab/version.py'
with open(fname) as f:
raw=f.read().split("\n")
for i,line in enumerate(raw):
if line.startswith("__counter__"):
if version is None:
version = int(line.split("=")[1])
raw[i]="__counter__=%d"%(version+1)
with open(fname,'w') as f:
f.write("\n".join(raw))
print("upgraded from version %03d to %03d"%(version,version+1)) |
def figureStimulus(abf,sweeps=[0]):
"""
Create a plot of one area of interest of a single sweep.
"""
stimuli=[2.31250, 2.35270]
for sweep in sweeps:
abf.setsweep(sweep)
for stimulus in stimuli:
S1=int(abf.pointsPerSec*stimulus)
S2=int(abf.pointsPerSec*(stimulus+0.001)) # 1ms of blanking
abf.sweepY[S1:S2]=np.nan # blank out the stimulus area
I1=int(abf.pointsPerSec*2.2) # time point (sec) to start
I2=int(abf.pointsPerSec*2.6) # time point (sec) to end
baseline=np.average(abf.sweepY[int(abf.pointsPerSec*2.0):int(abf.pointsPerSec*2.2)])
Ys=lowPassFilter(abf.sweepY[I1:I2])-baseline
Xs=abf.sweepX2[I1:I1+len(Ys)].flatten()
plt.plot(Xs,Ys,alpha=.5,lw=2)
return |
def phasicTonic(self,m1=None,m2=None,chunkMs=50,
quietPercentile=10,histResolution=1):
"""
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.
"""
# prepare sectioning values to be used later (marker positions)
m1=0 if m1 is None else m1*self.pointsPerSec
m2=len(abf.sweepY) if m2 is None else m2*self.pointsPerSec
m1,m2=int(m1),int(m2)
# prepare histogram values to be used later
padding=200 # pA or mV of maximum expected deviation
chunkPoints=int(chunkMs*self.pointsPerMs)
histBins=int((padding*2)/histResolution)
# center the data at 0 using peak histogram, not the mean
#Y=self.sweepY[m1:m2]
Y=self.sweepYfilteredHisto()[m1:m2]
hist,bins=np.histogram(Y,bins=2*padding)
#Yoffset=bins[np.where(hist==max(hist))[0][0]]
#Y=Y-Yoffset # we don't have to, but PDF math is easier
# create histogram for all data in the sweep
nChunks=int(len(Y)/chunkPoints)
hist,bins=np.histogram(Y,bins=histBins,range=(-padding,padding))
# create histogram for just the sweeps with the lowest variance
chunks=np.reshape(Y[:nChunks*chunkPoints],(nChunks,chunkPoints))
#variances=np.var(chunks,axis=1)
variances=np.ptp(chunks,axis=1)
percentiles=np.empty(len(variances))
for i,variance in enumerate(variances):
percentiles[i]=sorted(variances).index(variance)/len(variances)*100
blData=chunks[np.where(percentiles<=quietPercentile)[0]].flatten()
blHist,blBins=np.histogram(blData,bins=histBins,range=(-padding,padding))
blHist=blHist/max(blHist)*max(hist)
# determine the phasic current by subtracting-out the baseline
diff=hist-blHist
return diff/abf.pointsPerSec |
def doStuff(ABFfolder,analyze=False,convert=False,index=True,overwrite=True,
launch=True):
"""Inelegant for now, but lets you manually analyze every ABF in a folder."""
IN=INDEX(ABFfolder)
if analyze:
IN.analyzeAll()
if convert:
IN.convertImages() |
def analyzeSingle(abfFname):
"""Reanalyze data for a single ABF. Also remakes child and parent html."""
assert os.path.exists(abfFname) and abfFname.endswith(".abf")
ABFfolder,ABFfname=os.path.split(abfFname)
abfID=os.path.splitext(ABFfname)[0]
IN=INDEX(ABFfolder)
IN.analyzeABF(abfID)
IN.scan()
IN.html_single_basic([abfID],overwrite=True)
IN.html_single_plot([abfID],overwrite=True)
IN.scan()
IN.html_index()
return |
def scan(self):
"""
scan folder1 and folder2 into files1 and files2.
since we are on windows, simplify things by making them all lowercase.
this WILL cause problems on 'nix operating systems.If this is the case,
just run a script to rename every file to all lowercase.
"""
t1=cm.timeit()
self.files1=cm.list_to_lowercase(sorted(os.listdir(self.folder1)))
self.files2=cm.list_to_lowercase(sorted(os.listdir(self.folder2)))
self.files1abf=[x for x in self.files1 if x.endswith(".abf")]
self.files1abf=cm.list_to_lowercase(cm.abfSort(self.files1abf))
self.IDs=[x[:-4] for x in self.files1abf]
self.log.debug("folder1 has %d files",len(self.files1))
self.log.debug("folder1 has %d abfs",len(self.files1abf))
self.log.debug("folder2 has %d files",len(self.files2))
self.log.debug("scanning folders took %s",cm.timeit(t1)) |
def convertImages(self):
"""
run this to turn all folder1 TIFs and JPGs into folder2 data.
TIFs will be treated as micrographs and converted to JPG with enhanced
contrast. JPGs will simply be copied over.
"""
# copy over JPGs (and such)
exts=['.jpg','.png']
for fname in [x for x in self.files1 if cm.ext(x) in exts]:
ID="UNKNOWN"
if len(fname)>8 and fname[:8] in self.IDs:
ID=fname[:8]
fname2=ID+"_jpg_"+fname
if not fname2 in self.files2:
self.log.info("copying over [%s]"%fname2)
shutil.copy(os.path.join(self.folder1,fname),os.path.join(self.folder2,fname2))
if not fname[:8]+".abf" in self.files1:
self.log.error("orphan image: %s",fname)
# convert TIFs (and such) to JPGs
exts=['.tif','.tiff']
for fname in [x for x in self.files1 if cm.ext(x) in exts]:
ID="UNKNOWN"
if len(fname)>8 and fname[:8] in self.IDs:
ID=fname[:8]
fname2=ID+"_tif_"+fname+".jpg"
if not fname2 in self.files2:
self.log.info("converting micrograph [%s]"%fname2)
imaging.TIF_to_jpg(os.path.join(self.folder1,fname),saveAs=os.path.join(self.folder2,fname2))
if not fname[:8]+".abf" in self.files1:
self.log.error("orphan image: %s",fname) |
def analyzeAll(self):
"""analyze every unanalyzed ABF in the folder."""
searchableData=str(self.files2)
self.log.debug("considering analysis for %d ABFs",len(self.IDs))
for ID in self.IDs:
if not ID+"_" in searchableData:
self.log.debug("%s needs analysis",ID)
try:
self.analyzeABF(ID)
except:
print("EXCEPTION! "*100)
else:
self.log.debug("%s has existing analysis, not overwriting",ID)
self.log.debug("verified analysis of %d ABFs",len(self.IDs)) |
def analyzeABF(self,ID):
"""
Analye a single ABF: make data, index it.
If called directly, will delete all ID_data_ and recreate it.
"""
for fname in self.files2:
if fname.startswith(ID+"_data_"):
self.log.debug("deleting [%s]",fname)
os.remove(os.path.join(self.folder2,fname))
self.log.info("analyzing (with overwrite) [%s]",ID)
protocols.analyze(os.path.join(self.folder1,ID+".abf")) |
def htmlFor(self,fname):
"""return appropriate HTML determined by file extension."""
if os.path.splitext(fname)[1].lower() in ['.jpg','.png']:
html='<a href="%s"><img src="%s"></a>'%(fname,fname)
if "_tif_" in fname:
html=html.replace('<img ','<img class="datapic micrograph"')
if "_plot_" in fname:
html=html.replace('<img ','<img class="datapic intrinsic" ')
if "_experiment_" in fname:
html=html.replace('<img ','<img class="datapic experiment" ')
elif os.path.splitext(fname)[1].lower() in ['.html','.htm']:
html='LINK: %s'%fname
else:
html='<br>Not sure how to show: [%s]</br>'%fname
return html |
def html_single_basic(self,abfID,launch=False,overwrite=False):
"""
generate a generic flat file html for an ABF parent. You could give
this a single ABF ID, its parent ID, or a list of ABF IDs.
If a child ABF is given, the parent will automatically be used.
"""
if type(abfID) is str:
abfID=[abfID]
for thisABFid in cm.abfSort(abfID):
parentID=cm.parent(self.groups,thisABFid)
saveAs=os.path.abspath("%s/%s_basic.html"%(self.folder2,parentID))
if overwrite is False and os.path.basename(saveAs) in self.files2:
continue
filesByType=cm.filesByType(self.groupFiles[parentID])
html=""
html+='<div style="background-color: #DDDDDD;">'
html+='<span class="title">summary of data from: %s</span></br>'%parentID
html+='<code>%s</code>'%os.path.abspath(self.folder1+"/"+parentID+".abf")
html+='</div>'
catOrder=["experiment","plot","tif","other"]
categories=cm.list_order_by(filesByType.keys(),catOrder)
for category in [x for x in categories if len(filesByType[x])]:
if category=='experiment':
html+="<h3>Experimental Data:</h3>"
elif category=='plot':
html+="<h3>Intrinsic Properties:</h3>"
elif category=='tif':
html+="<h3>Micrographs:</h3>"
elif category=='other':
html+="<h3>Additional Files:</h3>"
else:
html+="<h3>????:</h3>"
#html+="<hr>"
#html+='<br>'*3
for fname in filesByType[category]:
html+=self.htmlFor(fname)
html+='<br>'*3
print("creating",saveAs,'...')
style.save(html,saveAs,launch=launch) |
def html_single_plot(self,abfID,launch=False,overwrite=False):
"""create ID_plot.html of just intrinsic properties."""
if type(abfID) is str:
abfID=[abfID]
for thisABFid in cm.abfSort(abfID):
parentID=cm.parent(self.groups,thisABFid)
saveAs=os.path.abspath("%s/%s_plot.html"%(self.folder2,parentID))
if overwrite is False and os.path.basename(saveAs) in self.files2:
continue
filesByType=cm.filesByType(self.groupFiles[parentID])
html=""
html+='<div style="background-color: #DDDDFF;">'
html+='<span class="title">intrinsic properties for: %s</span></br>'%parentID
html+='<code>%s</code>'%os.path.abspath(self.folder1+"/"+parentID+".abf")
html+='</div>'
for fname in filesByType['plot']:
html+=self.htmlFor(fname)
print("creating",saveAs,'...')
style.save(html,saveAs,launch=launch) |
def lowpass(data,filterSize=None):
"""
minimal complexity low-pass filtering.
Filter size is how "wide" the filter will be.
Sigma will be 1/10 of this filter width.
If filter size isn't given, it will be 1/10 of the data size.
"""
if filterSize is None:
filterSize=len(data)/10
kernel=kernel_gaussian(size=filterSize)
data=convolve(data,kernel) # do the convolution with padded edges
return data |
def convolve(signal,kernel):
"""
This applies a kernel to a signal through convolution and returns the result.
Some magic is done at the edges so the result doesn't apprach zero:
1. extend the signal's edges with len(kernel)/2 duplicated values
2. perform the convolution ('same' mode)
3. slice-off the ends we added
4. return the same number of points as the original
"""
pad=np.ones(len(kernel)/2)
signal=np.concatenate((pad*signal[0],signal,pad*signal[-1]))
signal=np.convolve(signal,kernel,mode='same')
signal=signal[len(pad):-len(pad)]
return signal |
def timeit(timer=None):
"""simple timer. returns a time object, or a string."""
if timer is None:
return time.time()
else:
took=time.time()-timer
if took<1:
return "%.02f ms"%(took*1000.0)
elif took<60:
return "%.02f s"%(took)
else:
return "%.02f min"%(took/60.0) |
def list_move_to_front(l,value='other'):
"""if the value is in the list, move it to the front and return it."""
l=list(l)
if value in l:
l.remove(value)
l.insert(0,value)
return l |
def list_move_to_back(l,value='other'):
"""if the value is in the list, move it to the back and return it."""
l=list(l)
if value in l:
l.remove(value)
l.append(value)
return l |
def list_order_by(l,firstItems):
"""given a list and a list of items to be first, return the list in the
same order except that it begins with each of the first items."""
l=list(l)
for item in firstItems[::-1]: #backwards
if item in l:
l.remove(item)
l.insert(0,item)
return l |
def abfSort(IDs):
"""
given a list of goofy ABF names, return it sorted intelligently.
This places things like 16o01001 after 16901001.
"""
IDs=list(IDs)
monO=[]
monN=[]
monD=[]
good=[]
for ID in IDs:
if ID is None:
continue
if 'o' in ID:
monO.append(ID)
elif 'n' in ID:
monN.append(ID)
elif 'd' in ID:
monD.append(ID)
else:
good.append(ID)
return sorted(good)+sorted(monO)+sorted(monN)+sorted(monD) |
def abfGroups(abfFolder):
"""
Given a folder path or list of files, return groups (dict) by cell.
Rules which define parents (cells):
* assume each cell has one or several ABFs
* that cell can be labeled by its "ID" or "parent" ABF (first abf)
* the ID is just the filename of the first abf without .abf
* if any file starts with an "ID", that ID becomes a parent.
* examples could be 16o14044.TIF or 16o14044-cell1-stuff.jpg
* usually this is done by saving a pic of the cell with same filename
Returns a dict of "parent IDs" representing the "children"
groups["16o14041"] = ["16o14041","16o14042","16o14043"]
From there, getting children files is trivial. Just find all files in
the same folder whose filenames begin with one of the children.
"""
# prepare the list of files, filenames, and IDs
files=False
if type(abfFolder) is str and os.path.isdir(abfFolder):
files=abfSort(os.listdir(abfFolder))
elif type(abfFolder) is list:
files=abfSort(abfFolder)
assert type(files) is list
files=list_to_lowercase(files)
# group every filename in a different list, and determine parents
abfs, IDs, others, parents, days = [],[],[],[],[]
for fname in files:
if fname.endswith(".abf"):
abfs.append(fname)
IDs.append(fname[:-4])
days.append(fname[:5])
else:
others.append(fname)
for ID in IDs:
for fname in others:
if fname.startswith(ID):
parents.append(ID)
parents=abfSort(set(parents)) # allow only one copy each
days=abfSort(set(days)) # allow only one copy each
# match up children with parents, respecting daily orphans.
groups={}
for day in days:
parent=None
for fname in [x for x in abfs if x.startswith(day)]:
ID=fname[:-4]
if ID in parents:
parent=ID
if not parent in groups.keys():
groups[parent]=[]
groups[parent].extend([ID])
return groups |
def abfGroupFiles(groups,folder):
"""
when given a dictionary where every key contains a list of IDs, replace
the keys with the list of files matching those IDs. This is how you get a
list of files belonging to each child for each parent.
"""
assert os.path.exists(folder)
files=os.listdir(folder)
group2={}
for parent in groups.keys():
if not parent in group2.keys():
group2[parent]=[]
for ID in groups[parent]:
for fname in [x.lower() for x in files if ID in x.lower()]:
group2[parent].extend([fname])
return group2 |
def parent(groups,ID):
"""given a groups dictionary and an ID, return its actual parent ID."""
if ID in groups.keys():
return ID # already a parent
if not ID in groups.keys():
for actualParent in groups.keys():
if ID in groups[actualParent]:
return actualParent # found the actual parent
return None |
def filesByType(fileList):
"""
given a list of files, return them as a dict sorted by type:
* plot, tif, data, other
"""
features=["plot","tif","data","other","experiment"]
files={}
for feature in features:
files[feature]=[]
for fname in fileList:
other=True
for feature in features:
if "_"+feature+"_" in fname:
files[feature].extend([fname])
other=False
if other:
files['other'].extend([fname])
return files |
def userFolder():
"""return the semi-temporary user folder"""
#path=os.path.abspath(tempfile.gettempdir()+"/swhlab/")
#don't use tempdir! it will get deleted easily.
path=os.path.expanduser("~")+"/.swhlab/" # works on windows or linux
# for me, path=r"C:\Users\swharden\.swhlab"
if not os.path.exists(path):
print("creating",path)
os.mkdir(path)
return os.path.abspath(path) |
def abfFname_Load():
"""return the path of the last loaded ABF."""
fname=userFolder()+"/abfFname.ini"
if os.path.exists(fname):
abfFname=open(fname).read().strip()
if os.path.exists(abfFname) or abfFname.endswith("_._"):
return abfFname
return os.path.abspath(os.sep) |
def abfFname_Save(abfFname):
"""return the path of the last loaded ABF."""
fname=userFolder()+"/abfFname.ini"
with open(fname,'w') as f:
f.write(os.path.abspath(abfFname))
return |
def gui_getFile():
"""
Launch an ABF file selection file dialog.
This is smart, and remembers (through reboots) where you last were.
"""
import tkinter as tk
from tkinter import filedialog
root = tk.Tk() # this is natively supported by python
root.withdraw() # hide main window
root.wm_attributes('-topmost', 1) # always on top
fname = filedialog.askopenfilename(title = "select ABF file",
filetypes=[('ABF Files', '.abf')],
initialdir=os.path.dirname(abfFname_Load()))
if fname.endswith(".abf"):
abfFname_Save(fname)
return fname
else:
print("didn't select an ABF!")
return None |
def gui_getFolder():
"""
Launch a folder selection dialog.
This is smart, and remembers (through reboots) where you last were.
"""
import tkinter as tk
from tkinter import filedialog
root = tk.Tk() # this is natively supported by python
root.withdraw() # hide main window
root.wm_attributes('-topmost', 1) # always on top
fname = filedialog.askdirectory(title = "select folder of ABFs",
initialdir=os.path.dirname(abfFname_Load()))
if len(fname)>3:
abfFname_Save(fname+"/_._")
return fname
else:
print("didn't select an ABF!")
return None |
async def _try_catch_coro(emitter, event, listener, coro):
"""Coroutine wrapper to catch errors after async scheduling.
Args:
emitter (EventEmitter): The event emitter that is attempting to
call a listener.
event (str): The event that triggered the emitter.
listener (async def): The async def that was used to generate the coro.
coro (coroutine): The coroutine that should be tried.
If an exception is caught the function will use the emitter to emit the
failure event. If, however, the current event _is_ the failure event then
the method reraises. The reraised exception may show in debug mode for the
event loop but is otherwise silently dropped.
"""
try:
await coro
except Exception as exc:
if event == emitter.LISTENER_ERROR_EVENT:
raise
emitter.emit(emitter.LISTENER_ERROR_EVENT, event, listener, exc) |
def _check_limit(self, event):
"""Check if the listener limit is hit and warn if needed."""
if self.count(event) > self.max_listeners:
warnings.warn(
'Too many listeners for event {}'.format(event),
ResourceWarning,
) |
def add_listener(self, event, listener):
"""Bind a listener to a particular event.
Args:
event (str): The name of the event to listen for. This may be any
string value.
listener (def or async def): The callback to execute when the event
fires. This may be a sync or async function.
"""
self.emit('new_listener', event, listener)
self._listeners[event].append(listener)
self._check_limit(event)
return self |
def once(self, event, listener):
"""Add a listener that is only called once."""
self.emit('new_listener', event, listener)
self._once[event].append(listener)
self._check_limit(event)
return self |
def remove_listener(self, event, listener):
"""Remove a listener from the emitter.
Args:
event (str): The event name on which the listener is bound.
listener: A reference to the same object given to add_listener.
Returns:
bool: True if a listener was removed else False.
This method only removes one listener at a time. If a listener is
attached multiple times then this method must be called repeatedly.
Additionally, this method removes listeners first from the those
registered with 'on' or 'add_listener'. If none are found it continue
to remove afterwards from those added with 'once'.
"""
with contextlib.suppress(ValueError):
self._listeners[event].remove(listener)
return True
with contextlib.suppress(ValueError):
self._once[event].remove(listener)
return True
return False |
def remove_all_listeners(self, event=None):
"""Remove all listeners, or those of the specified *event*.
It's not a good idea to remove listeners that were added elsewhere in
the code, especially when it's on an emitter that you didn't create
(e.g. sockets or file streams).
"""
if event is None:
self._listeners = collections.defaultdict(list)
self._once = collections.defaultdict(list)
else:
del self._listeners[event]
del self._once[event] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.