Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

modernize formatting code for python 3.6+ #944

Merged
merged 4 commits into from
Feb 7, 2019
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion ctapipe/calib/camera/gainselection.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ def __init__(self, config=None, parent=None, **kwargs):
self.log.debug("Loaded threshold table: \n %s", tab)

def __str__(self):
return "{}({})".format(self.__class__.__name__, self.thresholds)
return f"{self.__class__.__name__}({self.thresholds})"

def select_gains(self, cam_id, multi_gain_waveform):

Expand Down
4 changes: 2 additions & 2 deletions ctapipe/coordinates/representation.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,10 @@ def __init__(self, x, y, copy=True, **kwargs):
)

if not isinstance(x, self.attr_classes['x']):
raise TypeError('x should be a {0}'.format(self.attr_classes['x'].__name__))
raise TypeError('x should be a {}'.format(self.attr_classes['x'].__name__))

if not isinstance(y, self.attr_classes['y']):
raise TypeError('y should be a {0}'.format(self.attr_classes['y'].__name__))
raise TypeError('y should be a {}'.format(self.attr_classes['y'].__name__))

x = self.attr_classes['x'](x, copy=copy)
y = self.attr_classes['y'](y, copy=copy)
Expand Down
2 changes: 1 addition & 1 deletion ctapipe/core/component.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def __init__(self, parent=None, config=None, **kwargs):

for key, value in kwargs.items():
if not self.has_trait(key):
raise TraitError("Traitlet does not exist: {}".format(key))
raise TraitError(f"Traitlet does not exist: {key}")

# set up logging
if self.parent:
Expand Down
8 changes: 4 additions & 4 deletions ctapipe/core/container.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ def __init__(self, default, description="", unit=None, ucd=None):
self.ucd = ucd

def __repr__(self):
desc = '{}'.format(self.description)
desc = f'{self.description}'
if self.unit is not None:
desc += ' [{}]'.format(self.unit)
desc += f' [{self.unit}]'
return desc


Expand Down Expand Up @@ -173,7 +173,7 @@ def as_dict(self, recursive=False, flatten=False, add_prefix=False):
if isinstance(val, Container) or isinstance(val, Map):
if flatten:
d.update({
"{}_{}".format(key, k): v
f"{key}_{k}": v
for k, v in val.as_dict(
recursive,
add_prefix=add_prefix
Expand Down Expand Up @@ -236,7 +236,7 @@ def as_dict(self, recursive=False, flatten=False, add_prefix=False):
if isinstance(val, Container) or isinstance(val, Map):
if flatten:
d.update({
"{}_{}".format(key, k): v
f"{key}_{k}": v
for k, v in val.as_dict(
recursive, add_prefix=add_prefix
).items()
Expand Down
2 changes: 1 addition & 1 deletion ctapipe/core/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,4 @@ def format(self, record):
else:
record.highlevel = ""

return super(ColoredFormatter, self).format(record)
return super().format(record)
4 changes: 2 additions & 2 deletions ctapipe/core/provenance.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def start_activity(self, activity_name=sys.executable):
activity = _ActivityProvenance(activity_name)
activity.start()
self._activities.append(activity)
log.debug("started activity: {}".format(activity_name))
log.debug(f"started activity: {activity_name}")

def add_input_file(self, filename, role=None):
""" register an input to the current activity
Expand Down Expand Up @@ -115,7 +115,7 @@ def finish_activity(self, status='completed', activity_name=None):

activity.finish(status)
self._finished_activities.append(activity)
log.debug("finished activity: {}".format(activity.name))
log.debug(f"finished activity: {activity.name}")

@contextmanager
def activity(self, name):
Expand Down
2 changes: 1 addition & 1 deletion ctapipe/core/support.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@ class Singleton(type):

def __call__(cls, *args, **kw):
if not cls.instance:
cls.instance = super(Singleton, cls).__call__(*args, **kw)
cls.instance = super().__call__(*args, **kw)
return cls.instance
18 changes: 9 additions & 9 deletions ctapipe/core/tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ def main():

"""

config_file = Unicode(u'', help=("name of a configuration file with "
config_file = Unicode('', help=("name of a configuration file with "
"parameters to load in addition to "
"command-line parameters")).tag(config=True)

Expand All @@ -122,9 +122,9 @@ def initialize(self, argv=None):
""" handle config and any other low-level setup """
self.parse_command_line(argv)
if self.config_file != '':
self.log.debug("Loading config from '{}'".format(self.config_file))
self.log.debug(f"Loading config from '{self.config_file}'")
self.load_config_file(self.config_file)
self.log.info("ctapipe version {}".format(self.version_string))
self.log.info(f"ctapipe version {self.version_string}")

@abstractmethod
def setup(self):
Expand Down Expand Up @@ -158,20 +158,20 @@ def run(self, argv=None):
"""
try:
self.initialize(argv)
self.log.info("Starting: {}".format(self.name))
self.log.debug("CONFIG: {}".format(self.config))
self.log.info(f"Starting: {self.name}")
self.log.debug(f"CONFIG: {self.config}")
Provenance().start_activity(self.name)
Provenance().add_config(self.config)
self.setup()
self.is_setup = True
self.start()
self.finish()
self.log.info("Finished: {}".format(self.name))
self.log.info(f"Finished: {self.name}")
Provenance().finish_activity(activity_name=self.name)
except ToolConfigurationError as err:
self.log.error('{}. Use --help for more info'.format(err))
self.log.error(f'{err}. Use --help for more info')
except RuntimeError as err:
self.log.error('Caught unexpected exception: {}'.format(err))
self.log.error(f'Caught unexpected exception: {err}')
self.finish()
Provenance().finish_activity(activity_name=self.name,
status='error')
Expand All @@ -190,4 +190,4 @@ def run(self, argv=None):
@property
def version_string(self):
""" a formatted version string with version, release, and git hash"""
return "{}".format(version)
return f"{version}"
4 changes: 2 additions & 2 deletions ctapipe/core/traits.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,11 @@ def validate(self, obj, value):
if os.path.exists(value):
if os.path.isdir(value) and not self.directory_ok:
raise TraitError(
'Path "{}" must not be a directory'.format(value)
f'Path "{value}" must not be a directory'
)
if os.path.isfile(value) and not self.file_ok:
raise TraitError(
'Path "{}" must not be a file'.format(value)
f'Path "{value}" must not be a file'
)

return value
Expand Down
4 changes: 2 additions & 2 deletions ctapipe/image/geometry_converter_hex.py
Original file line number Diff line number Diff line change
Expand Up @@ -353,8 +353,8 @@ def convert_geometry_hex1d_to_rect2d(geom, signal, key=None, add_rot=0):
# total rotation angle:
rot_angle = (add_rot * 60 * u.deg) - extra_rot

logger.debug("geom={}".format(geom))
logger.debug("rot={}, extra={}".format(rot_angle, extra_rot))
logger.debug(f"geom={geom}")
logger.debug(f"rot={rot_angle}, extra={extra_rot}")

rot_x, rot_y = unskew_hex_pixel_grid(geom.pix_x, geom.pix_y,
cam_angle=rot_angle)
Expand Down
2 changes: 1 addition & 1 deletion ctapipe/image/muon/muon_diagnostic_plots.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def plot_muon_efficiency(outputpath):
contrw = axrw.hist(t['RingWidth'], nbins)
axrw.set_xlim(0.2 * min(t['RingWidth']), 1.2 * max(t['RingWidth']))
axrw.set_ylim(0., 1.2 * max(contrw[0]))
axrw.set_xlabel('Ring Width ($^\circ$)')
axrw.set_xlabel(r'Ring Width ($^\circ$)')

plt.draw()

Expand Down
2 changes: 1 addition & 1 deletion ctapipe/image/muon/muon_reco_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ def analyze_muon_source(source):
A ctapipe event container (MuonParameter) with muon information

"""
log.info("[FUNCTION] {}".format(__name__))
log.info(f"[FUNCTION] {__name__}")

if geom_dict is None:
geom_dict = {}
Expand Down
2 changes: 1 addition & 1 deletion ctapipe/instrument/atmosphere.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def get_atmosphere_profile_table(atmosphere_name='paranal'):
'altitude' (m), and 'thickness' (g cm-2) as well as others.

"""
table_name = '{}.atmprof'.format(atmosphere_name)
table_name = f'{atmosphere_name}.atmprof'
table = get_table_dataset(table_name=table_name,
role='dl0.arr.svc.atmosphere')
return table
Expand Down
10 changes: 5 additions & 5 deletions ctapipe/instrument/camera.py
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,7 @@ def from_name(cls, camera_id='NectarCam', version=None):
if version is None:
verstr = ''
else:
verstr = "-{:03d}".format(version)
verstr = f"-{version:03d}"

tabname = "{camera_id}{verstr}.camgeom".format(camera_id=camera_id,
verstr=verstr)
Expand Down Expand Up @@ -458,12 +458,12 @@ def rotate(self, angle):

def info(self, printer=print):
""" print detailed info about this camera """
printer('CameraGeometry: "{}"'.format(self))
printer(f'CameraGeometry: "{self}"')
printer(' - num-pixels: {}'.format(len(self.pix_id)))
printer(' - pixel-type: {}'.format(self.pix_type))
printer(f' - pixel-type: {self.pix_type}')
printer(' - sensitive-area: {}'.format(self.pix_area.sum()))
printer(' - pix-rotation: {}'.format(self.pix_rotation))
printer(' - cam-rotation: {}'.format(self.cam_rotation))
printer(f' - pix-rotation: {self.pix_rotation}')
printer(f' - cam-rotation: {self.cam_rotation}')

@classmethod
def make_rectangular(cls, npix_x=40, npix_y=40, range_x=(-0.5, 0.5),
Expand Down
10 changes: 5 additions & 5 deletions ctapipe/instrument/optics.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,18 +157,18 @@ def identifier(self):
return self.tel_type, self.tel_subtype

def info(self, printer=print):
printer('OpticsDescription: "{}"'.format(self))
printer(' - mirror_type: {}'.format(self.mirror_type))
printer(' - num_mirror_tiles: {}'.format(self.num_mirror_tiles))
printer(' - mirror_area: {}'.format(self.mirror_area))
printer(f'OpticsDescription: "{self}"')
printer(f' - mirror_type: {self.mirror_type}')
printer(f' - num_mirror_tiles: {self.num_mirror_tiles}')
printer(f' - mirror_area: {self.mirror_area}')

def __repr__(self):
return "{}(tel_type='{}', tel_subtype='{}')".format(
str(self.__class__.__name__), self.tel_type, self.tel_subtype)

def __str__(self):
if self.tel_subtype != '':
return "{}-{}".format(self.tel_type, self.tel_subtype)
return f"{self.tel_type}-{self.tel_subtype}"
else:
return self.tel_type

Expand Down
8 changes: 4 additions & 4 deletions ctapipe/instrument/subarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,9 @@ def info(self, printer=print):
for tel_id, desc in self.tels.items():
teltypes[str(desc)].append(tel_id)

printer("Subarray : {}".format(self.name))
printer("Num Tels : {}".format(self.num_tels))
printer("Footprint: {:.2f}".format(self.footprint))
printer(f"Subarray : {self.name}")
printer(f"Num Tels : {self.num_tels}")
printer(f"Footprint: {self.footprint:.2f}")
printer("")
printer(" TYPE Num IDmin IDmax")
printer("=====================================")
Expand Down Expand Up @@ -213,7 +213,7 @@ def to_table(self, kind="subarray"):
tab = Table(cols)

else:
raise ValueError("Table type '{}' not known".format(kind))
raise ValueError(f"Table type '{kind}' not known")

tab.meta.update(meta)
return tab
Expand Down
2 changes: 1 addition & 1 deletion ctapipe/instrument/tests/test_camera.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def test_get_min_pixel_seperation():
def test_find_neighbor_pixels():
x, y = np.meshgrid(np.linspace(-5, 5, 5), np.linspace(-5, 5, 5))
neigh = _find_neighbor_pixels(x.ravel(), y.ravel(), rad=3.1)
assert set(neigh[11]) == set([16, 6, 10, 12])
assert set(neigh[11]) == {16, 6, 10, 12}


@pytest.mark.parametrize("cam_id", cam_ids)
Expand Down
4 changes: 2 additions & 2 deletions ctapipe/io/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ def get_array_layout(instrument_name):
"""
name = instrument_name.lower()
try:
layoutfile = get_dataset_path('{}_arraylayout.fits'.format(name))
layoutfile = get_dataset_path(f'{name}_arraylayout.fits')
except KeyError:
layoutfile = get_dataset_path('{}_arraylayout.fits.gz'.format(name))
layoutfile = get_dataset_path(f'{name}_arraylayout.fits.gz')
return load_array_layout_from_file(layoutfile)


Expand Down
4 changes: 2 additions & 2 deletions ctapipe/io/eventseeker.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ def _get_event_by_index(self, index):
for event in self._source:
if event.count == index:
return event
raise IndexError("Event index {} not found in file".format(index))
raise IndexError(f"Event index {index} not found in file")

def _get_event_by_id(self, event_id):
"""
Expand All @@ -243,7 +243,7 @@ def _get_event_by_id(self, event_id):
for event in self: # Event Ids may not be in order
if event.r0.event_id == event_id:
return event
raise IndexError("Event id {} not found in file".format(event_id))
raise IndexError(f"Event id {event_id} not found in file")

def __len__(self):
"""
Expand Down
4 changes: 2 additions & 2 deletions ctapipe/io/eventsource.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,10 +125,10 @@ def __init__(self, config=None, tool=None, **kwargs):
if not exists(self.input_url):
raise FileNotFoundError("file path does not exist: '{}'"
.format(self.input_url))
self.log.info("INPUT PATH = {}".format(self.input_url))
self.log.info(f"INPUT PATH = {self.input_url}")

if self.max_events:
self.log.info("Max events being read = {}".format(self.max_events))
self.log.info(f"Max events being read = {self.max_events}")

Provenance().add_input_file(self.input_url, role='dl0.sub.evt')

Expand Down
4 changes: 2 additions & 2 deletions ctapipe/io/hdf5tableio.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,10 +159,10 @@ class Schema(tables.IsDescription):

if req_unit is not None:
tr = partial(tr_convert_and_strip_unit, unit=req_unit)
meta['{}_UNIT'.format(col_name)] = str(req_unit)
meta[f'{col_name}_UNIT'] = str(req_unit)
else:
tr = lambda x: x.value
meta['{}_UNIT'.format(col_name)] = str(value.unit)
meta[f'{col_name}_UNIT'] = str(value.unit)

value = tr(value)
self.add_column_transform(table_name, col_name, tr)
Expand Down
2 changes: 1 addition & 1 deletion ctapipe/io/targetioeventsource.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,6 @@ def _get_event_by_index(self, index):
def _get_event_by_id(self, event_id):
if ((event_id < self._first_event_id) |
(event_id > self._last_event_id)):
raise IndexError("Event id {} not found in file".format(event_id))
raise IndexError(f"Event id {event_id} not found in file")
index = self._reader.GetEventIndex(event_id)
return self._get_event_by_index(index)
2 changes: 1 addition & 1 deletion ctapipe/io/toymodel.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def toymodel_event_source(geoms, max_events=100, single_tel=False, n_channels=1,
centroid,
width,
length,
'{}d'.format(psi)
f'{psi}d'
)
image, _, _ = toymodel.make_toymodel_shower_image(
geom,
Expand Down
12 changes: 6 additions & 6 deletions ctapipe/plotting/bokeh_event_viewer.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,11 @@ def _set_image(self):
if t is None:
t = tels[0]
if t not in tels:
raise KeyError("Telescope {} has no data".format(t))
raise KeyError(f"Telescope {t} has no data")

try:
self.image = self._view_options[v](e, t, c, time)
self.fig.title.text = '{0} (T = {1})'.format(v, time)
self.fig.title.text = f'{v} (T = {time})'
except TypeError:
self.image = None

Expand Down Expand Up @@ -102,7 +102,7 @@ def view(self):
@view.setter
def view(self, val):
if val not in list(self._view_options.keys()):
raise ValueError("View is not valid: {}".format(val))
raise ValueError(f"View is not valid: {val}")
self._view = val
self._set_image()

Expand Down Expand Up @@ -205,11 +205,11 @@ def _set_waveform(self):
if t is None:
t = tels[0]
if t not in tels:
raise KeyError("Telescope {} has no data".format(t))
raise KeyError(f"Telescope {t} has no data")

try:
self.waveform = self._view_options[v](e, t, c, p)
self.fig.title.text = '{0} (Pixel = {1})'.format(v, p)
self.fig.title.text = f'{v} (Pixel = {p})'
except TypeError:
self.waveform = None

Expand Down Expand Up @@ -265,7 +265,7 @@ def view(self):
@view.setter
def view(self, val):
if val not in list(self._view_options.keys()):
raise ValueError("View is not valid: {}".format(val))
raise ValueError(f"View is not valid: {val}")
self._view = val
self._set_waveform()
self._set_integration_window()
Expand Down
Loading