def complete_groups(end_segments, single_segments, field_passes, num_rows_per_pass): groups = [] for end_segment in end_segments[:]: matching_field_passes = [fpass for fpass in field_passes if end_segment.row_number in [row.number for row in fpass]] if len(matching_field_passes) == 0: print "End segment {} with row {} isn't in field pass list.".format(end_segment.start_code.name, end_segment.row_number) continue field_pass = matching_field_passes[0] pass_index = [row.number for row in field_pass].index(end_segment.row_number) field_pass_index = field_passes.index(field_pass) if field_pass_index >= len(field_passes) - 1: print "End segment {} can't be matched since it's in the last pass. Treating as single segment.".format(end_segment.start_code.name) single_segments.append(end_segment) end_segments.remove(end_segment) continue next_pass = field_passes[field_pass_index+1] # Find row index in next pass matching this one. # If 3 rows then a pass_index of 0 should have a corresponding index of 2 in the next row. corresponding_row_index = num_rows_per_pass - pass_index - 1 try: this_planting_row = field_pass[pass_index] next_planting_row = next_pass[corresponding_row_index] except IndexError: single_segments.append(end_segment) end_segments.remove(end_segment) print "Segment at end of row {} in pass {} doesn't have corresponding row in next pass to match with. Treating as single segment.".format(end_segment.row_number, field_pass_index+1) continue if this_planting_row.direction == next_planting_row.direction: single_segments.append(end_segment) end_segments.remove(end_segment) print "End segment {} in row {} can't match to row {} since both rows are in the same direction ({}). Treating as single segment.".format(end_segment.start_code.name, this_planting_row.number, next_planting_row.number, this_planting_row.direction) continue if len(next_planting_row.group_segments) == 0: single_segments.append(end_segment) end_segments.remove(end_segment) print "End segment {} in row {} can't match to row {} since next row doesn't have any segments. Treating as single segment.".format(end_segment.start_code.name, this_planting_row.number, next_planting_row.number) continue matching_start_segment = next_planting_row.group_segments[0] new_group = PlantGroup() new_group.add_segment(end_segment) new_group.add_segment(matching_start_segment) groups.append(new_group) return groups
def handle_single_segments(single_segments, groups): for segment in single_segments: new_group = PlantGroup() new_group.add_segment(segment) groups.append(new_group)