示例#1
0
class Walker(App):
    def appStarted(self):
        self.the_shape = Shape()

    def keyPressed(self, event):
        if event.key == "Right":
            self.the_shape.rotate('r')

        elif event.key == "Up":
            self.the_shape.rotate('u')

        elif event.key == "Left":
            self.the_shape.rotate('l')

        elif event.key == "Down":
            self.the_shape.rotate('d')

    def redrawAll(self, canvas):
        canvas.create_rectangle(0,
                                0,
                                WIDTH,
                                HEIGHT,
                                fill=paintcan.toHex(paintcan.silver))
        canvas.create_text(WIDTH / 2,
                           25,
                           font=('Sans', 20),
                           text="Use the arrow keys to control.")

        self.the_shape.draw(canvas)
    def __init__(self, json):
        if JSONParser._parser(json) == 1:
            raise ValueError("Bad json")
        shapes = []
        self.screen = dict()
        self.palette = dict()

        for i in json["Palette"]:
            self.palette[i] = JSONParser.return_color(dict(),
                                                      json["Palette"][i])

        self.screen["width"] = json["Screen"]["width"]
        self.screen["height"] = json["Screen"]["height"]
        self.screen["bg_color"] = JSONParser.return_color(
            self.palette, json["Screen"]["bg_color"])
        self.screen["fg_color"] = JSONParser.return_color(
            self.palette, json["Screen"]["fg_color"])

        for i in json["Figures"]:
            type = i["type"]
            if type == "point":
                if "color" in i:
                    color = JSONParser.return_color(self.palette, i["color"])
                else:
                    color = self.screen["fg_color"]
                shapes.append(Shape.Point(i["x"], i["y"], color))
            elif type == "polygon":
                if "color" in i:
                    color = JSONParser.return_color(self.palette, i["color"])
                else:
                    color = self.screen["fg_color"]
                shapes.append(Shape.Polygon(i["points"], color))
            elif type == "rectangle":
                if "color" in i:
                    color = JSONParser.return_color(self.palette, i["color"])
                else:
                    color = self.screen["fg_color"]
                shapes.append(
                    Shape.Rectangle(i["x"], i["y"], i["width"], i["height"],
                                    color))
            elif type == "square":
                if "color" in i:
                    color = JSONParser.return_color(self.palette, i["color"])
                else:
                    color = self.screen["fg_color"]
                shapes.append(Shape.Square(i["x"], i["y"], i["size"], color))
            elif type == "circle":
                if "color" in i:
                    color = JSONParser.return_color(self.palette, i["color"])
                else:
                    color = self.screen["fg_color"]
                shapes.append(
                    Shape.Circle(i["x"], i["y"], i["radius"], color=color))
            else:
                print("Bad type of figure")
                raise ValueError("Bad type of figure")

        self.shapes = shapes
示例#3
0
 def shape(self):
     """
     Returns the `Shape` associated to self. Namely, it "forgets" the labels of the leafs.
     :return: `Shape` instance.
     """
     if self.is_leaf:
         return Shape(None)
     else:
         return Shape([x.shape() for x in self.children])
示例#4
0
 def __init__(self, p, v, ttl, size):
     self.ttl = ttl
     s = [(-size, -size, size, size, None),
          (-size, size, size, -size, None)]
     self.shape = Shape(s)
     WorldObject.__init__(self, OBJECT_TYPE_NONE, p, 0, v, 0)
     if random.random() < .5:
         self.spin = 5
     else:
         self.spin = -5
示例#5
0
    def __init__(self, signal):
        self.signal = signal
        self.curX = 0
        self.curY = 0
        self.curShape = Shape()  # 当前Shape
        self.isCurShapeDropped = False  # 当前shape是否落下完成
        self.board = []  # 游戏区域  Col * Row

        self.num_lines_removed = 0  # 消除的行数

        self.clear_board()
示例#6
0
    def nextpiece(self):
        self.curPiece, self.nextPiece, self.next2Piece, self.next3Piece, self.next4Piece = \
         (self.nextPiece, self.next2Piece, self.next3Piece, self.next4Piece, self.next5Piece)
        self.next5Piece = Shape()
        newShape = self.newPiece()
        self.next5Piece.setShape(newShape)

        self.curX = Board.BoardWidth // 2 + 1
        self.curY = Board.BoardHeight - 1 + self.curPiece.minY()

        #when cannot place new piece, GAME OVER !
        if not self.tryMove(self.curPiece, self.curX, self.curY):
            self.game_over()
示例#7
0
 def __init__(self):
     s = [(-5, 5, 10, 0, None), (-5, -5, 10, 0, None),
          (-5, -5, -5, 5, None)]
     self.shape = Shape(s)
     self.fireCannon = False
     self.fireTorpedo = False
     self.rounds = 50.0
     self.fuel = 50.0
     self.torpedos = 50.0
     self.torpedoDelay = 0
     WorldObject.__init__(self, OBJECT_TYPE_SHIP,
                          Point(SCREEN_WIDTH * .75, SCREEN_HEIGHT / 2), PI,
                          None, 7, SHIP_MASS)
示例#8
0
    def start(self, sides, centre=True):
        """

        Starts with a polygon, optionally connected to the centre

        """

        self.shapes = []

        self.points = []

        self.symetry = sides

        if sides < 3:

            raise "At least 3 sides are required"

        dt = math.pi / sides

        self.points = [
            SPoint.SPoint(math.cos(i * dt), math.sin(i * dt))
            for i in range(1, 2 * sides, 2)
        ]

        if centre:

            self.points.append(SPoint.SPoint(0, 0))

            for i in range(sides):

                s = Shape.Shape()

                s.addPoint(self.points[i])

                s.addPoint(self.points[(i + 1) % sides])

                s.addPoint(self.points[sides])

                self.shapes.append(s)

        else:

            s = Shape.Shape()

            for i in range(sides):

                s.addPoint(self.points[i])

            self.shapes.append(s)

        self.findLines()
示例#9
0
    def assemblePoints(self, p1, p2, p11, p12, p21, p22):
        """

        Common part of the two expand functions

        """

        new_s1 = Shape.Shape()

        new_s2 = Shape.Shape()

        new_s3 = Shape.Shape()

        new_s1.addPoint(p1)

        new_s1.addPoint(p11)

        new_s1.addPoint(p12)

        new_s2.addPoint(p11)

        new_s2.addPoint(p12)

        new_s2.addPoint(p22)

        new_s2.addPoint(p21)

        new_s3.addPoint(p2)

        new_s3.addPoint(p21)

        new_s3.addPoint(p22)

        self.new_shapes.append(new_s1)

        self.new_shapes.append(new_s2)

        self.new_shapes.append(new_s3)

        # Add the new points to our list

        self.addPoint(p11)

        self.addPoint(p12)

        self.addPoint(p21)

        self.addPoint(p22)
示例#10
0
    def getDual(self):
        """

        Return the dual of this pattern

        """

        dual = SPattern()

        for pt in self.points:

            shape = Shape.Shape()

            if len(pt.shapes) == len(pt.lines):

                for s in pt.shapes:

                    s.findCentre()

                    newpt = dual.findPoint(s.centre)

                    shape.addPoint(newpt)

                shape.sortPoints()

                dual.shapes.append(shape)

        dual.findLines()

        return dual
示例#11
0
def kmeans_Shape_DNA():
    ''' Was used to do kmeans on Shape DNA '''
    l_eig = []

    list_files = [
        "camel-poses/camel-01.obj",
        "camel-poses/camel-02.obj",
        "camel-poses/camel-03.obj",
        #"flamingo-poses/flam-04.obj", "flamingo-poses/flam-02.obj", "flamingo-poses/flam-03.obj", #buggy
        "lion-poses/lion-01.obj",
        "lion-poses/lion-02.obj",
        "lion-poses/lion-03.obj",
    ]
    list_shapes = []

    for name in list_files:
        t = time.time()
        list_shapes.append(Shape(name))
        list_shapes[-1].compute_shape_dna(10)
        l_eig.append(list_shapes[-1].eigenvalues)
        list_shapes[-1].clear()
        #print(l_eig[-1])
        print("Computed shape DNA for ", name, "in ", time.time() - t)

    print("Training k-means")
    kmeans = KMeans(init='k-means++', n_clusters=2, n_init=100)
    kmeans.fit(l_eig)
    print("Trained.")

    for i in range(len(list_files)):
        print("File ", list_files[i], "is associated to cluster ",
              kmeans.predict(l_eig[i].reshape(1, -1)))
示例#12
0
    def __init__(self):

        self.env = Environment(Shape.Worm())
        self.checkpoint_dir = os.path.join(os.path.dirname(__file__), 'mlflow')
        self.best_run = 0
        self.addative_noise_generator = noise_generators.OUActionNoise(
            output_size=self.env.action_size)
        self.multiplier_noise_generator = noise_generators.MarkovSaltPepperNoise(
            output_size=self.env.action_size)

        self.init_models()

        self.target_actor.set_weights(self.actor_model.get_weights())
        self.target_critic.set_weights(self.critic_model.get_weights())

        self.critic_optimizer = tf.keras.optimizers.RMSprop(
            learning_rate=self.CRITIC_LR)
        self.actor_optimizer = tf.keras.optimizers.RMSprop(
            learning_rate=self.ACTOR_LR)
        self.buffer = PrioritizedBuffer(self.env.state_size,
                                        self.env.action_size, self.GAMMA,
                                        self.BUFFER_SIZE, self.BATCH_SIZE)

        self.episode_reward_history = []
        # show controls the appearance of a window with graphics, controlled by 's' and 'a' on the keyboard
        self.show = False
        # show controls if the model is learning or not, affects the FPS of the graphics
        # controlled by 'l' and 'k' on the keyboard
        self.learn = True
        self.log_params()
示例#13
0
 def merge_shapes(self,slist,merged_name,replace=True):
     """
     Merges a set of shapes, by taking the average of their points.
     
     Args
         slist is a python list of the ShapeSet.shapes keys of the Shapes to
         merge.
         merged_name is a name of the merged Shape that will be added to the
         dataset.
         replace: if True, the original shapes will be removed from the 
         ShapeSet (default), if False, they will be left in
     
     The ShapeSet must be aligned before merging.
     
     Missing landmarks (with nan coordinates) will be ignored for 
     calculating the average of that landmark.
     """
     if self.__is_aligned__==False:
         raise Exception("ShapeSet must be aligned before shapes can be merged.")
     if len(slist)<2:
         raise Exception("Must be at least two shapes in slist to merge.")
     mean_lms = np.nanmean(np.array([self.shapes[i].landmarks for i in slist]), axis=0)
     merged_shape = Shape.Shape(data = mean_lms.tolist(),shape_name=merged_name)
     if replace==True:
         for s in slist:
             self.shapes.pop(s)
             self.n_shapes = self.n_shapes-1
     self.append_shape(merged_shape)
示例#14
0
    def __init__(self, parent, frame, attrpanel, treeview):
        wx.Panel.__init__(self, parent, size=(1, 1))
        self.frame = frame
        self.attrpanel = attrpanel
        self.treeview = treeview
        self.listener = None

        # create mini toolbar
        self.CreateToolbar()
        self.editor = sae.ShapeCanvas(self, self.attrpanel, self.frame)

        self.box = wx.BoxSizer(wx.VERTICAL)
        self.box.Add(self.toolbar, 0, wx.EXPAND)
        self.box.Add(wx.StaticLine(self), 0, wx.EXPAND)
        self.pathtext = wx.TextCtrl(self, -1, "", size=(80, -1))
        self.box.Add(self.pathtext, 0, wx.EXPAND)
        self.box.Add(self.editor, 1, wx.EXPAND)
        self.pathtext.SetEditable(False)

        self.box.Fit(self)
        self.SetSizer(self.box)

        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)

        acceltbl = wx.AcceleratorTable([
            (wx.ACCEL_CTRL, ord('S'), MENU_SAVE),
        ])
        self.SetAcceleratorTable(acceltbl)
示例#15
0
def kmeans_D2():
    ''' Was used to do kmeans on GPS-D2 '''
    l_d2 = []

    list_files = [
        "camel-collapse/camel-collapse-01.obj",
        "camel-gallop/camel-gallop-01.obj", "cat-poses/cat-01.obj",
        "elephant-gallop/elephant-gallop-01.obj",
        "elephant-poses/elephant-01.obj", "face-poses/face-01-anger.obj",
        "head-poses/head-01-anger.obj",
        "horse-collapse/horse-collapose-01.obj",
        "horse-gallop/horse-gallop-01.obj", "horse-poses/horse-01.obj",
        "lion-poses/lion-01.obj"
    ]
    list_shapes = []

    for name in list_files:
        t = time.time()
        list_shapes.append(Shape(name))
        list_shapes[-1].compute_D2(k=20, N=50000, nb_cases=3, m=5)
        l_d2.append(list_shapes[-1].histogram)
        list_shapes[-1].clear()
        print("Computed D2-distrib for ", name, "in ", time.time() - t)

    print("Training k-means")
    kmeans = KMeans(init='k-means++', n_clusters=2, n_init=100)
    kmeans.fit(l_d2)
    print("Trained.")

    for i in range(len(list_files)):
        print("File ", list_files[i], "is associated to cluster ",
              kmeans.predict(l_d2[i].reshape(1, -1)))
示例#16
0
def estimate_from_symmetry(shape, lm_pairs, **kwargs):
    """
    Estimates missing landmarks by reflecting through a plane of symmetry.
    
    Args:
        shape is a Shape object.
        lm_pairs is a list of lists/tuples of pairs of integers that specify
        which points are pairs.
        
        In addition either plane or midpoints needs to be specified.
        plane : a list of four numbers specifying a plane
        midpoints : a list of the integer indices of the landmarks that lie on
        the plane of symmetry.
    """
    assert ('plane' in kwargs.keys() or 'midpoints' in kwargs.keys())
    if 'plane' in kwargs.keys():
        plane = kwargs['plane']
    else:
        mid_lms = []
        for idx, lm in enumerate(shape.landmarks):
            if idx in kwargs['midpoints']:
                mid_lms.append(lm)
        plane = linear.fit_plane(mid_lms)
    new_lms = shape.landmarks
    for idx, p in enumerate(shape.landmarks):
        if __point_present__(p) == False:
            opp = __opposite_lm__(idx, lm_pairs)
            if opp != -1 and __point_present__(shape.landmarks[opp]) == True:
                new_lms[idx] = __symm_point__(shape.landmarks[opp], plane)
    filled_shape = Shape.Shape(data=new_lms,
                               shape_name=shape.name,
                               lm_names=shape.lm_names)
    return filled_shape
示例#17
0
def estimate_from_mean(shapeset, shapes=None):
    """
    Estimates missing landmarks in a ShapeSet from present values in other 
    specimens.
    
    Args:
        shapeset: the ShapeSet to be filled.
        shapes: an optional list of Shapes to have missing data imputed for. 
        If left as the default (None), then any taxa with missing data will be 
        estimated.
    
    Note: the shapeset must be aligned before using this function.
    """
    assert (shapeset.__is_aligned__ == True)
    mean_vals = np.nanmean(shapeset.__kmn__(typeof='np_array'),
                           axis=0).tolist()
    new_shapeset = ShapeSet.ShapeSet(shapeset_name=shapeset.name)
    if shapes == None:
        shapes = shapeset.shapes.keys()
    for t in shapeset.shapes.keys():
        new_data = np.array(shapeset.shapes[t].landmarks)
        for idx, lm in enumerate(shapeset.shapes[t].landmarks):
            if __point_present__(lm) == False:
                new_data[idx] = mean_vals[idx]
        new_shape = Shape.Shape(data=new_data.tolist(), shape_name=t)
        new_shapeset.append_shape(new_shape)
    return new_shapeset
def __detect_shape(img, height, width, shape):
    """
    The process to detect the shape.

    It detects the number of shape's edges. If a shape has 3 edges, it's a triangle.

    Parameters
    ----------
    img : numpy.ndarray
        The image whose shapes we want to detect
    height : int
        Image's height
    width : int
        Image's width
    shape : Shape
        The shape we want to detect
    Returns
    -------
    detected : Shape
        The detected shape
    last_cont : numpy.ndarray
        Contours of the shape.
    detected_shapes : list
        The detected shapes.
    center : tuple of float
        Center of the detected shape.
    angle : float
        Angle of rotation of the detected shape.
    """
    font = cv2.FONT_HERSHEY_SIMPLEX
    contours, _ = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    hull_list = __convex_hull(contours)
    minimal_area = 200
    maximal_area = (height * width) - 2000
    detected = None
    detected_shapes = []
    last_cont = np.array([])
    center = None
    angle = None
    for cont in hull_list:
        area = cv2.contourArea(cont)
        #continue if area is too small(noise) or too big
        if area < minimal_area or area >= maximal_area:
            continue
        approx = __approx_poly(cont, img)
        detected = __check_partial(detected, approx, width, height)
        if detected != Shape.Shape.PARTIAL.value:
            detected = __check_non_partial_shape(cont, area, approx)
        shape_name = Shape.Shape(detected).name
        detected_shapes.append(shape_name)
        if shape == Shape.Shape.ALL.value or detected == shape:
            x = cont[0][0][0]  #x value of a point of the shape
            y = cont[0][0][1]  #y value of a point of the shape
            cv2.putText(img, shape_name, (x, y), font, 0.5, (255))
            if detected == shape:
                last_cont = approx
                center, _, angle = cv2.minAreaRect(cont)
                break
    return detected, last_cont, detected_shapes, center, angle
示例#19
0
def shape_probs_from_list(X):
    """
    Return the probabilities of all the instances of `Shape` in a list (in string) of Newick codes.
    :param X: a string containing several Newick codes.
    :return: A list of symbolic expressions depending on `a`.
    """
    l = Shape.from_newick_list(X)
    return [prob_shape(t) for t in l]
示例#20
0
def read(filepath, filetype="Landmark.exe", shapename=None):
    if shapename == None:
        shapename == filepath
    if filetype == "Landmark.exe":
        n, p = __parse_landmarkexe__(filepath)
        return Shape.Shape(data=p, shape_name=shapename, lm_names=n)
    else:
        raise Exception("Trying to import an unknown file type: %s" % filepath)
示例#21
0
def updateNGonSlider(event):
    """Called as the nGonSlider command"""
    global shape
    global shapeMessage
    shape = Shape.NGon(nGonSlider.get(), 100, PVector(0, 0))
    shapeMessage = "Regular " + str(nGonSlider.get()) + "-gon\n"
    update()
    return
示例#22
0
def updateParallelogramSlider(event):
    """Called as the parallelogramSlider command"""
    global shape
    global shapeMessage
    shape = Shape.Parallelogram(parallelogramSlider.get(), PVector(0, 0), 100)
    shapeMessage = "Parallelogram with shearing " + str(
        parallelogramSlider.get()
    ) + ", the ratio of the distance between midpoints of the horizontal sides and the height of the parallelogram\n"
    update()
    return
示例#23
0
def updateKiteSlider(event):
    """Called as the kiteSlider command"""
    global shape
    global shapeMessage
    shape = Shape.Kite(kiteSlider.get(), PVector(0, 0), 100)
    shapeMessage = "Kite with droop " + str(
        kiteSlider.get()
    ) + ", the ratio of the vertical distance between the bottom and horizontal beam, and the top and the horizontal beam\n"
    update()
    return
示例#24
0
def push_and_close():
    i = 0
    while i < len(temporary_shapes):
        if len(temporary_shapes[i].new_entries) != 0:
            temporary_shapes[i].push_entries()
        else:
            temporary_shapes[i].close_entries()
            shapes_list.append(Shape(temporary_shapes[i].point_list))
            del temporary_shapes[i]
            i -= 1
        i += 1
示例#25
0
def shape_probs_from_file(fname, encoding='utf8', strip_comments=False, **kw):
    """
    Load a list of instances of `Shape` from a Newick formatted file and return their probabilities in a list, assuming
    they are instances of `Shape`.
    :param fname: file path.
    :param strip_comments: Flag signaling whether to strip comments enclosed in square \
    brackets.
    :param kw: Keyword arguments are passed through to `Node.read`.
    :return: A list of symbolic expressions depending on `a`.
    """
    l = newick.read(fname, encoding, strip_comments, **kw)
    return [prob_shape(Shape.newick_node_to_shape(t)) for t in l]
示例#26
0
 def test_addShapes(self):
     s1 = Shape()
     s1.setPoints([(0,0),(1,1),(2,1),(3,0)])
     s2 = Shape()
     s2.setPoints([(2,0),(4,2),(5,0)])
     s3 = s1+s2
     self.assertEqual(s3.points, [(0,0),(1,1),(2,1),(2.5,0.5),(4,2),(5,0)])
示例#27
0
class SmokeParticle(WorldObject):
    def __init__(self, p, v, ttl, size):
        self.ttl = ttl
        s = [(-size, -size, size, size, None),
             (-size, size, size, -size, None)]
        self.shape = Shape(s)
        WorldObject.__init__(self, OBJECT_TYPE_NONE, p, 0, v, 0)
        if random.random() < .5:
            self.spin = 5
        else:
            self.spin = -5

    def update(self, e):
        WorldObject.update(self, e)
        if self.ttl > 0:
            self.ttl -= 1
            return True
        else:
            return False

    def draw(self, canvas, p, a):
        self.shape.draw(canvas, p, a)
示例#28
0
def updateTrapezoidSlider(event):
    """Called as the trapezoidSlider command"""
    global shape
    global shapeMessage
    shape = Shape.Trapezoid(trapezoidSlider.get(), PVector(0, 0), 100)
    shapeMessage = "Trapezoid of Modulus [" + str(
        (float(trapezoidSlider.get()) / (float(trapezoidSlider.get()) - 1))
    ) + "] = " + str(
        int(
            floor(
                float(trapezoidSlider.get()) /
                (float(trapezoidSlider.get()) - 1)))
    ) + ", the ratio of the long horizontal edge to the difference in lengths between the two horizontal edges\n"  # Modulus = floor{|AB| / (|AB| - |CD|)} = floor{s / (s - 1)}, where s = float(trapezoidSlider.get())
    update()
    return
示例#29
0
 def setUp(self):
     self.c = Shape()
     self.ordered = [(20,0),(40,1),(60,0),(80,1),(100,0)]
     self.unordered = [(10.0,0.5),(12,1),(24.000,0),(14.0,0.500),(0,0)]
     self.mftri = MembershipFunction()
     self.mftri.tri(0,2,4)
     self.mftrap = MembershipFunction()
     self.mftrap.trap(0,2,4,6)
     self.mfout = MembershipFunction()
     self.mfout.tri(4,6,8)
     self.mfcold = MembershipFunction()
     self.mfcold.trap(0,0,2,4)
     self.mfdict = {}
     self.mfdict['cold'] = self.mfcold
     self.mfdict['blast'] = self.mfout
     self.rule = Rule(self.mfdict)
     self.cin = {}
     self.cin['temp']=3
示例#30
0
    def startGrid(self, n):
        """

        Starts with a square grid, n x n

        """

        self.shapes = []

        self.points = []

        self.symetry = 4

        if n < 1:

            raise "At least 1 square is required"

        for i in range(n + 1):

            for j in range(n + 1):

                self.points.append(SPoint.SPoint(i, j))

        for i in range(n):

            for j in range(n):

                s = Shape.Shape()

                pos = (n + 1) * i + j

                s.addPoint(self.points[pos])

                s.addPoint(self.points[pos + 1])

                s.addPoint(self.points[pos + n + 2])

                s.addPoint(self.points[pos + n + 1])

                self.shapes.append(s)

        self.findLines()
示例#31
0
    def evaluate_opening(self):

        res = 0
        black = 0
        white = 0

        territory = Territory.Territory(self._board, self._black_moves,
                                        self._white_moves, self._black_goban,
                                        self._white_goban)
        shape = Shape.Shape(self._board, self._black_moves, self._white_moves,
                            self._black_goban, self._white_goban)

        for move in self._black_moves:
            ufcoord = Goban.Board.name_to_coord(move)
            x = ufcoord[0]
            y = ufcoord[1]

            if (1 <= x <= 7) and (
                    1 <= y <=
                    7):  # pierres sur la deuxième ligne pour l'ouverture
                black = black + 3000

        for move in self._white_moves:
            ufcoord = Goban.Board.name_to_coord(move)
            x = ufcoord[0]
            y = ufcoord[1]

            if (1 <= x <= 7) and (
                    1 <= y <=
                    7):  # pierres sur la deuxième ligne pour l'ouverture
                white = white + 3000

        # On maximise le nombre de territoires cardinaux conquéris
        black = black + territory.count_territories_black()
        white = white + territory.count_territories_white()

        if self._mycolor == Goban.Board._BLACK:
            res = black - white
        else:
            res = white - black

        return res
示例#32
0
def initSim(nbobj, rad, pos1):
    # créé le sol
    p.createCollisionShape(p.GEOM_PLANE)
    basePlane = p.createMultiBody(0, 0)
    # met une seed au rng
    random.seed(time.time())
    # random.seed("Thibault")
    # créé la sphere qui sera le point centrale de la "Shape"
    nbPop = 100
    pop = []
    for i in range(0, nbPop - 1):
        body = p.createCollisionShape(p.GEOM_SPHERE, radius=rad * 4)
        temp = s.Shape(body, pos1)
        temp.createRandom(nbobj, rad)
        idtmp = temp.createBody()
        pop.append(temp)

        pop[i].setId(idtmp)

    for i in range(-1, nbobj):
        for j in range(-1, nbobj):
            for elem1 in range(0, nbPop - 1):
                for elem2 in range(elem1 + 1, nbPop - 1):
                    p.setCollisionFilterPair(pop[elem1].getId(),
                                             pop[elem2].getId(), i, j, 0)
        print((i + 2) / (nbobj + 1))

    # ==========================================================
    # Truc lié a la simulation
    # ==========================================================
    for elem in pop:
        for i in range(0, nbobj):
            p.setJointMotorControl2(bodyUniqueId=elem.getId(),
                                    jointIndex=i,
                                    controlMode=p.VELOCITY_CONTROL,
                                    targetVelocity=random.randint(0, 3))

    # met la gravité
    p.setGravity(0, 0, -9.81)

    return pop
示例#33
0
class TestShape(unittest.TestCase):
    def setUp(self):
        self.c = Shape()
        self.ordered = [(20,0),(40,1),(60,0),(80,1),(100,0)]
        self.unordered = [(10.0,0.5),(12,1),(24.000,0),(14.0,0.500),(0,0)]
        self.mftri = MembershipFunction()
        self.mftri.tri(0,2,4)
        self.mftrap = MembershipFunction()
        self.mftrap.trap(0,2,4,6)
        self.mfout = MembershipFunction()
        self.mfout.tri(4,6,8)
        self.mfcold = MembershipFunction()
        self.mfcold.trap(0,0,2,4)
        self.mfdict = {}
        self.mfdict['cold'] = self.mfcold
        self.mfdict['blast'] = self.mfout
        self.rule = Rule(self.mfdict)
        self.cin = {}
        self.cin['temp']=3
    def test_addPoint_presentationValue(self):
        p = [(20,0),(34,0.7),(46,0.7),(54,0.3),(66,0.3),(70,0.5),(100,0.5)]
        for point in p:
            self.c.addPoint(point)
        self.c.solve()
        self.assertEqual(round(self.c.x,3),60.943)
    def test_addPoint_sorted(self):
        p = self.ordered
        for point in p:
            self.c.addPoint(point)
        self.c.solve()
        self.assertEqual(self.c.x,60)
    def test_addPoint_unsorted(self):
        p = self.unordered
        for point in p:
            self.c.addPoint(point)
        self.c.solve()
        self.assertEqual(self.c.x,12)
    def test_setPoints_unsorted(self):
        p = self.unordered
        self.c.setPoints(p)
        self.c.solve()
        self.assertEqual(self.c.x,12)
    def test_resultTri(self):
        self.assertEqual(self.mftri.getResult(0.5).points,[(0,0),(1,0.5),(3,0.5),(4,0)])
    def test_resultTrap(self):
        self.assertEqual(self.mftrap.getResult(0.5).points,[(0,0),(1,0.5),(5,0.5),(6,0)])
    def test_getDegreeTrap(self):
        self.assertEqual(self.mftrap.getDegree(1),0.5)
    def test_getDegreeTri(self):
        self.assertEqual(self.mftri.getDegree(3),0.5)
    def test_heaterRule(self):
        self.rule.addCondition('temp', 'cold')
        self.rule.setResult('heater','blast')
        (feat, shape) = self.rule.getResult(self.cin)
        shape.solve()
        self.assertEqual(shape.x, 6)
    def test_intersects(self):
        s1 = Segment((0,0),(1,1))
        s2 = Segment((0,1),(1,0))
        self.assertTrue(s1.intersects(s2))
    def test_noIntersect(self):
        s1 = Segment((0,0),(1,1))
        s2 = Segment((0,1),(2,3))
        self.assertTrue(not s1.intersects(s2))
    def test_intersect1(self):
        s1 = Segment((0,0),(1,1))
        s2 = Segment((0,1),(1,0))
        self.assertEqual(s1.intersection(s2), (0.5,0.5))
    def test_intersect2(self):
        s1 = Segment((1,3),(3,1))
        s2 = Segment((1,1),(3,3))
        self.assertEqual(s1.intersection(s2), (2.0,2.0))
    def test_addSegment(self):
        s = Shape()
        s.addSegment(Segment((0,0),(1,1)))
        s.addSegment(Segment((1,1),(2,2)))
        s.addSegment(Segment((2,2),(3,0)))
        self.assertEqual(s.points, [(0,0),(1,1),(2,2),(3,0)])
    def test_addShapes(self):
        s1 = Shape()
        s1.setPoints([(0,0),(1,1),(2,1),(3,0)])
        s2 = Shape()
        s2.setPoints([(2,0),(4,2),(5,0)])
        s3 = s1+s2
        self.assertEqual(s3.points, [(0,0),(1,1),(2,1),(2.5,0.5),(4,2),(5,0)])
示例#34
0
 def test_addSegment(self):
     s = Shape()
     s.addSegment(Segment((0,0),(1,1)))
     s.addSegment(Segment((1,1),(2,2)))
     s.addSegment(Segment((2,2),(3,0)))
     self.assertEqual(s.points, [(0,0),(1,1),(2,2),(3,0)])