Skip to content

Commit

Permalink
Merge pull request #36 from joamatab/development
Browse files Browse the repository at this point in the history
clean code
  • Loading branch information
simbilod authored Aug 16, 2022
2 parents 86563dd + 2ca1d31 commit 1096763
Show file tree
Hide file tree
Showing 53 changed files with 634 additions and 660 deletions.
55 changes: 34 additions & 21 deletions lightlab/equipment/abstract_drivers/TekScopeAbstract.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,10 @@ def timebaseConfig(self, avgCnt=None, duration=None, position=None, nPts=None):
self.setConfigParam('DATA:START', 1)
self.setConfigParam('DATA:STOP', nPts)

presentSettings = dict()
presentSettings['avgCnt'] = self.getConfigParam('ACQUIRE:NUMAVG', forceHardware=True)
presentSettings = {
'avgCnt': self.getConfigParam('ACQUIRE:NUMAVG', forceHardware=True)
}

presentSettings['duration'] = self.getConfigParam('HORIZONTAL:MAIN:SCALE', forceHardware=True)
presentSettings['position'] = self.getConfigParam('HORIZONTAL:MAIN:POSITION', forceHardware=True)
presentSettings['nPts'] = self.getConfigParam(self._recLenParam, forceHardware=True)
Expand Down Expand Up @@ -101,13 +103,19 @@ def acquire(self, chans=None, timeout=None, **kwargs):

for c in chans:
if c > self.totalChans:
raise Exception('Received channel: ' + str(c) +
'. Max channels of this scope is ' + str(self.totalChans))
raise Exception(
(
f'Received channel: {str(c)}'
+ '. Max channels of this scope is '
)
+ str(self.totalChans)
)


# Channel select
for ich in range(1, 1 + self.totalChans):
thisState = 1 if ich in chans else 0
self.setConfigParam('SELECT:CH' + str(ich), thisState)
self.setConfigParam(f'SELECT:CH{str(ich)}', thisState)

isSampling = kwargs.get('avgCnt', 0) == 1
self._setupSingleShot(isSampling)
Expand Down Expand Up @@ -176,12 +184,11 @@ def __transferData(self, chan):
Todo:
Make this binary transfer to go even faster
'''
chStr = 'CH' + str(chan)
chStr = f'CH{str(chan)}'
self.setConfigParam('DATA:ENCDG', 'ASCII')
self.setConfigParam('DATA:SOURCE', chStr)

voltRaw = self.query_ascii_values('CURV?')
return voltRaw
return self.query_ascii_values('CURV?')

def __scaleData(self, voltRaw):
''' Scale to second and voltage units.
Expand All @@ -202,7 +209,10 @@ def __scaleData(self, voltRaw):
YZERO, the reference voltage, YOFF, the offset position, and
YSCALE, the conversion factor between position and voltage.
'''
get = lambda param: float(self.getConfigParam('WFMOUTPRE:' + param, forceHardware=True))
get = lambda param: float(
self.getConfigParam(f'WFMOUTPRE:{param}', forceHardware=True)
)

voltage = (np.array(voltRaw) - get('YOFF')) \
* get(self._yScaleParam) \
+ get('YZERO')
Expand Down Expand Up @@ -263,10 +273,13 @@ def setMeasurement(self, measIndex, chan, measType):
'''
if measIndex == 0:
raise ValueError('measIndex is 1-indexed')
measSubmenu = 'MEASUREMENT:MEAS' + str(measIndex) + ':'
self.setConfigParam(measSubmenu + self._measurementSourceParam, 'CH' + str(chan))
self.setConfigParam(measSubmenu + 'TYPE', measType.upper())
self.setConfigParam(measSubmenu + 'STATE', 1)
measSubmenu = f'MEASUREMENT:MEAS{str(measIndex)}:'
self.setConfigParam(
measSubmenu + self._measurementSourceParam, f'CH{str(chan)}'
)

self.setConfigParam(f'{measSubmenu}TYPE', measType.upper())
self.setConfigParam(f'{measSubmenu}STATE', 1)

def measure(self, measIndex):
'''
Expand All @@ -276,16 +289,16 @@ def measure(self, measIndex):
Returns:
(float)
'''
measSubmenu = 'MEASUREMENT:MEAS' + str(measIndex) + ':'
return float(self.getConfigParam(measSubmenu + 'VALUE', forceHardware=True))
measSubmenu = f'MEASUREMENT:MEAS{str(measIndex)}:'
return float(self.getConfigParam(f'{measSubmenu}VALUE', forceHardware=True))

def autoAdjust(self, chans):
''' Adjusts offsets and scaling so that waveforms are not clipped '''
# Save the current measurement status. They will be restored at the end.
self.saveConfig(dest='+autoAdjTemp', subgroup='MEASUREMENT')

for ch in chans:
chStr = 'CH' + str(ch)
chStr = f'CH{str(ch)}'

# Set up measurements
self.setMeasurement(1, ch, 'pk2pk')
Expand All @@ -299,8 +312,8 @@ def autoAdjust(self, chans):
pk2pk = self.measure(1)
mean = self.measure(2)

span = float(self.getConfigParam(chStr + ':SCALE'))
offs = float(self.getConfigParam(chStr + ':OFFSET'))
span = float(self.getConfigParam(f'{chStr}:SCALE'))
offs = float(self.getConfigParam(f'{chStr}:OFFSET'))

# Check if scale is correct within the tolerance
newSpan = None
Expand All @@ -310,7 +323,7 @@ def autoAdjust(self, chans):
elif pk2pk > 0.8 * span:
newSpan = 2 * span
if newSpan < 0.1 or newSpan > 100:
raise Exception('Scope channel ' + chStr + ' could not be adjusted.')
raise Exception(f'Scope channel {chStr} could not be adjusted.')

# Check if offset is correct within the tolerance
if abs(mean) > 0.05 * span:
Expand All @@ -321,8 +334,8 @@ def autoAdjust(self, chans):
break

# Adjust settings
self.setConfigParam(chStr + ':SCALE', newSpan / 10)
self.setConfigParam(chStr + ':OFFSET', newOffs)
self.setConfigParam(f'{chStr}:SCALE', newSpan / 10)
self.setConfigParam(f'{chStr}:OFFSET', newOffs)

# Recover the measurement setup from before adjustment
self.loadConfig(source='+autoAdjTemp', subgroup='MEASUREMENT')
Expand Down
63 changes: 26 additions & 37 deletions lightlab/equipment/abstract_drivers/configurable.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ class TekConfig(object):

def __init__(self, initDict=None):
if initDict is None:
initDict = dict()
initDict = {}
self.dico = initDict.copy()

def __str__(self):
Expand All @@ -57,13 +57,10 @@ def get(self, cStr, asCmd=True):
try:
val = dpath.util.get(self.dico, cStr, separator=self.separator)
except KeyError:
raise KeyError(cStr + ' is not present in this TekConfig instance')
raise KeyError(f'{cStr} is not present in this TekConfig instance')
if type(val) is dict and '&' in val.keys():
val = val['&']
if not asCmd:
return val
else:
return (cStr, str(val))
return (cStr, str(val)) if asCmd else val

def set(self, cStr, val):
''' Takes the value only, not a dictionary '''
Expand All @@ -89,7 +86,7 @@ def set(self, cStr, val):
try:
oldV = self.get(parent, asCmd=False)
except KeyError:
print('dpath did not take ' + str(cmd))
print(f'dpath did not take {cmd}')
raise
dpath.util.set(self.dico, parent, {'&': oldV}, separator=self.separator)
dpath.util.new(self.dico, *cmd, separator=self.separator)
Expand All @@ -105,8 +102,10 @@ def getList(self, subgroup='', asCmd=True):
list: list of valid commands (cstr, val) on the subgroup subdirectory
'''
cList = []
children = dpath.util.search(self.dico, subgroup + '*',
yielded=True, separator=self.separator)
children = dpath.util.search(
self.dico, f'{subgroup}*', yielded=True, separator=self.separator
)

for cmd in children:
s, v = cmd
if type(v) is not dict:
Expand All @@ -117,14 +116,13 @@ def getList(self, subgroup='', asCmd=True):
cList += self.getList(subgroup=cmd[0] + self.separator)
if asCmd:
return cList
else:
writeList = [None] * len(cList)
for i, cmd in enumerate(cList):
cStr, val = cmd
if cStr[-1] == '&': # check for tokens
cStr = cStr[:-2]
writeList[i] = cStr + ' ' + str(val)
return writeList
writeList = [None] * len(cList)
for i, cmd in enumerate(cList):
cStr, val = cmd
if cStr[-1] == '&': # check for tokens
cStr = cStr[:-2]
writeList[i] = f'{cStr} {str(val)}'
return writeList

def setList(self, cmdList):
''' The inverse of getList '''
Expand All @@ -146,7 +144,7 @@ def transfer(self, source, subgroup=''):
elif type(source) is type(self):
sCon = source
else:
raise Exception('Invalid source for transfer. Got ' + str(type(source)))
raise Exception(f'Invalid source for transfer. Got {str(type(source))}')
commands = sCon.getList(subgroup=subgroup)
self.setList(commands)
return self
Expand All @@ -171,7 +169,7 @@ def __parseShorthand(cls, setResponse):
cmdGrp = None
for i in range(len(pairs)):
words = pairs[i].split(' ')
cmdLeaf, val = words[0:2]
cmdLeaf, val = words[:2]
if len(words) > 2:
print('Warning 2-value returns not handled by TekConfig class. Ignoring...')
print(*words)
Expand All @@ -194,10 +192,9 @@ def fromSETresponse(cls, setResponse, subgroup=''):
full.setList(commandList)
if subgroup == '':
return full
else:
ret = cls()
ret.transfer(full, subgroup=subgroup)
return ret
ret = cls()
ret.transfer(full, subgroup=subgroup)
return ret

def save(self, fname, subgroup='', overwrite=False):
''' Saves dictionary parameters in json format. Merges if there's something already there, unless overwrite is True.
Expand Down Expand Up @@ -250,8 +247,7 @@ def __init__(self, headerIsOptional=True, verboseIsOptional=False, precedingColo
self.colon = precedingColon
self.space = interveningSpace

self.config = dict()
self.config['default'] = None
self.config = {'default': None}
self.config['init'] = TekConfig()
self.config['live'] = TekConfig()
self.separator = self.config['live'].separator
Expand Down Expand Up @@ -351,8 +347,7 @@ def getDefaultFilename(self):
(str): the default filename
'''
info = self.instrID().split(',')
deffile = defaultFileDir / '-'.join(info[:3]) + '.json'
return deffile
return defaultFileDir / '-'.join(info[:3]) + '.json'

def saveConfig(self, dest='+user', subgroup='', overwrite=False):
'''
Expand Down Expand Up @@ -446,17 +441,14 @@ def _getHardwareConfig(self, cStrList):
cStr = cStr[:-2]

try:
ret = self.query(cStr + '?')
ret = self.query(f'{cStr}?')
except VisaIOError:
logger.error('Problematic parameter was %s.\n'
'Likely it does not exist in this instrument command structure.', cStr)
raise
logger.debug('Queried %s, got %s', cStr, ret)

if self.header:
val = ret.split(' ')[-1]
else:
val = ret
val = ret.split(' ')[-1] if self.header else ret
# Type detection
try:
val = float(val)
Expand Down Expand Up @@ -509,12 +501,9 @@ def generateDefaults(self, filename=None, overwrite=False):
cfgBuild = TekConfig()

for cmd in allSetCmds:
if cmd[0][-1] != '&': # handle the sibling subdir token
cStr = cmd[0]
else:
cStr = cmd[0][:-2]
cStr = cmd[0] if cmd[0][-1] != '&' else cmd[0][:-2]
try:
val = self.query(cStr + '?', withTimeout=1000)
val = self.query(f'{cStr}?', withTimeout=1000)
cfgBuild.set(cStr, val)
logger.info(cStr, '<--', val)
except VisaIOError:
Expand Down
27 changes: 11 additions & 16 deletions lightlab/equipment/abstract_drivers/electrical_sources.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def _checkMode(cls, mode):
''' Returns mode in lower case
'''
if mode not in cls.supportedModes:
raise TypeError('Invalid mode: ' + str(mode) + '. Valid: ' + str(cls.supportedModes))
raise TypeError(f'Invalid mode: {str(mode)}. Valid: {str(cls.supportedModes)}')

return mode.lower()

Expand All @@ -58,7 +58,7 @@ def val2baseUnit(cls, value, mode):
valueWasDict = isinstance(value, dict)
if not valueWasDict:
value = {-1: value}
baseVal = dict()
baseVal = {}
for ch, vEl in value.items():
if mode == 'baseunit':
baseVal[ch] = vEl
Expand All @@ -72,10 +72,7 @@ def val2baseUnit(cls, value, mode):
baseVal[ch] = cls.val2baseUnit(np.sign(vEl) * np.sqrt(abs(vEl)), 'amp')
elif mode == 'mwperohm':
baseVal[ch] = cls.val2baseUnit(vEl / 1e3, 'wattperohm')
if valueWasDict:
return baseVal
else:
return baseVal[-1]
return baseVal if valueWasDict else baseVal[-1]

@classmethod
def baseUnit2val(cls, baseVal, mode):
Expand All @@ -89,7 +86,7 @@ def baseUnit2val(cls, baseVal, mode):
baseValWasDict = isinstance(baseVal, dict)
if not baseValWasDict:
baseVal = {-1: baseVal}
value = dict()
value = {}
for ch, bvEl in baseVal.items():
if mode == 'baseunit':
value[ch] = bvEl
Expand All @@ -103,10 +100,7 @@ def baseUnit2val(cls, baseVal, mode):
value[ch] = np.sign(bvEl) * (cls.baseUnit2val(bvEl, 'amp')) ** 2
elif mode == 'mwperohm':
value[ch] = cls.baseUnit2val(bvEl, 'wattperohm') * 1e3
if baseValWasDict:
return value
else:
return value[-1]
return value if baseValWasDict else value[-1]


class MultiChannelSource(object):
Expand All @@ -121,15 +115,16 @@ class MultiChannelSource(object):
def __init__(self, useChans=None, **kwargs):
if useChans is None:
logger.warning('No useChans specified for MultichannelSource')
useChans = list()
useChans = []
self.useChans = useChans
self.stateDict = dict([ch, 0] for ch in self.useChans)

# Check that the requested channels are available to be blocked out
if self.maxChannel is not None:
if any(ch > self.maxChannel - 1 for ch in self.useChans):
raise ChannelError(
'Requested channel is more than there are available')
if self.maxChannel is not None and any(
ch > self.maxChannel - 1 for ch in self.useChans
):
raise ChannelError(
'Requested channel is more than there are available')
super().__init__(**kwargs)

@property
Expand Down
Loading

0 comments on commit 1096763

Please sign in to comment.