예제 #1
0
def print_components_sizes(distance, points):
    """
    affichage des tailles triees de chaque composante
    """
    segments = []
    research_base = [point for point in points]
    origine = Point([0.0, 0.0])
    total = research_base.copy()
    s = 0
    enveloppe = []
    while len(research_base) > 0:
        current = research_base[0]
        research_base.pop(0)
        for point in research_base:
            if current.distance_to(point) < distance:
                s += 1
                segments.append(Segment([current, point]))
        enveloppe.append(s)
        print(enveloppe)
    tycat(origine, total, segments)
예제 #2
0
def naif(filename):
    """
    Fonction résolvant le problème de façon intuitive
    """
    coupe = 0
    intersections = []
    adjuster, segments = load_segments(filename)
    for i, seg_i in enumerate(segments):
        for seg_j in segments[i:]:
            inters = seg_i.intersection_with(seg_j)
            if inters is not None:
                inters = adjuster.hash_point(inters)
                if inters not in seg_i.endpoints or inters not in seg_j.endpoints:
                    if inters not in intersections:
                        intersections.append(inters)
                    coupe += 1
    print("le nombre d'intersections est : ", len(intersections))
    print("le nombre de coupes est :", coupe)
    tycat(segments, intersections)
    return intersections
예제 #3
0
def main():
    """
    petit exemple sur l'utilisation de tycat
    """
    print("lancez moi dans terminology")
    print("tycat permet d'afficher des points, des segments, des polygones")
    print("chaque argument doit etre un iterable sur des points \
et/ou segments et/ou polygones (ou juste un point/segment/polygone)")
    print("chaque argument est affiche d'une couleur differente")

    # un point
    origine = Point([0.0, 0.0])
    # un vecteur de points
    cercle = [Point([cos(c*pi/10), sin(c*pi/10)]) for c in range(20)]
    # un iterateur sur des segments (crees a la volee)
    segments = (
        Segment([p1, p2])
        for p1, p2 in zip(cercle, islice(cycle(cercle), 1, None))
        )
    # un carre
    carre = Polygon.square(-1, -1, 2)
    tycat(origine, cercle, segments, carre)
예제 #4
0
def main():
    """
    tycat example
    """
    points = [[Point([random(), random()]) for _ in range(5)] for _ in range(2)]
    segments = [[Segment(endpoints) for endpoints in combinations(p, r=2)] for p in points]
    print("tycat(points, segments)")
    tycat(points, segments)
    print("tycat(zip(iter(points), iter(segments)))")
    tycat(zip(iter(points), iter(segments)))
    print("tycat(*zip(iter(points), iter(segments)))")
    tycat(*zip(iter(points), iter(segments)))
    intersections = filter(None, (c[0].intersection_with(c[1]) for c in product(*segments)))
    print("intersections entre rouge et vert")
    tycat(segments[0], segments[1], intersections)
예제 #5
0
 def print_components_sizes(distance, points):
     """
     affichage des tailles triees de chaque composante
     """
     SortedX = sorted([point for point in points], key = abscisse)

     result = prochesX(SortedX, distance)
     dernier_pointX_1 = result[len(result)-1]
     dernier_indice = SortedX.index(dernier_pointX_1)

     origine = Point([0.0, 0.0])
     segment_1 = Segment([Point([dernier_pointX_1.x, 0]), Point([dernier_pointX_1.x, 1])])

     SortedY = sorted([point for point in result], key = ordonnee)
     result_bis = prochesY(SortedY, distance)
     dernier_pointXbis_1 = result_bis[len(result_bis)-1]
     dernier_indice_bis = SortedX.index(dernier_pointXbis_1)

     segment_2 = Segment([Point([0, dernier_pointXbis_1.y]), Point([1, dernier_pointXbis_1.y])])
     tycat(origine, points, (segment_1, segment_2))
     """
     affichage des tailles triees de chaque composante
     """
     segments = []
     research_base = [point for point in points]
     origine = Point([0.0, 0.0])
     total = research_base.copy()
     s = 0
     enveloppe = []
     while len(research_base) > 0:
         current = research_base[0]
         research_base.pop(0)
         for point in research_base:
             if current.distance_to(point) < distance:
                 s += 1
                 segments.append(Segment([current, point]))
         enveloppe.append(s)
     tycat(origine, total, segments)
예제 #6
0
def display(filename):
    """
    load segment file, get back connexity, get even degrees, display eulerian path.
    """
    segments = load_segments(filename)
    g = Graph(segments)
    tycat(g)
    print("{}: nous avons {} segments".format(filename, len(segments)))
    t1 = time.time()
    g.reconnect(True)
    t2 = time.time()
    tps = t2 - t1
    print("Temps reconnect hash:" + str(tps))

    t1 = time.time()
    g.even_degrees(True)
    t2 = time.time()
    tps = t2 - t1
    print("Temps degré pair hash:" + str(tps))

    g = Graph(segments)
    t1 = time.time()
    g.reconnect(False)
    t2 = time.time()
    tps = t2 - t1
    print("Temps reconnect quad:" + str(tps))

    t1 = time.time()
    g.even_degrees(False)
    t2 = time.time()
    tps = t2 - t1
    print("Temps degré pair quad:" + str(tps))
    t1 = time.time()
    g.eulerian_cycle()
    t2 = time.time()
    tps = t2 - t1
    print("Temps cycle eulérien:" + str(tps))
예제 #7
0
def bentley_ottmann(filename, nodisp=False, noinfo=False):
    """
    Fonction principale de notre projet
    """
    global COUPE
    COUPE = 0
    y_cour = None
    adjuster, segments = load_segments(filename)
    actifs = SortedList()
    evenements = [
    ]  #liste de nos evenements, valeurs des y, que lon transformera en Tas ensuite
    pt_inter = {
    }  #dictionnaire que lon retournera a la fin, associant les segments interseptés
    index = 0
    cache_inters = {}  #cache qui nous dira si on a deja compare 2 seg
    intersections = []  #liste contenant tous nos points dintersections

    for seg in segments:
        #initialisation de nos evenements
        (x_0, y_0) = seg.endpoints[0].coordinates
        (x_1, y_1) = seg.endpoints[1].coordinates
        Segment.y_cour = [x_0, y_0]
        if y_0 < y_1:  #Segments croissant suivant les y
            evenements.append([y_0, -x_0, seg, 'D'])
            evenements.append([y_1, -x_1, seg, 'F'])
        elif y_0 > y_1:  #Segments decroissant suivant les y:
            evenements.append([y_0, -x_0, seg, 'F'])
            evenements.append([y_1, -x_1, seg, 'D'])
        else:  #Cas d'un segment horizontal
            evenements.append([y_1, -min(x_0, x_1), seg, max(x_0, x_1)])

        pt_inter[seg] = []  #Initialisation du dictionnaire
        cache_inters[seg] = []

    heapify(
        evenements
    )  #Tas des evenement,3 types, 'D' 'F' 'I': Debut, fin, intersection

    #trié en fonction des y croissant, puis des x décroissants.

    def indice(seg):
        """
        Retourne l'indice de seg dans la liste actifs, None si le segment n'est
        pas présent. Cette fonction auxiliaire est implémentée suite aux
        problèmes majeurs rencontrés avec la méthode index de la classe
        SortedList
        """
        for i, elmt in enumerate(actifs):
            if seg is elmt:
                return i

    def intersection(seg, seg_2):
        """
        Fonction qui va légitimer et gérer l'intersection entre 2 segments
        donnés.
        """
        global COUPE
        if seg_2 not in cache_inters[seg]:  #On ne compare pas deux segments
            #déja comparés
            intersection = seg.intersection_with(seg_2)
            cache_inters[seg].append(seg_2)
            cache_inters[seg_2].append(seg)
            if intersection is not None:
                intersection = adjuster.hash_point(intersection)  #Ajustement
                if intersection not in seg.endpoints or intersection not in seg_2.endpoints:
                    #Le point nest pas lextrémitié des deux segments
                    pt_inter[seg].append(seg_2)
                    pt_inter[seg_2].append(seg)
                    heappush(evenements, [
                        intersection.coordinates[1],
                        -intersection.coordinates[0], seg, 'I', seg_2
                    ])
                    #L'ordre dans le tuple est important: il permet de savoir
                    #qui est à gauche ou à droite
                    if intersection not in intersections:
                        intersections.append(intersection)
                    COUPE += 1
        return

    while evenements:  #Boucle traitant tous les évènements tant que notre tas
        #n'est pas vide.
        y_cour = heappop(evenements)
        if y_cour[3] == 'D':  #evenement de debut de segment
            Segment.y_cour = [-y_cour[1], y_cour[0]]
            actifs = SortedList(actifs)  #Mise à jour de actifs
            seg = y_cour[2]
            actifs.add(seg)  #Ajout du nouveau segment aux actifs
            if len(actifs
                   ) > 1:  #Si un seul segment dans actifs: on ne fait rien
                try:
                    index = actifs.index(seg)
                except ValueError:
                    index = indice(seg)
                if index != len(actifs) - 1:
                    seg_2 = actifs[index + 1]
                    intersection(seg, seg_2)
                if index != 0:
                    seg_2 = actifs[index - 1]
                    intersection(seg_2, seg)

        elif y_cour[3] == 'F':  #evenement de fin de segment
            Segment.y_cour = [-y_cour[1], y_cour[0]]
            actifs = SortedList(actifs)  #Mise à jour de actifs
            seg = y_cour[2]
            try:
                index = actifs.index(seg)
            except ValueError:
                index = indice(seg)
            actifs.pop(index)

            actifs = SortedList(actifs)  #Mise à jour de actifs
            if len(actifs) > 1:
                if 0 < index < len(actifs):  #On n'enleve pas le seg le plus à
                    #droite/gauche
                    seg = actifs[index]
                    seg_2 = actifs[index - 1]
                    intersection(seg, seg_2)

        elif y_cour[3] == 'I':  #evenement de point d'intersection
            seg, seg_2 = y_cour[2], y_cour[4]
            try:
                actifs.remove(seg)
            except ValueError:
                index = indice(seg)
                if index is not None:  #Renvoie parfois une erreur:
                    #"segment not in actifs"
                    del actifs[index]
            try:
                actifs.remove(seg_2)
            except ValueError:
                index_2 = indice(seg_2)
                if index_2 is not None:
                    del actifs[index_2]

            Segment.y_cour = [-y_cour[1], y_cour[0] + 0.00000000001]
            #Cf. convention: A une intersection, on se situe
            #au dessus de l'intersection
            actifs = SortedList(actifs)  #Mise à jour de actifs
            actifs.add(seg)  #Une fois changés de place l'intersection passée,
            #on remet nos deux segments dans actifs
            actifs.add(seg_2)
            try:
                index = actifs.index(seg)  #Indice du seg a droite une fois
                #l'intersection faite
            except ValueError:
                index = indice(seg)

            if len(actifs
                   ) > 2:  #On teste les nouvelles intersections possibles
                if index < len(
                        actifs) - 1:  #Cas de l'extrémité droite de actifs
                    seg_2 = actifs[index + 1]
                    intersection(seg, seg_2)
                if index - 1 != 0:  #Cas de l'extrémité gauche
                    seg_2 = actifs[index - 2]
                    intersection(seg_2, y_cour[4])

        else:  #Cas dun segment horizontal
            seg_h = y_cour[2]
            for seg in actifs:
                inter = seg_h.intersection_with(seg)
                if inter:
                    inter = adjuster.hash_point(inter)
                    if inter not in seg_h.endpoints or inter not in seg.endpoints:
                        #Le point n'est pas l'extrémité ds deux segments
                        pt_inter[seg_h].append(seg)
                        pt_inter[seg].append(seg_h)
                        if inter not in intersections:
                            intersections.append(inter)
                        COUPE += 1
    if nodisp and noinfo:
        return pt_inter, intersections
    if noinfo:
        tycat(segments, intersections)
        return pt_inter, intersections
    if nodisp:
        print(
            "Le nombre d'intersections (= le nombre de points differents) est : ",
            len(intersections))
        print("Le nombre de coupes est : ", COUPE)
        return pt_inter, intersections
    print(
        "le nombre d'intersections (= le nombre de points differents) est : ",
        len(intersections))
    print("le nombre de coupes est : ", COUPE)
예제 #8
0
def test(filename):
    """
    run bentley ottmann
    """
    adjuster, segments = load_segments(filename)
    #segments = sorted(segments, key=lambda x: min(x.endpoints[0].coordinates[1],
    #                                              x.endpoints[0].coordinates[1]))
    events = SortedList()
    for s in segments:
        events.add((min(s.endpoints), "in", s))
        events.add((max(s.endpoints), "out", s))
    sweep = SweepLines()
    result = []
    if DEBUG:
        print("Events (init):", events)
        print("\n========\n  LOOP  \n========\n\n   ")
    while True:
        try:
            current, event_type, segment = events.pop(0)

            Segment.point = current

            if DEBUG:
                print("Current:", current, event_type, segment)
            if DEBUG:
                print("Events:", events)
            if DEBUG:
                print("SL:", len(sweep), sweep)

            tmp_sweep = SweepLines()
            for node in sweep:
                tmp_sweep.put(node.value)
            sweep = tmp_sweep
            if DEBUG:
                print("SL:", len(sweep), sweep)

            if event_type == "in":
                node = sweep.put(segment)
                left = node.predecessor()
                if left:
                    left = left.value
                    intrsctn = segment.intersection_with(left)
                    if intrsctn is not None:
                        intrsctn = adjuster.hash_point(intrsctn)
                        if intrsctn.coordinates[1] <= current.coordinates[
                                1] and intrsctn.coordinates[
                                    0] != current.coordinates[0]:
                            events.add((intrsctn, "x", (left, segment)))
                right = node.successor()
                if right:
                    right = right.value
                    intrsctn = segment.intersection_with(right)
                    if intrsctn is not None:
                        intrsctn = adjuster.hash_point(intrsctn)
                        if intrsctn.coordinates[1] <= current.coordinates[
                                1] and intrsctn.coordinates[
                                    0] != current.coordinates[0]:
                            events.add((intrsctn, "x", (segment, right)))

            elif event_type == "out":
                node = sweep.search(segment)
                left = node.predecessor()
                right = node.successor()
                if left and right:
                    left = left.value
                    right = right.value
                    intrsctn = left.intersection_with(right)
                    if intrsctn is not None:
                        intrsctn = adjuster.hash_point(intrsctn)
                        if intrsctn.coordinates[1] <= current.coordinates[
                                1] and intrsctn.coordinates[
                                    0] != current.coordinates[0]:
                            events.add((intrsctn, "x", (left, right)))
                sweep.delete(segment)

            else:  #event_type == "x"
                result.append(current)
                u = sweep.search(segment[0])
                right = u.successor()
                if right:
                    intrsctn = u.value.intersection_with(right.value)
                    if intrsctn is not None:
                        intrsctn = adjuster.hash_point(intrsctn)
                        if intrsctn.coordinates[1] <= current.coordinates[
                                1] and intrsctn.coordinates[
                                    0] != current.coordinates[0]:
                            events.add((intrsctn, "x", (u.value, right.value)))
                v = sweep.search(segment[1])
                left = v.predecessor()
                if left:
                    intrsctn = v.value.intersection_with(left.value)
                    if intrsctn is not None:
                        intrsctn = adjuster.hash_point(intrsctn)
                        if intrsctn.coordinates[1] <= current.coordinates[
                                1] and intrsctn.coordinates[
                                    0] != current.coordinates[0]:
                            events.add((intrsctn, "x", (left.value, v.value)))

            if DEBUG:
                print("Events:", events)
            if DEBUG:
                print("SL:", len(sweep), sweep)

            #tycat(segments, result, current)
            #input("Press [ENTER] to continue...\n")

        except IndexError:
            break

    print("\n\n=========\n THE END\n=========")
    if DEBUG:
        print("Events:", events)
        print("SL:", sweep)
        print("IL:", result)
    tycat(segments, result)
예제 #9
0
def print_polygons(polygons):
    print("we have", len(polygons), "polygons")
    tycat(*(poly.segments() for poly in polygons))
예제 #10
0
def display(filename):
    """
    load segment file, get back connexity, get even degrees, display eulerian path.
    """
    segments = load_segments(filename)
    graphe1 = Graph(segments)
    graphe2 = Graph(segments)

    tycat(graphe1)

    t1 = time.time()
    graphe1.reconnect(False)
    t2 = time.time()

    t1h = time.time()
    graphe2.reconnect(True)
    t2h = time.time()

    tycat(graphe1)
    tycat(graphe2)

    print("Temps mis pour reconnecter le graphe : ")
    print("Sans hash : {}".format(t2 - t1))
    print("Avec hash : {}".format(t2h - t1h))

    t1 = time.time()
    graphe1.even_degrees(False)
    t2 = time.time()

    t1h = time.time()
    graphe2.even_degrees(True)
    t2h = time.time()

    tycat(graphe1)
    tycat(graphe2)

    print("Temps mis par even_degrees: ")
    print("Sans hash : {}".format(t2 - t1))
    print("Avec hash : {}".format(t2h - t1h))

    t1 = time.time()
    cycle1 = graphe1.eulerian_cycle()
    t2 = time.time()

    t1h = time.time()
    cycle2 = graphe2.eulerian_cycle()
    t2h = time.time()

    tycat(cycle1)
    tycat(cycle2)

    print("Temps mis pour trouver un cycle eulérien : ")
    print("Sur graphe1 : {}".format(t2 - t1))
    print("Sur graphe2 : {}".format(t2h - t1h))

    print("Nombres de sommets : {}".format(len(graphe2.vertices.keys())))
    print("Nombres d'arêtes {}".format(len(segments)))
예제 #11
0
def test(filepath, bool_save, bool_tycat, bool_log):
    """
    - runs bentley ottmann and naive algorithm
    - prints the number of intersections and crossings within segments found with b_o
    - prints the runtime for both algorithm
    - if bool_save = True, saves the figure with all the crossings found with b_o
    - if bool_tycat = True, displays the figure with all the crossings found with b_o
    - if bool_log = True, save statistics in a log.csv file
    """

    adjuster, segments = load_segments(filepath)
    name_of_figure = re.match(r"(.*/|.*)(.+).bo", filepath).group(2)

    # Launching Bentley-Ottmann
    print("\n   Running Bentley Ottmann on {} ...\n".format(name_of_figure))
    results_bo, graph_bo = bentley_ottmann(adjuster, segments)

    # Printing some statistics
    unique_intersections = list(set().union(*results_bo.values()))
    number_of_unique_intersections = len(unique_intersections)
    number_of_crossings = sum([len(list) for list in results_bo.values()])
    if graph_bo[0][-1] >= 1199:
        runtime_bo = ">20m"
    else:
        runtime_bo = "{}m {}s".format(round(graph_bo[0][-1]//60), graph_bo[0][-1]%60)
    print("   Unique intersections          :   {}".format(number_of_unique_intersections))
    print("   Crossings within segments     :   {}".format(number_of_crossings))
    print("   Runtime for Bentley Ottmann   :   {}\n".format(runtime_bo))

    # Launching naive algorithm
    print("\n   Running naive algorithm on {} ...\n".format(name_of_figure))
    results_na, graph_na = naive(adjuster, segments)
    if graph_na[0][-1] >= 1199:
        runtime_na = ">20m"
    else:
        runtime_na = "{}m {}s".format(round(graph_na[0][-1]//60), graph_na[0][-1]%60)
    print("   Runtime for naive algorithm   :   {}\n".format(runtime_na))


    # Ploting the results to png file
    directory = "./outputs"
    if not exists(directory):
        makedirs(directory)
    plt.xlabel('Time elapsed (s)')
    plt.ylabel('Intersections processed')
    plt.title('{}.png'.format(name_of_figure))
    plt.plot(graph_bo[0], graph_bo[1], label='Bentley Ottmann')
    plt.plot(graph_na[0], graph_na[1], label='Naive algorithm')
    plt.legend()
    plt.savefig('./outputs/{}.png'.format(name_of_figure))
    plt.clf()


    # If Bentley-Ottmann didn't end before 20m, we save the results from the naive algorithm
    if runtime_bo == ">20m":
        unique_intersections = list(set().union(*results_na.values()))
        number_of_unique_intersections = len(unique_intersections)
        number_of_crossings = sum([len(list) for list in results_na.values()])


    # Printing and/or saving the figure with all the found crossings
    if bool_save:
        save_svg([segments, unique_intersections], filepath)
    if bool_tycat:
        tycat(segments, unique_intersections)


    #Saving the statistics in a csv file
    if bool_log:
        if not isfile("./log.csv"):
            with open("log.csv", "w") as file:
                file.write("File; Unique intersections;Crossings;Runtime with Bentley-Ottmann;Runtime with naive algorithm\n")
        with open("log.csv", "a") as file:
            file.write("{}; {}; {}; {}; {}\n".format(name_of_figure, number_of_unique_intersections, number_of_crossings, runtime_bo, runtime_na))
예제 #12
0
 def draw_step(self, living, current):
     """
     draw the living segments and the current_point on top of the normal draw
     """
     tycat(self.segments(), self.intersection_points(), living, current)
예제 #13
0
 def draw(self):
     """
     draws the segment and the intersection points
     """
     tycat(self.segments(), self.intersection_points())
예제 #14
0
파일: do.py 프로젝트: XAMEUS/Slic3r
def test(filename):
    """
    run bentley ottmann
    """
    adjuster, segments = load_segments(filename)
    #segments = sorted(segments, key=lambda x: min(x.endpoints[0].coordinates[1],
    #                                              x.endpoints[0].coordinates[1]))
    events = SortedList()
    for s in segments:
        events.add((min(s.endpoints), "in", s))
        events.add((max(s.endpoints), "out", s))
    sweep = SortedList()
    result = []
    if DEBUG:
        print("Events (init):", events)
        print("\n========\n  LOOP  \n========\n\n   ")
    while True:
        try:
            current, event_type, segment = events.pop(0)

            Segment.point = current

            if DEBUG:
                print("Current:", current, event_type, segment)
            if DEBUG:
                print("Events:", events)
            if DEBUG:
                print("SL:", len(sweep), sweep)

            tmp_sweep = SortedList()
            for line in sweep:
                tmp_sweep.add(line)
            sweep = tmp_sweep
            if DEBUG:
                print("SL:", len(sweep), sweep)

            if event_type == "in":
                sweep.add(segment)
                i = sweep.index(segment)
                left = i-1
                if left >= 0:
                    left = sweep[left]
                    intrsctn = segment.intersection_with(left)
                    if intrsctn is not None:
                        intrsctn = adjuster.hash_point(intrsctn)
                        if intrsctn.coordinates[1] <= current.coordinates[1] and intrsctn.coordinates[0] != current.coordinates[0]:
                            events.add((intrsctn, "x", (left, segment)))
                right = i+1
                if right < len(sweep):
                    right = sweep[right]
                    intrsctn = segment.intersection_with(right)
                    if intrsctn is not None:
                        intrsctn = adjuster.hash_point(intrsctn)
                        if intrsctn.coordinates[1] <= current.coordinates[1] and intrsctn.coordinates[0] != current.coordinates[0]:
                            events.add((intrsctn, "x", (segment, right)))

            elif event_type == "out":
                i = sweep.index(segment)
                left = i-1
                right = i+1
                if left >= 0 and right < len(sweep):
                    left = sweep[left]
                    right = sweep[right]
                    intrsctn = left.intersection_with(right)
                    if intrsctn is not None:
                        intrsctn = adjuster.hash_point(intrsctn)
                        if intrsctn.coordinates[1] <= current.coordinates[1] and intrsctn.coordinates[0] != current.coordinates[0]:
                            events.add((intrsctn, "x", (left, right)))
                sweep.remove(segment)

            else: #event_type == "x"
                result.append(current)
                u = sweep.index(segment[0])
                right = u+1
                if right < len(sweep):
                    u = sweep[u]
                    right = sweep[right]
                    intrsctn = u.intersection_with(right)
                    if intrsctn is not None:
                        intrsctn = adjuster.hash_point(intrsctn)
                        if intrsctn.coordinates[1] <= current.coordinates[1] and intrsctn.coordinates[0] != current.coordinates[0]:
                            events.add((intrsctn, "x", (u, right)))
                v = sweep.index(segment[1])
                left = v-1
                if left >= 0:
                    v = sweep[v]
                    left = sweep[left]
                    intrsctn = v.intersection_with(left)
                    if intrsctn is not None:
                        intrsctn = adjuster.hash_point(intrsctn)
                        if intrsctn.coordinates[1] <= current.coordinates[1] and intrsctn.coordinates[0] != current.coordinates[0]:
                            events.add((intrsctn, "x", (left, v)))

            if DEBUG:
                print("Events:", events)
            if DEBUG:
                print("SL:", len(sweep), sweep)

            #tycat(segments, result, current)
            #input("Press [ENTER] to continue...\n")

        except IndexError as e:
            print(e)
            break

    print("\n\n=========\n THE END\n=========")
    if DEBUG:
        print("Events:", events)
        print("SL:", sweep)
        print("IL:", result)
    tycat(segments, result)
예제 #15
0
def test(filename):
    """
    run bentley ottmann
    """
    #debug = True --> debug version, debug = False --> no debug option version
    debug = False
    #print the event_queue_list before the suppression
    debug1 = False
    #print details when the event is an intersection
    debug2 = False
    #print the event_queue in the beginning
    debug3 = False
    #print the intersections
    debug4 = False
    #print details when the event is an ending segment point
    debug5 = False
    adjuster, segments = load_segments(filename)
    tycat(segments)
    event_queue_list = Event_Queue(None, None)
    intersections = []
    for seg in segments:
        event_queue_list.add_segment(seg)
        if debug3:
            print("{}".format(seg))
            print("")
            event_queue_list.parcourir()
            print("")
            print("")
    if debug3:
        event_queue_list.parcourir()
    event_queue = event_queue_list.tete
    sweep_line = Sweep_Line(None, None)
    current_event = event_queue.point_list
    iteration = 0
    while event_queue is not None:
        if debug:
            print("je suis passé par le début")
        while current_event is not None:
            #case where event is the beginnig of a segment
            if (current_event.nature == -1):
                if debug:
                    print("the algo take the way of a first segment point")
                seg = sweep_line.insert(current_event.segment1,
                                        event_queue.value)
                seg_above = seg.next
                seg_below = seg.precedent
                seg = seg.segment
                if seg_above != None:
                    seg_above = seg_above.segment
                    intersec = seg.intersection_with(seg_above)
                    if intersec is not None:
                        if intersec == seg_above.endpoints[
                                0] or intersec == seg_above.endpoints[
                                    1] or intersec == seg.endpoints[
                                        0] or intersec == seg.endpoints[1]:
                            intersec = None
                    if intersec is not None:
                        event_queue_list.insert(intersec, 0, seg, seg_above)
                if seg_below != None:
                    seg_below = seg_below.segment
                    intersec = seg.intersection_with(seg_below)
                    if intersec is not None:
                        if intersec == seg_below.endpoints[
                                0] or intersec == seg_below.endpoints[
                                    1] or intersec == seg.endpoints[
                                        0] or intersec == seg.endpoints[1]:
                            intersec = None
                    if intersec is not None:
                        event_queue_list.insert(intersec, 0, seg_below, seg)
            #case when event is the end of a segment
            elif (current_event.nature == 1):
                if debug:
                    print("the algo take the way of an ending segment point")
                seg = sweep_line.tete
                while seg.segment != current_event.segment1:
                    seg = seg.next
                seg_above = seg.next
                seg_below = seg.precedent
                if debug5:
                    print(seg_below == None)
                    print(seg_above == None)
                seg = seg.segment
                if seg_below is None and seg_above is None:
                    sweep_line.tete = None
                    sweep_line.queue = None
                elif seg_below is None:
                    seg_above.precedent = None
                    sweep_line.tete = seg_above
                elif seg_above is None:
                    seg_below.next = None
                    sweep_line.queue = seg_below
                else:
                    seg_below.next = seg_above
                    seg_above.precedent = seg_below
                    seg_below = seg_below.segment
                    seg_above = seg_above.segment
                    intersec = seg_below.intersection_with(seg_above)
                    if intersec is not None:
                        if intersec == seg_below.endpoints[
                                0] or intersec == seg_below.endpoints[
                                    1] or intersec == seg_above.endpoints[
                                        0] or intersec == seg_above.endpoints[
                                            1]:
                            intersec = None
                    if intersec is not None:
                        if not event_queue_list.possess(intersec):
                            event_queue_list.insert(intersec, 0, seg_below,
                                                    seg_above)
            #case when event is an intersection
            else:
                if debug:
                    print("the algo take the way of an intersection point")
                intersections.append(
                    Point([event_queue.value, current_event.ordinate]))
                if debug2:
                    print(current_event.ordinate)
                    print(current_event.segment1)
                    print(current_event.segment2)
                seg_above = sweep_line.tete
                while seg_above.segment != current_event.segment2:
                    if debug2:
                        print(seg_above.segment)
                    seg_above = seg_above.next
                    if seg_above is None:
                        break
                seg_below = sweep_line.tete
                if debug2:
                    print(seg_below.segment)
                while seg_below.segment != current_event.segment1:
                    if debug2:
                        print(seg_below.segment)
                    seg_below = seg_below.next
                    if seg_below is None:
                        break
                if seg_below is None:
                    if debug2:
                        print("seg_below is None")
                elif seg_above is None:
                    if debug2:
                        print("seg_above is None")
                else:
                    if debug2:
                        print(seg_below.segment)
                        print(seg_above.segment)
                    seg_below.segment, seg_above.segment = seg_above.segment, seg_below.segment
                    seg_above2 = seg_above.next
                    seg_below2 = seg_below.precedent
                    if debug2:
                        print(seg_below.segment)
                        print(seg_above.segment)
                        if seg_below2 is not None:
                            print(seg_below2.segment)
                        else:
                            print("SEG_BELOW2 IS NONE")
                        if seg_above2 is not None:
                            print(seg_above2.segment)
                        else:
                            print("SEG_ABOVE2 IS NONE")
                    if seg_above2 is not None:
                        intersec = seg_above.segment.intersection_with(
                            seg_above2.segment)
                        if intersec is not None:
                            if intersec == seg_above.segment.endpoints[
                                    0] or intersec == seg_above.segment.endpoints[
                                        1] or intersec == seg_above2.segment.endpoints[
                                            0] or intersec == seg_above2.segment.endpoints[
                                                1]:
                                intersec = None
                        if intersec is not None:
                            if not event_queue_list.possess(intersec):
                                event_queue_list.insert(
                                    intersec, 0, seg_above.segment,
                                    seg_above2.segment)
                    if seg_below2 is not None:
                        intersec = seg_below.segment.intersection_with(
                            seg_below2.segment)
                        if intersec is not None:
                            if intersec == seg_below.segment.endpoints[
                                    0] or intersec == seg_below.segment.endpoints[
                                        1] or intersec == seg_below2.segment.endpoints[
                                            0] or intersec == seg_below2.segment.endpoints[
                                                1]:
                                intersec = None
                        if intersec is not None:
                            if not event_queue_list.possess(intersec):
                                event_queue_list.insert(
                                    intersec, 0, seg_below2.segment,
                                    seg_below.segment)
            #exit the current point_list
            if debug1:
                print("BEFORE THE SUPPRESSION")
                print(event_queue.value)
                event_queue_list.parcourir()
            if (current_event.next is None) and (current_event.precedent is
                                                 None):
                event_queue.point_list = None
                event_queue = event_queue.next
                if event_queue is not None:
                    current_event = event_queue.point_list
                else:
                    current_event = None
            elif current_event.next is None:
                current_event.precedent.next = None
                current_event = current_event.precedent
            elif current_event.precedent is None:
                current_event.next.precedent = None
                current_event = current_event.next
                event_queue.point_list = current_event
            else:
                current_event.precedent.next = current_event.next
                current_event.next.precedent = current_event.precedent
                current_event = current_event.next
            iteration += 1
            if debug:
                #some prints allows the text color to change in the terminal, it's easier to debug
                #print ('\033[1;32m\033[1;m')
                print("IT IS ITERATION NUMBER '{}'".format(iteration))
                #print ('\033[1;37m\033[1;m')
                #print ('\033[1;35m\033[1;m')
                event_queue_list.parcourir()
                #print ('\033[1;37m\033[1;m')
                sweep_line.parcourir()
                print("")
            if debug4:
                parcourir_liste(intersections)
                print("")
    if debug:
        print(iteration)
    tycat(segments, intersections)
    print(
        'le nombre d intersections (= le nombre de points differents) est "{}"'
        .format(len(intersections)))
예제 #16
0
def print_components_sizes(distance, points):
    origine = Point([0.0, 0.0])

    SortedX = sorted([point for point in points], key = abscisse)
    print("nombre de point est :", len(SortedX))
    # print(SortedX)
    result = prochesX(SortedX, distance)

    print("nombre de points dans result est :", len(result))

    n = len(result)
    dernier_pointX_1 = result[-1]

    segment_1 = Segment([Point([dernier_pointX_1.x, 0]), Point([dernier_pointX_1.x, 1])])

    result_droite = SortedX[n:]
    result_gauche = SortedX[:n]

    print(len(result_gauche), len(result_droite))

    SortedY = sorted([point for point in result_gauche], key = ordonnee)
    result_bis = prochesY(SortedY, distance)
    n_bis = len(result_bis)
    print(n_bis)
    print(result_bis)
    dernierbis = result_bis[-1]

    # segment_2 = Segment([Point([0, dernierbis.y]), Point([dernier_pointX_1.x, dernierbis.y])])

    result_bas = result_gauche[n_bis:]
    result_haut = result_gauche[:n_bis]

    print(len(result_haut), len(result_bas))
    #
    dernier_pointXbis_1 = result_bis[-1]
    #
    dernier_indice_bis = result_gauche.index(dernier_pointXbis_1)
    #
    result_haut = result_gauche[dernier_indice_bis + 1:]
    result_bas = result_gauche[:dernier_indice_bis + 1]
    #
    segment_2 = Segment([Point([0, dernier_pointXbis_1.y]), Point([dernier_pointX_1.x, dernier_pointXbis_1.y])])
    #
    # print("*********************************")
    # print(result_haut)
    # print("*********************************")
    # print(result_bas)
    # tycat(origine, points, segment_1)
    tycat(origine, points, (segment_1, segment_2))


    """
    affichage des tailles triees de chaque composante
    """
    segments = []
    research_base = [point for point in points]
    origine = Point([0.0, 0.0])
    total = research_base.copy()
    s = 0
    while len(research_base) > 0:
        current = research_base[0]
        research_base.pop(0)
        for point in research_base:
            if current.distance_to(point) < distance:
                s += 1
                segments.append(Segment([current, point]))


    tycat(origine, total, segments)