Skip to content

Sourcery refactored master branch #36

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
19 changes: 13 additions & 6 deletions grains/abaqus.py
Original file line number Diff line number Diff line change
Expand Up @@ -430,9 +430,11 @@ def add_sections(inp_file, output_file=None):
old = source.readlines()
if a.state['begin'] == a.state['end'] + 1: # input file does not contain materials
raise Exception('Material does not exist.')
sections = []
for material in a.materials.keys():
sections.append('*SOLID SECTION, ELSET={0}, MATERIAL={0}\n'.format(material))
sections = [
'*SOLID SECTION, ELSET={0}, MATERIAL={0}\n'.format(material)
for material in a.materials.keys()
]

Comment on lines -433 to +437
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Material.add_sections refactored with the following changes:

  • Convert for loop into list comprehension (list-comprehension)

new = old + sections
if not output_file:
name, extension = os.path.splitext(inp_file)
Expand Down Expand Up @@ -1180,13 +1182,18 @@ def __format(self):

"""
for step_name, modules in self.steps.items():
abaqus_format = ['\n** -------------------------------------------------------------\n']
abaqus_format.append('**\n** STEP: {0}\n**\n'.format(step_name))
abaqus_format = [
'\n** -------------------------------------------------------------\n',
'**\n** STEP: {0}\n**\n'.format(step_name),
]

nlgeom = modules['step_options']['nlgeom']
increment = modules['step_options']['inc']
abaqus_format.append('*Step, name={0}, nlgeom={1}, inc={2}\n'
.format(step_name, nlgeom, increment))
for module_name, module_items in modules.items():
if module_name == 'step_options':
continue
Comment on lines -1183 to +1196
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Procedure.__format refactored with the following changes:

  • Simplify conditional into switch-like form (switch)
  • Extract guard clause from elif block (guard)
  • Merge append into list declaration (merge-list-append)

if module_name == 'analysis':
abaqus_format.append('*Static\n')
abaqus_format.append(','.join(module_items) + '\n')
Expand All @@ -1196,7 +1203,7 @@ def __format(self):
abaqus_format.append('** Name: {0}\n'.format(bc_name))
abaqus_format.append('*Boundary\n')
abaqus_format.append(','.join(bc) + '\n')
elif module_name != 'step_options':
else:
raise Exception('Currently only boundary conditions and analysis types are '
'supported.')
abaqus_format.append('*End Step\n')
Expand Down
2 changes: 1 addition & 1 deletion grains/analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -376,7 +376,7 @@ def plot_grain_characteristic(characteristic, centers, interpolation='linear',
ff = f.copy()
ff[outside_region] = f_nearest[outside_region]
# Plot the distribution of the grain characteristic
ax = parsed_options['ax'] if parsed_options['ax'] else plt.figure().add_subplot()
ax = parsed_options['ax'] or plt.figure().add_subplot()
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function plot_grain_characteristic refactored with the following changes:

  • Simplify if expression by using or (or-if-exp-identity)

# fig, ax = plt.subplots()
image = ax.imshow(np.flipud(ff.T), interpolation='none', extent=(*x_range, *y_range))
if not parsed_options['show_axis']:
Expand Down
13 changes: 5 additions & 8 deletions grains/cad.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,11 +249,7 @@ def polygon_orientation(polygon):
for idx, vertex in enumerate(polygon):
next_vertex = polygon[(idx + 1) % n_vertex] # allow indexing past the last vertex
edge_sum += (next_vertex[0] - vertex[0]) * (next_vertex[1] + vertex[1])
if edge_sum > 0:
orientation = 'cw'
else:
orientation = 'ccw'
return orientation
return 'cw' if edge_sum > 0 else 'ccw'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function polygon_orientation refactored with the following changes:

  • Replace if statement with if expression (assign-if-exp)
  • Inline variable that is immediately returned (inline-immediately-returned-variable)



def branches2boundary(branches, orientation='ccw'):
Expand Down Expand Up @@ -320,7 +316,7 @@ def branches2boundary(branches, orientation='ccw'):
first_vertex = branches[last_branch][0, :]
last_vertex = branches[last_branch][-1, :]
# Visit all vertices of the would-be surface and find the chain of connecting branches
for vertex in range(n_branch - 1):
for _ in range(n_branch - 1):
Comment on lines -323 to +319
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function branches2boundary refactored with the following changes:

  • Replace unused for index with underscore (for-index-underscore)

if np.allclose(last_vertex, first_vertex): # one complete cycle is finished
break
# Search for branches connecting to the last vertex of the path
Expand Down Expand Up @@ -549,8 +545,9 @@ def fit_spline(points, degree_min=3, degree_max=8, continuity='C2', tol=1e-3):
pts.SetValue(i, gp_Pnt(float(points[i][0]), float(points[i][1]), 0))
# Construct the spline
continuity = _spline_continuity_enum(continuity)
spline = GeomAPI_PointsToBSpline(pts, degree_min, degree_max, continuity, tol).Curve()
return spline
return GeomAPI_PointsToBSpline(
pts, degree_min, degree_max, continuity, tol
).Curve()
Comment on lines -552 to +550
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function fit_spline refactored with the following changes:

  • Inline variable that is immediately returned (inline-immediately-returned-variable)



def region_as_splinegon(boundary_splines):
Expand Down
15 changes: 5 additions & 10 deletions grains/geometry.py
Original file line number Diff line number Diff line change
Expand Up @@ -543,10 +543,7 @@ def cell_set_area(self, cell_set):
cell_area

"""
area = 0
for cell in self.cell_sets[cell_set]:
area += self.cell_area(cell)
return area
return sum(self.cell_area(cell) for cell in self.cell_sets[cell_set])
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function TriMesh.cell_set_area refactored with the following changes:

  • Convert for loop into call to sum() (sum-comprehension)
  • Inline variable that is immediately returned (inline-immediately-returned-variable)


def plot(self, *args, **kwargs):
"""Plots the mesh.
Expand Down Expand Up @@ -615,7 +612,7 @@ def plot(self, *args, **kwargs):
method_options, matplotlib_options = parse_kwargs(kwargs, TriMesh.plot_options)

# Plot the cells
ax = method_options['ax'] if method_options['ax'] else plt.figure().add_subplot()
ax = method_options['ax'] or plt.figure().add_subplot()
Comment on lines -618 to +615
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function TriMesh.plot refactored with the following changes:

  • Simplify if expression by using or (or-if-exp-identity)

ax.set_aspect('equal')
ax.triplot(self.vertices[:, 0], self.vertices[:, 1], self.cells, *args,
**matplotlib_options)
Expand Down Expand Up @@ -717,7 +714,7 @@ def plot_field(self, component, *args, show_mesh=True, **kwargs):
if component not in range(n_component):
raise ValueError('Component must be in [0, {0}].'.format(n_component-1))
method_options, _ = parse_kwargs(kwargs, TriMesh.plot_options)
ax = method_options['ax'] if method_options['ax'] else plt.figure().add_subplot()
ax = method_options['ax'] or plt.figure().add_subplot()
Comment on lines -720 to +717
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function TriMesh.plot_field refactored with the following changes:

  • Simplify if expression by using or (or-if-exp-identity)

ax.set_aspect('equal')
ax.tricontourf(self.vertices[:, 0], self.vertices[:, 1], field[:, component], 1000)
if show_mesh:
Expand Down Expand Up @@ -745,9 +742,7 @@ def write_inp(self, filename):
# Cell-vertex connectivities
element_type = 'CPS3' # 3-node linear plane stress element; can be changed in Abaqus
inp_file += '*ELEMENT, TYPE=' + element_type + '\n'
global_elem_num = 0
for elem_vertices in self.cells:
global_elem_num += 1
for global_elem_num, elem_vertices in enumerate(self.cells, start=1):
Comment on lines -748 to +745
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function TriMesh.write_inp refactored with the following changes:

  • Replace manual loop counter with call to enumerate (convert-to-enumerate)

# TODO: avoid reallocation by temporary strings as done below
inp_file += str(global_elem_num) + ', ' + str(list(elem_vertices+1))[1:-1] + '\n'

Expand Down Expand Up @@ -1155,7 +1150,7 @@ def plot(self, *args, **kwargs):

"""
method_options, matplotlib_options = parse_kwargs(kwargs, Polygon.plot_options)
ax = method_options['ax'] if method_options['ax'] else plt.figure().add_subplot()
ax = method_options['ax'] or plt.figure().add_subplot()
Comment on lines -1158 to +1153
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Polygon.plot refactored with the following changes:

  • Simplify if expression by using or (or-if-exp-identity)

ax.set_aspect('equal')
vertex_idx = np.arange(-1, self.n_vertex) # close the polygon
ax.plot(self.vertices[vertex_idx, 0], self.vertices[vertex_idx, 1],
Expand Down
8 changes: 5 additions & 3 deletions grains/med.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,9 +97,11 @@ def get_nodes(mesh):
nodes = mesh.getCoords().toNumPyArray()
# Get the node groups
group_names = mesh.getGroupsOnSpecifiedLev(1)
node_groups = {}
for group_name in group_names:
node_groups[group_name] = mesh.getGroupArr(1, group_name).toNumPyArray()
node_groups = {
group_name: mesh.getGroupArr(1, group_name).toNumPyArray()
for group_name in group_names
}

Comment on lines -100 to +104
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get_nodes refactored with the following changes:

  • Convert for loop into dictionary comprehension (dict-comprehension)

return nodes, node_groups


Expand Down
6 changes: 2 additions & 4 deletions grains/meshing.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,9 @@ def __init__(self, leftright_periodicity=False,
super().__init__(leftright_periodicity, topbottom_periodicity)

def __repr__(self):
repr_OOF = "QuadSkeleton(left_right_periodicity={1}, " \
return "QuadSkeleton(left_right_periodicity={1}, " \
"top_bottom_periodicity={2})".format(self.leftright_periodicity,
self.topbottom_periodicity)
return repr_OOF
Comment on lines -40 to -43
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function QuadSkeletonGeometry.__repr__ refactored with the following changes:

  • Inline variable that is immediately returned (inline-immediately-returned-variable)


class TriSkeletonGeometry(SkeletonGeometry):

Expand All @@ -51,11 +50,10 @@ def __init__(self, leftright_periodicity=False,
self.arrangement = arrangement

def __repr__(self):
repr_OOF = "TriSkeleton(arrangement='{0}', left_right_periodicity={1}, " \
return "TriSkeleton(arrangement='{0}', left_right_periodicity={1}, " \
"top_bottom_periodicity={2})".format(self.arrangement,
self.leftright_periodicity,
self.topbottom_periodicity)
return repr_OOF
Comment on lines -54 to -58
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function TriSkeletonGeometry.__repr__ refactored with the following changes:

  • Inline variable that is immediately returned (inline-immediately-returned-variable)



class FixedDict:
Expand Down
5 changes: 1 addition & 4 deletions grains/segmentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,10 +126,7 @@ def initial_segmentation(self, *args):
Label image, output of the quick shift algorithm.
"""

if args:
image = args[0]
else:
image = self.original_image
image = args[0] if args else self.original_image
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Segmentation.initial_segmentation refactored with the following changes:

  • Replace if statement with if expression (assign-if-exp)

segment_mask = segmentation.quickshift(image)
if self.__interactive_mode:
io.imshow(color.label2rgb(segment_mask, self.original_image, kind='avg'))
Expand Down