示例#1
0
    def __init__(self, game, position=(0, 0), angle=0, is_inside=True, size=(1, 0.4), name='Hand'):
        width, height = size
        Composite.__init__(self, game, position, angle, is_inside=is_inside, name=name,
                           body=Rectangle(game,
                                          position=position,
                                          angle=angle,
                                          is_inside=is_inside,
                                          size=(height, height)))

        self.shoulder = self.body
        vertices = [(-width / 2, 0),
                    (-width / 4, height),
                    (0, height / 2),
                    (width / 2, height / 2),
                    (width / 2, -height / 2),
                    (-width / 4, -height)]

        forearm_pos = Vec2(position) + Vec2(-width / 2 + height / 2, 0)
        forearm_joint_pos = (width / 2 - height / 2, 0)

        self.forearm = FixtureObject(game,
                                     position=forearm_pos,
                                     angle=angle,
                                     is_inside=is_inside,
                                     vertices=vertices,
                                     name='forearm')

        self.add_part(self.forearm)
        '''
示例#2
0
文件: personage.py 项目: dregor/game
    def __init__(self, game, position=(0, 0), angle=0, additive=(0, 0), name='', speed=100, is_inside=True,
                 is_you=False, body=None, orientation=0):
        Composite.__init__(self, game=game, position=position, angle=angle, is_inside=is_inside, body=body)
        self.is_you = is_you
        self.name = name
        self.speed = speed
        self.additive = additive
        self.orientation = orientation

        for fixture in self.body.body.fixtures:
            fixture.filterData.maskBits = Bits.PERSONAGE_MASK
            fixture.filterData.categoryBits = Bits.PERSONAGE_BITS

        if self.is_you:
            self.center_box = self.game.world.CreateDynamicBody(position=self.get_position(),
                                                                shapes=B2.b2PolygonShape(box=(0.5, 0.5)))
            for item in self.center_box.fixtures:
                item.filterData.maskBits = Bits.NOTHING_MASK
                item.filterData.categoryBits = Bits.NOTHING_BITS

            self.game.world.CreatePrismaticJoint(bodyA=self.game.maw.center_box,
                                                 bodyB=self.center_box,
                                                 axis=(0, -1))

            self.game.world.CreateRevoluteJoint(bodyA=self.center_box,
                                                bodyB=self.body.body)
    def manufacture_nonprime_composite( self, the_nonprime ) :
        first_prime_factor = self.prime_factory.get_first_prime_factor( the_nonprime )
        second_factor = the_nonprime / first_prime_factor

        if ( first_prime_factor == second_factor ):
            return Composite( self.square_floor, first_prime_factor )
        if( self.prime_factory.is_prime( second_factor ) ):
            return Composite( self.square_floor, first_prime_factor, None, second_factor )

        return Composite( self.square_floor, first_prime_factor, self.composite_dictionary[ second_factor ] )
示例#4
0
文件: personage.py 项目: dregor/game
 def update(self):
     Composite.update(self)
     if not self.is_you:
         rand = randint(-3, 3)
         if rand != 0:
             self.move(rand)
     if self.MOVE_LEFT:
         self.move(-1)
     if self.MOVE_RIGHT:
         self.move()
示例#5
0
文件: personage.py 项目: dregor/game
    def event(self, event):
        Composite.event(self, event)
        if self.is_you:
            if event.type == KEYDOWN:
                key = pygame.key.get_pressed()

                if key[K_LEFT]:
                    self.MOVE_LEFT = True

                if key[K_RIGHT]:
                    self.MOVE_RIGHT = True

            if event.type == KEYUP:
                if event.key == K_LEFT:
                    self.MOVE_LEFT = False
                if event.key == K_RIGHT:
                    self.MOVE_RIGHT = False
    def setUp(self):
        """
        Sets up 3 2x2 arrays (self.arr1, self.arr2, self.arr3), 
        and from these:
        
          - writes 3 2x2 georeferenced geotiffs of different 
          values in a directory called 'test_composites'. 
          - creates a 3D array of these 3 arrays (self.arr)


        An instance of Composite (C) made with the a list of the 
        three geotiffs as input. 

        """

        self.arr1 = np.array([[1, 2], [3, 4]])
        self.arr2 = np.array([[5, 6], [7, 8]])
        self.arr3 = np.array([[9, 10], [11, 12]])

        self.arr = np.zeros((3, 2, 2))
        
        self.arr[0,...] = self.arr1
        self.arr[1,...] = self.arr2
        self.arr[2,...] = self.arr3

        os.mkdir('test_composites')

        self.outproj = osr.SpatialReference()
        self.outproj.SetWellKnownGeogCS("WGS84")        
        self.geotrans = [-180.0, 5, 0.0, 90.0, 0.0, -5]

        file_no = 1
        for a in [self.arr1, self.arr2, self.arr3]:
            
            outfile = gdal.GetDriverByName("GTiff")
            dst_ds  = outfile.Create('test_composites/file_{}.tif'.format(file_no), 2, 2, 1, gdal.GDT_Byte)
            
            dst_ds.SetProjection(self.outproj.ExportToWkt())
            dst_ds.SetGeoTransform(self.geotrans)

            band = dst_ds.GetRasterBand(1)
            band.WriteArray(a)
            file_no += 1

        self.filelist = ['test_composites/file_1.tif', 
                         'test_composites/file_2.tif',
                         'test_composites/file_3.tif']
        
        self.C = Composite(self.filelist)
示例#7
0
    def __new__(cls, **kwargs):
        stuff = copy.deepcopy(cls._pyhdl_stuff)
        gates = stuff['gate_list']
        inputs = stuff['inputs']
        outputs = stuff['outputs']
        internals = stuff['internals']
        gateDict = stuff['gates']

        for arg in kwargs:
            if arg in inputs:
                BridgeWire(kwargs[arg], inputs[arg])
            elif arg in outputs:
                BridgeWire(outputs[arg], kwargs[arg])

        return Composite(gates, inputs, outputs, internals, gateDict)
示例#8
0
  def convert(self, lg, choices = 1, adv_match = False, textures = TextureCache(), memory = 0):
    """Given a line graph this chops it into chunks, matches each chunk to the database of chunks and returns a new line graph with these chunks instead of the original. Output will involve heavy overlap requiring clever blending. choices is the number of options it select from the db - it grabs this many closest to the requirements and then randomly selects from them. If adv_match is True then instead of random selection from the choices it does a more advanced match, and select the best match in terms of colour distance from already-rendered chunks. This option is reasonably expensive. memory is how many recently use chunks to remember, to avoid repetition."""
    if memory > (choices - 1):
      memory = choices - 1

    # If we have no data just return the input...
    if self.empty(): return lg
    
    # Check if the indexing structure is valid - if not create it...
    if self.kdtree==None:
      data = numpy.array(map(lambda p: self.feature_vect(p[0], p[1]), self.chunks), dtype=numpy.float)
      self.kdtree = scipy.spatial.cKDTree(data, 4)
      
    # Calculate the radius scaler and distance for this line graph, by calculating the median radius...
    rads = map(lambda i: lg.get_vertex(i)[5], xrange(lg.vertex_count))
    rads.sort()
    median_radius = rads[len(rads)//2]
    radius_mult = 1.0 / median_radius
    
    dist = self.dist * median_radius
    
    # Create the list into which we dump all the chunks that will make up the return...
    chunks = []
    temp = LineGraph()
    
    # List of recently used chunks, to avoid obvious patterns...
    recent = []
    
    # If advanced match we need a Composite of the image thus far, to compare against...
    if adv_match:
      canvas = Composite()
      min_x, max_x, min_y, max_y = lg.get_bounds()
      canvas.set_size(int(max_x+8), int(max_y+8))
    
    # Iterate the line graph, choping it into chunks and matching a chunk to each chop...
    for chain in lg.chains():
      head = 0
      tail = 0
      length = 0.0
        
      while True:
        # Move tail so its long enough, or has reached the end...
        while length<dist and tail+1<len(chain):
          tail += 1
          v1 = lg.get_vertex(chain[tail-1])
          v2 = lg.get_vertex(chain[tail])
          length += numpy.sqrt((v1[0]-v2[0])**2 + (v1[1]-v2[1])**2)

        # Extract a feature vector for this chunk...
        temp.from_vertices(lg, chain[head:tail+1])
        fv = self.feature_vect(temp, median_radius)
        
        # Select a chunk from the database...
        if choices==1:
          selected = self.kdtree.query(fv)[1]
          orig_chunk = self.chunks[selected]
        else:
          options = list(self.kdtree.query(fv, choices)[1])
          options = filter(lambda v: v not in recent, options)
          if not adv_match:
            selected = random.choice(options)
            orig_chunk = self.chunks[selected]
          else:
            cost = 1e64 * numpy.ones(len(options))
            
            for i, option in enumerate(options):
              fn = filter(lambda t: t[0].startswith('texture:'), self.chunks[option][0].get_tags())
              if len(fn)!=0:
                fn = fn[0][0][len('texture:'):]
                tex = textures[fn]
                
                chunk = LineGraph()
                chunk.from_many(self.chunks[option][0])
                chunk.morph_to(lg, chain[head:tail+1])
              
                part = canvas.draw_line_graph(chunk)
                cost[i] = canvas.cost_texture_nearest(tex, part)
            
            selected = options[numpy.argmin(cost)]
            orig_chunk = self.chunks[selected]
        
        # Update recent list...
        recent.append(selected)
        if len(recent)>memory:
          recent.pop(0)

        # Distort it to match the source line graph...
        chunk = LineGraph()
        chunk.from_many(orig_chunk[0])
        chunk.morph_to(lg, chain[head:tail+1])
        
        # Record it for output...
        chunks.append(chunk)
        
        # If advanced matching is on write it out to canvas, so future choices will take it into account...
        if adv_match:
          fn = filter(lambda t: t[0].startswith('texture:'), chunk.get_tags())
          if len(fn)!=0:
            fn = fn[0][0][len('texture:'):]
            tex = textures[fn]

            part = canvas.draw_line_graph(chunk)
            canvas.paint_texture_nearest(tex, part)
         
        # If tail is at the end exit the loop...
        if tail+1 >= len(chain): break
          
        # Move head along for the next chunk...
        to_move = dist * self.factor
        while to_move>0.0 and head+2<len(chain):
          head += 1
          v1 = lg.get_vertex(chain[head-1])
          v2 = lg.get_vertex(chain[head])
          offset = numpy.sqrt((v1[0]-v2[0])**2 + (v1[1]-v2[1])**2)
          length -= offset
          to_move -= offset

    # Return the final line graph...
    ret = LineGraph()
    ret.from_many(*chunks)
    return ret
示例#9
0
文件: chunk_db.py 项目: zoginni/helit
    def convert(self,
                lg,
                choices=1,
                adv_match=False,
                textures=TextureCache(),
                memory=0):
        """Given a line graph this chops it into chunks, matches each chunk to the database of chunks and returns a new line graph with these chunks instead of the original. Output will involve heavy overlap requiring clever blending. choices is the number of options it select from the db - it grabs this many closest to the requirements and then randomly selects from them. If adv_match is True then instead of random selection from the choices it does a more advanced match, and select the best match in terms of colour distance from already-rendered chunks. This option is reasonably expensive. memory is how many recently use chunks to remember, to avoid repetition."""
        if memory > (choices - 1):
            memory = choices - 1

        # If we have no data just return the input...
        if self.empty(): return lg

        # Check if the indexing structure is valid - if not create it...
        if self.kdtree == None:
            data = numpy.array(map(lambda p: self.feature_vect(p[0], p[1]),
                                   self.chunks),
                               dtype=numpy.float)
            self.kdtree = scipy.spatial.cKDTree(data, 4)

        # Calculate the radius scaler and distance for this line graph, by calculating the median radius...
        rads = map(lambda i: lg.get_vertex(i)[5], xrange(lg.vertex_count))
        rads.sort()
        median_radius = rads[len(rads) // 2]
        radius_mult = 1.0 / median_radius

        dist = self.dist * median_radius

        # Create the list into which we dump all the chunks that will make up the return...
        chunks = []
        temp = LineGraph()

        # List of recently used chunks, to avoid obvious patterns...
        recent = []

        # If advanced match we need a Composite of the image thus far, to compare against...
        if adv_match:
            canvas = Composite()
            min_x, max_x, min_y, max_y = lg.get_bounds()
            canvas.set_size(int(max_x + 8), int(max_y + 8))

        # Iterate the line graph, choping it into chunks and matching a chunk to each chop...
        for chain in lg.chains():
            head = 0
            tail = 0
            length = 0.0

            while True:
                # Move tail so its long enough, or has reached the end...
                while length < dist and tail + 1 < len(chain):
                    tail += 1
                    v1 = lg.get_vertex(chain[tail - 1])
                    v2 = lg.get_vertex(chain[tail])
                    length += numpy.sqrt((v1[0] - v2[0])**2 +
                                         (v1[1] - v2[1])**2)

                # Extract a feature vector for this chunk...
                temp.from_vertices(lg, chain[head:tail + 1])
                fv = self.feature_vect(temp, median_radius)

                # Select a chunk from the database...
                if choices == 1:
                    selected = self.kdtree.query(fv)[1]
                    orig_chunk = self.chunks[selected]
                else:
                    options = list(self.kdtree.query(fv, choices)[1])
                    options = filter(lambda v: v not in recent, options)
                    if not adv_match:
                        selected = random.choice(options)
                        orig_chunk = self.chunks[selected]
                    else:
                        cost = 1e64 * numpy.ones(len(options))

                        for i, option in enumerate(options):
                            fn = filter(lambda t: t[0].startswith('texture:'),
                                        self.chunks[option][0].get_tags())
                            if len(fn) != 0:
                                fn = fn[0][0][len('texture:'):]
                                tex = textures[fn]

                                chunk = LineGraph()
                                chunk.from_many(self.chunks[option][0])
                                chunk.morph_to(lg, chain[head:tail + 1])

                                part = canvas.draw_line_graph(chunk)
                                cost[i] = canvas.cost_texture_nearest(
                                    tex, part)

                        selected = options[numpy.argmin(cost)]
                        orig_chunk = self.chunks[selected]

                # Update recent list...
                recent.append(selected)
                if len(recent) > memory:
                    recent.pop(0)

                # Distort it to match the source line graph...
                chunk = LineGraph()
                chunk.from_many(orig_chunk[0])
                chunk.morph_to(lg, chain[head:tail + 1])

                # Record it for output...
                chunks.append(chunk)

                # If advanced matching is on write it out to canvas, so future choices will take it into account...
                if adv_match:
                    fn = filter(lambda t: t[0].startswith('texture:'),
                                chunk.get_tags())
                    if len(fn) != 0:
                        fn = fn[0][0][len('texture:'):]
                        tex = textures[fn]

                        part = canvas.draw_line_graph(chunk)
                        canvas.paint_texture_nearest(tex, part)

                # If tail is at the end exit the loop...
                if tail + 1 >= len(chain): break

                # Move head along for the next chunk...
                to_move = dist * self.factor
                while to_move > 0.0 and head + 2 < len(chain):
                    head += 1
                    v1 = lg.get_vertex(chain[head - 1])
                    v2 = lg.get_vertex(chain[head])
                    offset = numpy.sqrt((v1[0] - v2[0])**2 +
                                        (v1[1] - v2[1])**2)
                    length -= offset
                    to_move -= offset

        # Return the final line graph...
        ret = LineGraph()
        ret.from_many(*chunks)
        return ret
示例#10
0
文件: personage.py 项目: dregor/game
 def draw(self):
     Composite.draw(self)
示例#11
0
def render(lg, border = 8, textures = TextureCache(), cleverness = 0, radius_growth = 3.0, stretch_weight = 0.5, edge_weight = 0.5, smooth_weight = 2.0, alpha_weight = 1.0, unary_mult = 1.0, overlap_weight = 0.0, use_linear = True):
  """Given a line_graph this will render it, returning a numpy array that represents an image (As the first element in a tuple - second element is how many graph cut problems it solved.). It will transform the entire linegraph to obtain a suitable border. The cleverness parameter indicates how it merges the many bits - 0 means last layer (stupid), 1 means averaging; 2 selecting a border using max flow; 3 using graph cuts to take into account weight as well."""

  # Setup the compositor...
  comp = Composite()
  min_x, max_x, min_y, max_y = lg.get_bounds()
  
  do_transform = False
  offset_x = 0.0
  offset_y = 0.0
  
  if min_x<border:
    do_transform = True
    offset_x = border-min_x
    
  if min_y<border:
    do_transform = True
    offset_y = border-min_y
  
  if do_transform:
    hg = numpy.eye(3, dtype=numpy.float32)
    hg[0,2] = offset_x
    hg[1,2] = offset_y
    
    lg.transform(hg)
    
    max_x += offset_x
    max_y += offset_y
  
  comp.set_size(int(max_x+border), int(max_y+border))


  # Break the lg into segments, as each can have its own image - draw & paint each in turn...
  lg.segment()
  duplicate_sets = dict()

  for s in xrange(lg.segments):

    slg = LineGraph()
    slg.from_segment(lg, s)
    part = comp.draw_line_graph(slg, radius_growth, stretch_weight)
    
    done = False
    fn = filter(lambda t: t[0].startswith('texture:'), slg.get_tags())
    if len(fn)!=0: fn = fn[0][0][len('texture:'):]
    else: fn = None
    
    for pair in filter(lambda t: t[0].startswith('duplicate:'), slg.get_tags()):
      key = pair[0][len('duplicate:'):]
      if key in duplicate_sets: duplicate_sets[key].append(part)
      else: duplicate_sets[key] = [part]
    
    tex = textures[fn]
    
    if tex!=None:
      if use_linear:
        comp.paint_texture_linear(tex, part)
      else:
        comp.paint_texture_nearest(tex, part)
      done = True
    
    if not done:
      comp.paint_test_pattern(part)

  
  # Bias towards pixels that are opaque...
  comp.inc_weight_alpha(alpha_weight)
  
  # Arrange for duplicate pairs to have complete overlap, by adding transparent pixels, so graph cuts doesn't create a feather effect...
  if overlap_weight>1e-6:
    for values in duplicate_sets.itervalues():
      for i, part1 in enumerate(values):
        for part2 in values[i:]:
          comp.draw_pair(part1, part2, overlap_weight)
  
  # If requested use maxflow to find optimal cuts, to avoid any real blending...
  count = 0
  if cleverness==2:
    count = comp.maxflow_select(edge_weight, smooth_weight, maxflow)
  elif cleverness==3:
    count = comp.graphcut_select(edge_weight, smooth_weight, unary_mult, maxflow)
  
  if cleverness==0:
    render = comp.render_last()
  else:
    render = comp.render_average()

  # Return the rendered image (If cleverness==0 this will actually do some averaging, otherwise it will just create an image)...
  return render, count
示例#12
0
 def event(self, event):
     Composite.event(self, event)
示例#13
0
 def update(self):
     Composite.update(self)
示例#14
0
# coding: utf-8

# In[1]:

from composite import Component, Leaf, Composite

# In[6]:

if __name__ == '__main__':

    composite = Composite()
    leaf1 = Leaf('leaf1')
    leaf2 = Leaf('leaf2')
    leaf3 = Leaf('leaf3')
    leaf4 = Leaf('leaf4')

    print('Adding leafs')

    composite.add(leaf1)
    composite.add(leaf2)
    composite.add(leaf3)
    composite.add(leaf4)
    composite.do()

    print('\nRemoving some leafs')
    composite.remove(leaf3)
    composite.remove(leaf1)
    composite.do()
示例#15
0
文件: generate.py 项目: zoginni/helit
def render(lg,
           border=8,
           textures=TextureCache(),
           cleverness=0,
           radius_growth=3.0,
           stretch_weight=0.5,
           edge_weight=0.5,
           smooth_weight=2.0,
           alpha_weight=1.0,
           unary_mult=1.0,
           overlap_weight=0.0,
           use_linear=True):
    """Given a line_graph this will render it, returning a numpy array that represents an image (As the first element in a tuple - second element is how many graph cut problems it solved.). It will transform the entire linegraph to obtain a suitable border. The cleverness parameter indicates how it merges the many bits - 0 means last layer (stupid), 1 means averaging; 2 selecting a border using max flow; 3 using graph cuts to take into account weight as well."""

    # Setup the compositor...
    comp = Composite()
    min_x, max_x, min_y, max_y = lg.get_bounds()

    do_transform = False
    offset_x = 0.0
    offset_y = 0.0

    if min_x < border:
        do_transform = True
        offset_x = border - min_x

    if min_y < border:
        do_transform = True
        offset_y = border - min_y

    if do_transform:
        hg = numpy.eye(3, dtype=numpy.float32)
        hg[0, 2] = offset_x
        hg[1, 2] = offset_y

        lg.transform(hg)

        max_x += offset_x
        max_y += offset_y

    comp.set_size(int(max_x + border), int(max_y + border))

    # Break the lg into segments, as each can have its own image - draw & paint each in turn...
    lg.segment()
    duplicate_sets = dict()

    for s in xrange(lg.segments):

        slg = LineGraph()
        slg.from_segment(lg, s)
        part = comp.draw_line_graph(slg, radius_growth, stretch_weight)

        done = False
        fn = filter(lambda t: t[0].startswith('texture:'), slg.get_tags())
        if len(fn) != 0: fn = fn[0][0][len('texture:'):]
        else: fn = None

        for pair in filter(lambda t: t[0].startswith('duplicate:'),
                           slg.get_tags()):
            key = pair[0][len('duplicate:'):]
            if key in duplicate_sets: duplicate_sets[key].append(part)
            else: duplicate_sets[key] = [part]

        tex = textures[fn]

        if tex is not None:
            if use_linear:
                comp.paint_texture_linear(tex, part)
            else:
                comp.paint_texture_nearest(tex, part)
            done = True

        if not done:
            comp.paint_test_pattern(part)

    # Bias towards pixels that are opaque...
    comp.inc_weight_alpha(alpha_weight)

    # Arrange for duplicate pairs to have complete overlap, by adding transparent pixels, so graph cuts doesn't create a feather effect...
    if overlap_weight > 1e-6:
        for values in duplicate_sets.itervalues():
            for i, part1 in enumerate(values):
                for part2 in values[i:]:
                    comp.draw_pair(part1, part2, overlap_weight)

    # If requested use maxflow to find optimal cuts, to avoid any real blending...
    count = 0
    if cleverness == 2:
        count = comp.maxflow_select(edge_weight, smooth_weight, maxflow)
    elif cleverness == 3:
        count = comp.graphcut_select(edge_weight, smooth_weight, unary_mult,
                                     maxflow)

    if cleverness == 0:
        render = comp.render_last()
    else:
        render = comp.render_average()

    # Return the rendered image (If cleverness==0 this will actually do some averaging, otherwise it will just create an image)...
    return render, count
示例#16
0
    def __init__(self, root, position="0 3 0", orientation="0. -1 0. 0.", density="1", scale="1", pinned="false", dim="8 2 8", restitution=None, friction=None, spinner=False, height="3", velocity="0 0 0", omega="0 0 0"):
        self.root = root
        self.position = position
        self.dim = dim.split()
        d = self.dim

        if not spinner:
            Box( root, name="platform", position=position, orientation=orientation, velocity=velocity, density=density, omega=omega, dim=dim, pinned=pinned, magnetic="false", restitution=restitution, friction=friction)
        else:
            composite = Composite( root, name="platform", obj=None, position=position, orientation=orientation, density=density, pinned=pinned, magnetic="false", restitution=restitution, friction=friction, velocity=velocity, omega=omega)
            dx=str(float(d[0])/2.-float(d[1])/2.)
            dy=str(float(height)/2.-float(d[1])/2.)
            dz=str(float(d[2])/2.-float(d[1])/2.)

            composite.addBox(position="0. 0. 0.", dim=d[0]+" "+d[1]+" "+d[2])
            composite.addBox(position="0. "+dy+" 0.", dim=d[0]+" "+height+" "+d[1])
            composite.addBox(position="0. "+dy+" "+dz, dim=d[0]+" "+height+" "+d[1])
            composite.addBox(position="0. "+dy+" -"+dz, dim=d[0]+" "+height+" "+d[1])
            composite.addBox(position="0. "+dy+" 0.", dim=d[1]+" "+height+" "+d[2])
            composite.addBox(position=" "+dx+" "+dy+" 0.", dim=d[1]+" "+height+" "+d[2])
            composite.addBox(position=" -"+dx+" "+dy+" 0.", dim=d[1]+" "+height+" "+d[2])
示例#17
0
    def addStand(self, k="3", d="10", width="5", height="20", springShift="0", orientation="0. -1 0. 0.", scale="1", obj=None, restitution=None, friction=None, thickness="1", pinned="false", weirdCoeff="10"):

        composite = Composite(self.root, name="stand", obj=obj, position="0 0 0", orientation=orientation, scale=scale, restitution=restitution, friction=friction, pinned=pinned)
        composite.addBox(dim=str(float(width)*2.+float(thickness))+" "+thickness+" "+thickness, position="0 "+height+" 0")
        composite.addBox(dim=thickness+" "+height+" "+thickness, position=width+" "+str(float(height)/2.)+" 0")
        composite.addBox(dim=thickness+" "+height+" "+thickness, position="-"+width+" "+str(float(height)/2.)+" 0")
        composite.addBox(dim=thickness+" "+thickness+" 10", position=width+" 0 0")
        composite.addBox(dim=thickness+" "+thickness+" 10", position="-"+width+" 0 0")
        stand = composite.get()

        dim = self.dim
        x = str(float(dim[0])/2.)
        y = str(float(dim[1])/2.)
        z = str(float(dim[2])/2.)
        pB = [x+" "+y+" "+z,
              "-"+x+" "+y+" "+z,
              "-"+x+" "+y+" -"+z,
              x+" "+y+" -"+z,]
        ybody2=self.position.split()[1]
        #com is moving weirdly with respect to width... (something wrong in Java code...)
        y = str(float(height)/2.+float(thickness)*2+float(weirdCoeff))
        pB2 = [springShift+" "+y+" 0",
              "-"+springShift+" "+y+" 0",
              "-"+springShift+" "+y+" 0",
              springShift+" "+y+" 0",]
        for i in range(4):
            spring = ET.SubElement(stand, 'spring')
            spring.set('pB', pB2[i])
            spring.set('k', k)
            spring.set('d', d)
            spring.set('body2', "platform")
            spring.set('pB2', pB[i])
示例#18
0
def admin(component1: Component, component2: Component) -> None:
    if component1.is_composite():
        component1.add(component2)

    print(f"Compras: {component1.operation()}", end="")
    print(f"Costo total: {component1.getCost()}", end="")


if __name__ == "__main__":

    simple = Shoes()
    print("Cliente: Quiero un par de zapatos:")
    client_code(simple)
    print("\n")

    tree = Composite()

    branch1 = Composite()
    branch1.add(Shoes())
    branch1.add(Socks())

    branch2 = Composite()
    branch2.add(Socks())

    tree.add(branch1)
    tree.add(branch2)

    print("Cliente: Tengo una lista de pedidos para dos personas:")
    client_code(tree)
    print("\n")
示例#19
0
class TestComp(unittest.TestCase):
    
    def setUp(self):
        """
        Sets up 3 2x2 arrays (self.arr1, self.arr2, self.arr3), 
        and from these:
        
          - writes 3 2x2 georeferenced geotiffs of different 
          values in a directory called 'test_composites'. 
          - creates a 3D array of these 3 arrays (self.arr)


        An instance of Composite (C) made with the a list of the 
        three geotiffs as input. 

        """

        self.arr1 = np.array([[1, 2], [3, 4]])
        self.arr2 = np.array([[5, 6], [7, 8]])
        self.arr3 = np.array([[9, 10], [11, 12]])

        self.arr = np.zeros((3, 2, 2))
        
        self.arr[0,...] = self.arr1
        self.arr[1,...] = self.arr2
        self.arr[2,...] = self.arr3

        os.mkdir('test_composites')

        self.outproj = osr.SpatialReference()
        self.outproj.SetWellKnownGeogCS("WGS84")        
        self.geotrans = [-180.0, 5, 0.0, 90.0, 0.0, -5]

        file_no = 1
        for a in [self.arr1, self.arr2, self.arr3]:
            
            outfile = gdal.GetDriverByName("GTiff")
            dst_ds  = outfile.Create('test_composites/file_{}.tif'.format(file_no), 2, 2, 1, gdal.GDT_Byte)
            
            dst_ds.SetProjection(self.outproj.ExportToWkt())
            dst_ds.SetGeoTransform(self.geotrans)

            band = dst_ds.GetRasterBand(1)
            band.WriteArray(a)
            file_no += 1

        self.filelist = ['test_composites/file_1.tif', 
                         'test_composites/file_2.tif',
                         'test_composites/file_3.tif']
        
        self.C = Composite(self.filelist)


    def test_create_arr(self):
        """
        Test to create a 3D array from input files. 

        Tests against self.arr which was created in 
        self.setUp()

        """
        
        test_arr = self.C.getarray(self.filelist)
        self.assertEqual(test_arr.all(), self.arr.all(), 'Composite.getarray produced wrong result')


    def test_average_arr(self):
        """
        Tests the mean and median calculation
        """
        
        av_arr_expected = np.array([[5, 6],[7, 8]])
        mean_arr_result = self.C.averagearr(self.arr, calculation='mean')
        median_arr_result = self.C.averagearr(self.arr, calculation='median')
        self.assertEqual(av_arr_expected.all(), mean_arr_result.all(), 'Mean calculation failed')
        self.assertEqual(av_arr_expected.all(), median_arr_result.all(), 'Median calculation failed')
       

    def test_save_arr(self):
        """
        Test whether the composite.savearr() method actually
        saves an array to a geotiff
        """

        self.C.savearr(self.arr1, 'test_composites/test_write.tif')
        self.assertTrue(os.path.exists('test_composites/test_write.tif'))


    def tearDown(self):
        shutil.rmtree('test_composites')
示例#20
0
    def __init__(self,
                 root,
                 body2,
                 dimBody2,
                 ybody2,
                 k="100",
                 d="10",
                 width="5",
                 height="20",
                 orientation="0. -1 0. 0.",
                 scale="1",
                 restitution=None,
                 friction=None,
                 thickness="1",
                 pinned="false"):

        composite = Composite(root,
                              obj=None,
                              name="stand",
                              position="0 0 0",
                              orientation=orientation,
                              scale=scale,
                              restitution=restitution,
                              friction=friction,
                              pinned=pinned)
        composite.addBox(dim=str(float(width) * 2. + float(thickness)) + " " +
                         thickness + " " + thickness,
                         position="0 " + height + " " + width)
        composite.addBox(dim=str(float(width) * 2. + float(thickness)) + " " +
                         thickness + " " + thickness,
                         position="0 " + height + " -" + width)
        composite.addBox(dim=thickness + " " + thickness + " " +
                         str(float(width) * 2. + float(thickness)),
                         position=width + " " + height + " 0")
        composite.addBox(dim=thickness + " " + thickness + " " +
                         str(float(width) * 2. + float(thickness)),
                         position=" -" + width + " " + height + " 0")
        composite.addBox(dim=thickness + " " + height + " " + thickness,
                         position=width + " " + str(float(height) / 2.) + " " +
                         width)
        composite.addBox(dim=thickness + " " + height + " " + thickness,
                         position="-" + width + " " + str(float(height) / 2.) +
                         " " + width)
        composite.addBox(dim=thickness + " " + height + " " + thickness,
                         position=width + " " + str(float(height) / 2.) +
                         " -" + width)
        composite.addBox(dim=thickness + " " + height + " " + thickness,
                         position="-" + width + " " + str(float(height) / 2.) +
                         " -" + width)
        stand = composite.get()

        dim = dimBody2.split()
        x = str(float(dim[0]) / 2.)
        y = str(float(dim[1]) / 2.)
        z = str(float(dim[2]) / 2.)
        pB2 = [
            x + " " + y + " " + z,
            "-" + x + " " + y + " " + z,
            "-" + x + " " + y + " -" + z,
            x + " " + y + " -" + z,
        ]
        y = str(float(height) - float(ybody2) + float(thickness) * 2)
        pB = [
            str(float(width)) + " " + y + " " + str(float(width)),
            "-" + str(float(width)) + " " + y + " " + str(float(width)),
            "-" + str(float(width)) + " " + y + " -" + str(float(width)),
            str(float(width)) + " " + y + " -" + str(float(width))
        ]
        for i in range(4):
            spring = ET.SubElement(stand, 'spring')
            spring.set('pB', pB[i])
            spring.set('k', k)
            spring.set('d', d)
            spring.set('body2', body2)
            spring.set('pB2', pB2[i])