def ellipses(sizes, correlations, mean, variance):
    correlation = Correlation()
    for size in sizes:
        for rho in correlations:
            x, y = correlation.multivariate_normal(mean, variance, rho, size)
            ellipse = Ellipse(x, y, size, rho)
            ellipse.plot()
Exemple #2
0
 def update(self):
     if len(self.cells) > 0:
         self.ellipse = Ellipse(self.cells,
                                min_ellipse_axis=self.min_ellipse_axis)
         for dim in range(0, 2):
             self.box[0][dim] = numpy.min([c[dim] for c in self.cells])
             self.box[1][dim] = numpy.max([c[dim] for c in self.cells])
def equiprobability_ellipse(capacities):
    for capacity in capacities:
        _, sp = plt.subplots(1, 3, figsize=(16, 6))
        for cor_cov, subplot in zip([0, 0.5, 0.9], sp):
            sample = stats.multivariate_normal.rvs([0, 0], [[1, cor_cov], [cor_cov, 1]], capacity)

            x = sample[:, 0]
            y = sample[:, 1]

            ellipse = EllipseClass(0, 0,
                              1, 1, cor_cov)

            subplot.scatter(x, y)

            x = np.linspace(min(x) - 2, max(x) + 2, 100)
            y = np.linspace(min(y) - 2, max(y) + 2, 100)
            x, y = np.meshgrid(x, y)
            z = ellipse.z(x, y)
            t = ellipse.rad2(sample)
            subplot.contour(x, y, z, [ellipse.rad2(sample)])

            title = f"n = {capacity} rho = {cor_cov}"

            subplot.set_title(title)
            subplot.set_xlabel("X")
            subplot.set_ylabel("Y")

        plt.savefig(f"{capacity}" + f".png")
Exemple #4
0
def extract_ellipses(contours, extract_garbage=True):
    ellipses = []
    garbage = []
    other_contours = []
    for c in contours:
        if extract_garbage and Ellipse.is_strong_garbage(c):
            garbage.append(c)
        elif Ellipse.is_strong_ellipse(c):
            ellipses.append(c)
        else:
            other_contours.append(c)

    return ellipses, other_contours, garbage
Exemple #5
0
    def update_ellipse(self):
        self._ellipse = Ellipse(self._init_position, self._final_position,
                                self._arrival.get_cost() / 2)
        self._ellipse_cost_limit = self._arrival.get_cost()

        self._outside_nodes = self._outside_nodes + list(
            filter(
                lambda node: False == self._ellipse.is_point_in(
                    node.get_position()), self._nodes))
        for node in self._outside_nodes:
            node.set_outside_state(True)
        self._nodes = list(
            filter(lambda node: self._ellipse.is_point_in(node.get_position()),
                   self._nodes))
Exemple #6
0
def ellipseplot(theta,pts):
    ### Trace les ellipses de corrélation des paramètres pour les param cosmo theta
    covarmat = constraints(theta,pts)[1]
    fig,axes = plt.subplots(figsize=(15,15),ncols=len(theta)-1,nrows=len(theta)-1,sharex='col', sharey='row')
    for i in range(len(theta)-1):
        for j in range(len(theta)-1):
            if i<j:
                axes[i,j].axis('off')
            else:
                a2=(covarmat[i+1,i+1]+covarmat[j,j])/2 + np.sqrt((covarmat[i+1,i+1]-covarmat[j,j])**2/4 + covarmat[i+1,j]**2)
                b2=(covarmat[i+1,i+1]+covarmat[j,j])/2 - np.sqrt((covarmat[i+1,i+1]-covarmat[j,j])**2/4 + covarmat[i+1,j]**2)
                a = 1.52*np.sqrt(a2)
                b = 1.52*np.sqrt(b2)
                #print(a)
                #print(b)
                tan2T=2*covarmat[i+1,j]/(covarmat[j,j]-covarmat[i+1,i+1])
                T=0.5*np.arctan(tan2T)
                #print(T*180/np.pi)
                ellipse = Ellipse((theta[j],theta[i+1]),a,b,T)
                axes[i,j].plot(ellipse[0],ellipse[1],color='darkred', lw=2)
                if j==0:
                    axes[i,j].set_ylabel(name_param[i+1])
                if i==4:
                    axes[i,j].set_xlabel(name_param[j])
                if j!=0:
                    axes[i,j].set_yticklabels([])
                if i!=4:
                    axes[i,j].set_xticklabels([])
    fig.savefig('Figures/error_figs_tau/cov_plot.png',dpi=300)
Exemple #7
0
 def __init__(self, imageId, major_axis, minor_axis, speed, rot_speed, size, textureMoon=None, moonOrbitParams=None):
     self.texture = Texture(imageId)
     self.qobj = gluNewQuadric()
     gluQuadricTexture(self.qobj, GL_TRUE)
     self.ellipse = Ellipse(major_axis, minor_axis, speed)
     self.rotation = 0
     self.lastCoords = 0
     self.rot_speed = rot_speed
     self.size = size
     if(textureMoon is None):
         self.moon = False
     else:
         self.moon = True
         self.textureMoon = Texture(textureMoon)
         self.moonSize = moonOrbitParams[2]
         self.moonOrbit = Ellipse(moonOrbitParams[0], moonOrbitParams[0], moonOrbitParams[1])
Exemple #8
0
def curve():
    # Get current and desired points for ellipse generation
    cur_point = gps.getValues()
    point_to = gps.getValues()
    point_to[0] -= curve_sep
    # Make ellipse from points
    ellipse = Ellipse(cur_point, point_to)
    to_travel = ellipse.ellipse_points

    # Take x,z coord pairs and have robot drive to each one
    for x, z in to_travel:
        # Finding correct angle to drive on
        cur_point = gps.getValues()
        # Calculate the distance between current location and (x,z)
        dist = math.sqrt((cur_point[0] - x)**2 + (cur_point[2] - z)**2)
        # Calculate the abs(x_diff) between current location and (x,z)
        x_diff = abs(cur_point[0] - x)

        # Calculate angle from x axis for proper travel (radians)
        theta = math.acos(x_diff / dist)
        # Convert to degrees
        theta = theta * (180 / math.pi)
        # Adjust theta based on which moving up or down
        if z < cur_point[2]:
            theta += 90
        else:
            theta = 90 - theta
        # Adjust to new angle
        adjust_to_angle_degrees(theta)

        # Drive to point
        drive_to_point_ellipse([x, 0, z])

    # Reset to line for next curve or final step
    adjust_to_angle_degrees(90)
Exemple #9
0
    def __init__(self, x, y, mode, fileName, scene, parent=None):
        super(AddItemCommand, self).__init__(parent)

        from designerscene import DesignerScene
        from rectangle import Rectangle
        from ellipse import Ellipse
        from text import Text
        from bitmap import Bitmap
        from vectorgraphic import Vectorgraphic
        self.scene = scene
        self.item = None

        if mode == DesignerScene.RECTANGLE:
            self.item = Rectangle(self.scene)
            self.item.setId("Rectangle")
            self.item.setPen(QPen(Qt.black))
            self.item.setBrush(QBrush(Qt.blue))
            self.item.setFlag(QGraphicsItem.ItemIsMovable, True)
            self.item.setFlag(QGraphicsItem.ItemIsSelectable, True)
            self.item.setPos(x, y)
            self.item.setWidth(50)
            self.item.setHeight(50)
            self.setText("Add Rectangle")

        elif mode == DesignerScene.ELLIPSE:
            self.item = Ellipse(self.scene)
            self.item.setId("Ellipse")
            self.item.setPen(QPen(Qt.black))
            self.item.setBrush(QBrush(Qt.blue))
            self.item.setFlag(QGraphicsItem.ItemIsMovable, True)
            self.item.setFlag(QGraphicsItem.ItemIsSelectable, True)
            self.item.setPos(x, y)
            self.item.setWidth(50)
            self.item.setHeight(50)
            self.setText("Add Ellipse")

        elif mode == DesignerScene.TEXT:
            self.item = Text("Lorem ipsum dolor", self.scene)
            self.item.setId("Text")
            self.item.setFlag(QGraphicsItem.ItemIsMovable, True)
            self.item.setFlag(QGraphicsItem.ItemIsSelectable, True)
            self.item.setPos(x, y)
            self.setText("Add Text")

        elif mode == DesignerScene.BITMAP:
            self.item = Bitmap(fileName, self.scene)
            self.item.setId("Bitmap")
            self.item.setFlag(QGraphicsItem.ItemIsMovable, True)
            self.item.setFlag(QGraphicsItem.ItemIsSelectable, True)
            self.item.setPos(x, y)
            self.setText("Add Bitmap")

        elif mode == DesignerScene.SVG:
            self.item = Vectorgraphic(fileName, self.scene)
            self.item.setId("Vectorgraphic")
            self.item.setFlag(QGraphicsItem.ItemIsMovable, True)
            self.item.setFlag(QGraphicsItem.ItemIsSelectable, True)
            self.item.setPos(x, y)
            self.setText("Add Vectorgraphic")
Exemple #10
0
    def __init__(self, start, goal, search_range, domain, collision_manager,
                 controller, informed, kinodynamic, initial_state, max_iters,
                 seed):
        self.start = start
        self.goal = goal
        self.graph = Graph(start, goal, state0=initial_state)
        self.x_domain, self.y_domain, self.z_domain = domain
        self.search_range = search_range
        self.collision_manager = collision_manager
        self.controller = controller
        self.informed = informed
        self.kinodynamic = kinodynamic
        self.max_iters = max_iters

        self.ellipse = Ellipse(start, goal, domain=domain)

        np.random.seed(seed)
Exemple #11
0
 def AddShape(self, e: wx.MouseEvent):
     if self.FindWindow("Shape").Value == "Line":
         self.shapes.append(Line(self.CurrentPen, e.x, e.y))
     elif self.FindWindow("Shape").Value == "Rectangle":
         self.shapes.append(Rectangle(self.CurrentPen, e.x, e.y))
     elif self.FindWindow("Shape").Value == "Ellipse":
         self.shapes.append(Ellipse(self.CurrentPen, e.x, e.y))
     elif self.FindWindow("Shape").Value == "Circle":
         self.shapes.append(Circle(self.CurrentPen, e.x, e.y))
Exemple #12
0
 def __extract_strong_ellipses(contours):
     strong = []
     not_ellipses = []
     for c in contours:
         if Ellipse.is_strong_ellipse(c):
             strong.append(c)
         else:
             not_ellipses.append(c)
     return strong, not_ellipses
Exemple #13
0
    def __init__(self, detail_return):
        # Filters parameters
        self.whitening = 0.2
        self.size_filter_gaussian = (9, 9)
        self.type_gaussian = 0
        self.size_median = 3
        self.thresh_threshold = 25
        self.maxvalue_threshold = 255
        self.kernel_size_morphology = ((5, 5), (7, 7), (10, 10), (12, 12),
                                       (15, 15), (17, 17))
        self.color_circle = (255, 255, 0)
        self.thickness_circle = 3
        self.position_text = (120, 30)
        self.font_text = cv2.FONT_HERSHEY_DUPLEX
        self.font_scale = 0.2
        self.min_area = 50000

        self.ellipse = Ellipse()
        self.noise = Noise(self.min_area)
Exemple #14
0
def plot_subplanck(theta,pts):
    constr = constraints(theta,pts)
    std_l= constr[0]
    fig = plt.figure(figsize=(15,7.5))
    for i in range(len(theta)):
        ax = fig.add_subplot(231+i)
        ax.grid(True,linestyle='dotted')
        stds = std_l[i]
        textstr = r'$\frac{\sigma_p}{\sigma_F} =$ '+str(round(planck_values[i]/stds,3))
        props = dict(boxstyle='round',facecolor='white')
        ax.text(0.05,0.95,textstr,transform=ax.transAxes,verticalalignment='top',bbox=props)
        abs = np.linspace(theta[i]-4*planck_values[i],theta[i]+4*planck_values[i],500)
        ord = gaussian(abs,theta[i],stds)
        ord2 = gaussian(abs,theta[i],planck_values[i])
        ax.plot(abs,ord/np.max(ord),color='darkred',label ="Fischer")
        ax.plot(abs,ord2/np.max(ord2),color='darkblue',label="Planck")
        ax.set_xlabel(name_param[i])
    handles, labels = ax.get_legend_handles_labels()
    fig.legend(handles, labels, loc='upper right')
    fig.suptitle(r'$L_{max}$ = '+str(pts))
    if not(os.path.isdir('Figures/error_figs_tau')):
        os.mkdir('Figures/error_figs_tau/')
    fig.savefig('Figures/error_figs_tau/error_plot.png',dpi=300)
    covarmat = constr[1]
    fig,axes = plt.subplots(figsize=(15,15),ncols=len(theta)-1,nrows=len(theta)-1)
    for i in range(len(theta)-1):
        for j in range(len(theta)-1):
            if i<j:
                axes[i,j].axis('off')
            else:
                a2=(covarmat[i+1,i+1]+covarmat[j,j])/2 + np.sqrt((covarmat[i+1,i+1]-covarmat[j,j])**2/4 + covarmat[i+1,j]**2)
                b2=(covarmat[i+1,i+1]+covarmat[j,j])/2 - np.sqrt((covarmat[i+1,i+1]-covarmat[j,j])**2/4 + covarmat[i+1,j]**2)
                a = 1.52*np.sqrt(a2)
                b = 1.52*np.sqrt(b2)
                #print(a)
                #print(b)
                tan2T=2*covarmat[i+1,j]/(covarmat[j,j]-covarmat[i+1,i+1])
                T=0.5*np.arctan(tan2T)
                #print(T*180/np.pi)
                ellipse = Ellipse((theta[j],theta[i+1]),a,b,T)
                axes[i,j].plot(ellipse[0],ellipse[1],color='darkred', lw=2)
                if j==0:
                    axes[i,j].set_ylabel(name_param[i+1])
                if i==4:
                    axes[i,j].set_xlabel(name_param[j])
                if j!=0:
                    axes[i,j].set_yticklabels([])
                if i!=4:
                    axes[i,j].set_xticklabels([])
    fig.savefig('Figures/error_figs_tau/cov_plot.png',dpi=300)


    return(constr)
Exemple #15
0
def copy_shape(shape):

    """Create and return a deep copy of the passed shape"""

    if type(shape) == Circle:

        return Circle(shape.center, shape.radius)

    if type(shape) == Ellipse:

        return Ellipse(shape.center, shape.half_width, shape.half_height, shape.polygon)

    return copy.deepcopy(shape)
Exemple #16
0
    def drawEllipse(self, qp):
        pen = QPen(Qt.black, 2, Qt.SolidLine)
        qp.setPen(pen)
        size = self.size()

        if self.position is not None:
            self.points = Ellipse(self.position, size)
            if self.index < len(self.points):
                self.outPoints.append(self.points[self.index])
                self.index += 1
            # 用index调控每一次要输出的数目
        for outPoint in self.outPoints:
            qp.drawPoint(outPoint[0], outPoint[1])
class Asteroid:
    def __init__(self, fire):
        self.asteroid = OBJ("asteroid.obj", textureFile="asteroid.jpg")
        self.ellipse = Ellipse(18, 4, 0.17)
        self.fire = fire
        self.angle = 0

    def draw(self):
        coords = self.ellipse.getCoords()
        glPushMatrix()
        glTranslatef(13.0, 0.0, 8.0)
        glRotatef(35, 0.0, 1.0, 0.0)
        self.ellipse.render()
        glTranslatef(coords[0], 0, coords[1] - 0.35)
        glPushMatrix()
        glScalef(0.0006, 0.0006, 0.0006)
        self.asteroid.render()
        glPopMatrix()
        glRotatef(90, 0, 0, 1)
        glRotatef(90 * math.sin(math.radians(self.angle)), 1.0, 0.0, 0.0)
        self.fire.drawSystem()
        glPopMatrix()
        self.angle += 0.17
Exemple #18
0
    def update(self):
        """
        performs update of all single shape until convergence or termination 
        picks shape that minimises loss
        """
        #init centroid
        centroid = self.pick_centroid()
        if (centroid == None):
            return
        #pick shape and init and init at centroid
        shapes = [
            Rectangle([centroid, 1, 1, 0]),
            Ellipse([centroid, 3, 3]),
            Triangle([
                centroid, (centroid[0] + 2, centroid[1]),
                ((centroid[0] + 1, centroid[1] + 2))
            ])
        ]

        shapes_losses = []
        old_loss = self.current_loss()
        for shape in shapes:
            current_loss = self.current_loss()
            for i in range(0, N_ITERATIONS):
                old_shape = copy.deepcopy(shape)

                shape.update_params()
                self.shapes.append(shape)
                new_loss = self.current_loss()

                if (new_loss > current_loss):
                    shape = copy.deepcopy(old_shape)
                else:
                    current_loss = new_loss
                del self.shapes[-1]
            shapes_losses.append((shape, current_loss))
        min_shape_idx = np.argmin([x[1] for x in shapes_losses])
        min_loss = shapes_losses[min_shape_idx][1]
        print(min_loss)
        if ((min_loss >= old_loss) and (len(self.shapes) > 0)):
            return
        else:
            self.shapes.append(shapes_losses[min_shape_idx][0])
Exemple #19
0
class Planet:
    def __init__(self, imageId, major_axis, minor_axis, speed, rot_speed, size, textureMoon=None, moonOrbitParams=None):
        self.texture = Texture(imageId)
        self.qobj = gluNewQuadric()
        gluQuadricTexture(self.qobj, GL_TRUE)
        self.ellipse = Ellipse(major_axis, minor_axis, speed)
        self.rotation = 0
        self.lastCoords = 0
        self.rot_speed = rot_speed
        self.size = size
        if(textureMoon is None):
            self.moon = False
        else:
            self.moon = True
            self.textureMoon = Texture(textureMoon)
            self.moonSize = moonOrbitParams[2]
            self.moonOrbit = Ellipse(moonOrbitParams[0], moonOrbitParams[0], moonOrbitParams[1])

    def draw(self):
        coords = self.ellipse.getCoords()
        glPushMatrix()
        glTranslatef(coords[0], 0.0, coords[1])
        self.lastCoords = coords
        if(self.moon):
            glPushMatrix()
            self.moonOrbit.render()
            coords = self.moonOrbit.getCoords()
            glTranslatef(coords[0], 0.0, coords[1])
            glScalef(self.moonSize, self.moonSize, self.moonSize)
            glBindTexture(GL_TEXTURE_2D, self.textureMoon.textureId)
            gluSphere(self.qobj, 1, 50, 50)
            glPopMatrix()
        glRotatef(270, 1.0, 0.0, 0.0)
        glRotatef(self.rotation, 0.0, 0.0, 1.0)
        glScalef(self.size, self.size, self.size)
        glBindTexture(GL_TEXTURE_2D, self.texture.textureId)
        gluSphere(self.qobj, 1, 50, 50)
        glPopMatrix()
        self.ellipse.render()
        self.rotation += self.rot_speed
Exemple #20
0
class Filters:
    def __init__(self, detail_return):
        # Filters parameters
        self.whitening = 0.2
        self.size_filter_gaussian = (9, 9)
        self.type_gaussian = 0
        self.size_median = 3
        self.thresh_threshold = 25
        self.maxvalue_threshold = 255
        self.kernel_size_morphology = ((5, 5), (7, 7), (10, 10), (12, 12),
                                       (15, 15), (17, 17))
        self.color_circle = (255, 255, 0)
        self.thickness_circle = 3
        self.position_text = (120, 30)
        self.font_text = cv2.FONT_HERSHEY_DUPLEX
        self.font_scale = 0.2
        self.min_area = 50000

        self.ellipse = Ellipse()
        self.noise = Noise(self.min_area)

    def pupil_analysis(self, frame, nember_frame):
        if frame is None:
            raise Exception("Frame is none!")

        original = np.copy(frame[:, :, 0])

        yuv = cv2.cvtColor(frame, cv2.COLOR_BGR2YUV)
        yuv[:, :, 0] = cv2.equalizeHist(yuv[:, :, 0])
        bgr = cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR)

        gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)
        gaussian = cv2.GaussianBlur(gray, self.size_filter_gaussian,
                                    self.type_gaussian)
        median = cv2.medianBlur(gaussian, self.size_median)

        final = np.copy(gray)
        for size in self.kernel_size_morphology:
            kernel = np.ones(size, np.uint8)
            erode = cv2.erode(median, kernel=kernel, iterations=1)
            dilate = cv2.dilate(erode, kernel=kernel, iterations=1)
            threshold = cv2.threshold(dilate, self.thresh_threshold,
                                      self.maxvalue_threshold,
                                      cv2.THRESH_BINARY)[1]

            contours, _ = cv2.findContours(threshold, cv2.RETR_TREE,
                                           cv2.CHAIN_APPROX_SIMPLE)
            contours = sorted(contours,
                              key=lambda x: cv2.contourArea(x),
                              reverse=True)

            center, radius = self.ellipse.search_ellipse(image=threshold,
                                                         contours=contours)
            if center is not None and radius > 0:
                cv2.circle(final, center, radius, self.color_circle,
                           self.thickness_circle)
                break

        images = {
            'gray': gray,
            'gaussian': gaussian,
            'median': median,
            'erode': erode,
            'dilate': dilate
        }
        return center, radius, images

    def write_radius(self, frame, radius):
        cv2.putText(frame, "radius: %d" % radius, self.position_text,
                    self.font_text, 1, self.color_circle)
        return frame

    @staticmethod
    def resize(figure):
        return cv2.resize(figure, (0, 0), fx=0.5, fy=0.5)
Exemple #21
0
 def __str__(self):
     return ('%s: (%d, %d), area=%.2f, r=%d' % (self.name, self.centre_x, self.centre_y,Ellipse.area(self), self.radius_x))
Exemple #22
0
 def __init__(self, centre_x, centre_y, radius,name = 'Circle'):
     Ellipse.__init__(self, centre_x, centre_y,radius, radius, name)
Exemple #23
0
def testInsideEllipse():
    rect0 = {(2, 2), (3, 2), (6, 2), (7, 2), (8, 2), (2, 3), (3, 3), (6, 3),
             (7, 3), (8, 3), (2, 4), (3, 4), (6, 4), (7, 4), (8, 4), (2, 5),
             (3, 5), (4, 5), (5, 5), (6, 5), (7, 5), (8, 5)}
    rect1 = {(3, 2), (3, 3), (2, 4), (3, 4), (4, 5), (3, 5), (4, 6), (3, 6)}
    rect2 = {(2, 4), (3, 4), (4, 5), (3, 5), (4, 6), (3, 6), (4, 7)}
    rect3 = {(4, 3), (4, 4), (5, 3), (5, 4)}
    c0 = Cluster(rect0)
    c1 = Cluster(rect1)
    c2 = Cluster(rect2)
    c3 = Cluster(rect3)
    ell0 = Ellipse(c0.cells, min_ellipse_axis=6)
    ell1 = Ellipse(c1.cells, min_ellipse_axis=6)
    ell2 = Ellipse(c2.cells, min_ellipse_axis=6)
    ell3 = Ellipse(c3.cells, min_ellipse_axis=6)
    if ell1.isEllipseInsideOf(ell0, 1.0):
        print 'ell1 is inside of ell0'
    if ell2.isEllipseInsideOf(ell1, 0.8):
        print 'ell2 is inside of ell1'
    if ell3.isEllipseInsideOf(ell0, 0.8):
        print 'ell3 is inside of ell0'
    if ell0.isEllipseInsideOf(ell3, 0.8):
        print 'ell0 is inside of ell3'
Exemple #24
0
def testAngle():
    rect0 = {(2, 3), (3, 3), (4, 3), (5, 3), (6, 3), (7, 3), (8, 3), (2, 4),
             (3, 4), (4, 4), (5, 4), (6, 4), (7, 4), (8, 4), (2, 5), (3, 5),
             (4, 5), (5, 5), (6, 5), (7, 5), (8, 5), (2, 6), (3, 6), (4, 6),
             (5, 6), (6, 6), (7, 6), (8, 6)}
    rect1 = {(2, 3), (3, 3), (2, 4), (3, 4), (2, 5), (3, 5), (2, 6), (3, 6)}
    rect2 = {(4, 6), (4, 7), (2, 4), (3, 4), (2, 5), (3, 5), (2, 6), (3, 6)}
    rect3 = {(2, 2), (2, 3), (3, 2), (3, 3), (3, 4), (4, 3), (4, 4)}
    rect4 = {(2, 2), (2, 3), (2, 4), (1, 4)}
    c0 = Cluster(rect0)
    c1 = Cluster(rect1)
    c2 = Cluster(rect2)
    c3 = Cluster(rect3)
    c4 = Cluster(rect4)
    ell0 = Ellipse(c0.cells, min_ellipse_axis=1)
    print 'c0', ell0.centre, ell0.a, ell0.b, ell0.angle
    ell0.show()
    ell1 = Ellipse(c1.cells, min_ellipse_axis=1)
    print 'c1', ell1.centre, ell1.a, ell1.b, ell1.angle
    ell1.show()
    ell2 = Ellipse(c2.cells, min_ellipse_axis=1)
    print 'c2', ell2.centre, ell2.a, ell2.b, ell2.angle
    ell2.show()
    ell3 = Ellipse(c3.cells, min_ellipse_axis=1)
    print 'c3', ell3.centre, ell3.a, ell3.b, ell3.angle
    ell3.show()
    ell4 = Ellipse(c4.cells, min_ellipse_axis=1)
    print 'c4', ell4.centre, ell4.a, ell4.b, ell4.angle
    ell4.show()
def create_knapsack_packing_problems_with_manual_solutions(can_print=False):

    """Create a set of Knapsack-Packing problem instances that are solved (optimally) with manual placements (using actions available for all the algorithms); both the problems and solutions are returned"""

    problems, solutions = list(), list()

    start_time = time.time()

    # Problem 1

    max_weight = 120.
    container_shape = Circle((3.3, 3.3), 3.3)
    container = Container(max_weight, container_shape)
    items = [Item(Polygon([(0, 0), (0, 4.5), (4.5, 4.5), (4.5, 0)]), 40., 50.),
             Item(Circle((0, 0), 0.45), 20., 5.),
             Item(Circle((0, 0), 0.45), 20., 10.),
             Item(Circle((0, 0), 0.45), 20., 15.),
             Item(Circle((0, 0), 0.45), 20., 20.)]
    problem = Problem(container, items)
    problems.append(problem)

    solution = Solution(problem)
    solutions.append(solution)

    print_if_allowed(solution.add_item(0, (3.3, 3.3), 0.), can_print)
    print_if_allowed(solution.add_item(1, (3.3, 6.05), 0.), can_print)
    print_if_allowed(solution.add_item(2, (3.3, 0.55), 0.), can_print)
    print_if_allowed(solution.add_item(3, (6.05, 3.3), 0.), can_print)
    print_if_allowed(solution.add_item(4, (0.55, 3.3), 0.), can_print)

    # Problem 2

    max_weight = 100.
    container_shape = Point(5, 5).buffer(5, 4)
    container = Container(max_weight, container_shape)
    items = [Item(MultiPolygon([(Point(5, 5).buffer(4.7, 4).exterior.coords,
                                 [tuple(Point(5, 5).buffer(4, 4).exterior.coords)])]), 10., 25.),
             Item(MultiPolygon([(Point(5, 5).buffer(3.7, 4).exterior.coords,
                                 [tuple(Point(5, 5).buffer(3, 4).exterior.coords)])]), 10., 15.),
             Item(MultiPolygon([(Point(5, 5).buffer(2.7, 4).exterior.coords,
                                 [tuple(Point(5, 5).buffer(2, 4).exterior.coords)])]), 10., 20.),
             Item(MultiPolygon([(Point(5, 5).buffer(1.7, 4).exterior.coords,
                                 [tuple(Point(5, 5).buffer(1, 4).exterior.coords)])]), 20., 20.),
             Item(Circle((0., 0.), 0.7), 20., 10)]
    problem = Problem(container, items)
    problems.append(problem)

    solution = Solution(problem)
    solutions.append(solution)

    print_if_allowed(solution.add_item(0, (5., 5.), 0.), can_print)
    print_if_allowed(solution.add_item(1, (5., 5.), 0.), can_print)
    print_if_allowed(solution.add_item(2, (5., 5.), 0.), can_print)
    print_if_allowed(solution.add_item(3, (5., 5.), 0.), can_print)
    print_if_allowed(solution.add_item(4, (5., 5.), 0.), can_print)

    # Problem 3

    max_weight = 32.
    container_shape = Polygon([(0, 0), (0, 10), (10, 10), (10, 0)])
    container = Container(max_weight, container_shape)
    items = [Item(Polygon([(0, 0), (0, 6.), (6., 0)]), 10., 20.),
             Item(Polygon([(0, 0), (0, 6.), (6., 0)]), 10., 10.),
             Item(Ellipse((0, 0), 1.5, 0.3), 10., 5.),
             Item(Ellipse((0, 0), 3, 0.3), 5., 5.),
             Item(Ellipse((0, 0), 1.5, 0.3), 5., 5.),
             Item(Ellipse((0, 0), 3, 0.3), 10., 5.)]
    problem = Problem(container, items)
    problems.append(problem)

    solution = Solution(problem)
    solutions.append(solution)

    print_if_allowed(solution.add_item(0, (4.99, 5), 0.), can_print)
    print_if_allowed(solution.add_item(1, (5.01, 5), 180.), can_print)
    print_if_allowed(solution.add_item(3, (5., 1.65), 0), can_print)
    print_if_allowed(solution.add_item(4, (5., 8.35), 0), can_print)

    # Problem 4

    max_weight = 50.
    container_shape = Ellipse((3., 2.), 3., 2.)
    container = Container(max_weight, container_shape)
    items = [Item(Ellipse((0., 0.), 0.7, 0.5), 5., 7),
             Item(Ellipse((0., 0.), 0.3, 0.1), 7., 2),
             Item(Ellipse((0., 0.), 0.2, 0.4), 8., 4),
             Item(Ellipse((0., 0.), 0.5, 0.3), 3., 5),
             Item(Circle((0., 0.), 0.4), 4., 5),
             Item(Circle((0., 0.), 0.25), 3., 2),
             Item(Circle((0., 0.), 0.2), 9., 5),
             Item(Circle((0., 0.), 0.1), 4., 3.),
             Item(Circle((0., 0.), 0.7), 9., 3.)]
    problem = Problem(container, items)
    problems.append(problem)

    solution = Solution(problem)
    solutions.append(solution)

    print_if_allowed(solution.add_item(0, (3., 1.94), 0.), can_print)
    print_if_allowed(solution.add_item(2, (3., 3.24), 90.), can_print)
    print_if_allowed(solution.add_item(3, (3., 2.74), 0.), can_print)
    print_if_allowed(solution.add_item(4, (2.25, 3.5), 0.), can_print)
    print_if_allowed(solution.add_item(5, (3., 3.71), 0.), can_print)
    print_if_allowed(solution.add_item(6, (3.46, 3.75), 0.), can_print)
    print_if_allowed(solution.add_item(7, (3.44, 3.43), 0.), can_print)
    print_if_allowed(solution.add_item(8, (3., 0.72), 0.), can_print)

    # Problem 5

    max_weight = 100.
    container_shape = MultiPolygon([(((0, 0), (0.5, 3), (0, 5), (5, 4.5), (5, 0)),
                                     [((0.1, 0.1), (0.1, 0.2), (0.2, 0.2), (0.2, 0.1)),
                                      ((0.3, 0.3), (0.3, 1.2), (1.6, 2.9), (0.75, 0.4)),
                                      ((3.1, 1.5), (3.5, 4.5), (4.9, 4.4), (4.8, 1.2))])])
    container = Container(max_weight, container_shape)
    items = [Item(Polygon([(0, 0), (1, 1), (1, 0)]), 15., 32.),
             Item(Polygon([(1, 2), (1.5, 3), (4, 5), (1, 4)]), 30., 100.),
             Item(MultiPolygon([(((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)),
                                 [((0.1, 0.1), (0.1, 0.2), (0.2, 0.2), (0.2, 0.1)),
                                  ((0.3, 0.3), (0.3, 0.6), (0.6, 0.6), (0.6, 0.4))])]), 12., 30.),
             Item(Polygon([(0.1, 0.1), (0.1, 0.2), (0.2, 0.2)]), 10., 10.),
             Item(MultiPolygon([(((0., 0.), (0., 1.4), (2., 1.3), (2., 0.)),
                                 [((0.1, 0.1), (0.1, 0.15), (0.15, 0.15), (0.15, 0.1)),
                                  ((0.2, 0.2), (0.2, 1.2), (1.8, 1.1), (1.8, 0.2))
                                  ])]), 1., 5.),
             Item(Circle((0., 0.), 0.4), 1., 14.),
             Item(Circle((0., 0.), 0.1), 2., 12.),
             Item(Ellipse((0., 0.), 0.5, 0.2), 3., 12.),
             Item(Polygon([(0., 0.), (0., 0.3), (0.3, 0.3)]), 1., 10.),
             Item(Ellipse((0., 0.), 0.8, 0.3), 10., 12.),
             Item(Ellipse((0., 0.), 0.1, 0.05), 1., 2.),
             # random items
             # Item(shape_functions.create_random_polygon(0, 0, 0.8, 0.8, 10), 1., 5.),
             # Item(shape_functions.create_random_triangle_in_rectangle_corner(0, 0, 0.8, 0.8), 1., 5.),
             # Item(shape_functions.create_random_quadrilateral_in_rectangle_corners(0, 0, 0.8, 0.8), 1., 5.),
             # out-items
             Item(Circle((0., 0.), 0.2), 50., 1.),
             ]
    problem = Problem(container, items)
    problems.append(problem)

    solution = Solution(problem)
    solutions.append(solution)

    # solution.visualize()

    # print(solution.add_item(0, (1.2, 0.5), 150.))
    print_if_allowed(solution.add_item(0, (1.2, 0.5), 0.), can_print)
    print_if_allowed(solution.add_item(1, (2., 3.), 0.), can_print)
    print_if_allowed(solution.add_item(2, (2.5, 2.5), 0.), can_print)
    print_if_allowed(solution.move_item_in_direction(2, (1, -1), evolutionary.MUTATION_MODIFY_MOVE_UNTIL_INTERSECTION_POINT_NUM, evolutionary.MUTATION_MODIFY_MOVE_UNTIL_INTERSECTION_MIN_DIST_PROPORTION, 9999), can_print)
    print_if_allowed(solution.add_item(3, (2.5, 2.4), 0.), can_print)
    print_if_allowed(solution.add_item(4, (3., 0.7), 0.), can_print)
    print_if_allowed(solution.add_item(5, (3.03, 0.73), 0.), can_print)
    print_if_allowed(solution.add_item(6, (3.45, 1.02), 0.), can_print)
    print_if_allowed(solution.add_item(7, (3., 3.82), 45.), can_print)
    print_if_allowed(solution.add_item(8, (2.4, 0.7), 0.), can_print)
    print_if_allowed(solution.move_item(0, (0.29, 0)), can_print)
    # print_if_allowed(solution.move_item_to(0, (1.49, 2.5)), can_print)
    print_if_allowed(solution.rotate_item_to(0, 180.), can_print)
    print_if_allowed(solution.rotate_item(0, 90.), can_print)
    # print_if_allowed(solution.remove_item(0), can_print)
    # print_if_allowed(solution.rotate_item(4, 20), can_print)
    # print_if_allowed(solution.move_item(7, (1, 0)), can_print)
    # print_if_allowed(solution.rotate_item(7, -45), can_print)
    # print_if_allowed(solution.move_item(5, (-0.4, 0)), can_print)
    print_if_allowed(solution.add_item(9, (1.2, 4.07), 15.), can_print)
    print_if_allowed(solution.add_item(10, (3.6, 0.45), 30.), can_print)
    # print_if_allowed(solution.add_item(11, (4.5, 0.5), 0.), can_print)

    # Problem 6

    max_weight = 150.
    container_shape = MultiPolygon([(((0., 0.), (5., 0.), (5., 5.), (0., 5.)),
                                     [((0.7, 0.7), (1.5, 0.7), (1.5, 1.5), (0.7, 1.5)),
                                      ((2.4, 0.3), (4.3, 0.3), (4.3, 4.3), (2.4, 4.3)),
                                      ((0.7, 2.7), (1.5, 2.7), (1.5, 3.5), (0.7, 3.5))])])
    container = Container(max_weight, container_shape)
    items = [Item(Polygon([(0., 0.), (1.6, 0.), (1.4, 0.2), (1.7, 1.)]), 6., 13.),
             Item(Polygon([(0., 0.), (1.6, 3.), (2.8, 2.9), (1.5, 2.7), (1.9, 1.6)]), 11., 12.),
             Item(Polygon([(0., 0.), (1.8, 1.5), (0., 2.8)]), 15., 25.),
             Item(Polygon([(0., 0.), (1.5, 0.), (1.5, 0.2), (0., 0.2)]), 14., 10.),
             Item(Polygon([(0., 0.), (2.5, 0.), (1.5, 0.2), (0., 0.2)]), 10., 12.),
             Item(Polygon([(0., 0.), (1.6, 0.), (0.8, 0.45), (0.6, 0.7), (0., 0.45)]), 17., 8.),
             Item(Polygon([(0., 0.), (1.5, 0.), (0.8, 0.15), (0., 0.1)]), 13., 12.),
             Item(Polygon([(0., 0.), (1.5, 0.), (0.8, 0.15), (0., 0.1)]), 15., 7.),
             Item(Ellipse((0., 0.), 0.5, 0.3), 15., 8.),
             Item(Ellipse((0., 0.), 0.2, 0.8), 14., 21.),
             Item(Circle((0., 0.), 0.2), 18., 18.),
             Item(Circle((0., 0.), 0.6), 11., 12.),
             Item(Circle((0., 0.), 0.35), 12., 9.)]
    problem = Problem(container, items)
    problems.append(problem)

    solution = Solution(problem)
    solutions.append(solution)

    print_if_allowed(solution.add_item(0, (0.9, 2.02), 0.), can_print)
    print_if_allowed(solution.add_item(3, (0.78, 0.12), 0.), can_print)
    print_if_allowed(solution.add_item(4, (2.8, 0.12), 0.), can_print)
    print_if_allowed(solution.add_item(5, (0.8, 3.85), 0.), can_print)
    print_if_allowed(solution.add_item(6, (0.78, 0.3), 0.), can_print)
    print_if_allowed(solution.add_item(7, (2.3, 2.57), 90.), can_print)
    print_if_allowed(solution.add_item(8, (0.3, 2.98), 90.), can_print)
    print_if_allowed(solution.add_item(9, (2.17, 1.05), 0.), can_print)
    print_if_allowed(solution.add_item(10, (1.8, 0.45), 0.), can_print)
    print_if_allowed(solution.add_item(11, (1.77, 4.38), 0.), can_print)
    print_if_allowed(solution.add_item(12, (0.35, 4.63), 0.), can_print)

    # Problem 7

    max_weight = 122.
    container_shape = Polygon([(3.5, 0.6), (0.5, 0.9), (3.7, 5.5), (1.7, 4.), (0., 6.5), (0.2, 8.6), (0.8, 9.8), (1.7, 8.9), (2, 9.1), (4.4, 9.3), (4.2, 6.7), (4.9, 7.5), (6.5, 8.4), (6.6, 7.9), (7.4, 8.2), (8.7, 5.5), (9.3, 4.8), (6.3, 0.2), (5., 3.5), (5, 0.7), (3.5, 0.6)])
    container = Container(max_weight, container_shape)
    items = [Item(Polygon([(0, 3), (0, 2.), (4., 0)]), 5., 6.),
             Item(Polygon([(0, 0), (1., 2.), (2.5, 2), (1, 1.2)]), 10., 7.),
             Item(Polygon([(0, 1), (1, 2.), (3., 0)]), 9., 4.),
             Item(Polygon([(0, 0.5), (1, 1.), (3, 1), (2., 0)]), 19., 14.),
             Item(Polygon([(0, 0.6), (2, 1), (2., 1.5), (1.2, 1.5)]), 19., 15.),
             Item(Polygon([(0, 0), (0, 2.), (0.5, 2), (0.5, 0.5), (2.5, 0.5), (2.5, 0)]), 7., 15.),
             Item(MultiPolygon([(((0.0, 0.0), (0.0, 1.8), (1.0, 2.7), (2.3, 0.0)),
                                 [((0.2, 0.2), (0.2, 1.4), (0.7, 2.1), (1.8, 0.5))])]), 12., 6.),
             Item(MultiPolygon([(((0.0, 0.0), (1.0, 1.8), (2.0, 2.5), (2.6, 0.7)),
                                 [((0.2, 0.2), (1.2, 1.4), (2.1, 1.7))])]), 7., 13.),
             Item(Ellipse((0, 0), 0.5, 0.2), 4., 9.),
             Item(Ellipse((0, 0), 0.2, 1.5), 21., 14.),
             Item(Ellipse((0, 0), 2.5, 3.5), 16., 30.),
             Item(Circle((0, 0), 0.4), 7., 12.),
             Item(Circle((0, 0), 0.3), 10., 3.),
             Item(Circle((0, 0), 1.), 1., 3.)]
    problem = Problem(container, items)
    problems.append(problem)

    solution = Solution(problem)
    solutions.append(solution)

    print_if_allowed(solution.add_item(0, (5.73, 3.02), 318.), can_print)
    print_if_allowed(solution.add_item(1, (6.3, 4.1), 40.), can_print)
    print_if_allowed(solution.add_item(2, (4.58, 2.5), 315.), can_print)
    print_if_allowed(solution.add_item(3, (1.3, 5.4), 320.), can_print)
    print_if_allowed(solution.add_item(4, (1.4, 1.7), 20.), can_print)
    print_if_allowed(solution.add_item(5, (2.9, 7.9), 180.), can_print)
    print_if_allowed(solution.add_item(6, (8.2, 4), 300.), can_print)
    print_if_allowed(solution.add_item(7, (2.5, 7.4), 340.), can_print)
    print_if_allowed(solution.add_item(8, (7.3, 4.), 320.), can_print)
    print_if_allowed(solution.add_item(9, (2.9, 3.9), 330.), can_print)
    print_if_allowed(solution.add_item(11, (7.8, 4.4), 0.), can_print)
    print_if_allowed(solution.add_item(13, (6.2, 6.8), 0.), can_print)

    # Problem 8

    max_weight = 100.
    container_shape = Polygon([(0., 0.), (0., 5.), (2.5, 3.4), (5., 5.), (5., 0), (2.5, 1.6)])
    container = Container(max_weight, container_shape)
    items = [Item(Polygon([(0., 0.), (0., 3.), (0.25, 3.), (0.25, 0.25), (2., 2.5), (3.75, 0.25), (3.75, 3.), (4., 3.), (4., 0.), (3.75, 0.), (2., 2.), (0.25, 0.)]), 100., 100.),
             Item(Polygon([(0., 0.), (1.6, 1.), (1.8, 1.9), (0.9, 1.6)]), 11., 12.),
             Item(Polygon([(0., 0.), (1.8, 2.5), (0., 1.8)]), 15., 5.),
             Item(Polygon([(0., 0.), (0.5, 0.), (1.2, 0.4), (0., 0.5)]), 4., 10.),
             Item(Polygon([(0., 0.), (2.5, 0.), (1.5, 0.2), (0., 0.5)]), 1., 2.),
             Item(Polygon([(0., 0.), (0.7, 0.25), (1.6, 1.5), (0.6, 0.7), (0., 0.45)]), 17., 8.),
             Item(Polygon([(0., 0.), (0.8, 0.5), (1.5, 1.2), (0., 0.5)]), 13., 11.),
             Item(Polygon([(0., 0.), (1.5, 0.), (1.2, 0.6), (0., 0.3)]), 15., 7.),
             Item(Ellipse((0., 0.), 0.6, 0.4), 15., 8.),
             Item(Ellipse((0., 0.), 2., 0.5), 15., 8.),
             Item(Ellipse((0., 0.), 0.5, 0.3), 24., 6.),
             Item(Ellipse((0., 0.), 0.4, 0.1), 4., 3.),
             Item(Circle((0., 0.), 0.6), 11., 2.),
             Item(Circle((0., 0.), 0.35), 12., 4.),
             Item(Circle((0., 0.), 0.2), 18., 8.)]
    problem = Problem(container, items)
    problems.append(problem)

    solution = Solution(problem)
    solutions.append(solution)

    print_if_allowed(solution.add_item(0, (2.5, 2.02), 0.), can_print)

    # Problem 9

    max_weight = 200.
    container_shape = Point(5, 5).buffer(5, 3)
    container = Container(max_weight, container_shape)
    items = [Item(MultiPolygon([(Point(5, 5).buffer(4.7, 2).exterior.coords,
                                 [((9., 5.), (5., 1.), (1., 5.), (5., 9.))])]), 120., 110.),
             Item(Polygon([(0., 0.), (0., 5.), (5., 5.), (5., 0.)]), 50., 80.),
             Item(Polygon([(1., 4.2), (1.5, 2.), (4., 0)]), 15., 14.),
             Item(Polygon([(0, 0), (1., 2.), (2.5, 2), (1, 1.2)]), 11., 11.),
             Item(Polygon([(0, 1), (1, 2.), (3., 0)]), 11., 4.),
             Item(Polygon([(0, 0.5), (1, 1.), (3, 1), (2., 0)]), 19., 14.),
             Item(Polygon([(0, 0.4), (1.8, .8), (1.5, 1.3), (1.2, 3.3)]), 17., 15.),
             Item(Polygon([(0, 0), (0, 2.), (0.9, 2), (0.9, 0.5), (1.5, 0.5), (1.5, 0)]), 70., 15.),
             Item(Ellipse((0, 0), 0.8, 1.2), 14., 13.),
             Item(Ellipse((0, 0), 1.2, 1.5), 12., 6.),
             Item(Ellipse((0, 0), 2.5, 1.7), 16., 10.),
             Item(Circle((0, 0), 0.7), 17., 11.),
             Item(Circle((0, 0), 0.8), 13., 10.),
             Item(Circle((0, 0), 1.), 4., 4.),
             Item(Circle((0, 0), 2.), 22., 8.)]
    problem = Problem(container, items)
    problems.append(problem)

    solution = Solution(problem)
    solutions.append(solution)

    print_if_allowed(solution.add_item(0, (5., 5.), 0.), can_print)
    print_if_allowed(solution.add_item(1, (5., 5.), 45.), can_print)

    # Problem 10

    max_weight = 150.
    container_shape = Polygon([(2., 5.), (3., 5), (3., 3.), (5., 3.), (5., 2.), (3., 2.), (3., 0.), (2., 0.), (2., 2.), (0., 2.), (0., 3.), (2., 3.)])
    container = Container(max_weight, container_shape)
    items = [Item(Polygon([(0., 0.), (1.5, 0.), (1.5, 0.95)]), 10., 10.),
             Item(Polygon([(0., 0.), (1.5, 0.), (1.5, 0.95)]), 10., 10.),
             Item(Polygon([(0., 0.), (1.5, 0.), (1.5, 0.95)]), 10., 10.),
             Item(Polygon([(0., 0.), (1.5, 0.), (1.5, 0.95)]), 10., 10.),
             Item(Polygon([(0., 0.), (1.5, 0.), (1.5, 0.95)]), 10., 10.),
             Item(Polygon([(0., 0.), (1.5, 0.), (1.5, 0.95)]), 10., 10.),
             Item(Polygon([(0., 0.), (1.5, 0.), (1.5, 0.95)]), 10., 10.),
             Item(Polygon([(0., 0.), (1.5, 0.), (1.5, 0.95)]), 10., 10.),
             Item(Polygon([(0., 0.), (1.5, 0.), (1.5, 0.95)]), 10., 10.),
             Item(Polygon([(0., 0.), (1.5, 0.), (1.5, 0.95)]), 10., 10.),
             Item(Polygon([(0., 0.), (1.5, 0.), (1.5, 0.95), (0., 0.95)]), 20., 10.),
             Item(Polygon([(0., 0.), (1.5, 0.), (1.5, 0.95), (0., 0.95)]), 20., 10.),
             Item(Polygon([(0., 0.), (1.5, 0.), (1.5, 0.95), (0., 0.95)]), 20., 10.),
             Item(Polygon([(0., 0.), (1.5, 0.), (1.5, 0.95), (0., 0.95)]), 20., 10.),
             Item(Polygon([(0., 0.), (1.5, 0.), (1.5, 0.95), (0., 0.95)]), 20., 10.),
             Item(Polygon([(0., 0.), (1.5, 0.), (1.5, 0.95), (0., 0.95)]), 20., 10.),
             Item(Polygon([(0., 0.), (0.8, 0.), (0.8, 0.45), (0., 0.45)]), 20., 30.),
             Item(Polygon([(0., 0.), (0.8, 0.), (0.8, 0.45), (0., 0.45)]), 20., 30.),
             Item(Polygon([(0., 0.), (0.8, 0.), (0.8, 0.1), (0., 0.1)]), 5., 25.),
             Item(Polygon([(0., 0.), (0.8, 0.), (0.8, 0.1), (0., 0.1)]), 5., 25.)]
    problem = Problem(container, items)
    problems.append(problem)

    solution = Solution(problem)
    solutions.append(solution)

    print_if_allowed(solution.add_item(0, (4.23, 2.48), 0.), can_print)
    print_if_allowed(solution.add_item(1, (4.23, 2.52), 180.), can_print)
    print_if_allowed(solution.add_item(2, (0.77, 2.48), 0.), can_print)
    print_if_allowed(solution.add_item(3, (0.77, 2.52), 180.), can_print)
    print_if_allowed(solution.add_item(4, (2.48, 0.76), 270.), can_print)
    print_if_allowed(solution.add_item(5, (2.52, 0.76), 90.), can_print)
    print_if_allowed(solution.add_item(6, (2.48, 4.24), 270.), can_print)
    print_if_allowed(solution.add_item(7, (2.52, 4.24), 90.), can_print)
    print_if_allowed(solution.add_item(8, (2.5, 2.48), 0.), can_print)
    print_if_allowed(solution.add_item(9, (2.5, 2.52), 180.), can_print)
    print_if_allowed(solution.add_item(16, (2.5, 3.25), 0.), can_print)
    print_if_allowed(solution.add_item(17, (2.5, 1.75), 0.), can_print)
    print_if_allowed(solution.add_item(18, (1.64, 2.5), 90.), can_print)
    print_if_allowed(solution.add_item(19, (3.36, 2.5), 90.), can_print)

    # show elapsed time
    elapsed_time = get_time_since(start_time)
    print_if_allowed("Manual elapsed time: {} ms".format(round(elapsed_time, 3)), can_print)

    return problems, [str(i + 1) for i in range(len(problems))], solutions
Exemple #26
0
class Cluster:
    def __init__(self, cells={}, min_ellipse_axis=1):
        """
        Constructor
        @param cells: set of (i,j) tuples
        @param min_ellipse_axis: minimum axis length used in isCentreInsideOfExt
        """
        # set of i,j cells
        self.cells = cells

        # want the ellipse axes to scale to at least this area
        self.min_ellipse_axis = min_ellipse_axis

        # ellipse representing the "average" distribution
        # of cells
        self.ellipse = None

        # min/max indices of the box containing the set of points
        self.box = [[None, None], [None, None]]

        # compute the ellipse...
        self.update()

    def getNumberOfCells(self):
        """
        Get the number of cells
        @return number
        """
        return len(self.cells)

    def update(self):
        if len(self.cells) > 0:
            self.ellipse = Ellipse(self.cells,
                                   min_ellipse_axis=self.min_ellipse_axis)
            for dim in range(0, 2):
                self.box[0][dim] = numpy.min([c[dim] for c in self.cells])
                self.box[1][dim] = numpy.max([c[dim] for c in self.cells])

    def isCentreInsideOf(self, otherCluster):
        """
        Check if this ellipse' centre is inside the other cluster's ellipse
        @param otherCluster: other cluster
        @return True if inside
        """
        return otherCluster.ellipse.isPointInside(self.ellipse.getCentre())

    def isCentreInsideOfExt(self, otherCluster):
        """
        Check if this ellipse' centre is inside the other cluster's extended ellipse
        @param otherCluster: other cluster
        @return True if inside
        """
        return otherCluster.ellipse.isPointInsideExt(self.ellipse.getCentre())

    def isClusterInsideOf(self, otherCluster, frac=0.99):
        """
        Check if fraction of this cluster is inside other cluster
        @param otherCluster: other cluster
        @param frac: fraction of min area of self
        @return True if at least frac is inside
        """
        min_area = min(len(self.cells), len(otherCluster.cells))
        return len(self.cells.intersection(
            otherCluster.cells)) >= frac * min_area

    def getCentre(self):
        """
        Get the centre
        @return array
        """
        return self.ellipse.getCentre()

    def getDistance(self, otherCluster):
        """
        Get the distance between the two clusters' centres
        @param otherCluster
        @return distance
        """
        d = self.ellipse.getCentre() - otherCluster.ellipse.getCentre()
        return numpy.sqrt(d.dot(d))

    def __mul__(self, otherCluster):
        """
        Overload of * operator, returns a cluster that is the intersection of
        this and otherCluster
        @param otherCluster
        @return intersection of self with otherCluster
        """
        return Cluster(self.cells.intersection(otherCluster.cells))

    def __iadd__(self, otherCluster):
        """
        Overload of += operator, add othercluster cells to self
        @param otherCluster: other cluster
        """
        self.cells = self.cells.union(otherCluster.cells)
        self.update()
        return self

    def writeFile(self, filename):
        """
        Write to netcdf file
        @param filename: file name
        """
        import netCDF4
        iCoords, jCoords, ijValues = self.toArray()
        nc = netCDF4.Dataset(filename, 'w', format="NETCDF4")
        iDim = nc.createDimension('iDim', size=iCoords.shape[0])
        jDim = nc.createDimension('jDim', size=jCoords.shape[0])
        iVar = nc.createVariable('i', 'i4', dimensions=('iDim', ))
        jVar = nc.createVariable('j', 'i4', dimensions=('jDim', ))
        nbVar = nc.createVariable('nb', 'i4', dimensions=('iDim', 'jDim'))
        iVar[:] = iCoords
        jVar[:] = jCoords
        nbVar[:, :] = ijValues
        nc.close()

    def toArray(self, bounds=[]):
        """
        Convert this cluster to numpy (dense) array
        @param bounds: [[iMin, jMin], [iMax, jMax]]
        @return array of coordinates, array of zeros and ones
        """
        if len(self.cells) <= 0:
            return numpy.array([]), numpy.array([]), numpy.array([])

        if not bounds:
            bounds = self.box
        iCoords = numpy.arange(bounds[0][0], bounds[1][0] + 1)
        jCoords = numpy.arange(bounds[0][1], bounds[1][1] + 1)
        ijValues = numpy.zeros((len(iCoords), len(jCoords)), numpy.int32)
        iMin, jMin = bounds[0]
        for c in self.cells:
            ijValues[c[0] - iMin, c[1] - jMin] = 1

        return iCoords, jCoords, ijValues

    def __repr__(self):
        """
        Print object
        """
        res = """
        Cluster: num cells = {} box = {} ellipse centre = {} a = {} b = {} transf = {} angle = {}
        """.format(len(self.cells), self.box, \
            self.ellipse.centre, self.ellipse.a, self.ellipse.b, \
            self.ellipse.ij2AxesTransf, self.ellipse.angle)
        return res
        area = round(((magnifiedArea * rect.getArea())/n), 4)

    return area

def getAreaOfOverlap(e1, e2):
    """
    Calculates a rectangle that embeds both the Ellipse and calls the computeAreaOfOverlap method to calculate the area of overlap between two Ellipse passed as parametersself.

    Parameters:
        e1 (Ellipse): First instance of Ellipse class
        e2 (Ellipse): Second instance of Ellipse class

    Returns:
        area (float): Area of overlap between two Ellipse.
    """
    rect = getRectangle(e1, e2)
    area = computeAreaOfOverlap(e1, e2, rect)
    return area

if __name__ == '__main__':
    eclipse1FocalPoint1 = Point(-2.236, 0)
    eclipse1FocalPoint2 = Point(2.236, 0)
    e1 = Ellipse(eclipse1FocalPoint1, eclipse1FocalPoint2, 6)
    eclipse2FocalPoint1 = Point(-1.8284, -0.5)
    eclipse2FocalPoint2 = Point(3.8284, -0.5)
    e2 = Ellipse(eclipse2FocalPoint1, eclipse2FocalPoint2, 6)
    print(e1)
    print(e2)
    print("Area of overlap = {}".format(getAreaOfOverlap(e1, e2)))
    def _estimate(cls, ellipse_cand):
        """Estimate ellipse parameters

        Args:
            ellipse_cand: A EllipseCandidate instance.

        Returns:
            A Ellipse instance.
        """

        seg_i, seg_j, cij, ra_ij, rb_ij, sa_ij, sb_ij = ellipse_cand.seg_pair_ij.all_params
        seg_k, _, cki, ra_ki, rb_ki, sa_ki, sb_ki = ellipse_cand.seg_pair_ki.all_params

        # Estimate ellipse center
        xc = (cij[0] + cki[0]) / 2
        yc = (cij[1] + cki[1]) / 2

        # Estimate ellipse angle (rho) and N (ratio of major and minor axis
        q_values = [
            [ra_ij, sa_ij, ra_ki, sa_ki],
            [ra_ij, sa_ij, rb_ki, sb_ki],
            [rb_ij, sb_ij, rb_ki, sb_ki],
            [rb_ij, sb_ij, ra_ki, sa_ki],
        ]

        # Estimate N and rho(angle of ellipse).
        n_acc = [0] * cls.NUM_BIN_N_ACCUMULATOR      # N \in [0, 1]
        rho_acc = [0] * cls.NUM_BIN_RHO_ACCUMULATOR  # \rho \in [-\pi/2, \pi/2]
        for i in range(4):
            q1, q2_list, q3, q4_list = q_values[i]
            for q2 in q2_list:
                for q4 in q4_list:
                    alpha = q1 * q2 - q3 * q4
                    beta = (q3 * q4 + 1) * (q1 + q2) - (q1 * q2 + 1) * (q3 + q4)
                    k_plus = (-beta + math.sqrt(beta ** 2 + 4 * alpha ** 2)) / (2 * alpha)
                    try:
                        v = ((q1 - k_plus) * (q2 - k_plus) / ((1 + q1 * k_plus) * (1 + q2 * k_plus)))
                        n_plus = math.sqrt(-v)
                    except ValueError:
                        print('ValueError exception')
                        continue  # TODO: Avoid plus v value. Is avoiding ValueError wrong process?

                    if n_plus <= 1:
                        n = n_plus
                    else:
                        n = 1.0 / n_plus

                    if n_plus <= 1:
                        rho = math.atan(k_plus)
                    else:
                        rho = math.atan(k_plus) + math.pi / 2

                    if rho > math.pi / 2:
                        rho -= math.pi

                    rho_bin = int((rho + math.pi / 2) / math.pi * (cls.NUM_BIN_RHO_ACCUMULATOR - 1))
                    n_bin = int(n * (cls.NUM_BIN_N_ACCUMULATOR - 1))

                    n_acc[n_bin] += 1
                    rho_acc[rho_bin] += 1

        n = np.argmax(n_acc) / (cls.NUM_BIN_N_ACCUMULATOR - 1.0)
        rho = np.argmax(rho_acc) / (cls.NUM_BIN_RHO_ACCUMULATOR - 1.0) * math.pi - math.pi / 2  # Ellipse angle
        k = math.tan(rho)

        a_acc = [0] * (cls.MAX_MAJOR_SEMI_AXIS_LEN + 1)
        for xi, yi in np.r_[seg_i.points, seg_j.points, seg_k.points]:
            x0 = ((xi - xc) + (yi - yc) * k) / math.sqrt(k ** 2 + 1)
            y0 = (-(xi - xc) * k + (yi - yc)) / math.sqrt(k ** 2 + 1)
            ax = math.sqrt((x0 ** 2 * n ** 2 + y0 ** 2) / (n ** 2 * (k ** 2 + 1)))
            a = ax / math.cos(rho)
            a_acc[int(a)] += 1

        a = np.argmax(a_acc)  # Major semi-axis length
        b = a * n             # Minor semi-axis length

        # Compute accuracy score
        ellipse = Ellipse(center=np.array([xc, yc], dtype=np.float32), major_len=a, minor_len=b, angle=rho)
        accuracy_score = (ellipse.count_lying_points(seg_i) + ellipse.count_lying_points(seg_j) + ellipse.count_lying_points(seg_k)) / float(seg_i.points.shape[0] + seg_j.points.shape[0] + seg_k.points.shape[0])
        ellipse.accuracy_score = accuracy_score

        return ellipse
Exemple #29
0
class RRStarAlgo:
    def __init__(self, init_position, final_position, safety_coeff: float = 2):
        self._init_position = init_position
        self._final_position = final_position
        self._safety_coeff = safety_coeff
        self._tree = Node(init_position)
        self._nodes = [self._tree]
        self._outside_nodes = []
        self._obstacles = [
            Obstacle(randint(10, 30), [
                randint(50, CANVAS_SIZE[0] - 50),
                randint(50, CANVAS_SIZE[1] - 50)
            ]) for _ in range(40)
        ]
        self._arrival = None
        self._ellipse = None
        self._counter = 0
        self._ellipse_cost_limit = inf

    def step(self):
        new_node = self.create_random_node()
        if not self.is_valid_node(new_node):
            return

        best_node, near_nodes = self.choose_parent(new_node)
        if not best_node:
            return

        self.insert_node(best_node, new_node)

        if not near_nodes == []:
            near_nodes.remove(best_node)
            self.rewire(near_nodes, new_node)

        if self.is_final_node(new_node):
            self.update_arrival_node(new_node)

        if self._arrival:
            if self._ellipse:
                if self._arrival.get_cost() < self._ellipse_cost_limit * 0.9:
                    self.update_ellipse()
            else:
                self.update_ellipse()

    def choose_parent(self, new_node):
        best_node = None
        near_nodes = self.find_near(new_node, 50)
        best_cost = None

        for node in near_nodes:
            cost = node.get_cost() + Node.nodes_distance(node, new_node)

            if (best_cost is None) or (cost < best_cost):

                if self.does_line_intersect(new_node.get_position(),
                                            node.get_position()):
                    continue

                best_cost = cost
                best_node = node

        if not best_node:
            nearest_node = self.find_nearest(new_node)
            if not self.does_line_intersect(nearest_node.get_position(),
                                            new_node.get_position()):
                best_node = nearest_node

        return best_node, near_nodes

    def insert_node(self, best_node, new_node):
        new_node.set_cost(best_node.get_cost() +
                          Node.nodes_distance(best_node, new_node))
        best_node.add_node(new_node)
        self._nodes.append(new_node)

    def rewire(self, near_nodes, new_node):
        if near_nodes:
            new_code_cost = new_node.get_cost()
            for node in near_nodes:
                if node.get_cost() > (new_code_cost +
                                      Node.nodes_distance(node, new_node)):
                    if self.does_line_intersect(new_node.get_position(),
                                                node.get_position()):
                        continue

                    node.set_cost(new_code_cost +
                                  Node.nodes_distance(node, new_node))
                    node.reconnect(new_node)

    def does_line_intersect(self, start_position, end_position):
        for obstacle in self._obstacles:
            if obstacle.does_line_intersect(start_position, end_position):
                return True
        return False

    def print_tree(self, canvas: Canvas):
        self._tree.print(canvas)

    def print_obstacles(self, canvas: Canvas):
        for obstacle in self._obstacles:
            obstacle.print(canvas)

    def print_arrival(self, canvas: Canvas):
        if self._arrival:
            position = self._final_position
            canvas.create_oval(position[0] - ARRIVAL_RADIUS,
                               position[1] - ARRIVAL_RADIUS,
                               position[0] + ARRIVAL_RADIUS,
                               position[1] + ARRIVAL_RADIUS,
                               fill="blue")

    def print_solution(self, canvas: Canvas):
        if self._arrival:
            self._arrival.print_path_to_root(canvas)

    def find_nearest(self, node: Node):
        return min(self._nodes, key=lambda x: Node.nodes_distance(x, node))

    def find_near(self, node: Node, radius):
        return list(
            filter(lambda x: Node.nodes_distance(x, node) < radius,
                   self._nodes))

    def is_valid_node(self, new_node: Node):
        for obstacle in self._obstacles:
            if obstacle.is_point_in(new_node, self._safety_coeff):
                return False

        if self._ellipse:
            if not self._ellipse.is_point_in(new_node.get_position()):
                return False

        return True

    def is_final_node(self, node: Node):
        position = node.get_position()
        return (((position[0] - self._final_position[0])**2 +
                 (position[1] - self._final_position[1])**2) <
                (ARRIVAL_RADIUS**2))

    def update_arrival_node(self, node: Node):
        if self._arrival:
            if self._arrival.get_cost() > node.get_cost():
                self._arrival = node
        else:
            self._arrival = node

    def create_random_node(self):
        if self._ellipse:
            return Node(self._ellipse.random_point_in())
        else:
            return Node(
                [randint(0, CANVAS_SIZE[0]),
                 randint(0, CANVAS_SIZE[1])])

    def update_ellipse(self):
        self._ellipse = Ellipse(self._init_position, self._final_position,
                                self._arrival.get_cost() / 2)
        self._ellipse_cost_limit = self._arrival.get_cost()

        self._outside_nodes = self._outside_nodes + list(
            filter(
                lambda node: False == self._ellipse.is_point_in(
                    node.get_position()), self._nodes))
        for node in self._outside_nodes:
            node.set_outside_state(True)
        self._nodes = list(
            filter(lambda node: self._ellipse.is_point_in(node.get_position()),
                   self._nodes))
Exemple #30
0
            # Connected Components Labelling 
            labelNum, label, stat, centroid = cv.connectedComponentsWithStats(edges, 8)
            # Discard small connected components 
            filteredLabelNum = filterLabelNum(stat, labelNum, args.blob_area)
            logging.info(f'Blob Area     : {args.blob_area}')
            # Compute CCL image
            ccl = computeCCL(filteredLabelNum, label)
            ################## RANSAC PROGRAM ##################
            i = 1 # Counter 
            # Run RANSAC on each connected component
            for labelNum in filteredLabelNum : 
                logging.debug(f'COMPONENT : {i}')
                # Compiling the coordinates of the pixels in the contour into data points
                dataPoints = compileDataPoints(label, labelNum)
                # Initialize an ellispe class 
                ellipse = Ellipse()
                # Run RANSAC on the data points 
                model = RANSAC(
                    ellipse, 
                    dataPoints, 
                    args.sample_size, 
                    args.iteration, 
                    args.threshold, 
                    args.tolerance
                )
                # Draw ellipse 
                if (model != []) :
                    drawEllipse(out, model, args.crop)

                logging.info(f'Component {i} process complete.')
                i = i + 1
 def __init__(self, fire):
     self.asteroid = OBJ("asteroid.obj", textureFile="asteroid.jpg")
     self.ellipse = Ellipse(18, 4, 0.17)
     self.fire = fire
     self.angle = 0