_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q263900 | ABFplot.figure_protocol | validation | def figure_protocol(self):
"""plot the current sweep protocol."""
self.log.debug("creating overlayed protocols plot")
self.figure()
| python | {
"resource": ""
} |
q263901 | ABFplot.figure_protocols | validation | 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)
| python | {
"resource": ""
} |
q263902 | clampfit_rename | validation | 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 character must be a single character"
assert os.path.exists(path), "path doesn't exist"
| python | {
"resource": ""
} |
q263903 | filesByExtension | validation | 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:
| python | {
"resource": ""
} |
q263904 | filesByCell | validation | 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 enumerate([elem for elem in fnames if elem.startswith(day) and elem.endswith(".abf")]):
| python | {
"resource": ""
} |
q263905 | ABFindex.folderScan | validation | 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)
self.log.info("scanning [%s]",self.abfFolder)
if not os.path.exists(self.abfFolder):
self.log.error("path doesn't exist: [%s]",abfFolder)
return
self.abfFolder2=os.path.abspath(self.abfFolder+"/swhlab/")
if not os.path.exists(self.abfFolder2):
self.log.error("./swhlab/ doesn't exist. creating it...")
os.mkdir(self.abfFolder2)
self.fnames=os.listdir(self.abfFolder)
self.fnames2=os.listdir(self.abfFolder2)
self.log.debug("./ has %d files",len(self.fnames))
self.log.debug("./swhlab/ | python | {
"resource": ""
} |
q263906 | ABFindex.html_index | validation | 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_splash.html" target="content">./%s/</a><br>'%os.path.basename(self.abfFolder)
for ID in smartSort(self.fnamesByCell.keys()):
link=''
if ID+".html" in self.fnames2:
link='href="%s.html" target="content"'%ID
| python | {
"resource": ""
} |
q263907 | ABFindex.html_singleAll | validation | 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":
| python | {
"resource": ""
} |
q263908 | proto_01_01_HP010 | validation | 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
| python | {
"resource": ""
} |
q263909 | proto_01_12_steps025 | validation | 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
| python | {
"resource": ""
} |
q263910 | proto_01_13_steps025dual | validation | 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_'+feature)
f1=swhlab.ap.getAvgBySweep(abf,'freq',None,1)
f2=swhlab.ap.getAvgBySweep(abf,'freq',1,None)
f1=np.nan_to_num(f1)
f2=np.nan_to_num(f2)
Xs=abf.clampValues(abf.dataX[int(abf.protoSeqX[1]+.01)])
swhlab.plot.new(abf,title="gain function",xlabel="command current (pA)",
| python | {
"resource": ""
} |
q263911 | proto_02_01_MT70 | validation | def proto_02_01_MT70(abf=exampleABF):
"""repeated membrane tests."""
standard_overlayWithAverage(abf)
swhlab.memtest.memtest(abf)
| python | {
"resource": ""
} |
q263912 | proto_02_03_IVfast | validation | 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)
| python | {
"resource": ""
} |
q263913 | proto_04_01_MTmon70s2 | validation | def proto_04_01_MTmon70s2(abf=exampleABF):
"""repeated membrane tests, likely with drug added. Maybe IPSCs."""
standard_inspect(abf)
swhlab.memtest.memtest(abf)
| python | {
"resource": ""
} |
q263914 | proto_VC_50_MT_IV | validation | 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) | python | {
"resource": ""
} |
q263915 | indexImages | validation | 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.basename(item)
| python | {
"resource": ""
} |
q263916 | BaseActivatableModel.save | validation | 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 != current_activable_value
self.__original_activatable_value = current_activable_value
ret_val = super(BaseActivatableModel, self).save(*args, **kwargs)
# Emit the signals for when the is_active flag is changed | python | {
"resource": ""
} |
q263917 | BaseActivatableModel.delete | validation | 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)
| python | {
"resource": ""
} |
q263918 | Command.show | validation | 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>',
'batch_description': '<batch_description>',
'launcher': '<launcher>',
'timestamp_format': '<timestamp_format>',
| python | {
"resource": ""
} |
q263919 | Launcher.get_root_directory | validation | 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:
| python | {
"resource": ""
} |
q263920 | Launcher._append_log | validation | 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 = | python | {
"resource": ""
} |
q263921 | Launcher._record_info | validation | 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
info file is updated with the end-time.
"""
info_path = os.path.join(self.root_directory, ('%s.info' % self.batch_name))
if setup_info is None:
try:
with open(info_path, 'r') as info_file:
setup_info = json.load(info_file) | python | {
"resource": ""
} |
q263922 | Launcher._launch_process_group | validation | 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"
| python | {
"resource": ""
} |
q263923 | Launcher.summary | validation | 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:
| python | {
"resource": ""
} |
q263924 | QLauncher._qsub_collate_and_launch | validation | 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', | python | {
"resource": ""
} |
q263925 | QLauncher._qsub_block | validation | 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(
| python | {
"resource": ""
} |
q263926 | ScriptLauncher._launch_process_group | validation | 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
| python | {
"resource": ""
} |
q263927 | review_and_launch.cross_check_launchers | validation | 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
| python | {
"resource": ""
} |
q263928 | review_and_launch._launch_all | validation | def _launch_all(self, launchers):
"""
Launches all available launchers.
"""
for launcher in launchers:
| python | {
"resource": ""
} |
q263929 | review_and_launch._review_all | validation | 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:
| python | {
"resource": ""
} |
q263930 | review_and_launch.input_options | validation | 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()
| python | {
"resource": ""
} |
q263931 | FileType.save | validation | 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:
| python | {
"resource": ""
} |
q263932 | FileType._savepath | validation | 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,
| python | {
"resource": ""
} |
q263933 | FileType.file_supported | validation | 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
| python | {
"resource": ""
} |
q263934 | ImageFile.save | validation | def save(self, filename, imdata, **data):
"""
Data may be either a PIL Image object or a Numpy array.
"""
if isinstance(imdata, numpy.ndarray):
| python | {
"resource": ""
} |
q263935 | fileModifiedTimestamp | validation | def fileModifiedTimestamp(fname):
"""return "YYYY-MM-DD" when the file was modified."""
modifiedTime=os.path.getmtime(fname)
| python | {
"resource": ""
} |
q263936 | loadResults | validation | 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
| python | {
"resource": ""
} |
q263937 | ndist | validation | 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))
| python | {
"resource": ""
} |
q263938 | ABF.abfinfo | validation | 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)
| python | {
"resource": ""
} |
q263939 | ABF.headerHTML | validation | 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
| python | {
"resource": ""
} |
q263940 | ABF.generate_colormap | validation | 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 | python | {
"resource": ""
} |
q263941 | ABF.get_data_around | validation | 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) | python | {
"resource": ""
} |
q263942 | ABF.filter_gaussian | validation | 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:
| python | {
"resource": ""
} |
q263943 | validate_activatable_models | validation | 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:
| python | {
"resource": ""
} |
q263944 | to_table | validation | 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 | python | {
"resource": ""
} |
q263945 | PrettyPrinted.pprint_args | validation | 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'
| python | {
"resource": ""
} |
q263946 | Arguments.spec_formatter | validation | def spec_formatter(cls, spec):
" Formats the elements of an argument set appropriately"
| python | {
"resource": ""
} |
q263947 | Arguments._collect_by_key | validation | 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
| python | {
"resource": ""
} |
q263948 | Arguments.summary | validation | 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 | python | {
"resource": ""
} |
q263949 | Args._build_specs | validation | 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])
| python | {
"resource": ""
} |
q263950 | Args.show | validation | 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 | python | {
"resource": ""
} |
q263951 | Args.lexsort | validation | 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.)")
| python | {
"resource": ""
} |
q263952 | Range.linspace | validation | def linspace(self, start, stop, n):
""" Simple replacement for numpy linspace"""
if n == 1: return [start]
L = [0.0] * n
nm1 = n - 1
nm1inv = | python | {
"resource": ""
} |
q263953 | Log.extract_log | validation | 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:
| python | {
"resource": ""
} |
q263954 | Log.write_log | validation | 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):
| python | {
"resource": ""
} |
q263955 | FilePattern.directory | validation | 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 + | python | {
"resource": ""
} |
q263956 | FilePattern.fields | validation | def fields(self):
"""
Return the fields specified in the pattern using Python's
formatting mini-language.
"""
| python | {
"resource": ""
} |
q263957 | FilePattern._load_expansion | validation | 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 | python | {
"resource": ""
} |
q263958 | FilePattern._expand_pattern | validation | 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
| python | {
"resource": ""
} |
q263959 | FileInfo.from_pattern | validation | 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:
| python | {
"resource": ""
} |
q263960 | FileInfo.load_table | validation | 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()))
| python | {
"resource": ""
} |
q263961 | FileInfo.load_dframe | validation | 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"
| python | {
"resource": ""
} |
q263962 | FileInfo._info | validation | 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 = {}
| python | {
"resource": ""
} |
q263963 | EventIterator._push | validation | async def _push(self, *args, **kwargs):
"""Push new data into the buffer. Resume looping if paused."""
self._data.append((args, kwargs))
if self._future | python | {
"resource": ""
} |
q263964 | figureStimulus | validation | 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) | python | {
"resource": ""
} |
q263965 | doStuff | validation | def doStuff(ABFfolder,analyze=False,convert=False,index=True,overwrite=True,
launch=True):
"""Inelegant for | python | {
"resource": ""
} |
q263966 | analyzeSingle | validation | 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)
| python | {
"resource": ""
} |
q263967 | INDEX.scan | validation | 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))
| python | {
"resource": ""
} |
q263968 | INDEX.convertImages | validation | 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)
| python | {
"resource": ""
} |
q263969 | INDEX.analyzeAll | validation | 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)
| python | {
"resource": ""
} |
q263970 | INDEX.htmlFor | validation | 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 | python | {
"resource": ""
} |
q263971 | INDEX.html_single_basic | validation | 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>"
| python | {
"resource": ""
} |
q263972 | INDEX.html_single_plot | validation | 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;">'
| python | {
"resource": ""
} |
q263973 | convolve | validation | 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
| python | {
"resource": ""
} |
q263974 | timeit | validation | 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)
| python | {
"resource": ""
} |
q263975 | list_move_to_front | validation | 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 | python | {
"resource": ""
} |
q263976 | list_move_to_back | validation | 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 | python | {
"resource": ""
} |
q263977 | list_order_by | validation | 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 | python | {
"resource": ""
} |
q263978 | abfSort | validation | 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:
| python | {
"resource": ""
} |
q263979 | abfGroupFiles | validation | 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():
| python | {
"resource": ""
} |
q263980 | parent | validation | 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():
| python | {
"resource": ""
} |
q263981 | userFolder | validation | 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 | python | {
"resource": ""
} |
q263982 | _try_catch_coro | validation | 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.
| python | {
"resource": ""
} |
q263983 | EventEmitter._check_limit | validation | def _check_limit(self, event):
"""Check if the listener limit is hit and warn if needed."""
if self.count(event) > self.max_listeners: | python | {
"resource": ""
} |
q263984 | EventEmitter.add_listener | validation | 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
| python | {
"resource": ""
} |
q263985 | EventEmitter.once | validation | def once(self, event, listener):
"""Add a listener that is only called once."""
self.emit('new_listener', event, listener)
| python | {
"resource": ""
} |
q263986 | EventEmitter.remove_listener | validation | 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 | python | {
"resource": ""
} |
q263987 | EventEmitter._dispatch_coroutine | validation | def _dispatch_coroutine(self, event, listener, *args, **kwargs):
"""Schedule a coroutine for execution.
Args:
event (str): The name of the event that triggered this call.
listener (async def): The async def that needs to be executed.
*args: Any number of positional arguments.
**kwargs: Any number of keyword arguments.
The values of *args and **kwargs are passed, unaltered, to the async
def when generating the coro. If there is an exception generating the
coro, such as the wrong number of arguments, the emitter's error event
is triggered. If the triggering event _is_ the emitter's error event
then the exception is reraised. The reraised exception may show in
| python | {
"resource": ""
} |
q263988 | EventEmitter._dispatch_function | validation | def _dispatch_function(self, event, listener, *args, **kwargs):
"""Execute a sync function.
Args:
event (str): The name of the event that triggered this call.
listener (def): The def that needs to be executed.
*args: Any number of positional arguments.
**kwargs: Any number of keyword arguments.
The values of *args and **kwargs are passed, unaltered, to the def
when exceuting. If there is an exception executing the def, such as the
wrong number of arguments, the emitter's error event is triggered. If
the triggering event _is_ the emitter's error event then the exception
is reraised. The | python | {
"resource": ""
} |
q263989 | EventEmitter._dispatch | validation | def _dispatch(self, event, listener, *args, **kwargs):
"""Dispatch an event to a listener.
Args:
event (str): The name of the event that triggered this call.
listener (def or async def): The listener to trigger.
*args: Any number of positional arguments.
**kwargs: Any number of keyword arguments.
This method inspects the listener. If it is a def it dispatches the
listener to a method that will execute that def. If it is an async def
it dispatches it to a method that will schedule the resulting coro with
the event loop.
| python | {
"resource": ""
} |
q263990 | EventEmitter.emit | validation | def emit(self, event, *args, **kwargs):
"""Call each listener for the event with the given arguments.
Args:
event (str): The event to trigger listeners on.
*args: Any number of positional arguments.
**kwargs: Any number of keyword arguments.
This method passes all arguments other than the event name directly
to the listeners. If a listener raises an exception for any reason the
'listener-error', or current value of LISTENER_ERROR_EVENT, is emitted.
Listeners to this event are given the event name, listener object, and
the exception raised. If an error listener fails it does so silently.
All event listeners are fired in a deferred way so this method returns
immediately. The calling coro must yield at some point for | python | {
"resource": ""
} |
q263991 | EventEmitter.count | validation | def count(self, event):
"""Get the number of listeners for the event.
Args:
event (str): The event for which to count all listeners.
The resulting count is a combination | python | {
"resource": ""
} |
q263992 | genPNGs | validation | def genPNGs(folder,files=None):
"""Convert each TIF to PNG. Return filenames of new PNGs."""
if files is None:
files=glob.glob(folder+"/*.*")
new=[]
for fname in files:
ext=os.path.basename(fname).split(".")[-1].lower()
if ext in ['tif','tiff']:
| python | {
"resource": ""
} |
q263993 | htmlABF | validation | def htmlABF(ID,group,d,folder,overwrite=False):
"""given an ID and the dict of files, generate a static html for that abf."""
fname=folder+"/swhlab4/%s_index.html"%ID
if overwrite is False and os.path.exists(fname):
return
html=TEMPLATES['abf']
| python | {
"resource": ""
} |
q263994 | genIndex | validation | def genIndex(folder,forceIDs=[]):
"""expects a folder of ABFs."""
if not os.path.exists(folder+"/swhlab4/"):
print(" !! cannot index if no /swhlab4/")
return
timestart=cm.timethis()
files=glob.glob(folder+"/*.*") #ABF folder
files.extend(glob.glob(folder+"/swhlab4/*.*"))
print(" -- indexing glob took %.02f ms"%(cm.timethis(timestart)*1000))
files.extend(genPNGs(folder,files))
files=sorted(files)
timestart=cm.timethis()
d=cm.getIDfileDict(files) #TODO: this is really slow
print(" -- filedict length:",len(d))
print(" -- generating ID dict took %.02f ms"%(cm.timethis(timestart)*1000))
groups=cm.getABFgroups(files)
print(" -- groups length:",len(groups))
for ID in sorted(list(groups.keys())):
overwrite=False
for abfID in groups[ID]:
| python | {
"resource": ""
} |
q263995 | plotAllSweeps | validation | def plotAllSweeps(abfFile):
"""simple example how to load an ABF file and plot every sweep."""
r = io.AxonIO(filename=abfFile)
bl = r.read_block(lazy=False, cascade=True)
print(abfFile+"\nplotting %d sweeps..."%len(bl.segments))
plt.figure(figsize=(12,10))
plt.title(abfFile)
for sweep in range(len(bl.segments)): | python | {
"resource": ""
} |
q263996 | plot_shaded_data | validation | def plot_shaded_data(X,Y,variances,varianceX):
"""plot X and Y data, then shade its background by variance."""
plt.plot(X,Y,color='k',lw=2)
nChunks=int(len(Y)/CHUNK_POINTS)
for i in range(0,100,PERCENT_STEP):
varLimitLow=np.percentile(variances,i)
varLimitHigh=np.percentile(variances,i+PERCENT_STEP)
varianceIsAboveMin=np.where(variances>=varLimitLow)[0]
| python | {
"resource": ""
} |
q263997 | show_variances | validation | def show_variances(Y,variances,varianceX,logScale=False):
"""create some fancy graphs to show color-coded variances."""
plt.figure(1,figsize=(10,7))
plt.figure(2,figsize=(10,7))
varSorted=sorted(variances)
plt.figure(1)
plt.subplot(211)
plt.grid()
plt.title("chronological variance")
plt.ylabel("original data")
plot_shaded_data(X,Y,variances,varianceX)
plt.margins(0,.1)
plt.subplot(212)
plt.ylabel("variance (pA) (log%s)"%str(logScale))
plt.xlabel("time in sweep (sec)")
plt.plot(varianceX,variances,'k-',lw=2)
plt.figure(2)
plt.ylabel("variance (pA) (log%s)"%str(logScale))
plt.xlabel("chunk number")
plt.title("sorted variance")
plt.plot(varSorted,'k-',lw=2)
for i in range(0,100,PERCENT_STEP):
varLimitLow=np.percentile(variances,i)
varLimitHigh=np.percentile(variances,i+PERCENT_STEP)
label="%2d-%d percentile"%(i,i++PERCENT_STEP)
color=COLORMAP(i/100)
print("%s: variance = %.02f - %.02f"%(label,varLimitLow,varLimitHigh))
| python | {
"resource": ""
} |
q263998 | AP.ensureDetection | validation | def ensureDetection(self):
"""
run this before analysis. Checks if event detection occured.
If not, runs AP detection on all sweeps.
"""
if self.APs==False:
| python | {
"resource": ""
} |
q263999 | AP.detect | validation | def detect(self):
"""runs AP detection on every sweep."""
self.log.info("initializing AP detection on all sweeps...")
t1=cm.timeit()
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.