Skip to content

Commit

Permalink
Explicitely numbered replacement fields
Browse files Browse the repository at this point in the history
  • Loading branch information
quantifiedcode-bot committed Feb 6, 2016
1 parent 1f8ddbe commit a352d51
Show file tree
Hide file tree
Showing 11 changed files with 39 additions and 39 deletions.
10 changes: 5 additions & 5 deletions pylinac/cbct.py
Expand Up @@ -300,7 +300,7 @@ def plot_analyzed_subimage(self, subimage='hu', delta=True, interactive=False, s
plt.axis('on')
points = self.spatialres.plot_mtf(plt.gca())
if interactive:
labels = ['MTF: {:3.3f}'.format(i) for i in self.spatialres.line_pair_mtfs]
labels = ['MTF: {0:3.3f}'.format(i) for i in self.spatialres.line_pair_mtfs]
tooltip = mpld3.plugins.PointLabelTooltip(points[0], labels, location='top right')
mpld3.plugins.connect(plt.gcf(), tooltip)
elif 'lin' in subimage:
Expand All @@ -311,15 +311,15 @@ def plot_analyzed_subimage(self, subimage='hu', delta=True, interactive=False, s
delta_values = [roi.value_diff for roi in self.hu.rois.values()]
actual_values = [roi.pixel_value for roi in self.hu.rois.values()]
names = [roi for roi in self.hu.rois.keys()]
labels = ['{} -- Actual: {:3.1f}; Difference: {:3.1f}'.format(name, actual, delta) for name, actual, delta in zip(names, actual_values, delta_values)]
labels = ['{0} -- Actual: {1:3.1f}; Difference: {2:3.1f}'.format(name, actual, delta) for name, actual, delta in zip(names, actual_values, delta_values)]
tooltip = mpld3.plugins.PointLabelTooltip(points[0], labels, location='top right')
mpld3.plugins.connect(plt.gcf(), tooltip)
elif 'prof' in subimage:
subimage = 'prof'
plt.axis('on')
self.uniformity.plot_profiles(plt.gca())
else:
raise ValueError("Subimage parameter {} not understood".format(subimage))
raise ValueError("Subimage parameter {0} not understood".format(subimage))

if show:
if interactive and (subimage in ('mtf', 'lin', 'prof')):
Expand Down Expand Up @@ -349,7 +349,7 @@ def save_analyzed_subimage(self, filename, subimage='hu', interactive=False, **k
else:
plt.savefig(filename, **kwargs)
if isinstance(filename, str):
print("CBCT subimage figure saved to {}".format(osp.abspath(filename)))
print("CBCT subimage figure saved to {0}".format(osp.abspath(filename)))

def return_results(self):
"""Return the results of the analysis as a string. Use with print()."""
Expand All @@ -375,7 +375,7 @@ def return_results(self):
def _return_results(self):
"""Helper function to spit out values that will be tested."""
print(self.return_results())
print("Phantom roll: {}".format(self.settings.phantom_roll))
print("Phantom roll: {0}".format(self.settings.phantom_roll))
mtfs = {}
for mtf in (60, 70, 80, 90, 95):
mtfval = self.spatialres.mtf(mtf)
Expand Down
10 changes: 5 additions & 5 deletions pylinac/core/decorators.py
Expand Up @@ -16,7 +16,7 @@ def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(func.__name__, 'took {:3.2f}s'.format(end-start))
print(func.__name__, 'took {0:3.2f}s'.format(end-start))
return result
return wrapper

Expand All @@ -36,11 +36,11 @@ def wrapper(*args, **kwargs):
if name in bound_types:
if type(bound_types[name]) in (type, ABCMeta): # Single-type comparisons
if not isinstance(value, bound_types[name]):
raise TypeError("Argument '{}' must be {}".format(name, bound_types[name]))
raise TypeError("Argument '{0}' must be {1}".format(name, bound_types[name]))
else:
if type(value) not in bound_types[name]:
if value not in bound_types[name]:
raise TypeError("Argument '{}' must be {}".format(name, bound_types[name]))
raise TypeError("Argument '{0}' must be {1}".format(name, bound_types[name]))
return func(*args, **kwargs)
return wrapper
return decorate
Expand All @@ -63,13 +63,13 @@ def wrapper(*args, **kwargs):
if type(value) in (float, int, np.float64):
# value must be within a number range
if not bound_values[name][0] <= value <= bound_values[name][1]:
raise ValueError("Argument '{}' needs to be between {:f} and {:f}".format(name,
raise ValueError("Argument '{0}' needs to be between {1:f} and {2:f}".format(name,
bound_values[name][0],
bound_values[name][1]))
else:
# value is a str and must be one of the accepted str values
if value not in bound_values[name]:
raise ValueError("Argument '{}' must be one of {}".format(name, bound_values[name]))
raise ValueError("Argument '{0}' must be one of {1}".format(name, bound_values[name]))
return func(*args, **kwargs)
return wrapper
return decorate
Expand Down
4 changes: 2 additions & 2 deletions pylinac/core/geometry.py
Expand Up @@ -32,7 +32,7 @@ def __init__(self, x=0, y=0, z=0):
self.z = z

def __repr__(self):
return "Vector(x={:.2f}, y={:.2f}, z={:.2f})".format(self.x, self.y, self.z)
return "Vector(x={0:.2f}, y={1:.2f}, z={2:.2f})".format(self.x, self.y, self.z)

def as_scalar(self):
"""Return the scalar equivalent of the vector."""
Expand Down Expand Up @@ -122,7 +122,7 @@ def as_array(self, only_coords=True):
return np.array([getattr(self, item) for item in self._attr_list if (getattr(self, item) is not None)])

def __repr__(self):
return "Point(x={:3.2f}, y={:3.2f}, z={:3.2f})".format(self.x, self.y, self.z)
return "Point(x={0:3.2f}, y={1:3.2f}, z={2:3.2f})".format(self.x, self.y, self.z)

def __eq__(self, other):
# if all attrs equal, points considered equal
Expand Down
8 changes: 4 additions & 4 deletions pylinac/core/image.py
Expand Up @@ -83,7 +83,7 @@ def load(cls, path, **kwargs):
elif cls._is_image_file(path):
return FileImage(path, **kwargs)
else:
raise TypeError("The argument `{}` was not found to be a valid DICOM file, Image file, or array".format(path))
raise TypeError("The argument `{0}` was not found to be a valid DICOM file, Image file, or array".format(path))

@classmethod
def load_url(cls, url, **kwargs):
Expand Down Expand Up @@ -172,7 +172,7 @@ def __init__(self, path):
if isinstance(path, BytesIO):
path.seek(0)
elif not osp.isfile(path):
raise FileExistsError("File `{}` does not exist".format(path))
raise FileExistsError("File `{0}` does not exist".format(path))
else:
self.filename = path

Expand Down Expand Up @@ -681,7 +681,7 @@ def _get_datasets(self, folder, zip=False, dtype=None):
temp_folder = TemporaryZipDirectory(folder)
folder = temp_folder.name
else:
raise FileExistsError("Zip archive `{}` not found".format(folder))
raise FileExistsError("Zip archive `{0}` not found".format(folder))

# load in images in their received order
for pdir, sdir, files in os.walk(folder):
Expand All @@ -697,7 +697,7 @@ def _get_datasets(self, folder, zip=False, dtype=None):

# check that at least 1 image was loaded
if len(self.images) < 1:
raise FileNotFoundError("No files were found in the specified location: {}".format(folder))
raise FileNotFoundError("No files were found in the specified location: {0}".format(folder))

# error checking
self._check_all_from_same_study()
Expand Down
8 changes: 4 additions & 4 deletions pylinac/core/io.py
Expand Up @@ -29,7 +29,7 @@ def load_zipfile(zfilename, read=False):
elif zipfile.is_zipfile(zfilename):
zfiles = zipfile.ZipFile(zfilename)
else:
raise FileExistsError("File '{}' given was not a valid zip file".format(zfilename))
raise FileExistsError("File '{0}' given was not a valid zip file".format(zfilename))
if read:
return (BytesIO(zfiles.read(name)) for name in zfiles.namelist())
else:
Expand Down Expand Up @@ -87,7 +87,7 @@ def is_valid_file(file_path, raise_error=True):
elif not raise_error:
return False
else:
raise FileExistsError("{} is not a valid file".format(file_path))
raise FileExistsError("{0} is not a valid file".format(file_path))

def open_file(file, mode='rb'):
"""Open a file if a file is a string, or open the object if file is a file object.
Expand All @@ -102,7 +102,7 @@ def open_file(file, mode='rb'):
file.seek(0)
openfile = file
except:
raise TypeError("Could not open file: {}".format(file))
raise TypeError("Could not open file: {0}".format(file))
return openfile

def is_valid_dir(dir_path, raise_error=True):
Expand All @@ -112,4 +112,4 @@ def is_valid_dir(dir_path, raise_error=True):
elif not raise_error:
return False
else:
raise NotADirectoryError("{} does not point to a valid directory".format(dir_path))
raise NotADirectoryError("{0} does not point to a valid directory".format(dir_path))
2 changes: 1 addition & 1 deletion pylinac/core/utilities.py
Expand Up @@ -40,7 +40,7 @@ def prop(self):
@prop.setter
def prop(self, value):
if not isinstance(value, expected_type_or_tuple_of_types):
raise TypeError("{} must be a {}. Got: {}".format(name, expected_type_or_tuple_of_types, type(value)))
raise TypeError("{0} must be a {1}. Got: {2}".format(name, expected_type_or_tuple_of_types, type(value)))
setattr(self, storage_name, value)

return prop
Expand Down
20 changes: 10 additions & 10 deletions pylinac/flatsym.py
Expand Up @@ -233,31 +233,31 @@ def _convert_position(self, position, plane):
y = self._parse_position(position[0], 'x')
x = self._parse_position(position[1], 'y')
else:
raise ValueError("Position argument '{}' must be 'auto' or 2-element sequence to do both planes".format(position))
raise ValueError("Position argument '{0}' must be 'auto' or 2-element sequence to do both planes".format(position))
return [y, x]
elif _is_crossplane(plane) or _is_inplane(plane):
if position == 'auto':
loc = self._determine_center(plane)
elif isnumeric(position):
loc = self._parse_position(position, plane)
else:
raise ValueError("Position argument '{}' must be 'auto' or a number to do single planes".format(position))
raise ValueError("Position argument '{0}' must be 'auto' or a number to do single planes".format(position))
return [loc,]
else:
raise ValueError("Plane argument '{}' not understood".format(plane))
raise ValueError("Plane argument '{0}' not understood".format(plane))

def _check_position_inbounds(self, position, plane):
"""Check that the position is within the image index bounds."""
if _is_crossplane(plane):
if position >= self.image.shape[1]:
raise IndexError("Y-position {} is out of bounds of image array".format(position))
raise IndexError("Y-position {0} is out of bounds of image array".format(position))
elif _is_inplane(plane):
if position >= self.image.shape[0]:
raise IndexError("X-position {} is out of bounds of image array".format(position))
raise IndexError("X-position {0} is out of bounds of image array".format(position))

def _parse_position(self, position, plane):
if not _is_crossplane(plane) and not _is_inplane(plane):
raise ValueError("Plane argument '{}' must be either inplane or crossplane".format(plane))
raise ValueError("Plane argument '{0}' must be either inplane or crossplane".format(plane))
if isinstance(position, (float, np.float64)) and 0 < position < 1:
if _is_crossplane(plane):
arr_side = self.image.shape[0]
Expand All @@ -267,7 +267,7 @@ def _parse_position(self, position, plane):
elif isinstance(position, (int, float, np.float64)):
pos = int(position)
else:
raise ValueError("Position argument '{}' not understood.".format(position))
raise ValueError("Position argument '{0}' not understood.".format(position))

self._check_position_inbounds(pos, plane)
return pos
Expand Down Expand Up @@ -303,7 +303,7 @@ def _get_symmetry(self, profile, method):
# symmetry = (100 * abs(lt_area - rt_area) / (lt_area + rt_area)) / 2
# max_idx = 0
else:
raise ValueError("Method parameter '{}' invalid".format(method))
raise ValueError("Method parameter '{0}' invalid".format(method))

lt_edge, rt_edge = profile.field_edges(field_width=0.8)

Expand Down Expand Up @@ -362,7 +362,7 @@ def _get_flatness(self, profile, method):
dmin = profile.field_calculation(field_width=0.8, calculation='min')
flatness = 100 * (dmax / dmin)
else:
raise ValueError("Method parameter '{}' invalid".format(method))
raise ValueError("Method parameter '{0}' invalid".format(method))

lt_edge, rt_edge = profile.field_edges(field_width=0.8)

Expand Down Expand Up @@ -439,7 +439,7 @@ def _plot_annotation(self, ax, value, method, profile, flat_or_sym='sym'):
else:
t = 'Flatness'
ax.text(near_left_edge, near_top,
'{}: {:2.2f}%'.format(t, value) + '\nUsing ' + method.capitalize() + ' convention',
'{0}: {1:2.2f}%'.format(t, value) + '\nUsing ' + method.capitalize() + ' convention',
rotation=-90)

return ax
Expand Down
4 changes: 2 additions & 2 deletions pylinac/picketfence.py
Expand Up @@ -357,7 +357,7 @@ def _add_leaf_error_subplot(self, ax, fig, interactive):

# add tooltips if interactive
if interactive:
labels = [['Leaf pair {}/{}, Avg Error: {:3.3f}mm, Stdev: {:3.3f}mm'.format(leaf_num[0], leaf_num[1], err, std)]
labels = [['Leaf pair {0}/{1}, Avg Error: {2:3.3f}mm, Stdev: {3:3.3f}mm'.format(leaf_num[0], leaf_num[1], err, std)]
for leaf_num, err, std in zip(leaf_nums, vals, err)]
mpld3 = import_mpld3()
for num, patch in enumerate(axtop.axes.patches):
Expand All @@ -382,7 +382,7 @@ def save_analyzed_image(self, filename, guard_rails=True, mlc_peaks=True, overla
else:
plt.savefig(filename, **kwargs)
if isinstance(filename, str):
print("Picket fence image saved to: {}".format(osp.abspath(filename)))
print("Picket fence image saved to: {0}".format(osp.abspath(filename)))

def return_results(self):
"""Return results of analysis. Use with print()."""
Expand Down
2 changes: 1 addition & 1 deletion pylinac/vmat.py
Expand Up @@ -392,7 +392,7 @@ def save_analyzed_subimage(self, filename, subimage='dmlc', interactive=False, *
else:
plt.savefig(filename, **kwargs)
if isinstance(filename, str):
print("VMAT subimage figure saved to {}".format(osp.abspath(filename)))
print("VMAT subimage figure saved to {0}".format(osp.abspath(filename)))

@property
def median_profiles(self):
Expand Down
6 changes: 3 additions & 3 deletions pylinac/winston_lutz.py
Expand Up @@ -353,7 +353,7 @@ def __init__(self, file):
self.bb = self._find_bb()

def __repr__(self):
return "WLImage(G={:.1f}, B={:.1f}, P={:.1f})".format(self.gantry_angle, self.collimator_angle, self.couch_angle)
return "WLImage(G={0:.1f}, B={1:.1f}, P={2:.1f})".format(self.gantry_angle, self.collimator_angle, self.couch_angle)

def _find_field_centroid(self):
"""Find the centroid of the radiation field based on a 50% height threshold.
Expand Down Expand Up @@ -527,8 +527,8 @@ def plot(self, ax=None, show=True, clear_fig=False):
ax.set_xlim([self.bounding_box[2], self.bounding_box[3]])
ax.set_yticklabels([])
ax.set_xticklabels([])
ax.set_xlabel("G={:.0f}, B={:.0f}, P={:.0f}".format(self.gantry_angle, self.collimator_angle, self.couch_angle))
ax.set_ylabel("CAX to BB: {:3.2f}mm".format(self.cax2bb_distance))
ax.set_xlabel("G={0:.0f}, B={1:.0f}, P={2:.0f}".format(self.gantry_angle, self.collimator_angle, self.couch_angle))
ax.set_ylabel("CAX to BB: {0:3.2f}mm".format(self.cax2bb_distance))
if show:
plt.show()
return ax
Expand Down
4 changes: 2 additions & 2 deletions tests/utils.py
Expand Up @@ -19,6 +19,6 @@ def save_file(method, *args, as_file_object=None, **kwargs):

def test_point_equality(point1, point2):
if point1.x != point2.x:
raise ValueError("{} does not equal {}".format(point1.x, point2.x))
raise ValueError("{0} does not equal {1}".format(point1.x, point2.x))
if point1.y != point2.y:
raise ValueError("{} does not equal {}".format(point1.y, point2.y))
raise ValueError("{0} does not equal {1}".format(point1.y, point2.y))

0 comments on commit a352d51

Please sign in to comment.