def printPath(path): """Prints path in a nice way. path should be a Path, CubicBezier, Line, or list of CubicBezier objects and Line objects.""" if not isinstance(path, Path): if isinstance(path, Line) or isinstance(path, CubicBezier): path = Path(path) elif all([isinstance(seg, Line) or isinstance(seg, CubicBezier) for seg in path]): path = Path(*path) else: print "This path is not a path... and is neither a Line object nor a CubicBezier object." return try: path[0] except IndexError: print "This path seems to be empty." return output_string = "" for seg_index_, seg in enumerate(path): if seg_index_ != 0: output_string += "\n" if isinstance(seg, CubicBezier): tmp = [] for z in cubPoints(seg): tmp += [z.real, z.imag] nicePts = "(%.1f + i%.1f, %.1f + i%.1f, %.1f + i%.1f, %.1f + i%.1f)" % tuple( tmp) output_string += "[%s] - CubicBezier: " % seg_index_ + nicePts elif isinstance(seg, Line): nicePts = "(%.1f + i%.1f, %.1f + i%.1f)" % ( seg.start.real, seg.start.imag, seg.end.real, seg.end.imag,) output_string += "[%s] - Line : " % seg_index_ + nicePts else: print("+" * 50) print(seg) raise Exception("This path contains a segment that is neither a Line nor a CubicBezier.") if path[0].start == path[-1].end: closure = "Closed" else: closure = "Open " output_string += "\n" + "[*] " + closure + " : |path.point(0) - path.point(1)| = %s" % abs( path.point(0) - path.point(1)) print(output_string)
def _paperjs_path_to_polygon(co): ''' Convert Paper.js paths to a polygon (a line composed of consecutive vertices). Used by `download_microdraw_contours_as_polygons`. Note: Paper.js Bézier curves are encoded as px, py, ax, ay, bx, by, where px, py is an anchor point, ax, ay is the previous handle and bx, by the next handle. SVG path tools use a more standard encoding: p1x,p1y, b1x, b1y, a2x, a2y, p2x, p2y, where p1x, p1y is the start anchor point, p2x, p2y the end anchor point, b1x, b1y is the handle coming out from p1x, p1y, and a2x, a2y is the handle entering into the end anchor point. ''' mysegs = [] for i in range(len(co)): c = co[i % len(co)] c1 = co[(i + 1) % len(co)] try: if isinstance(c[0], (list, np.ndarray)): # print("c[0] is list") [s, sj], [_, _], [b, bj] = c else: # print("c[0] is not list:", type(c[0])) s, sj, b, bj = c[0], c[1], 0, 0 if isinstance(c1[0], (list, np.ndarray)): # print("c1[0] is list") [s1, s1j], [a1, a1j], [_, _] = c1 else: # print("c1[0] is not list:", type(c1[0])) s1, s1j, a1, a1j = c1[0], c1[1], 0, 0 # print("c:", c) # print("c1:", c1) # print("s,sj:",s,sj,", b,bj:",b,bj, ", s1,sij:", s1,s1j, ", a1,a1j:",a1,a1j) seg = CubicBezier(complex(s, sj), complex(s + b, sj + bj), complex(s1 + a1, s1j + a1j), complex(s1, s1j)) mysegs.append(seg) except: # ValueError as err: # print(err) pass if len(mysegs) < 5: # print("len(mysegs) is < 5") return p = Path(*mysegs) NUM_SAMPLES = int(p.length()) my_path = [] for i in range(NUM_SAMPLES): x = p.point(i / (NUM_SAMPLES - 1)) my_path.append([x.real, x.imag]) return np.array(my_path)
class Astrolabe: """A proper traveling astrolabe would have a set of plates for each clime, with maybe extra plates for special places. Morrison: > The earliest astrolabes, which were deeply influenced by Greek tradition, included plates for the latitudes of the *climates.* The climates of the world were defined by Ptolemy to be the latitudes where the length of the longest day of the year varied by one-half hour. Ptolemy calculated the latitude corresponding to a 15-minute difference in the length of the longest day (using a value of 23 degrees 51 minutes 20 seconds for the obliquity of the ecliptic) for 39 latitudes, which covered the Earth from the equator to the North Pole. The ones called the classic *climata* were for the half-hour differences in the longest day covering the then populated world.""" climata = { "Meroe": 16.45, "Soene": 23.85, "Lower Egypt": 30.37, "Rhodes": 36.00, "Hellespont": 40.93, "Mid-Pontus": 45.02, "Mouth of Borysthinia": 48.53, } def __init__(self, obliquity=23.4443291, radius_capricorn=100, plate_parameters=None): self.obliquity = obliquity self._obliquityRadians = math.radians(obliquity) self._obliquityRadiansArgument = math.radians( (90 - self.obliquity) / 2) self.RadiusCapricorn = radius_capricorn self.plate_parameters = self.climata self.plate_altitudes = list(range(0, 90, 10)) self.plate_azimuths = list(range(10, 90, 10)) self.tropic_arcs() self.plates(plate_parameters=plate_parameters) # Parameters for layout of graduated limb. self.short_tick_angles = list(range(0, 361, 1)) self.long_tick_angles = list(range(0, 375, 15)) self.short_tick = 5 self.long_tick = 15 self.ticks = { "inner_radius": self.RadiusCapricorn, "center_radius": self.RadiusCapricorn + self.short_tick, "outer_radius": self.RadiusCapricorn + self.long_tick, "short_tick_angles": self.short_tick_angles, "long_tick_angles": self.long_tick_angles, } # Ecliptic self.RadiusEcliptic = (self.RadiusCapricorn + self.RadiusCancer) / 2.0 self.yEclipticCenter = (self.RadiusCapricorn - self.RadiusCancer) / 2.0 self.xEclipticCenter = 0.0 self.ecliptic_pole = self.RadiusEquator * math.tan( self._obliquityRadiansArgument / 2.0) self.ecliptic_center = self.RadiusEquator * math.tan( self._obliquityRadiansArgument) self.ecliptic = { "cx": self.xEclipticCenter, "cy": self.yEclipticCenter, "r": self.RadiusEcliptic, "width": 5, } self.ecliptic_path = Path( Arc( start=complex(0, self.ecliptic["cy"] + self.ecliptic["r"]), radius=(complex(self.ecliptic["r"], self.ecliptic["r"])), rotation=0.0, large_arc=True, sweep=False, end=complex(0, self.ecliptic["cy"] - self.ecliptic["r"]), ), Arc( start=complex(0, self.ecliptic["cy"] - self.ecliptic["r"]), radius=(complex(self.ecliptic["r"], self.ecliptic["r"])), rotation=0.0, large_arc=True, sweep=False, end=complex(0, self.ecliptic["cy"] + self.ecliptic["r"]), ), ) def plates(self, plate_parameters=None): if plate_parameters is not None: self.plate_parameters.update(plate_parameters) self.plates = {} for location, latitude in self.plate_parameters.items(): if location not in self.plates: self.plates[location] = { "location": location, "latitude": latitude } # Note: if different locations with same name, will overwrite. self.plate(location=location) def plate(self, location=None): """Compute parts for one plate""" plate = self.plates[location] plate_latitude = plate["latitude"] almucantars = self.almucantar_arcs(altitudes=self.plate_altitudes, latitude=plate_latitude) plate["almucantars"] = almucantars almucantar_center = self.almucantar_arc(altitude=80, latitude=plate_latitude) plate["almucantar_center"] = almucantar_center plate["horizon"] = self.horizon(latitude=plate_latitude) prime_vertical = self.azimuth_arc(azimuth=90, latitude=plate_latitude, prime=True) plate["prime_vertical"] = prime_vertical[0] # TODO: clean this up azimuth_arcs = self.azimuth_arcs(latitude=plate_latitude) plate["azimuths"] = azimuth_arcs def horizon(self, latitude=None): radiansLatitude = math.radians(latitude) rHorizon = self.RadiusEquator / math.sin(radiansLatitude) yHorizon = self.RadiusEquator / math.tan(radiansLatitude) xHorizon = 0.0 return {"cx": xHorizon, "cy": yHorizon, "r": rHorizon} def tropic_arcs(self): r""" The size of an astrolabe is contolled by the radius of the tropic of Capricorn. Recall that the tropics represent the extreme positions of the sun on its path (the ecliptic) through the course of a year. Summer solstice occurs when the sun reaches the tropic of Cancer and winter solstice when the sun reaches the tropic of Capricorn. The stereographic projection, from the south pole onto the plane of the equator, is visualized as lines from the south pole tracing out new curves on the plane of the equator. The projection sees the tropics as three concentric circles. From the view of the south pole, the tropic of Capricorn is the outer circle and the tropic of Cancer is the inner circle. Plate grid equation 1, the tropics. R_{Equator} = R_{Capricorn} \tan(\frac{90 - \epsilon}{2}), R_{Cancer} = R_{Equator} \tan(\frac{90 - \epsilon}{2}) """ self.RadiusEquator = self.RadiusCapricorn * math.tan( self._obliquityRadiansArgument) self.RadiusCancer = self.RadiusEquator * math.tan( self._obliquityRadiansArgument) def almucantar_arc(self, altitude, latitude): r"""Generate circle of constant altitude. Plate grid equation 2, circles of equal altitude (almucantars). y_{center} &= R_{Equator}(\frac{\cos\phi}{\sin\phi + \sin a}), & r_{a} &= R_{Equator} (\frac{\cos a}{\sin\phi + \sin a}) \\ r_{U} &= R_{Equator} \cot(\frac{\phi + a}{2}), & r_{L} &= -R_{Equator} \tan(\frac{\phi - a}{2}) """ radiansAltitude = math.radians(altitude) radiansLatitude = math.radians(latitude) almucantarCenter = self.RadiusEquator * ( math.cos(radiansLatitude) / (math.sin(radiansLatitude) + math.sin(radiansAltitude))) almucantarRadius = self.RadiusEquator * ( math.cos(radiansAltitude) / (math.sin(radiansLatitude) + math.sin(radiansAltitude))) return { "alt": altitude, "cx": 0, "cy": almucantarCenter, "r": almucantarRadius } def almucantar_arcs(self, altitudes=None, latitude=None): almucantar_coords = [] for altitude in altitudes: almucantar_coords.append( self.almucantar_arc(altitude=altitude, latitude=latitude)) return almucantar_coords def azimuth_arc(self, azimuth=None, latitude=None, prime=False): # Plate grid equation 3, circles of azimuth. radiansMinus = math.radians((90 - latitude) / 2.0) radiansPlus = math.radians((90 + latitude) / 2.0) yZenith = self.RadiusEquator * math.tan(radiansMinus) yNadir = -self.RadiusEquator * math.tan(radiansPlus) yCenter = (yZenith + yNadir) / 2.0 yAzimuth = (yZenith - yNadir) / 2.0 radiansAzimuth = math.radians(azimuth) xAzimuth = yAzimuth * math.tan(radiansAzimuth) radiusAzimuth = yAzimuth / math.cos(radiansAzimuth) if prime is True: coord_left = {"az": 90, "cx": 0, "cy": yCenter, "r": yAzimuth} coord_right = {"az": 90, "cx": 0, "cy": yCenter, "r": yAzimuth} else: coord_left = { "az": azimuth, "cx": xAzimuth, "cy": yCenter, "r": radiusAzimuth, } coord_right = { "az": azimuth, "cx": -xAzimuth, "cy": yCenter, "r": radiusAzimuth, } return [coord_left, coord_right] def azimuth_arcs(self, latitude=None): azimuth_coords = [] for azimuth in self.plate_azimuths: coords = self.azimuth_arc(azimuth=azimuth, latitude=latitude) azimuth_coords.extend(coords) return azimuth_coords def ecliptic_division(self, constructionAngle=None): # The procedure for dividing the ecliptic is (Figure 6-7 with the following steps numbered): # 1. Locate the ecliptic pole on the meridian at $R_{eq} \tan(\epsilon / 2)$ from the center. # 2. Divide the equator into equal segments of longitude: 12 divisions of 30 for the entry # into each zodiac sign: more divisions depending on the resolution desired. # 3. Draw a line from each equator division to the ecliptic pole. The corresponding longitude # point on the ecliptic is where this line intersects the ecliptic circle. # 4. A tic mark on the ecliptic is drawn toward the center of the instrument. # Endpoint of line on the Equator, through origin with slope give by angle. x0 = self.RadiusEquator * math.cos(math.radians(constructionAngle)) y0 = self.RadiusEquator * math.sin(math.radians(constructionAngle)) # Endpoint of a line from the ecliptic pole to mark on equator makes # an angle theta2. theta2 = math.atan2((y0 - self.ecliptic_pole), x0) if x0 > 0.0: slope = (y0 - self.ecliptic_pole) / x0 # Draw line through equator division and ecliptic pole. # Since the ecliptic is inside the tropic of capricorn circle, overshoot # by picking x2 = rcap x2 = self.RadiusCapricorn y2 = slope * x2 + self.ecliptic_pole constructionLine = Line(complex(0, self.ecliptic_pole), complex(x2, y2)) elif x0 < 0.0: slope = (y0 - self.ecliptic_pole) / x0 # Draw line through equator division and ecliptic pole. # Since the ecliptic is inside the tropic of capricorn circle, overshoot # by picking x2 = rcap x2 = -self.RadiusCapricorn y2 = slope * x2 + self.ecliptic_pole constructionLine = Line(complex(0, self.ecliptic_pole), complex(x2, y2)) else: constructionLine = Line(complex(0, self.ecliptic_pole), complex(0, self.RadiusCapricorn)) intersections = [] for (T1, seg1, t1), (T2, seg2, t2) in self.ecliptic_path.intersect(constructionLine): p = self.ecliptic_path.point(T1) intersections.append(p) intersections = [i for i in intersections if i is not None] intersections = list(set([(p.real, p.imag) for p in intersections])) match_list = [] while len(intersections) > 0: p = intersections.pop() l = [p] for m, q in enumerate(intersections): if math.isclose(p[0], q[0], abs_tol=0.01) and math.isclose( p[1], q[1], abs_tol=0.01): l.append(q) intersections.pop(m) match_list.append(l) match_list = [{ "angle": constructionAngle, "x2": m[0][0], "y2": m[0][1] } for m in match_list] return match_list[0]
def main(): parser = argparse.ArgumentParser() parser.add_argument('--folder', '-f', help='Path to data folder') parser.add_argument('--point_num', '-p', help='Point number for each sample', type=int, default=1024) parser.add_argument('--save_ply', '-s', help='Convert .pts to .ply', action='store_true') parser.add_argument('--augment', '-a', help='Data augmentation', action='store_true') args = parser.parse_args() print(args) batch_size = 2048 fold_num = 3 tag_aug = '_ag' if args.augment else '' folder_svg = args.folder if args.folder else '../../data/tu_berlin/svg' root_folder = os.path.dirname(folder_svg) folder_pts = os.path.join(root_folder, 'pts' + tag_aug) filelist_svg = [line.strip() for line in open(os.path.join(folder_svg, 'filelist.txt'))] category_label = dict() with open(os.path.join(os.path.dirname(folder_svg), 'categories.txt'), 'w') as file_categories: for filename in filelist_svg: category = os.path.split(filename)[0] if category not in category_label: file_categories.write('%s %d\n' % (category, len(category_label))) category_label[category] = len(category_label) filelist_svg_failed = [] data = np.zeros((batch_size, args.point_num, 6)) label = np.zeros((batch_size), dtype=np.int32) for idx_fold in range(fold_num): filelist_svg_fold = [filename for i, filename in enumerate(filelist_svg) if i % fold_num == idx_fold] random.seed(idx_fold) random.shuffle(filelist_svg_fold) filename_filelist_svg_fold = os.path.join(root_folder, 'filelist_fold_%d.txt' % (idx_fold)) with open(filename_filelist_svg_fold, 'w') as filelist_svg_fold_file: for filename in filelist_svg_fold: filelist_svg_fold_file.write('%s\n' % (filename)) idx_h5 = 0 idx = 0 filename_filelist_h5 = os.path.join(root_folder, 'fold_%d_files%s.txt' % (idx_fold, tag_aug)) with open(filename_filelist_h5, 'w') as filelist_h5_file: for idx_file, filename in enumerate(filelist_svg_fold): filename_svg = os.path.join(folder_svg, filename) try: paths, attributes = svg2paths(filename_svg) except: filelist_svg_failed.append(filename_svg) print('{}-Failed to parse {}!'.format(datetime.now(), filename_svg)) continue points_array = np.zeros(shape=(args.point_num, 3), dtype=np.float32) normals_array = np.zeros(shape=(args.point_num, 3), dtype=np.float32) path = Path() for p in paths: p_non_empty = Path() for segment in p: if segment.length() > 0: p_non_empty.append(segment) if len(p_non_empty) != 0: path.append(p_non_empty) path_list = [] if args.augment: for removal_idx in range(6): path_with_removal = Path() for p in path[:math.ceil((0.4 + removal_idx * 0.1) * len(paths))]: path_with_removal.append(p) path_list.append(path_with_removal) path_list = path_list + augment(path, 6) else: path_list.append(path) for path_idx, path in enumerate(path_list): for sample_idx in range(args.point_num): sample_idx_float = (sample_idx + random.random()) / (args.point_num - 1) while True: try: point = path.point(sample_idx_float) normal = path.normal(sample_idx_float) break except: sample_idx_float = random.random() continue points_array[sample_idx] = (point.real, sample_idx_float, point.imag) normals_array[sample_idx] = (normal.real, random.random() * 1e-6, normal.imag) points_min = np.amin(points_array, axis=0) points_max = np.amax(points_array, axis=0) points_center = (points_min + points_max) / 2 scale = np.amax(points_max - points_min) / 2 points_array = (points_array - points_center) * (0.8 / scale, 0.4, 0.8 / scale) if args.save_ply: tag_aug_idx = tag_aug + '_' + str(path_idx) if args.augment else tag_aug filename_pts = os.path.join(folder_pts, filename[:-4] + tag_aug_idx + '.ply') data_utils.save_ply(points_array, filename_pts, normals=normals_array) idx_in_batch = idx % batch_size data[idx_in_batch, ...] = np.concatenate((points_array, normals_array), axis=-1).astype(np.float32) label[idx_in_batch] = category_label[os.path.split(filename)[0]] if ((idx + 1) % batch_size == 0) \ or (idx_file == len(filelist_svg_fold) - 1 and path_idx == len(path_list) - 1): item_num = idx_in_batch + 1 filename_h5 = 'fold_%d_%d%s.h5' % (idx_fold, idx_h5, tag_aug) print('{}-Saving {}...'.format(datetime.now(), os.path.join(root_folder, filename_h5))) filelist_h5_file.write('./%s\n' % (filename_h5)) file = h5py.File(os.path.join(root_folder, filename_h5), 'w') file.create_dataset('data', data=data[0:item_num, ...]) file.create_dataset('label', data=label[0:item_num, ...]) file.close() idx_h5 = idx_h5 + 1 idx = idx + 1 if len(filelist_svg_failed) != 0: print('{}-Failed to parse {} sketches!'.format(datetime.now(), len(filelist_svg_failed)))
class IncompleteRing(object): def __init__(self, ring): self.ring = ring self.innerCR_ring = None self.outerCR_ring = None self.completed_path = Path() self.overlap0 = False #This is related to a deprecated piece of code and must be False. self.overlap1 = False #This is related to a deprecated piece of code and must be False. self.corrected_start = None #set in case of overlap (point, seg,t) where seg is a segment in self and seg(t)=point self.corrected_end = None #set in case of overlap (point, seg,t) where seg is a segment in self and seg(t)=point self.ir_start = self.ring.point(0) self.ir_end = self.ring.point(1) self.up_ladders = [] self.down_ladder0 = None #(irORcr0,T0) ~ startpoint down-ladder on this ir and (and T-val on connecting ring it connects at - irORcr0 can be incompleteRing object or completeRing object) self.down_ladder1 = None self.transect0fails = [] #records IRs are "below" self, but failed to provide a transect to self.ir_start self.transect1fails = [] #records IRs are "below" self, but failed to provide a transect to self.ir_end self.transect0found = False self.transect1found = False self.isCore = False self.ORring = self.ring # def __repr__(self): # return '<IncompleteRing based on ring = %s>' %self.ring def __eq__(self, other): if not isinstance(other, IncompleteRing): return NotImplemented if self.ring != other.ring: return False return True def __ne__(self, other): if not isinstance(other, CompleteRing): return NotImplemented return not self == other def set_inner(self, ring): self.innerCR_ring = ring def set_outer(self, ring): self.outerCR_ring = ring def sortUpLadders(self): self.up_ladders = sortby(self.up_ladders,1) self.up_ladders.reverse() # this as my newer cleaned up version, but I broke it i think (7-19-16) # def addSegsToCP(self, segs, tol_closure=opt.tol_isApproxClosedPath): # """input a list of segments to append to self.completed_path # this function will stop adding segs if a seg endpoint is near the # completed_path startpoint""" # if len(segs)==0: # raise Exception("No segs given to insert") # # # Iterate through segs to check if segments join together nicely # # and (fix them if need be and) append them to completed_path # for seg in segs: # # This block checks if cp is (nearly) closed. # # If so, closes it with a Line, and returns the fcn # if len(self.completed_path)!=0: # cp_start, cp_end = self.completed_path[0].start, self.completed_path[-1].end # if abs(cp_start - cp_end) < tol_closure: # if cp_start==cp_end: # # then do nothing else and return # return # else: # # then close completed_path with a line and return # self.completed_path.append(Line(cp_start, cp_end)) # return # # elif seg.start != self.completed_path[-1].end: # # then seg does not start at the end of completed_path, # # fix it then add it on # current_endpoint = self.completed_path[-1].end # if abs(seg.start - current_endpoint) < tol_closure: # # then seg is slightly off from current end of # # completed_path, fix seg and insert it into # # completed_path # if isinstance(seg, CubicBezier): # P0, P1, P2, P3 = seg.bpoints() # newseg = CubicBezier(current_endpoint, P1, P2, P3) # elif isinstance(seg, Line): # newseg = Line(current_endpoint, seg.end) # else: # raise Exception('Path segment is neither Line ' # 'object nor CubicBezier object.') # self.completed_path.insert(len(self.completed_path), newseg) # else: # raise Exception("Segment being added to path does not " # "start at path endpoint.") # else: # # then seg does not need to be fixed, so go ahead and insert it # self.completed_path.insert(len(self.completed_path), seg) def addSegsToCP(self, segs, tol_closure=opt.tol_isApproxClosedPath): #input a list of segments to append to self.completed_path #this function will stop adding segs if a seg endpoint is near the completed_path startpoint if len(segs)==0: raise Exception("No segs given to insert") #Iterate through segs to check if segments join together nicely #and (fix them if need be and) append them to completed_path for seg in segs: #This block checks if cp is (nearly) closed. #If so, closes it with a Line, and returns the fcn if len(self.completed_path)!=0: cp_start, cp_end = self.completed_path[0].start, self.completed_path[-1].end if abs(cp_start - cp_end) < tol_closure: if cp_start==cp_end: #then do nothing else and return return else: #then close completed_path with a line and return self.completed_path.append(Line(cp_start,cp_end)) return if len(self.completed_path)!=0 and seg.start != self.completed_path[-1].end: #then seg does not start at the end of completed_path, fix it then add it on current_endpoint = self.completed_path[-1].end if abs(seg.start - current_endpoint) < tol_closure: #then seg is slightly off from current end of completed_path, fix seg and insert it into completed_path if isinstance(seg,CubicBezier): P0,P1,P2,P3 = cubPoints(seg) newseg = CubicBezier(current_endpoint,P1,P2,P3) elif isinstance(seg,Line): newseg = Line(current_endpoint,seg.end) else: raise Exception('Path segment is neither Line object nor CubicBezier object.') self.completed_path.insert(len(self.completed_path),newseg) else: raise Exception("Segment being added to path does not start at path endpoint.") else: #then seg does not need to be fixed, so go ahead and insert it self.completed_path.insert(len(self.completed_path),seg) def addConnectingPathToCP(self, connecting_path, seg0, t0, seg1, t1): # first find orientation by checking whether t0 is closer to start or end. T0, T1 = segt2PathT(connecting_path, seg0, t0), segt2PathT(connecting_path, seg1, t1) i0, i1 = connecting_path.index(seg0), connecting_path.index(seg1) first_seg = reverseSeg(trimSeg(seg1, 0, t1)) last_seg = reverseSeg(trimSeg(seg0, t0, 1)) if T0 > T1: # discontinuity between intersection points if isApproxClosedPath(connecting_path): middle_segs = [reverseSeg(connecting_path[i1-i]) for i in range(1, (i1-i0) % len(connecting_path))] else: raise Exception("ir jumps another ir's gap. This case is not " "implimented yet") elif T0 < T1: # discontinuity NOT between intersection points middle_segs = [reverseSeg(connecting_path[i1+i0-i]) for i in range(i0 + 1, i1)] else: raise Exception("T0=T1, this means there's a bug in either " "pathXpathIntersections fcn or " "trimAndAddTransectsBeforeCompletion fcn") # first seg if isDegenerateSegment(first_seg): tmpSeg = copyobject(middle_segs.pop(0)) tmpSeg.start = first_seg.start first_seg = tmpSeg if first_seg.end == self.completed_path[0].start: self.completed_path.insert(0,first_seg) else: printPath(first_seg) printPath(last_seg) printPath(connecting_path) raise Exception("first_seg is set up wrongly") # middle segs self.addSegsToCP(middle_segs) # last seg if isDegenerateSegment(last_seg): middle_segs[-1].end = last_seg.end else: self.addSegsToCP([last_seg]) def trimAndAddTransectsBeforeCompletion(self): # Retrieve transect endpoints if necessary (irORcr0, T0), (irORcr1, T1) = self.down_ladder0, self.down_ladder1 tr0_start_pt = irORcr0.ORring.point(T0) tr1_end_pt = irORcr1.ORring.point(T1) if not self.overlap0: # then no overlap at start, add transect0 to beginning of # connected path (before the ir itself) i0 = -1 startSeg = Line(tr0_start_pt, self.ir_start) else: # overlap at start, trim the first seg in the ir (don't connect # anything, just trim) i0 = self.ring.path.index(self.corrected_start[1]) startSeg = trimSeg(self.corrected_start[1], self.corrected_start[2],1) if not self.overlap1: # then no overlap at end to add transect1 to connected path # (append to end of the ir) i1 = len(self.ring.path) endSeg = Line(self.ir_end, tr1_end_pt) else: # overlap at end, trim the last seg in the ir (don't connect # anything, just trim) i1 = self.ring.path.index(self.corrected_end[1]) endSeg = trimSeg(self.corrected_end[1], 0, self.corrected_end[2]) # first seg if isDegenerateSegment(startSeg): tmpSeg = copyobject(self.ring.path[i0 + 1]) tmpSeg.start = startSeg.start startSeg = tmpSeg i0 += 1 self.addSegsToCP([startSeg]) else: self.addSegsToCP([startSeg]) # middle segs if i0 + 1 != i1: self.addSegsToCP([self.ring.path[i] for i in range(i0+1, i1)]) # last seg if isDegenerateSegment(endSeg): self.completed_path[-1].end = endSeg.end else: self.addSegsToCP([endSeg]) def irpoint(self, pos): return self.ring.point(pos) def area(self): if not isinstance(self.completed_path,Path): return "Fail" if (self.completed_path is None or not isApproxClosedPath(self.completed_path)): # raise Exception("completed_path not complete. Distance between start and end: %s"%abs(self.completed_path.point(0) - self.completed_path.point(1))) return "Fail" return areaEnclosed(self.completed_path) def type(self, colordict): for (key, val) in colordict.items(): if self.ring.color == val: return key else: raise Exception("Incomplete Ring color not in colordict... you shouldn't have gotten this far. Bug detected.") # def info(self,cp_index): # ###### "complete ring index, complete?, inner BrookID, outer BrookID, inner color, outer color, area, area Ignoring IRs, averageRadius, minR, maxR, IRs contained" # return str(cp_index) + "," + "Incomplete"+"," + "N/A" + ", " + self.ring.brook_tag + "," + "N/A" + ", " + self.ring.color +"," + str(self.area()) +", "+ "N/A"+","+str(self.ring.aveR())+","+str(self.ring.minR)+","+str(self.ring.maxR)+","+"N/A" def info(self, cp_index, colordict): ###### "complete ring index, type, # of IRs contained, minR, maxR, aveR, area, area Ignoring IRs" return str(cp_index)+","+self.type(colordict)+","+"N/A"+","+str(self.ring.minR)+","+ str(self.ring.maxR)+","+str(self.ring.aveR())+","+str(self.area())+","+"N/A" def followPathBackwards2LadderAndUpDown(self, irORcr, T0): """irORcr is the path being followed, self is the IR to be completed returns (traveled_path,irORcr_new,t_new) made from the part of irORcr's path before T0 (and after ladder) plus the line from ladder (the first one that is encountered)""" rds = remove_degenerate_segments irORcr_path = irORcr.ORring.path thetaprekey = Theta_Tstar(T0) thetakey = lambda lad: thetaprekey.distfcn(lad[1]) sorted_upLadders = sorted(irORcr.up_ladders, key=thetakey) if isinstance(irORcr, CompleteRing): ir_new, T = sorted_upLadders[0] if T != T0: reversed_path_followed = reversePath(cropPath(irORcr_path, T, T0)) else: # this happens when up and down ladder are at same location reversed_path_followed = Path() # add the ladder to reversed_path_followed if (irORcr, T) == ir_new.down_ladder0: if not ir_new.overlap0: ladder = Line(irORcr_path.point(T), ir_new.irpoint(0)) reversed_path_followed.append(ladder) T_ir_new = 0 else: T_ir_new = segt2PathT(ir_new.ring.path, ir_new.corrected_start[1], ir_new.corrected_start[2]) elif (irORcr, T) == ir_new.down_ladder1: if not ir_new.overlap1: ladder = Line(irORcr_path.point(T), ir_new.irpoint(1)) reversed_path_followed.append(ladder) T_ir_new = 1 else: T_ir_new = segt2PathT(ir_new.ring.path, ir_new.corrected_end[1], ir_new.corrected_end[2]) else: raise Exception("this case shouldn't be reached, mistake in " "logic or didn't set downladder somewhere.") return rds(reversed_path_followed), ir_new, T_ir_new else: # current ring to follow to ladder is incomplete ring irORcr_path = irORcr.ring.path for ir_new, T in sorted_upLadders: if T < T0: # Note: always following path backwards reversed_path_followed = irORcr_path.cropped(T, T0).reversed() if (irORcr, T) == ir_new.down_ladder0: if not ir_new.overlap0: ladder = Line(irORcr_path.point(T), ir_new.irpoint(0)) reversed_path_followed.append(ladder) T_ir_new = 0 else: T_ir_new = segt2PathT(ir_new.ring.path, ir_new.corrected_start[1], ir_new.corrected_start[2]) elif (irORcr, T) == ir_new.down_ladder1: if not ir_new.overlap1: ladder = Line(irORcr_path.point(T), ir_new.irpoint(1)) reversed_path_followed.append(ladder) T_ir_new = 1 else: T_ir_new = segt2PathT(ir_new.ring.path, ir_new.corrected_end[1], ir_new.corrected_end[2]) else: tmp_mes = ("this case shouldn't be reached, mistake " "in logic or didn't set downladder " "somewhere.") raise Exception(tmp_mes) return rds(reversed_path_followed), ir_new, T_ir_new # none of the upladder were between 0 and T0, # so use downladder at 0 else: (irORcr_new, T_new) = irORcr.down_ladder0 irORcr_new_path = irORcr_new.ORring.path ###Should T0==0 ever? if T0 != 0: reversed_path_followed = irORcr.ring.path.cropped(0, T0).reversed() else: reversed_path_followed = Path() if irORcr.overlap0 == False: ladder = Line(irORcr_path.point(0), irORcr_new_path.point(T_new)) reversed_path_followed.append(ladder) return rds(reversed_path_followed), irORcr_new, T_new def findMiddleOfConnectingPath(self): #creates path starting of end of down_ladder1, go to nearest (with t> t0) up-ladder or if no up-ladder then down_ladder at end and repeat until getting to bottom of down_ladder0 maxIts = 1000 #### Tolerance traveled_path = Path() iters = 0 (irORcr_new,T_new) = self.down_ladder1 doneyet = False while iters < maxIts and not doneyet: iters =iters+ 1 # ##DEBUG sd;fjadsfljkjl; # if self.ring.path[0].start == (260.778+153.954j): # from misc4rings import dis # from svgpathtools import Line # p2d=[self.completed_path, # self.down_ladder0[0].ORring.path, # self.down_ladder1[0].ORring.path] # clrs = ['blue','green','red'] # if iters>1: # p2d.append(Path(*traveled_path)) # clrs.append('black') # lad0a = self.down_ladder0[0].ORring.path.point(self.down_ladder0[1]) # lad0b = self.ORring.path[0].start # lad0 = Line(lad0a,lad0b) # lad1a = self.ORring.path[-1].end # lad1b = self.down_ladder1[0].ORring.path.point(self.down_ladder1[1]) # lad1 = Line(lad1a,lad1b) # dis(p2d,clrs,lines=[lad0,lad1]) # print abs(lad0.start-lad0.end) # print abs(lad1.start-lad1.end) # bla=1 # ##end of DEBUG sd;fjadsfljkjl; traveled_path_part, irORcr_new, T_new = self.followPathBackwards2LadderAndUpDown(irORcr_new, T_new) for seg in traveled_path_part: traveled_path.append(seg) if irORcr_new == self: return traveled_path # if irORcr_new == self.down_ladder0[0]: # doneyet = True # irORcr_new_path = irORcr_new.ORring.path # if T_new != self.down_ladder0[1]: # for seg in reversePath(cropPath(irORcr_new_path,self.down_ladder0[1],T_new)): # traveled_path.append(seg) # break if (irORcr_new, T_new) == self.down_ladder0: return traveled_path if iters >= maxIts-1: raise Exception("findMiddleOfConnectingPath reached maxIts") return traveled_path def hardComplete(self, tol_closure=opt.tol_isApproxClosedPath): self.trimAndAddTransectsBeforeCompletion() meatOf_connecting_path = self.findMiddleOfConnectingPath() ###this is a Path object self.addSegsToCP(meatOf_connecting_path) cp_start,cp_end = self.completed_path[0].start, self.completed_path[-1].end #check newly finished connecting_path is closed if abs(cp_start - cp_end) >= tol_closure: raise Exception("Connecting path should be finished but is not closed.") #test for weird .point() bug where .point(1) != end if (abs(cp_start - self.completed_path.point(0)) >= tol_closure or abs(cp_end - self.completed_path.point(1)) >= tol_closure): self.completed_path = parse_path(path2str(self.completed_path)) raise Exception("weird .point() bug where .point(1) != end... I just added this check in on 3-5-15, so maybe if this happens it doesn't even matter. Try removing this code-block... or change svgpathtools.Path.point() method to return one or the other.") def findTransect2endpointFromInnerPath_normal(self,irORcr_innerPath,innerPath,T_range,Tpf,endBin): #Tpf: If The T0 transect intersects self and the T1 does not, then Tpf should be True, otherwise it should be false. #Note: If this endpoint's transect is already found, then this function returns (False,False,False,False) #Returns: (irORcr,nL,seg_irORcr,t_irORcr) where irORcr is the inner path that the transect, nL, leaves from and seg_irORcr and t_irORcr correspond to innerPath and nL points from seg_irORcr.point(t_irORcr) to the desired endpoint #Note: irORcr will differ from irORcr_innerPath in the case where irORcr_innerPath admits a transect but this transect intersects with a (less-inner) previously failed path. The less-inner path is then output. (T0,T1) = T_range if T1<T0: if T1==0: T1=1 else: Exception("I don't think T_range should ever have T0>T1. Check over findTransect2endpointsFromInnerPath_normal to see if this is acceptable.") if endBin == 0 and self.transect0found: return False, False, False, False elif endBin == 1 and self.transect1found: return False, False, False, False elif endBin not in {0,1}: raise Exception("endBin not a binary - so there is a typo somewhere when calling this fcn") if irORcr_innerPath.isCore: return irORcr_innerPath, Line(irORcr_innerPath.inner.path.point(0), self.irpoint(endBin)), irORcr_innerPath.inner.path[0], 0 # make transect from center (actually path.point(0)) to the endpoint maxIts = 100 ##### tolerance its = 0 while (abs(innerPath.point(T0) - innerPath.point(T1)) >= opt.tol_isApproxClosedPath and its <= maxIts): its += 1 T = float((T0+T1))/2 center = self.ring.center nL = normalLineAtT_toInner_intersects_withOuter(T,innerPath,self.ring.path,center)[0] #check if transect from innerPath.point(T) intersects with outerPath if Tpf: #p x f if nL != False: #p p f T0 = T else: #p f f T1 = T else: #f x p if nL != False: #f p p T1 = T else: #f f p T0 = T # ###DEBUG asdfkljhjdkdjjjdkkk # if self.ORring.point(0)==(296.238+285.506j): # from misc4rings import dis # print "endBin=%s\nT0=%s\nT=%s\nT1=%s\n"%(endBin,T0,T,T1) # if isNear(innerPath.point(T0),innerPath.point(T1)): # print "Exit Criterion Met!!!" # if nL==False: # nLtmp = normalLineAtT_toInner_intersects_withOuter(T,innerPath,self.ring.path,center,'debug')[0] # else: # nLtmp = nL # dis([innerPath,self.ring.path,Path(nLtmp)],['green','red','blue'],nodes=[center,innerPath.point(T0),innerPath.point(T1)],node_colors=['blue','green','red']) # bla=1 # ###end of DEBUG asdfkljhjdkdjjjdkkk if its>=maxIts: raise Exception("while loop for finding transect by bisection reached maxIts without terminating") if nL != False: #x p x t_inner, seg_inner = pathT2tseg(innerPath, T) else: #x f x if Tpf: #p f f nL = normalLineAtT_toInner_intersects_withOuter(T0,innerPath,self.ring.path,center)[0] (t_inner,seg_inner) = pathT2tseg(innerPath,T0) else: #f f p nL = normalLineAtT_toInner_intersects_withOuter(T1,innerPath,self.ring.path,center)[0] (t_inner,seg_inner) = pathT2tseg(innerPath,T1) transect_info = (irORcr_innerPath,nL,seg_inner,t_inner) ###Important Note: check that transect does not go through any other rings while headed to its target endpoint (Andy has note explaining this "7th case") ###If this intersection does happen... just cut off the line at the intersection point - this leads to transect not being normal to the ring it emanates from. if endBin == 0: failed_IRs_2check = self.transect0fails else: failed_IRs_2check = self.transect1fails keyfcn = lambda x: x.ORring.sort_index failed_IRs_2check = sorted(failed_IRs_2check,key=keyfcn) tr_line = transect_info[1] exclusions = [] #used to check the line from closest_pt to endpoint doesn't intersect num_passed = 0 run_again = True while run_again: run_again = False for idx,fIR in enumerate(failed_IRs_2check): num_passed +=1 if idx in exclusions: continue intersectionList = pathXpathIntersections(Path(tr_line),fIR.ring.path) if len(intersectionList) == 0: continue else: if len(intersectionList) > 1: print("Warning: Transect-FailedPath intersection check returned multiple intersections. This is possible, but should be very rare.") # (seg_tl, seg_fIR, t_tl, t_fIR) = intersectionList[0] t_fIR,seg_fIR = closestPointInPath(self.ORring.point(endBin),fIR.ring.path)[1:3] fIR_closest_pt = seg_fIR.point(t_fIR) if endBin: new_nonNormal_transect = Line(self.ring.path[-1].end,fIR_closest_pt) else: new_nonNormal_transect = Line(fIR_closest_pt,self.ring.path[0].start) transect_info = (fIR,new_nonNormal_transect,seg_fIR,t_fIR) exclusions += range(idx+1) run_again = True break return transect_info def findTransects2endpointsFromInnerPath_normal(self,irORcr_innerPath,innerPath): """Finds transects to both endpoints (not just that specified by endBin - see outdated description below) Note: This fcn will attempt to find transects for endpoints where the transects have not been found and will return (False, False, False) for those that have. Returns: (irORcr,nL,seg_irORcr,t_irORcr) where irORcr is the inner path that the transect, nL, leaves from and seg_irORcr and t_irORcr correspond to innerPath and nL points from seg_irORcr.point(t_irORcr) to the desired endpoint. Note: irORcr will differ from irORcr_innerPath in the case where irORcr_innerPath admits a transect but this transect intersects with a (less-inner) previously failed path. The less-inner path is then output.""" #Outdated Instructions #This fcn is meant to find the transect line from (and normal to) the # inner path that goes through OuterPt. It does this using the # bisection method. #INPUT: innerPath and outerPath are Path objects, center is a point # representing the core, endBin specifies which end point in outerPath # we hope to find the transect headed towards (so must be a 0 or a 1) #OUTPUT: Returns (transect_Line,inner_seg,inner_t) where normal_line # is the transverse Line object normal to innerPath intersecting # outerPath at outerPt or, if such a line does not exist, returns # (False,False,False,False) # inner_seg is the segment of innerPath that this normal transect line # begins at, s.t. seg.point(inner_t) = transect_Line.point(0) outerPath = self.ring.path center = self.ring.center tol_numberDetectionLines_transectLine_normal = 20 ##### tolerance N = tol_numberDetectionLines_transectLine_normal # if self.transect0found and not self.transect1found: # return (False,False,False,False), self.findTransect2endpointFromInnerPath_normal(innerPath) # if not self.transect0found and self.transect1found: # return self.findTransect2endpoint0FromInnerPath_normal(innerPath), (False,False,False,False) # if self.transect0found and self.transect1found: # raise Exception("Both transects already found... this is a bug.") # For a visual explanation of the following code block and the six # cases, see Andy's "Gap Analysis of Transects to Endpoints" # check if transect from innerPath.point(0) intersect with outerPath nL_from0, seg_from0, t_from0 = normalLineAtT_toInner_intersects_withOuter(0, innerPath, outerPath, center) if isApproxClosedPath(innerPath): (nL_from1,seg_from1,t_from1) = (nL_from0,seg_from0,t_from0) else: #check if transect from innerPath.point(1) intersect with outerPath nL_from1, seg_from1, t_from1 = normalLineAtT_toInner_intersects_withOuter(1, innerPath, outerPath, center) #Case: TF if nL_from0 and not nL_from1: return (False,False,False,False), self.findTransect2endpointFromInnerPath_normal(irORcr_innerPath,innerPath,(0,1),True,1) #Case: FT if (not nL_from0) and nL_from1: return self.findTransect2endpointFromInnerPath_normal(irORcr_innerPath,innerPath,(0,1),False,0), (False,False,False,False) # determine All, None, or Some (see notes in notebook on this agorithm # for explanation) max_pass_Tk = 0 min_pass_Tk = 1 max_fail_Tk = 0 min_fail_Tk = 1 somePass = False someFail = False dT = float(1)/(N-1) for k in range(1,N-1): Tk = k*dT nLk, outer_segk, outer_tk = normalLineAtT_toInner_intersects_withOuter(Tk, innerPath, outerPath, center) if nLk != False: somePass = True if Tk > max_pass_Tk: max_pass_Tk = Tk # max_pass = (nLk,outer_segk,outer_tk) if Tk < min_pass_Tk: min_pass_Tk = Tk # min_pass = (nLk,outer_segk,outer_tk) else: someFail = True if Tk > max_fail_Tk: max_fail_Tk = Tk # max_fail = (nLk,outer_segk,outer_tk) if Tk < min_fail_Tk: min_fail_Tk = Tk # min_fail = (nLk,outer_segk,outer_tk) if somePass and someFail: #Case: TT & only some pass [note: TT & some iff TT & T0>T1] if nL_from0 and nL_from1: Trange0 = (max_fail_Tk, (max_fail_Tk + dT)%1) Tpf0 = False Trange1 = ((min_fail_Tk - dT)%1, min_fail_Tk) Tpf1 = True #Case: FF & only some pass elif (not nL_from0) and (not nL_from1): Trange0 = ((min_pass_Tk - dT)%1, min_pass_Tk) Tpf0 = False Trange1 = (max_pass_Tk, (max_pass_Tk + dT)%1) Tpf1 = True for Ttestindex,T2test in enumerate(Trange0 + Trange1): #debugging only if T2test>1 or T2test < 0: print Ttestindex print T2test raise Exception() args = irORcr_innerPath, innerPath, Trange0, Tpf0, 0 tmp1 = self.findTransect2endpointFromInnerPath_normal(*args) args = irORcr_innerPath, innerPath, Trange1, Tpf1, 1 tmp2 = self.findTransect2endpointFromInnerPath_normal(*args) return tmp1, tmp2 #Cases: (TT & all) or (FF & none) [note: TT & all iff TT & T0<T1] else: return (False, False, False, False), (False, False, False, False)