예제 #1
0
 def __init__(self, state, position, momentum):
     Particle.__init__(self, state, position, momentum)
     self.values.set('ignoreDrag', True)
     self.values.set('ignoreGravity', True)
     self.values.add('attraction', 300)
     self.physicsName = 'attractors'
     self.name = 'attractor'
예제 #2
0
 def __genElasticConn(self, particle, elasticParticles):
     '''
     Find elastc neighbour for particle
     extend elastic connections list
     '''
     nMi = elasticParticles.index(particle)*self.nMuscles/len(elasticParticles);
     neighbour_collection = [p for p in elasticParticles if Particle.dot_particles(particle, p) <= Const.r0_squared * 3.05 and p != particle ]
     neighbour_collection.sort(key=lambda p: Particle.distBetween_particles(particle, p))
     if len(neighbour_collection) > Const.MAX_NUM_OF_NEIGHBOUR:
         neighbour_collection = neighbour_collection[0:Const.MAX_NUM_OF_NEIGHBOUR]
     elastic_connections_collection = []
     for p in neighbour_collection:
         nMj = elasticParticles.index(p) * self.nMuscles / len(elasticParticles)
         val1 = 0
         if self.nMuscles > 0:
             if nMj == nMi:
                 dx2 = particle.position.x - p.position.x
                 dy2 = particle.position.y - p.position.y
                 dz2 = particle.position.z - p.position.z
                 dx2 *= dx2
                 dy2 *= dy2
                 dz2 *= dz2 
                 val1 = (1.1+nMi)*float((dz2 > 100*dx2)and(dz2 > 100*dy2))  
         elastic_connections_collection.append( ElasticConnection(self.particles.index(p),Particle.distBetween_particles(p,particle), val1, 0) )
     '''
     If number of elastic connection less that MAX_NUM_OF_NEIGHBOUR then 
     we extend collection of elastic connection with non particle value
     '''
     if len(neighbour_collection) < Const.MAX_NUM_OF_NEIGHBOUR:
         elastic_connections_collection.extend([ElasticConnection(Const.NO_PARTICEL_ID,0,0,0)] * (Const.MAX_NUM_OF_NEIGHBOUR - len(neighbour_collection)) )
     self.elasticConnections.extend( elastic_connections_collection )
예제 #3
0
def create_population(population):
    pop = []
    for particle in xrange(population):
        particle = Particle()
        particle.initialize()
        pop.append(particle)
    return pop
예제 #4
0
def create_population(population):
	pop = []
	for particle in xrange(population):
		particle = Particle()
		particle.initialize()
		pop.append(particle)
	return pop
예제 #5
0
파일: Schema.py 프로젝트: vimov/Deployer
 def installInstanceAttrs(self,sschema):
   sschema.eltStack=['a']              # hack
   for (attrn,basen) in _instanceAttrs:
     fake=attributeElt(sschema,None)
     fake.name=attrn
     fake.type=basen
     fake.init(None)
     fake.component.typeDefinitionName=QName(None,basen,
                                                       XMLSchemaNS)
     self.attributeTable[attrn]=fake.component
   for (attrn,itemn) in _instanceLists:
     fake=attributeElt(sschema,None)
     fake.name=attrn
     fake.simpleType=simpleTypeElt(sschema,None)
     fake.simpleType.list=listElt(sschema,None)
     fake.simpleType.list.init(None)
     fake.simpleType.list.component.itemtypeName=QName(None,itemn,
                                                                 XMLSchemaNS)
     fake.simpleType.init(None)
     fake.simpleType.component.variety='list'
     fake.simpleType.component.basetype=Type.urSimpleType
     fake.init(None)
     wf=Whitespace(sschema,None)
     wf.value='collapse'
     wf.fixed=1
     fake.simpleType.component.facets={'whiteSpace':wf}
     self.attributeTable[attrn]=fake.component
   sschema.eltStack=[]              # hack
   ap=Particle(sschema,None,
                         AnyAny(sschema,None),None)
   ap.term.processContents='lax'
   ap.occurs=(0,None)
예제 #6
0
 def __generateNMuscle(self):
     '''
     Generate nMuscles connected muscle
     '''
     nEx = 7
     nEy = 4
     nEz = 1  #7
     for nM in range(self.nMuscles):
         for x in range(nEx):
             for y in range(nEy):
                 for z in range(nEz):
                     p_x = Const.xmax / 2.0 + float(
                         x) * Const.r0 - nEx * Const.r0 / 2.0 - Const.r0 * (
                             nEx) / 2.0 + Const.r0 * (nEx +
                                                      0.4) * float(nM > 2)
                     p_y = Const.ymax / 2.0 + y * Const.r0 - nEy * Const.r0 / 2.0
                     p_z = Const.zmax / 2.0 + z * Const.r0 - nEz * Const.r0 / 2.0 - (
                         nM <= 2) * (nM - 1) * (nEz * Const.r0) - float(
                             nM > 2) * (
                                 Const.r0 / 2 +
                                 (nM - 4) * Const.r0) * nEz - (
                                     nM == 1) * Const.r0 / 2.5 - (
                                         nM == 2) * Const.r0 * 2 / 2.5 + (
                                             nM == 4) * Const.r0 / 2.5
                     particle = Particle(p_x, p_y, p_z,
                                         Const.elastic_particle)
                     particle.setVelocity(
                         Float4(0.0, 0.0, 0.0, Const.elastic_particle))
                     self.particles.append(particle)
예제 #7
0
    def testSpecificParticleNormalizedWeightsAfterResampling(self):
        self.p_distrib.particle_list = [
            Particle(x=1.1026683979627143,
                     y=1.3169624148597046,
                     theta=204,
                     weight=0.0409339465492),
            Particle(x=0.4660179516836995,
                     y=0.3570517416074323,
                     theta=305,
                     weight=0.199876196252),
            Particle(x=1.9121964510843559,
                     y=0.49645320731338294,
                     theta=209,
                     weight=0.1986675867),
            Particle(x=1.1026683979627143,
                     y=1.3169624148597046,
                     theta=204,
                     weight=0.0409339465492),
            Particle(x=0.20860576164448363,
                     y=0.2618577992238944,
                     theta=318,
                     weight=0.199474254139)
        ]
        print("Weird Distrib")
        self.p_distrib.print_distribution()

        self.p_distrib.normalize_weights()
        self.assertTrue(abs(1 - sum(self.p_distrib.get_weights())) <= 0.0001)
예제 #8
0
    def add_particles(self, n=1, **kargs):
        """
            Add an amount n of particles with the past kargs
        """
        margin = 10
        for i in range(n):
            repeat = True
            while repeat:
                inside = False
                radius = kargs.get('radius', random.randint(10, 15))
                pos = kargs.get('pos', (random.randint(radius+margin, self.width-radius-margin),\
                                       random.randint(radius+margin, self.height-radius-margin)))
                color = kargs.get('color', random_color_vibrant())
                speed = kargs.get('speed', random.randint(20, 100))
                vel = vector2(0, 1).rotate(random.uniform(0, 360)) * speed
                new_particle = Particle(pos, radius, color)
                new_particle.vel = vel

                if 'pos' not in kargs:
                    for particles in self.particles:
                        if particles.inside(new_particle):
                            inside = True
                            break

                if inside == False:
                    self.particles.append(new_particle)
                    repeat = False
예제 #9
0
    def __init__(self):
        rospy.init_node("propagation_test_node")

        self.tf_helper = TFHelper()

        self.base_link_pose = PoseStamped()
        self.base_link_pose.header.frame_id = "base_link"
        self.base_link_pose.header.stamp = rospy.Time(0)

        self.last_odom_pose = PoseStamped()
        self.last_odom_pose.header.frame_id = "odom"
        self.last_odom_pose.header.stamp = rospy.Time(0)

        self.particle_pose_pub = rospy.Publisher('/particle_pose_array',
                                                 PoseArray,
                                                 queue_size=10)
        self.odom_pose_pub = rospy.Publisher('/odom_pose',
                                             PoseArray,
                                             queue_size=10)

        self.pose_array = PoseArray()
        self.pose_array.header.stamp = rospy.Time(0)
        self.pose_array.header.frame_id = "odom"

        self.p = Particle(x=0, y=0, theta=180, weight=0)
        self.p_array = PoseArray()
        self.p_array.header.stamp = rospy.Time(0)
        self.p_array.header.frame_id = "map"

        self.is_first = True
예제 #10
0
파일: Schema.py 프로젝트: vimov/Deployer
 def doBuiltIns(self,sschema):
   self.doAbInitios(sschema)
   # TODO: implement fixed facets
   for (bitn,basen,facets,idt) in builtinTypeNames:
     fake=simpleTypeElt(sschema,None)
     fake.name=bitn
     fake.restriction=restrictionElt(sschema,None)
     fake.restriction.init(None)
     fake.init(None)
     fake.component.basetypeName=QName(None,basen,XMLSchemaNS)
     fake.component.variety='atomic'
     fake.component.idt=idt
     bit=fake.restriction.component
     bit.builtin=1
     bit.rootName=fake.component.basetype.rootName
     self.typeTable[bitn]=fake.component
     for (fc,fv) in facets:
       nf=fc(sschema,None)
       fake.restriction.facets[fc.name]=nf
       if fc.name=="pattern":
         nf.stringValue=fv
       else:
         nf.value=fv
   for (bitn,basen,idt) in builtinLists:
     fake=simpleTypeElt(sschema,None)
     fake.name=bitn
     fake.list=listElt(sschema,None)
     fake.list.init(None)
     fake.init(None)
     fake.component.basetype=Type.urSimpleType
     fake.component.variety='list'
     fake.list.component.itemtypeName=QName(None,basen,XMLSchemaNS)
     wf=Whitespace(sschema,None)
     wf.value='collapse'
     wf.fixed=1
     mf=MinLength(sschema,None)
     mf.value=1
     fake.component.facets={'whiteSpace':wf,'minLength':mf}
     fake.component.idt=idt
     self.typeTable[bitn]=fake.component
   ap=Particle(sschema,None,
                         AnyAny(sschema,None),None)
   ap.term.processContents='lax'
   ap.occurs=(0,None)
   if not Type.urType.model.term.particles:
     Type.urType.model.term.particles.append(ap)
     au=AttributeUse(sschema,None,
                               AnyAny(sschema,None),'optional')
     au.attributeDeclaration.processContents='lax'
     Type.urType.attributeDeclarations={'#any':au}
   else:
     shouldnt('dbl ur')
   self.typeTable['anyType']=Type.urType
   Type.urSimpleType.schema=Type.urType.schema=self
   Type.urSimpleType.sschema=Type.urType.sschema=sschema
   ws=Whitespace(sschema,None)
   ws.value="preserve"
   Type.urSimpleType.facets['whiteSpace']=ws
   self.typeTable['anySimpleType']=Type.urSimpleType
예제 #11
0
 def buildSwarm(self):
     #build sizeSwarm particles, by defualt they are initialized randomly
     for i in range(self.sizeSwarm):
         p = Particle(self.dimension, self.function, self.funcType)
         p.randomInit()
         self.particles += [p]
     #check for global best
     self.updateGlobalBest()
예제 #12
0
 def buildSwarm(self, weights):
     #build sizeSwarm particles, by defualt they are initialized randomly
     for i in range(self.sizeSwarm):
         p = Particle(self.dimension, self.trainTeser)
         p.seedInit(weights, self.seedRadius, self.seedVelocity)
         self.particles += [p]
     #check for global best
     self.updateGlobalBest()
예제 #13
0
 def addParticles(self, count: int):
     gen = QRandomGenerator()
     for i in range(count):
         # print(random(self.scene.width()))
         part = Particle(QPointF(gen.bounded(self.width()),\
             gen.bounded(self.height())))
         part.setVisible(False)
         self.addItem(part)
예제 #14
0
def update_global_best(population, current_best=None):
    population.sort(key=lambda k: k.cost)
    best = population[0]
    if (current_best == None or best.cost <= current_best.cost):
        current_best = Particle()
        current_best = best
        current_best.position = best.best_position[:]
        current_best.cost = best.cost
    return current_best
예제 #15
0
def test_visualize():
    particles = [
        Particle(0.3, 0.5, 1),
        Particle(0.0, -0.5, -1),
        Particle(-0.1, -0.4, 3)
    ]

    simulator = ParticleSimulator(particles)
    visualize(simulator)
def test_Particle_should_move_with_constant_velocity(r, x, y, vx, vy):
    p = Particle(r, (x, y), (vx, vy))
    dt = 10
    p.move(dt)
    assert p.r == r
    assert p.x == x + dt * p.vx
    assert p.y == y + dt * p.vy
    assert p.vx == vx
    assert p.vy == vy
예제 #17
0
def update_global_best( population, current_best= None):
	population.sort(key=lambda k: k.cost)
	best = population[0]
	if (current_best == None or best.cost <= current_best.cost):
		current_best = Particle()
		current_best = best
		current_best.position = best.best_position[:]
		current_best.cost = best.cost
	return current_best
def test_Particle_bounce_should_be_elastic(comment, r, x, y, vx, vy, xmin,
                                           xmax, ymin, ymax, x_new, y_new,
                                           vx_new, vy_new):
    p = Particle(r, (x, y), (vx, vy))
    p.bounce((xmin, xmax, ymin, ymax))
    assert p.x == x_new
    assert p.y == y_new
    assert p.vx == vx_new
    assert p.vy == vy_new
예제 #19
0
def test_Particle_should_move_with_constant_velocity(r,x,y,vx,vy):
    p = Particle(r, (x,y), (vx,vy), COL)
    dt = 10
    p.move(dt)
    assert p.r    ==  r
    assert p.p.x  ==  x + dt * p.v.x
    assert p.p.y  ==  y + dt * p.v.y
    assert p.v.x  == vx
    assert p.v.y  == vy
def test_bounce_should_leave_Particle_within_boundaries(
        comment, r, x, y, vx, vy, xmin, xmax, ymin, ymax, x_new, y_new, vx_new,
        vy_new):
    p = Particle(r, (x, y), (vx, vy))
    p.bounce((xmin, xmax, ymin, ymax))
    assert p.x + p.r <= xmax
    assert p.x - p.r >= xmin
    assert p.y + p.r <= ymax
    assert p.y - p.r >= ymin
예제 #21
0
    def test_step1(self):

        p = Particle(
            -83.3685483757,
            -56.9606215782,
            -5.71920888457,
            -1.81401481103
        )

        p.take_step((0, 0), 100)
예제 #22
0
    def test_step2(self):

        p = Particle(
            5.27467021743,
            -9.44845648513,
            -0.280971148454,
            -0.95971621521
        )

        p.take_step((0, 0), 10)
예제 #23
0
파일: Timebubble.py 프로젝트: jogi1/energy
 def __init__(self, state, position, momentum):
     Particle.__init__(self, state, position, momentum)
     self.values.set('ignoreGravity', True)
     self.values.set('ignoreDrag',  True)
     self.values.set('unattractable', True)
     self.values.add('timeScale', 0.01)
     self.values.add('timeRadius', 200)
     self.timeRadius = 200
     self.physicsName = 'timebubbles'
     self.name = 'timebubble'
예제 #24
0
 def __init__(self, state, position, momentum):
     Particle.__init__(self, state, position, momentum)
     self.values.set('ignoreGravity', True)
     self.values.set('ignoreDrag', True)
     self.values.set('unattractable', True)
     self.values.add('timeScale', 0.01)
     self.values.add('timeRadius', 200)
     self.timeRadius = 200
     self.physicsName = 'timebubbles'
     self.name = 'timebubble'
예제 #25
0
def main():
    pygame.init()
    clock = pygame.time.Clock()  
    pygame.key.set_repeat(1, 50)
    size = FIELD_SIZE, FIELD_SIZE
    screen = pygame.display.set_mode(size)
    font = pygame.font.SysFont("Courier New", 18)
    black = 0, 0, 0
    
    ball = Particle(screen.get_rect(), max_speed=15, color=(125,5,230), gravity=GRAVITY,friction=FRICTION_COEFFICIENT)
    
    done = False
    
    while not done:
        dt = clock.tick(FRAME_RATE) #limit to 120 fps
        screen.fill(black)
        read_keyboard()
        
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
                
        # ball.move_keyboard(pygame.key.get_pressed(),KEY_ACCEL)
        ball.move_mouse(50/FRAME_RATE)
        ball.movetowards((450,450),KEY_ACCEL)
        
        ball.move()
        ball.draw(screen)  
        
        pygame.display.flip()
    pygame.quit()
예제 #26
0
 def __init__(self, physworld, gravity, pos):
     self.mWorld = physworld
     self.__mParticles = []
     
     for x in range(self.__mNrOfParticles):
         rs = random.uniform(0.03, 0.12)
         particle = Particle(physworld, -gravity/4.0, b2Vec2(rs, rs), min(rs * 10, 1), pos)
         randDir = b2Vec2(random.uniform(-0.5, 0.5), random.uniform(-0.8, 0.2))
         randDir.Normalize()
         particle.mVelocity = randDir * (particle.mSpeed * random.uniform(0.2, 1.5))         
         self.__mParticles.append(particle)
예제 #27
0
 def getParticle(self,id):
     par = Particle()
     icounter = 0
     for line in self.eventArray:
         items = line.split()
         #print '--> items printout' ,items
         if(icounter!=0):
             if(int(items[2])==1 and int(items[3])==id):
                 par.set(id,float(items[6]),float(items[7]),float(items[8]))
         icounter = icounter + 1
     return par
	def extract_particles(self, p_type, line, xml_pattern, vertex_pattern):
		particles = []
		for xml in re.finditer(xml_pattern, line.rstrip()):
			for vertex in re.finditer(vertex_pattern, xml.group(2)):
				p_x = vertex.group(1)
				p_y = vertex.group(2)
				p_z = vertex.group(3)						
				particle = Particle(float(p_x),float(p_y),float(p_z),float(p_type))
				particle.setVelocity(Float4(0.0,0.0,0.0,float(p_type)))
				particles.append(particle)		

		return particles
예제 #29
0
 def getParticle(self, id):
     par = Particle()
     icounter = 0
     for line in self.eventArray:
         items = line.split()
         #print '--> items printout' ,items
         if (icounter != 0):
             if (int(items[2]) == 1 and int(items[3]) == id):
                 par.set(id, float(items[6]), float(items[7]),
                         float(items[8]))
         icounter = icounter + 1
     return par
예제 #30
0
 def createParticles(self, n):
     for i in range(n):
         # x = np.random.rand()*10-5
         # y = np.random.rand()*10-5
         # theta = (np.random.rand()*2*np.pi)-np.pi
         groundTruthStart = self.data.robots[
             self.robotId].groundTruthPosition[0]
         x = groundTruthStart[1]
         y = groundTruthStart[2]
         theta = groundTruthStart[3]
         p = Particle(self.n, [x, y, theta], self.data.map, i)
         self.particles.append(p.copy())
def test_EulerCromer():
    """
    This test checks that the Euler Cromer method is correctly updating a particle's position and
    velocity.
    """
    proton = Particle('proton', const.m_p, [0,0,0], [-100,200,300], [10,20,-30])
    deltaT = 0.5
    calculated_velocity = np.array([-95,210,285], dtype=float)
    calculated_position = np.array([-47.5,105,142.5], dtype=float)
    proton.eulerCromer(deltaT)
    assert np.array_equal(calculated_velocity,proton.velocity)
    assert np.array_equal(calculated_position,proton.position)
예제 #32
0
def test_bounce_should_leave_Particle_within_boundaries(
    comment,
    r,x,y,vx,vy,
    xmin, xmax,   ymin, ymax,
    x_new, y_new, vx_new, vy_new
    ):

    p = Particle(r, (x,y), (vx,vy), COL)
    p.bounce((xmin, xmax, ymin, ymax))
    assert p.p.x + p.r <= xmax
    assert p.p.x - p.r >= xmin
    assert p.p.y + p.r <= ymax
    assert p.p.y - p.r >= ymin
예제 #33
0
파일: main.py 프로젝트: cschlick/TrimerSSA
def seed(trimer_generator, options):
    seed_vertex1 = Vertex(np.array([198.829, 170.530, 360.401]))
    seed_vertex2 = Vertex(np.array([161.790, 244.135, 376.374]))
    seed_vertex3 = Vertex(np.array([124.752, 199.392, 315.765]))
    seed_edge1 = Edge([seed_vertex1, seed_vertex2])
    seed_edge2 = Edge([seed_vertex2, seed_vertex3])
    seed_edge3 = Edge([seed_vertex3, seed_vertex1])
    seed_trimer = Trimer([seed_edge1, seed_edge2, seed_edge3])
    seed_center = np.array([231.149, 245.5, 262.1035])
    particle = Particle(seed_trimer,
                        trimer_generator=trimer_generator,
                        options=options)
    particle.centroid = seed_center
    return particle
예제 #34
0
def test_Particle_bounce_should_be_elastic(
    comment,
    r,
    x,y,vx,vy,
    xmin, xmax,   ymin, ymax,
    x_new, y_new, vx_new, vy_new
    ):
    
    p = Particle(r, (x,y), (vx,vy), COL)
    p.bounce((xmin, xmax, ymin, ymax))
    assert p.p.x ==  x_new
    assert p.p.y ==  y_new
    assert p.v.x == vx_new
    assert p.v.y == vy_new
예제 #35
0
    def __init__(self, particles, rows, columns):
        self.map = Map(columns, rows)

        first_half = [
            Particle(random.randint(1, columns // 2), random.randint(1, rows),
                     'g') for x in range(particles // 2)
        ]
        second_half = [
            Particle(random.randint(columns // 2 + 1, columns),
                     random.randint(1, rows), 'r')
            for x in range(particles // 2 + (1 if particles % 2 == 0 else 0))
        ]

        self.particles = first_half + second_half
 def populate(self, num_particle=50):
     """Populates the _field with randomly-positioned _particles.
     """
     self._field.clear()
     particle_new = Particle(Position(max=self.size), Direction(),
                             self._colours.get(State.INFECTED), self._field)
     self._particles.append(particle_new)
     for p in range(num_particle - 1):
         position = Position(
             max=self.size)  # generate 0 <= random Position < size
         direction = Direction()
         color = self._colours.get(State.SUSCEPTIBLE)
         particle_new = Particle(position, direction, color, self._field)
         self._particles.append(particle_new)
예제 #37
0
 def generate_particle(self):
     self.paint_gl = 0
     self.start_time = time.clock()
     self.start_time_gl = time.clock()
     N_p = int(self.lineEdit_N.text())
     del particle_system[:]
     particle_system.append(
         Particle(Coord(0, 0, 0), Speed(0, 0, 0), 1000, (0.1, 0.1, 0.8)))
     self.number = N_p
     if counts != 0:
         self.number = counts
     for i in range(1, self.number):
         crd = Coord(random.randint(-100, 100), random.randint(-100, 100),
                     random.randint(-100, 100))
         vel = Speed(
             random.randint(-10, 10) / 100000.0,
             random.randint(-10, 10) / 100000.0,
             random.randint(-10, 10) / 100000.0)
         mass = random.uniform(1, 500)
         rgb_col = [
             random.uniform(0.0, 1.0),
             random.uniform(0.0, 1.0),
             random.uniform(0.0, 1.0)
         ]
         particle_system.append(Particle(crd, vel, mass, rgb_col))
     self.gl_widget_.update()
     if self.comboBox.currentIndex() == 1:
         # self.timer_1.timeout.connect(self.gl_widget_.verlet)
         # self.timer_1.start(10)
         self.gl_widget_.verlet()
     if self.comboBox.currentIndex() == 0:
         self.gl_widget_.verlet_scipy()
     if self.comboBox.currentIndex() == 2:
         print('index = 2')
         self.vrl_slv.verlet__scipy()
     if self.comboBox.currentIndex() == 3:
         print('index = 3')
         self.vrl_slv.verlet__()
     if self.comboBox.currentIndex() == 4:
         print('index = 4')
         self.vrl_slv.verlet_threading()
     if self.comboBox.currentIndex() == 5:
         print('index = 5')
         self.vrl_slv.verlet_cython()
     if self.comboBox.currentIndex() == 6:
         print('index = 5')
         self.vrl_slv.verlet_opencl()
     self.gl_widget_.update()
예제 #38
0
 def createPopulation(self):
     population = []
     max_coords = []
     min_coords = []
     max_velocities = []
     min_velocities = []
     for velocity in self.vel_range:
         min_velocities.append(velocity[0])
         max_velocities.append(velocity[1])
     for coord in self.search_space:
         min_coords.append(coord[0])
         max_coords.append(coord[1])
     for i in range(0, self.population_size):
         population.append(
             Particle(coord_max=max_coords,
                      coord_min=min_coords,
                      min_vel=min_velocities,
                      max_vel=max_velocities,
                      fitness_func=self.fitness_func))
     for index, particle in enumerate(population):
         pos_before = index - 1
         pos_after = (index + 1) % self.population_size
         particle.setNeighborhood(
             [population[pos_before], population[pos_after]])
     self.population = population
예제 #39
0
    def __init__(self, w, a1, a2, dim, population_size, time_steps,
                 search_range, points):

        # Here we use values that are (somewhat) known to be good
        # There are no "best" parameters (No Free Lunch), so try using different ones
        # There are several papers online which discuss various different tunings of a1 and a2
        # for different types of problems
        self.w = w  # Inertia
        self.a1 = a2  # Attraction to personal best
        self.a2 = a2  # Attraction to global best
        self.dim = dim
        self.swarm = []

        for label in points:
            temp_swarm = [
                Particle(dim, -search_range, search_range, points[label],
                         label, points)
                for i in range(int(population_size / 2))
            ]
            self.swarm += temp_swarm

        self.X = [p.position for p in self.swarm]
        self.Y = [p.label for p in self.swarm]

        print(self.X)
        print(self.Y)

        self.time_steps = time_steps

        # Initialising global best, you can wait until the end of the first time step
        # but creating a random initial best and fitness which is very high will mean you
        # do not have to write an if statement for the one off case

        self.best_swarm_pos = np.random.uniform(low=-500, high=500, size=dim)
        self.best_swarm_fitness = 1e100
예제 #40
0
def LoadMembrane():
    InitialState = pickle.load(open('Membranes/' + membrane_id, 'rb'))

    particles = []
    springs = []

    for i_p in range(0, len(InitialState['particles']['pos'])):
        p = Particle(i_p, InitialState['particles']['pos'][i_p],
                     InitialState['particles']['mass'][i_p],
                     InitialState['particles']['fixed'][i_p],
                     InitialState['particles']['w_feed'][i_p],
                     InitialState['particles']['w_in'][i_p])
        particles.append(p)

    for i_s in range(0, len(InitialState['springs']['l0'])):
        s = Spring(InitialState['springs']['l0'][i_s],
                   InitialState['springs']['p1'][i_s],
                   InitialState['springs']['p2'][i_s],
                   InitialState['springs']['k'][i_s],
                   InitialState['springs']['d'][i_s])
        springs.append(s)

    m = InitialState['mesh']
    n = InitialState['nb_edge']
    id = InitialState['id']
    w = InitialState['washout_time']
    dim = InitialState['net_dim']

    M = MembraneSystem(particles, springs, m, n, dim)
    M.network_id = id
    M.washout_time = w

    return M
예제 #41
0
 def generateRandomParticle(self):
     x = np.random.uniform(MIN_X, MAX_X)
     z = np.random.uniform(MIN_Z, MAX_Z)
     angle = np.random.uniform(MIN_ANGLE, MAX_ANGLE)
     weight = 1.0
     # print("x: %f, z: %f, angle: %f" % (x,z,angle))
     return Particle(x, z, angle, weight)
예제 #42
0
파일: Swarm.py 프로젝트: bl21812/SixHumpPSO
    def __init__(self, popSize, c1, c2):
        length = int(math.sqrt(popSize))
        self.pop = numpy.empty([length, length], dtype=Particle)
        self.c1 = c1
        self.c2 = c2
        self.phi = c1 + c2

        self.bestPerGen = []  # Stores value of best sol per generation
        self.bestSol = [0, 0]
        self.bestSolValue = 99999
        self.averagePerGen = []  # Stores average fitness per generation

        self.iter = 0

        for i in range(length):  # init pop
            for j in range(length):
                tempX = random.random() * 10.0 - 5.0
                tempY = random.random() * 10.0 - 5.0
                initW = 0.792
                self.pop[i][j] = Particle([tempX, tempY], [0, 0], initW)
        for i in range(length):  # init neighbours for pop
            for j in range(length):
                self.setNeighbours(i, j, self.pop[i][j])
        # Set neighbourhood best values
        for i in range(len(self.pop)):
            for j in range(len(self.pop)):
                self.pop[i][j].nbestUpdate()
def test_Particle_constructor_should_set_basic_attributes(r, x, y, vx, vy):
    p = Particle(r, (x, y), (vx, vy))
    assert p.r == r
    assert p.x == x
    assert p.y == y
    assert p.vx == vx
    assert p.vy == vy
예제 #44
0
def meta_pso(algorithm, ft, dimensions, bounds, m_stop_count, stop_prec,
             m_fitness, timeout):
    swarm = []
    for i in range(m_parts):
        swarm.append(Particle(bounds))
    res = {"params": [0] * dimensions, "fit": 0, "value": 100, "time": 100}
    for i in range(m_stop_count):
        tournament = []
        for particle in swarm:
            particle.update_v(res["params"], m_cp, m_cs, m_cg)
            particle.update_pos(bounds)
            ftres = {"value": 0, "time": 0}

            # print("\na: {}, d_prec: {}".format(particle.pos[0], particle.pos[1]))

            lcount = 5
            for j in range(lcount):
                tmpres = algorithm(ft, 2, [[-10, 10], [-10, 10]],
                                   round(particle.pos[1]), stop_prec,
                                   particle.pos[0], 0.1, 0.75,
                                   round(particle.pos[2]), m_fitness[0],
                                   timeout)
                ftres["value"] += tmpres["fvalue"]
                ftres["time"] += tmpres["time"]
            ftres["value"] /= lcount
            ftres["time"] /= lcount

            tournament.append([particle.pos,
                               [ftres["value"],
                                ftres["time"]]])  # adding result to tournament

            # fit = m_fitness([ftres["value"], ftres["time"]])
            #
            # # print(ftres, fit)
            #
            # if fit > particle.best_fit:
            #     particle.best = particle.pos
            #     particle.best_fit = fit

        board, winner_i = best_tournament(tournament, m_fitness, 2)

        print(tournament[winner_i])

        for j in range(m_parts):
            if board[j] > swarm[j].best_fit:
                swarm[j].best_fit = board[j]
                swarm[j].best = tournament[j][0]
                if swarm[j].best_fit > res["fit"]:
                    res["params"] = swarm[j].best
                    res["fit"] = swarm[j].best_fit
                    res["value"] = tournament[j][1][0]
                    res["time"] = tournament[j][1][1]

        note = "[{}] {}".format(
            datetime.datetime.now().strftime("%d/%m/%Y %H:%M:%S"), res)
        print(note)
        log = open("log.txt", mode="a+")
        log.write(str(note) + "\n")
        log.close()
    return res
예제 #45
0
 def __generateNMuscle(self):
     '''
     Generate nMuscles connected muscle
     '''
     nEx = 7
     nEy = 4
     nEz = 7
     for nM in range(self.nMuscles):
         for x in range(nEx):
             for y in range(nEy):
                 for z in range(nEz):
                     p_x = Const.xmax / 2.0 + float(x) * Const.r0 - nEx * Const.r0 / 2.0 - Const.r0 * (nEx)/2.0 + Const.r0*(nEx+0.4)*float(nM>2)
                     p_y = Const.ymax / 2.0 + y * Const.r0 - nEy * Const.r0 / 2.0
                     p_z = Const.zmax / 2.0 + z * Const.r0 - nEz * Const.r0 / 2.0  - (nM<=2)*(nM-1)*(nEz*Const.r0) - float(nM>2)*(Const.r0/2+(nM-4)*Const.r0)*nEz - (nM==1)*Const.r0/2.5 - (nM==2)*Const.r0*2/2.5 + (nM==4)*Const.r0/2.5;
                     particle = Particle(p_x,p_y,p_z,Const.elastic_particle)
                     particle.setVelocity(Float4(0.0,0.0,0.0,Const.elastic_particle))
                     self.particles.append(particle)
예제 #46
0
 def __generateElasticCub(self):
     '''
     In this function we generate elastic worm 
     '''
     nx = (int)( ( Const.xmax - Const.xmin ) / Const.r0 ); #X
     ny = (int)( ( Const.ymax - Const.ymin ) / Const.r0 ); #Y
     nz = (int)( ( Const.zmax - Const.zmin ) / Const.r0 ); #Z
 
     nEx = 9;
     nEy = 5;
     nEz = 35;
     for x in range(nEx):
         for y in range(nEy):
             for z in range(nEz):
                 p_x = Const.xmax/2 + x * Const.r0 - nEx * Const.r0 / 2
                 p_y = Const.ymax/2 + y * Const.r0 - nEy * Const.r0 / 2 + Const.ymax * 3 / 8
                 p_z = Const.zmax/2 + z * Const.r0 - nEz * Const.r0 / 2
                 particle = Particle(p_x,p_y,p_z,Const.elastic_particle)
                 particle.setVelocity(Float4(0.0,0.0,0.0,Const.elastic_particle))
                 self.particles.append(particle)
예제 #47
0
def inelastic_particles(particle0: Particle, particle1: Particle, dt: float):
    """
    TODO extending for moveable walls
    Determines the resulting velocity of a set of colliding particles with mid-fram correction
    :param particle0: First particle in the collision
    :param particle1: Second particle in the collision
    """

    # Determine mass ratios
    mass_ratio0 = 2 * particle1.mole.mass / (particle0.mole.mass + particle1.mole.mass)
    mass_ratio1 = 2 * particle0.mole.mass / (particle0.mole.mass + particle1.mole.mass)

    # generate relative terms
    X = particle0.x - particle1.x
    U = particle1.u - particle0.u
    R = particle0.mole.radius + particle1.mole.radius

    a = np.dot(U, U)
    b = 2*np.dot(X, U)
    c = np.dot(X, X) - R*R

    # Determine time of collision
    dt0 = (-b + np.sqrt(b*b - 4*a*c))/(2*a)

    x0 = particle0.x - particle0.u*dt0
    x1 = particle1.x - particle1.u*dt0

    u0 = particle0.u
    u1 = particle1.u

    # Direction magnitude
    dir_mag = np.dot(u0 - u1, x0 - x1) / (np.dot(x0 - x1, x0 - x1))
    dir_vec = (x0 - x1)

    # Set new velocities
    particle0.u -= mass_ratio0 * dir_mag * dir_vec
    particle1.u -= mass_ratio1 * dir_mag * -dir_vec

    # Correct positions
    particle0.x = x0 + particle0.u * dt0
    particle1.x = x1 + particle1.u * dt0
예제 #48
0
def inelastic_wall(wall: Wall, particle: Particle, dt: float):
    """
    TODO extending for moveable walls
    Determines the resulting velocity of a particle bouncing off a wall, with mid-frame position correction
    :param wall: the wall object that may intersect the particle
    :param particle: the particle in the vicinity of the wall
    :param dt: length of the timestep
    :return: Boolean value of true if a collision occured
    """
    x0 = particle.x
    u0 = particle.u
    x1 = wall.vert[0, :]
    p = x0 - x1
    r = particle.mole.radius

    unit = wall.unit
    norm = wall.norm
    dis = np.dot(p, norm)

    # Determine if a collision actually occured
    if dis > r:
        return False


    #if norm_dir > 0:
    #    return False

    # Decompose particles velocity normal and tangential to wall
    norm_dir = np.dot(u0, norm)
    nu = np.multiply(norm_dir, norm)
    uu = np.multiply(np.dot(u0, unit), unit)

    # Update velocity and position
    x0 -= u0 * dt
    dt0 = (np.abs(np.dot(x0 - x1, norm)) - r) / np.linalg.norm(nu)
    x0 += u0 * dt0
    particle.u = uu - nu
    particle.x = x0 + particle.u*(dt - dt0)

    return True
	def import_conf(self, in_file):
		boundbox_sect = True
		particle_sect = False
		boundry_box = []
		particles = []

		with open(in_file, "r") as ins:
			for line in ins:
				if line.rstrip() == "[velocity]":
					particle_sect = False
				elif line.rstrip() == "[position]":
					boundbox_sect = False
					particle_sect = True
				elif boundbox_sect == True and line.rstrip() != "":
					boundry_box.append(float(line.rstrip()))					
				elif particle_sect == True and line.rstrip() != "":
					p_x,p_y,p_z,p_t = line.rstrip().split("\t")
					p_type = "{0:.2g}".format(float(p_t))
					particle = Particle(float(p_x),float(p_y),float(p_z),float(p_type))
					particle.setVelocity(Float4(0.0,0.0,0.0,float(p_type)))
					particles.append(particle)

		return boundry_box, particles
예제 #50
0
 def __generateBoundaryParticles(self):
     '''
     Generate boundary particles: Boundary particles can locate 
     in three different places first it can be at box corner, 
     second at box edge and third at box face. We should take it into account 
     when calculating a velocity for boundary particle because a velocity should 
     have a length == 1 also vector vector of velocity should have direction ??
     TODO: generate better comment
     '''
     nx = int( ( Const.xmax - Const.xmin ) / Const.r0 )  # Numbers of boundary particles on X-axis  
     ny = int( ( Const.ymax - Const.ymin ) / Const.r0 )  # Numbers of boundary particles on Y-axis 
     nz = int( ( Const.zmax - Const.zmin ) / Const.r0 )  # Numbers of boundary particles on Z-axis
     # 1 - top and bottom 
     for ix in range(nx):
         for iy in range(ny):
             if ( ( ix == 0 ) or ( ix == nx - 1) ) or ( (iy == 0) or (iy == ny - 1 ) ) :
                 if ( ( ix == 0 ) or ( ix == nx - 1 ) ) and ( ( iy == 0 ) or ( iy == ny - 1 ) ): #corners
                     x = ix * Const.r0 + Const.r0 / 2.0
                     y = iy * Const.r0 + Const.r0 / 2.0
                     z = 0.0 * Const.r0 + Const.r0 / 2.0
                     vel_x = ( 1.0 * float( ix == 0 ) - 1.0 * float( ix == nx - 1 ) ) / math.sqrt( 3.0 )
                     vel_y = ( 1.0 * float( iy == 0 ) - 1.0 * float( iy == ny - 1 ) ) / math.sqrt( 3.0 )
                     vel_z = 1.0 / math.sqrt( 3.0 )
                     particle1 = Particle(x,y,z, Const.boundary_particle)
                     particle1.setVelocity(Float4(vel_x, vel_y, vel_z))
                     x = ix * Const.r0 + Const.r0 / 2.0
                     y = iy * Const.r0 + Const.r0 / 2.0
                     z = (nz - 1.0) * Const.r0 + Const.r0 / 2.0
                     vel_x = ( 1.0 * float( ix == 0 ) - 1.0 * float( ix == nx - 1 ) ) / math.sqrt( 3.0 )
                     vel_y = ( 1.0 * float( iy == 0 ) - 1.0 * float( iy == ny - 1 ) ) / math.sqrt( 3.0 )
                     vel_z = -1.0 / math.sqrt( 3.0 )
                     particle2 = Particle(x,y,z, Const.boundary_particle)
                     particle2.setVelocity(Float4(vel_x, vel_y, vel_z))
                     self.particles.append(particle1)
                     self.particles.append(particle2)
                 else: #edges
                     x = ix * Const.r0 + Const.r0 / 2.0
                     y = iy * Const.r0 + Const.r0 / 2.0
                     z = 0.0 * Const.r0 + Const.r0 / 2.0
                     vel_x = ( 1.0 * ( float( ix == 0 ) - float( ix == nx - 1 ) ) ) / math.sqrt( 2.0 )
                     vel_y = ( 1.0 * ( float( iy == 0 ) - float( iy == ny - 1 ) ) ) / math.sqrt( 2.0 )
                     vel_z = 1.0 / math.sqrt( 2.0 )
                     particle1 = Particle(x,y,z, Const.boundary_particle)
                     particle1.setVelocity(Float4(vel_x, vel_y, vel_z))
                     x = ix * Const.r0 + Const.r0 / 2.0
                     y = iy * Const.r0 + Const.r0 / 2.0
                     z = (nz - 1.0) * Const.r0 + Const.r0 / 2.0
                     vel_x = ( 1.0 * ( float( ix == 0 ) - float( ix == nx - 1 ) ) ) / math.sqrt( 2.0 )
                     vel_y = ( 1.0 * ( float( iy == 0 ) - float( iy == ny - 1 ) ) ) / math.sqrt( 2.0 )
                     vel_z = -1.0 / math.sqrt( 2.0 )
                     particle2 = Particle(x,y,z, Const.boundary_particle)
                     particle2.setVelocity(Float4(vel_x, vel_y, vel_z))
                     self.particles.append(particle1)
                     self.particles.append(particle2)
             else: #planes
                 x = ix * Const.r0 + Const.r0 / 2.0
                 y = iy * Const.r0 + Const.r0 / 2.0
                 z = 0.0 * Const.r0 + Const.r0 / 2.0
                 vel_x = 0.0
                 vel_y = 0.0
                 vel_z = 1.0
                 particle1 = Particle(x,y,z, Const.boundary_particle)
                 particle1.setVelocity(Float4(vel_x, vel_y, vel_z))
                 x = ix * Const.r0 + Const.r0 / 2.0
                 y = iy * Const.r0 + Const.r0 / 2.0
                 z = (nz - 1.0) * Const.r0 + Const.r0 / 2.0
                 vel_x = 0.0
                 vel_y = 0.0
                 vel_z = -1.0
                 particle2 = Particle(x,y,z, Const.boundary_particle)
                 particle2.setVelocity(Float4(vel_x, vel_y, vel_z))
                 self.particles.append(particle1)
                 self.particles.append(particle2)
     #2 - side walls OX-OZ and opposite
     for ix in range(nx):
         for iz in range(1,nz - 1):
             if (ix == 0) or (ix == nx - 1):
                 x = ix * Const.r0 + Const.r0 / 2.0
                 y = 0.0 * Const.r0 + Const.r0 / 2.0
                 z = iz * Const.r0 + Const.r0 / 2.0
                 vel_x = 0.0
                 vel_y = 1.0 / math.sqrt(2.0)
                 vel_z = 1.0 * ( float( iz == 0 ) - float(iz == nz - 1 ) ) / math.sqrt(2.0)
                 particle1 = Particle(x,y,z, Const.boundary_particle)
                 particle1.setVelocity(Float4(vel_x, vel_y, vel_z))
                 x = ix * Const.r0 + Const.r0 / 2.0
                 y = ( ny - 1 ) * Const.r0 + Const.r0 / 2.0
                 z = iz * Const.r0 + Const.r0 / 2.0
                 vel_x = 0.0
                 vel_y = -1.0 / math.sqrt(2.0)
                 vel_z = 1.0 * (float(iz == 0) - float(iz == nz - 1)) / math.sqrt(2.0)
                 particle2 = Particle(x,y,z, Const.boundary_particle)
                 particle2.setVelocity(Float4(vel_x, vel_y, vel_z))
                 self.particles.append(particle1)
                 self.particles.append(particle2)
             else:
                 x = ix * Const.r0 + Const.r0 / 2.0
                 y = 0.0 * Const.r0 + Const.r0 / 2.0
                 z = iz * Const.r0 + Const.r0 / 2.0
                 vel_x = 0.0
                 vel_y = 1.0
                 vel_z = 0.0
                 particle1 = Particle(x,y,z, Const.boundary_particle)
                 particle1.setVelocity(Float4(vel_x, vel_y, vel_z))
                 x = ix * Const.r0 + Const.r0 / 2.0
                 y = ( ny - 1 ) * Const.r0 + Const.r0 / 2.0
                 z = iz * Const.r0 + Const.r0 / 2.0
                 vel_x = 0.0
                 vel_y = -1.0
                 vel_z = 0.0 
                 particle2 = Particle(x,y,z, Const.boundary_particle)
                 particle2.setVelocity(Float4(vel_x, vel_y, vel_z))
                 self.particles.append(particle1)
                 self.particles.append(particle2)
         #3 - side walls OY-OZ and opposite
     for iy in range(1,ny - 1):
         for iz in range(1,nz - 1):
             x = 0.0 * Const.r0 + Const.r0 / 2.0
             y = iy * Const.r0 + Const.r0 / 2.0
             z = iz * Const.r0 + Const.r0 / 2.0
             vel_x = 1.0
             vel_y = 0.0
             vel_z = 0.0
             particle1 = Particle(x,y,z, Const.boundary_particle)
             particle1.setVelocity(Float4(vel_x, vel_y, vel_z))
             x = (nx - 1) * Const.r0 + Const.r0 / 2.0
             y = iy * Const.r0 + Const.r0 / 2.0
             z = iz * Const.r0 + Const.r0 / 2.0
             vel_x = -1.0
             vel_y = 0.0
             vel_z = 0.0 
             particle2 = Particle(x,y,z, Const.boundary_particle)
             particle2.setVelocity(Float4(vel_x, vel_y, vel_z))
             self.particles.append(particle1)
             self.particles.append(particle2)
예제 #51
0
    def test_step3(self):

        p = Particle(
            -20.9750481543,
            88.6462764876,
            -3.32917469238,
            7.27437941461
        )

        print p.position, p.velocity

        p.take_step((0, 0), 100)
        p.take_step((0, 0), 100)
        p.take_step((0, 0), 100)
        p.take_step((0, 0), 100)
        p.take_step((0, 0), 100)
        p.take_step((0, 0), 100)

        # we definetly moved away from the barrier
        print p.position, p.velocity

        p.take_step((0, 0), 100)
        p.take_step((0, 0), 100)
        p.take_step((0, 0), 100)
        p.take_step((0, 0), 100)
        p.take_step((0, 0), 100)
        p.take_step((0, 0), 100)
        p.take_step((0, 0), 100)
        p.take_step((0, 0), 100)
        p.take_step((0, 0), 100)
        p.take_step((0, 0), 100)
        p.take_step((0, 0), 100)
        p.take_step((0, 0), 100)
        p.take_step((0, 0), 100)
        p.take_step((0, 0), 100)
        p.take_step((0, 0), 100)
        p.take_step((0, 0), 100)
        p.take_step((0, 0), 100)
        p.take_step((0, 0), 100)
        p.take_step((0, 0), 100)
        p.take_step((0, 0), 100)
        p.take_step((0, 0), 100)

        # we hit the barrier again!
        print p.position, p.velocity
        p.scale_for_temperature(0.5)
        print p.position, p.velocity
예제 #52
0
def pretty_print(p1in, p2in, p1out, p2out, attr = None):    
    FORMAT = "{} + {} --> {} + {}"
    if not (attr == None): 
        attrmap = attr.MAP
        print FORMAT.format(attrmap[p1in.getAttr(attr)], attrmap[p2in.getAttr(attr)], attrmap[p1out.getAttr(attr)], attrmap[p2out.getAttr(attr)])
    else:        
        print FORMAT.format(p1in, p2in, p1out, p2out)
    
def wrap(x):
    if x == -1: return 3
    if x == -2: return 2
    if x == -3: return 1
    return x
    
p1in = Particle(Color.BLUE, Shape.CIRCLE, Symbol.HEART)
p2in = Particle(Color.RED, Shape.SQUARE, Symbol.SPADE)
(p1out, p2out) = p1in.collide(p2in)

pretty_print(p1in, p2in, p1out, p2out)
#pretty_print(p1in, p2in, p1out, p2out, attr = Color)
#pretty_print(p1in, p2in, p1out, p2out, attr = Shape)
#pretty_print(p1in, p2in, p1out, p2out, attr = Symbol)

line = ["\t0\t1\t2\t3\n"]
for x in range(4):
    line.append("%d\t" % x)
    p1in = Particle(x, Shape.CIRCLE, Symbol.HEART)
    for y in range(4):        
        p2in = Particle(y, Shape.CIRCLE, Symbol.HEART)
        (p1out, p2out) = p1in.collide(p2in)
예제 #53
0
    
    Bx = 0;
    By = 0.2;
    Bz = 0;
    
    return [Bx, By, Bz];


r0 = np.array([0,0,0])

v0 = np.array([0.6 * Constants.c,0,0])
m = Constants.me
q = Constants.e
tStart = 0
tEnd = 1e-9
dt = 1e-13

E = Field(E_Feld)
B = Field(B_Feld)
particle = Particle(r0, v0, m, q)

comput = Computer(dt)
comput.start(E, B, particle, tStart, tEnd)


r = Drawer()
r.DrawTrajectory(particle.getTrajectory())
#r.DrawKineticEnergy(particle.getKineticEnergy(), tStart, tEnd, dt)

#r.DrawKineticEnergy(particle.getVelocities(), tStart, tEnd, dt)
	def import_collada(self, col_file, dist_scalar, dist_exp):
		'''
		Importing boundry box assumes box verticies are in collada file in format vertice 1-8 =
		(0 0 0) (0 0 1) (0 1 0) (0 1 1) (1 0 0) (1 0 1) (1 1 0) (1 1 1)

		Importing collada transforms need 'TransRotLoc' and not 'Matrix' style 
		transforms currently

		TODO: rotation not implemented in transformations yet

		Currently only importing one elastic mesh and boundry box is supported.  Multiple 
		liquid meshes can be imported.

		The size of elastic_connections_collection = [None]*Const.MAX_NUM_OF_NEIGHBOUR*len(particles)*3
		is a heuristic which provides enough size in the list to random access indices before the real
		list values are created, in order to add the real values.  It is the max connections that could exist.
		'''
		print("collada import")
		boundry_box = [0, 100.2, 0, 66.8, 0, 668] #default
		boundry_parts = []
		elast_pos_section = re.compile(".*<float_array id=\"(elastic.*)-mesh-positions-array\" count=\"\d+\">.*")
		liquid_pos_section = re.compile(".*<float_array id=\"(liquid.*)-mesh-positions-array\" count=\"\d+\">.*")
		bound_pos_section = re.compile(".*<float_array id=\"(boundry.*)-mesh-positions-array\" count=\"\d+\">.*")
		material_section = re.compile(".*<polylist material=\"(.*)-material\" count=\"\d+\">.*")
		geo_section_end = re.compile(".*</geometry>.*")
		elastic_pattern = re.compile("elastic.*") 
		liquid_pattern = re.compile("liquid.*")
		boundry_pattern = re.compile("boundry.*")
		sect_patterns = [elastic_pattern, liquid_pattern, boundry_pattern]
		section_coords = []		
		transf_section = re.compile(".*<node id=\".*\" name=\"(.*)\" type=\"NODE\">.*")
		tran_loc_sect = re.compile(".*<translate sid=\"location\">(.*)</translate>.*")
		tran_scale_sect = re.compile(".*<scale sid=\"scale\">(.*)</scale>.*")
		trans_loc = []
		trans_scale = []
		trans_axis_values = 4
		elastic_found = False
		ptype_found = False
		tris_section = re.compile("\s+<p>(.*)</p>")
		tris_triplet = re.compile("(\S+)\s(\S+)\s(\S+)\s(\S+)\s(\S+)\s(\S+)\s?")
		xml_pattern = "(.*[>])+(.*)([<].*)+"
		vertex_pattern = "(\S+)\s(\S+)\s(\S+)(\s?)"
		current_transf_name = ""
		current_ptype_name = ""
		elastic_particles = []
		liquid_particles = []
		particles = []
		unsorted_connections = []
		membranes = []
		parm_memb_index = []
		elastic_connections_collection = []
		nMuscles = 1
		muscle_particles = []

		with open(col_file, "r") as ins:
			for line in ins:
				if elast_pos_section.match(line.rstrip()):
					p_type = 2.1
					new_particles = self.extract_particles(p_type, line, xml_pattern, vertex_pattern)
					elastic_particles.extend(new_particles)
					elastic_found = True	

					object_3d_name = elast_pos_section.match(line.rstrip()).group(1)
					section_coords.append([object_3d_name, 0, len(new_particles)])
					particles.extend(elastic_particles)					
				elif liquid_pos_section.match(line.rstrip()):
					p_type = 1.1
					new_particles = self.extract_particles(p_type, line, xml_pattern, vertex_pattern)
					liquid_particles.extend(new_particles)

					object_3d_name = liquid_pos_section.match(line.rstrip()).group(1)
					section_coords.append([object_3d_name, 0, len(new_particles)])
				elif bound_pos_section.match(line.rstrip()):
					p_type = 3.1
					new_particles = self.extract_particles(p_type, line, xml_pattern, vertex_pattern)
					boundry_parts.extend(new_particles)

					x_b, y_b, z_b = [], [], []
					for i in range(len(boundry_parts)):
						x_b.append(boundry_parts[i].position.x)
						y_b.append(boundry_parts[i].position.y)
						z_b.append(boundry_parts[i].position.z)
					x_b.sort(); y_b.sort(); z_b.sort()

					x1, x2, y1, y2, z1, z2 = x_b[0], x_b[-1], y_b[0], y_b[-1], z_b[0], z_b[-1]
					boundry_box = [x1, x2, y1, y2, z1, z2]			

					object_3d_name = bound_pos_section.match(line.rstrip()).group(1)
				elif material_section.match(line.rstrip()):
					current_ptype_name = material_section.match(line.rstrip()).group(1)
					ptype_found = True
				elif transf_section.match(line.rstrip()):
					current_transf_name = transf_section.match(line.rstrip()).group(1)
				elif tran_loc_sect.match(line.rstrip()):
					trans_entry = [current_transf_name]
					trans_coords = tran_loc_sect.match(line.rstrip()).group(1)
					trans_entry.extend(trans_coords.split(' '))
					trans_loc.append(trans_entry)
				elif tran_scale_sect.match(line.rstrip()):
					trans_entry = [current_transf_name]
					trans_coords = tran_scale_sect.match(line.rstrip()).group(1)
					trans_entry.extend(trans_coords.split(' '))
					trans_scale.append(trans_entry)
				elif tris_section.match(line.rstrip()) and elastic_found == True:
					for tris in re.finditer(tris_triplet, tris_section.match(line.rstrip()).group(1)):
						# read in elastic connections
						p1 = int(tris.group(1))
						p3 = int(tris.group(3))
						p5 = int(tris.group(5))
								
						unsorted_connections.append([[p1,p3],[p1,p5],[p3,p5]])

						# create membranes
						membrane_triple = [p1, p3, p5]
						if not membrane_triple in membranes:
							membranes.append(membrane_triple)

						# find muscles
						if ptype_found == True and current_ptype_name == "muscle":
							muscle_particles.append([p1,p3])
							muscle_particles.append([p1,p5])
							muscle_particles.append([p3,p5])
					ptype_found = False

				if geo_section_end.match(line.rstrip()) and elastic_found == True:
					# after unsorted_connections is filled up now elastic connections are created
					for p_i in range(len(particles)):
						total_conn = 0
						found_j = []
						new_conns = []
						conn_1 = 0
						conn_2 = 0
						for con_i in range(len(unsorted_connections)):
							for connection in unsorted_connections[con_i]:
								conn_1 = connection[0]
								conn_2 = connection[1]
								if (p_i == conn_1 or p_i == conn_2) and (total_conn < Const.MAX_NUM_OF_NEIGHBOUR):
									part_i = particles[p_i]
									j_index = (p_i == conn_1) and conn_2 or conn_1
									part_j = particles[j_index]
									if not j_index in found_j:
										#val1 = self.calc_part_val1(particles, part_i, part_j, nMuscles)
										val1 = self.calc_ptype(muscle_particles, p_i, j_index)
										dist = ((Particle.distBetween_particles(part_j,part_i)**float(dist_exp)) * float(dist_scalar))
										new_conns.append( ElasticConnection(particles.index(part_j)+0.2, dist, val1, 0) )
										found_j.append(j_index)
										total_conn += 1

						sorted_conns = self.sort_conns(new_conns)
						elastic_connections_collection.extend(sorted_conns)
						elastic_connections_collection.extend([ElasticConnection(Const.NO_PARTICEL_ID,0,0,0)] * (Const.MAX_NUM_OF_NEIGHBOUR - total_conn))

					elastic_found = False

			particles.extend(liquid_particles)

			# create pmis
			print("particles:")
			print(float(len(particles)))
			for p_i in range(len(particles)):
				if particles[p_i].type == 2.1:
					pmi_group = []
					for m_i in range(len(membranes)):
						for memb_vert in membranes[m_i]:
							if p_i == memb_vert and len(pmi_group) < Const.MAX_MEMBRANES_INCLUDING_SAME_PARTICLE:
								pmi_group.append(m_i)

					for pmi_i in pmi_group:
						parm_memb_index.append(pmi_i)

					for blank_i in range(Const.MAX_MEMBRANES_INCLUDING_SAME_PARTICLE - len(pmi_group)):
						parm_memb_index.append(-1)

			print("parm_memb_index:")
			print(len(parm_memb_index)/float(Const.MAX_MEMBRANES_INCLUDING_SAME_PARTICLE))

			# transforms	
			boundry_box, particles = self.translate_mesh(trans_scale, trans_loc, section_coords, sect_patterns, boundry_box, particles)

			# test removing sections
			#membranes = []
			#parm_memb_index = []
			#elastic_connections_collection = []

		return boundry_box, particles, elastic_connections_collection, membranes, parm_memb_index