Example #1
0
def get_data(vocabs=""):
    print("==> Load Word Embedding")
    word_embedding = utils.load_glove(use_index=True)

    validation_data = []
    training_data = []
    if not vocabs:
        non_words = utils.load_file(p.non_word, False)
        for w in non_words:
            w_ = w.replace('\n', '').split(' ')
            validation_data.append(int(w_[-1]))
        training_data = utils.sub(range(len(word_embedding)), validation_data)
    else:
        vocabs_set = utils.load_file(vocabs)
        print("vc", len(vocabs_set))
        training_data = [w for _, w in vocabs_set.iteritems()]
        tm = range(len(word_embedding))
        validation_data = list(utils.sub(set(tm), set(training_data)))
        length = int(math.ceil(len(training_data) * 1.0 / p.compression_batch_size)) * p.compression_batch_size - len(training_data)
        print('before', 'vd', len(validation_data), 'td', len(training_data))
        if length:
            add_on = np.random.choice(validation_data, length)
            training_data += add_on.tolist()
            validation_data = utils.sub(set(validation_data), set(add_on))
        print('vd', len(validation_data), 'td', len(training_data))
    # utils.save_file(p.glove_path, training_data)
    return word_embedding, training_data, validation_data
Example #2
0
    def castRay(self, origin, direction):
        material, intersect = self.sceneIntersect(origin, direction)
        
        if material is None:
            return self.currentColor

        lightDir = norm(sub(self.light.position, intersect.point))
        lightDistance = length(sub(self.light.position, intersect.point))
        
        offsetNormal = mul(intersect.normal, 1.1)
        shadowOrigin = sub(intersect.point, offsetNormal) if dot(lightDir, intersect.normal) < 0 else sum(intersect.point, offsetNormal)
        shadowMaterial, shadowIntersect = self.sceneIntersect(shadowOrigin, lightDir)
        shadowIntensity = 0

        if shadowMaterial and length(sub(shadowIntersect.point, shadowOrigin)) < lightDistance:
            shadowIntensity = 0.9

        intensity = self.light.intensity * max(0, dot(lightDir, intersect.normal)) * (1 - shadowIntensity)

        reflection = reflect(lightDir, intersect.normal)
        specularIntensity = self.light.intensity * (
            max(0, -dot(reflection, direction)) ** material.spec
        )

        diffuse = material.diffuse * intensity * material.albedo[0]
        specular = Color(255, 255, 255) * specularIntensity * material.albedo[1]
        return diffuse + specular
Example #3
0
    def make_game_state(self, rng: SeededRandomNumberGenerator) -> GameState:
        enemy_goal_center: Vector3 = Vector3(0, 5120 * self.team, 93)
        car_spawn_block: utils.Area = utils.RectPrism(Vector3(0, 0, 17), 8000,
                                                      8000, 0)
        car_loc: Vector3 = car_spawn_block.random_point_inside(rng)
        car_facing: Rotator = utils.rotator_from_dir(
            sub(enemy_goal_center, car_loc))
        relative: Vector3 = sub(enemy_goal_center, car_loc)
        #Spawn the ball halfway between us and the enemy goal
        ball_loc: Vector3 = add(
            car_loc, Vector3(relative.x / 2, relative.y / 2, relative.z / 2))
        ball_loc.z = 93

        return GameState(
            ball=BallState(physics=Physics(location=ball_loc,
                                           velocity=Vector3(0, 0, 0),
                                           angular_velocity=Vector3(0, 0, 0))),
            cars={
                0:
                CarState(physics=Physics(location=car_loc,
                                         rotation=car_facing,
                                         velocity=Vector3(0, 0, 0),
                                         angular_velocity=Vector3(0, 0, 0)),
                         boost_amount=33),
            },
            boosts={i: BoostState(0)
                    for i in range(34)},
        )
Example #4
0
    def side(self, v0, v1, v2, origin, direction):
        v0v1 = sub(v1, v0)
        v0v2 = sub(v2, v0)

        N = cross(v0v1, v0v2)
        
        raydirection = dot(N, direction)

        if abs(raydirection) < 0.0001:
            return None
        
        d = dot(N, v0)
        
        t = (dot(N, origin) + d) / raydirection
        
        if t < 0:
            return None

        P = sum(origin, mul(direction, t))
        U, V, W = barycentric(v0, v1, v2, P)
        
        if U < 0 or V < 0 or W < 0:
            return None
        else: 
            return Intersect(distance = d,
                         point = P,
                         normal = norm(N))
Example #5
0
def rule18(q, a, r, c):
    nq = q.size()
    zeroQ = buildZERO(nq)
    oneQ = buildONE(nq)
    oneQ1 = buildONE(nq + 1)
    sr = sub(q & r)
    sa = sub(q & a)
    return (castBVinCond(
        If(
            UGT(sa, sr), oneQ,
            If(
                nxor(Concat(extract1BV(q, c), sa),
                     Concat(buildONE(1), sr)) == oneQ1, oneQ, zeroQ))))
def threat_level(vip_pos, guard_pos, hostile_pos):

    tv = utils.sub(hostile_pos, vip_pos)
    gv = utils.sub(guard_pos, vip_pos)

    if utils.norm2(tv) == 0:
        return 0

    dst_threat = 70 * math.exp(-math.sqrt(utils.dst2(vip_pos, hostile_pos)))

    coverage = 0
    if utils.norm2(gv) != 0 and utils.norm2(gv) < utils.norm2(tv):
        coverage = 10 * max(utils.dot(tv, gv), 0) / \
          math.sqrt(utils.norm2(tv) * utils.norm2(gv))

    return dst_threat - coverage
Example #7
0
def get_vector_to(p2):
    p1 = h.Player.ped_id().get_coords(1)

    v = utils.sub(p2, p1)
    v = h.Vector3(v.x, v.y, 0.0)
    v = utils.normalize(v)

    return v
Example #8
0
 def rayIntersect(self, origin, direction):
   L = sub(self.center, origin)
   tca = dot(L, direction)
   l = length(L)
   d2 = l ** 2 - tca ** 2
   if d2 > self.radius ** 2:
       return None
   thc = (self.radius ** 2 - d2) ** 0.5
   t0 = tca - thc
   t1 = tca + thc
   if t0 < 0:
       t0 = t1
   if t0 < 0:
       return None
   hit = sum(origin, mul(direction, t0))
   normal = norm(sub(hit, self.center))
   return Intersect(
       distance=t0,
       point=hit,
       normal=normal
   )
Example #9
0
    def castRay(self, origin, direction, recursion=0):
        material, intersect = self.sceneIntersect(origin, direction)

        if material is None or recursion >= MAX_RECURSION_DEPTH:
            return self.currentColor
            # Si el rayo no golpeo nada o si llego al limite de recursion

        lightDir = norm(sub(self.light.position, intersect.point))
        lightDistance = length(sub(self.light.position, intersect.point))

        offsetNormal = mul(intersect.normal, 1.1)
        shadowOrigin = sub(
            intersect.point,
            offsetNormal) if dot(lightDir, intersect.normal) < 0 else sum(
                intersect.point, offsetNormal)
        shadowMaterial, shadowIntersect = self.sceneIntersect(
            shadowOrigin, lightDir)
        shadowIntensity = 0

        if shadowMaterial and length(sub(shadowIntersect.point,
                                         shadowOrigin)) < lightDistance:
            shadowIntensity = 0.9

        intensity = self.light.intensity * max(
            0, dot(lightDir, intersect.normal)) * (1 - shadowIntensity)

        reflection = reflect(lightDir, intersect.normal)
        specularIntensity = self.light.intensity * (max(
            0, -dot(reflection, direction))**material.spec)

        if material.albedo[2] > 0:
            reflectDir = reflect(direction, intersect.normal)
            reflectOrigin = sub(intersect.point, offsetNormal) if dot(
                reflectDir, intersect.normal) < 0 else sum(
                    intersect.point, offsetNormal)
            reflectedColor = self.castRay(reflectOrigin, reflectDir,
                                          recursion + 1)
        else:
            reflectedColor = self.currentColor

        if material.albedo[3] > 0:
            refractDir = refract(direction, intersect.normal,
                                 material.refractionIndex)
            refractOrigin = sub(intersect.point, offsetNormal) if dot(
                refractDir, intersect.normal) < 0 else sum(
                    intersect.point, offsetNormal)
            refractedColor = self.castRay(refractOrigin, refractDir,
                                          recursion + 1)
        else:
            refractedColor = self.currentColor

        diffuse = material.diffuse * intensity * material.albedo[0]
        specular = Color(255, 255,
                         255) * specularIntensity * material.albedo[1]
        reflected = reflectedColor * material.albedo[2]
        refracted = refractedColor * material.albedo[3]

        return diffuse + specular + reflected + refracted
Example #10
0
    def _find_safest(bounds = m_bounds, offset = (0, 0), depth = 0, carry = []):
        sector_width = (bounds[1][0] - bounds[0][0])
        sector_height = (bounds[1][1] - bounds[0][1])

        center_point = (
            int(offset[0] + floor(sector_width / 2)),
            int(offset[1] + floor(sector_height / 2))
        )

        if depth == max_depth or (sector_height * sector_width <= 1):
            return sorted(carry, lambda cell_1, cell_2: cell_1[1] < cell_2[1])[:3]
        else:
            # filter cells that we've already rated
            carry_cells = [ cell[0] for cell in carry ]
            surrounding_ratings = [
                ((cell[0], cell[1]), _rate_cell((cell[0], cell[1]), board, True))
                for cell in surrounding(center_point)
                if cell not in carry_cells and board.inside(cell) and board.get_cell(cell) != SNAKE
            ]

            # randomize to remove bias towards last in surrounding list
            random.shuffle(surrounding_ratings)
            position, rating = reduce(lambda m_carry, cell: cell if cell[1] > m_carry[1] else m_carry, surrounding_ratings, (None, -100000000000))

            new_bounds = bounds
            if position is not None:
                carry = carry + [(position, rating)]
                direction_vector = sub(position, center_point)

                # diagnal
                if abs(direction_vector[0]) == abs(direction_vector[1]):
                    direction_vector = list(direction_vector) # tuples are immutable
                    direction_vector[int(time.time()) % 2] = 0 # 300% faster than random.randint()
                    direction_vector = tuple(direction_vector) # back to tuple because DIR_VECTOR contains tuples

                direction = DIR_NAMES[DIR_VECTORS.index(direction_vector)]

                if direction == "up":
                    new_bounds = [offset, (bounds[1][0], bounds[1][1])]
                elif direction == "down":
                    offset = (offset[0], center_point[1])
                    new_bounds = [offset, (bounds[1][0], bounds[1][1])]
                elif direction == "left":
                    new_bounds = [offset, (center_point[0], bounds[1][1])]
                else: # right
                    offset = (center_point[0], offset[1])
                    new_bounds = [offset, (bounds[0][0], bounds[1][1])]

            return _find_safest(new_bounds, offset, depth + 1, carry = carry)
Example #11
0
 def ray_intersect(self, orig, direction):
     L = sub(self.center, orig)
     tca = dot(L, direction)
     l = length(L)
     d2 = l**2 - tca**2
     if d2 > self.radius**2:
         return False
     thc = (self.radius**2 - d2)**1 / 2
     t0 = tca - thc
     t1 = tca + thc
     if t0 < 0:
         t0 = t1
     if t0 < 0:
         return False
     return True
Example #12
0
    def rayIntersect(self, orig, dir):
        # t = (( position - origRayo) dot normal) / (dirRayo dot normal)

        denom = dot(dir, self.normal)

        if abs(denom) > 0.0001:
            t = dot(self.normal, sub(self.position, orig)) / denom
            if t > 0:
                # P = O + tD
                hit = sum(orig, mul(dir, t))

                return Intersect(distance = t,
                                 point = hit,
                                 normal = self.normal)

        return None
Example #13
0
    def rayIntersect(self, origin, direction):
        L = sub(self.center, origin)
        tca = dot(L, direction)
        l = length(L)
        # distancia al cuadrado
        dc = l**2 - tca**2

        if dc > self.radius**2:
            return False

        thc = (self.radius**2 - dc)**0.5
        t0 = tca - thc
        t1 = tca + thc

        if t0 < 0:
            t0 = t1
        if t0 < 0:
            return False
        return True
Example #14
0
 def make_game_state(self, rng: SeededRandomNumberGenerator) -> GameState:
     car_spawn_area: utils.Area = utils.RectPrism(Vector3(0, 0, 17), 8000, 8000, 0)
     ball_spawn_area: utils.Area = utils.RectPrism(Vector3(0, 0, 1000), 8000, 8000, 400)
     ball_velocity_area: utils.Area = utils.Sphere(Vector3(0, 0, 0), 600)
     ball_loc: Vector3 = ball_spawn_area.random_point_inside(rng)
     car_loc: Vector3 = car_spawn_area.random_point_inside(rng)
     return GameState(
         ball=BallState(physics=Physics(
             location=ball_loc,
             velocity=ball_velocity_area.random_point_inside(rng),
             angular_velocity=Vector3(0, 0, 0))),
         cars={
             0: CarState(
                 physics=Physics(
                     location=car_loc,
                     rotation=utils.rotator_from_dir(sub(ball_loc, car_loc)),
                     velocity=Vector3(0, 0, 0),
                     angular_velocity=Vector3(0, 0, 0)),
                 boost_amount=100),
         },
         boosts={i: BoostState(0) for i in range(34)},
     )
def heuristic_evaluation(points, edges, gaps, speed, quadNum):
    """
    Evaluates the edges based on experimental heuristics
    :param points: list of point coordinates
    :param edges: edges between points
    :param gaps: gaps between obstacles for each edge
    :param speed: max speed of quadrotors
    :param quadNum: number of quadrotors
    :return: evaluated edges (edge costs)
    """
    costs = [0] * len(edges)
    for i in range(len(edges)):
        length = ut.norm(ut.sub(points[edges[i][0]], points[edges[i][1]]))
        costs[i] = 0.117 * length / speed

        if gaps[i] is not None:
            if quadNum == 1:
                costs[i] += 3.87 * math.exp(-0.77 * gaps[i])
            else:
                costs[i] += (4.353 + 2.957 * quadNum) * math.exp(
                    -(1.215 + 0.004 * quadNum) * gaps[i])
    return costs
Example #16
0
if conf.SAVE:
    sys.path.append('../../minecraftcodex')
    os.environ['DJANGO_SETTINGS_MODULE'] = 'local_settings'
    from database.models import Language, LanguageString

###
#   GLOBALS
###
STRINGS = []
LANGUAGES = []
LANGUAGES_STR = []

###
#   LOOK FOR CORRECT JAVA FILES
###
utils.sub("Looking for languages files:")
directory_list = os.listdir(conf.LANGUAGES_PATH)
utils.echo("found %d file(s)" % len(directory_list), end='\n')

###
#   GET LANGUAGES
###
try:
    OLD_STRINGS = json.loads(open('strings.json').read())
except:
    OLD_STRINGS = []
try:
    OLD_LANGUAGES = json.loads(open('languages.json').read())
except:
    OLD_LANGUAGES = []
Example #17
0
utils.title("ITEMS")

if conf.SAVE:
    sys.path.append('../../minecraftcodex')
    os.environ['DJANGO_SETTINGS_MODULE'] = 'local_settings'
    from database.models import Item, Texture

###
#   GLOBALS
###
ITEMS = []

###
#   LOOK FOR CORRECT JAVA FILES
###
utils.sub("Looking for java files: ")
#utils.sub("Keywords: %s" % ', '.join(conf.ITEMS_JAVA_KEYWORDS), end='\n')
for keyword in conf.ITEMS_JAVA_KEYWORDS:
    cmd = utils.run('grep \'%s\' ./classes/*' % keyword)
    for result in cmd:
        if result and result is not '':
            java_file = os.path.basename(result.strip().split()[0][:-1])
            if java_file not in conf.ITEMS_FILES:
                utils.echo("%s " % java_file, end='')
                conf.ITEMS_FILES.append(java_file)

utils.echo('\r')

###
#   GET ITEMS INFO FROM CLASSFILE
###
Example #18
0
                name=texture.name,
                type=texture.type
            )
        except Texture.DoesNotExist:
            item = Texture(
                name=texture.name,
                type=texture.type,
                image=texture.path
            )
            item.save()


# SUMMARY
new_old_data = {}
new_old_data['list'] = []
[new_old_data['list'].append(x.name) for x in TEXTURES]
new_items = len(new_old_data['list'])-len(OLD_TEXTURES['list'])
utils.info('Found %d textures (%d new)' % (len(TEXTURES), new_items))
if new_items != 0:
    utils.sub('Modifications', end='\n')
    for item in TEXTURES:
        if item.name not in OLD_TEXTURES['list']:
            utils.sub(' + %s' % item.name, end='\n', color=utils.colors.GREEN)

    for item in OLD_TEXTURES['list']:
        if item not in new_old_data['list']:
            utils.sub(' - %s' % item, end='\n', color=utils.colors.RED)

olditems = open('textures.json', 'w')
olditems.write(json.dumps(new_old_data))
Example #19
0
 def direction(self):
     return utils.normalize(utils.sub(self.look_at, self.look_from))
Example #20
0
 def focal_distance(self):
     return utils.length(utils.sub(self.look_at, self.look_from))
def start(clientID, quads, targets, speed, proxs, path, leadfoll=False):
    """
    Boids model program for experimental graph edges evaluation
    :param clientID: ID of the VRep connection
    :param quads: quadrotor handles
    :param targets: quadrotor target handles
    :param speed: speed of quadrotors
    :param proxs: proximity sensor handles
    :param path: quadrotor path coordinates
    :param leadfoll: True - leader/followers mode, False - all boids following path (default)
    """

    # definition of constants
    quadsNum = len(quads)  # number of quadrotors
    viewRange = 3  # view range of quadrotors
    smp = 0.2  # sampling period
    kS = [0.30,
          2.0]  # separation constants [multiplication const, power const]
    kC = [0.30, 0.0]  # cohesion constants [multiplication const, power const]
    kA = [0.00, 0.0]  # alignment constants [multiplication const, power const]
    kD = [speed,
          1.0]  # path following constants [multiplication const, power const]
    kO = [0.20, 2.0
          ]  # obstacle avoidance constants [multiplication const, power const]

    # data stream init
    for i in range(quadsNum):
        vrep.simxGetObjectPosition(clientID, quads[i], -1,
                                   vrep.simx_opmode_streaming)
        vrep.simxGetObjectVelocity(clientID, quads[i],
                                   vrep.simx_opmode_streaming)
        vrep.simxReadProximitySensor(clientID, proxs[i],
                                     vrep.simx_opmode_streaming)

    # variables init
    position = [[0 for _ in range(3)]
                for _ in range(quadsNum)]  # position of quadrotors
    velocity = [[0 for _ in range(3)]
                for _ in range(quadsNum)]  # velocity of quadrotors
    closest = [[0 for _ in range(3)]
               for _ in range(quadsNum)]  # coords of closest obstacle to quads
    visibleQuads = [[0 for _ in range(quadsNum)]
                    for _ in range(quadsNum)]  # visible quadrotors
    individualTarget = [
        0
    ] * quadsNum  # current waypoint index for each quadrotor

    # get closest boid to starting point
    leader = 0
    _, tmp = vrep.simxGetObjectPosition(clientID, quads[0], -1,
                                        vrep.simx_opmode_buffer)
    dist = ut.norm(ut.sub(path[1], tmp))
    for i in range(1, quadsNum):
        _, tmp = vrep.simxGetObjectPosition(clientID, quads[i], -1,
                                            vrep.simx_opmode_buffer)
        nrm = ut.norm(ut.sub(path[1], tmp))
        if nrm < dist:
            dist = nrm
            leader = i

    # main boids program
    print('Evaluating ' + str(len(path)) + ' edges:')
    number = 0
    cnt = [0] * quadsNum
    finished = [0] * len(path)
    last = [False] * quadsNum
    end = False
    t1 = vrep.simxGetLastCmdTime(clientID)
    ec = []
    while vrep.simxGetConnectionId(clientID) != -1:
        time.sleep(smp)

        separation = [[0 for _ in range(3)]
                      for _ in range(quadsNum)]  # separation force
        cohesion = [[0 for _ in range(3)]
                    for _ in range(quadsNum)]  # cohesion force
        alignment = [[0 for _ in range(3)]
                     for _ in range(quadsNum)]  # alignment force
        destination = [[0 for _ in range(3)]
                       for _ in range(quadsNum)]  # path following force
        avoidance = [[0 for _ in range(3)]
                     for _ in range(quadsNum)]  # obstacle avoidance force
        output = [[0 for _ in range(3)]
                  for _ in range(quadsNum)]  # output force

        # read data from VRep
        for i in range(quadsNum):
            _, position[i] = vrep.simxGetObjectPosition(
                clientID, quads[i], -1, vrep.simx_opmode_buffer)
            _, velocity[i], _ = vrep.simxGetObjectVelocity(
                clientID, quads[i], vrep.simx_opmode_buffer)
            _, res, closest[i], _, _ = vrep.simxReadProximitySensor(
                clientID, proxs[i], vrep.simx_opmode_buffer)
            if not res:
                closest[i] = [0, 0, 0]
            closest[i][2] = 0

        # compute visible quadrotors
        for i in range(quadsNum):
            for j in range(quadsNum):
                if i != j:
                    temp = ut.sub(position[i], position[j])
                    if ut.norm(temp) < viewRange:
                        visibleQuads[i][j] = 1
                    else:
                        visibleQuads[i][j] = 0

        for i in range(quadsNum):
            # compute separation force
            for j in range(quadsNum):
                if i != j and visibleQuads[i][j] == 1:
                    temp = ut.sub(position[i], position[j])
                    nrm = ut.norm(temp)
                    if nrm != 0:
                        temp = ut.mul(temp, kS[0] / (nrm**kS[1]))
                        separation[i] = ut.add(separation[i], temp)

            # compute cohesion and alignment forces
            center = [0, 0, 0]  # center of the swarm
            if sum(visibleQuads[i]) != 0:
                for j in range(quadsNum):
                    if i != j and visibleQuads[i][j] == 1:
                        temp = ut.mul(position[j], 1 / sum(visibleQuads[i]))
                        center = ut.add(center, temp)
                        temp = ut.mul(velocity[j], 1 / sum(visibleQuads[i]))
                        alignment[i] = ut.add(alignment[i], temp)
                cohesion[i] = ut.sub(center, position[i])
            nrm = ut.norm(cohesion[i])
            if nrm != 0:
                cohesion[i] = ut.mul(cohesion[i], kC[0] / (nrm**kC[1]))
            nrm = ut.norm(alignment[i])
            if nrm != 0:
                alignment[i] = ut.mul(alignment[i], kA[0] / (nrm**kA[1]))

            # compute path following force
            check = False
            if not leadfoll or i == leader or end:
                nrm = ut.norm(
                    ut.sub(position[i][0:2], path[individualTarget[i]][0:2]))
                if end:
                    if finished[i] == 0 and nrm < 2:
                        finished[i] += 1
                    if sum(finished) == quadsNum:
                        return ec
                else:
                    if individualTarget[i] != 0:
                        if not last[i]:
                            tmp = min(individualTarget)
                            if individualTarget[i] == tmp and tmp != max(
                                    individualTarget):
                                cnt[i] += 1
                            vec1 = ut.sub(path[individualTarget[i] - 1],
                                          path[individualTarget[i]])
                            vec2 = ut.sub(position[i],
                                          path[individualTarget[i]])
                            if nrm <= 1 or cnt[i] > 30 or ut.angle(
                                    vec1, vec2) >= math.pi / 2:
                                if cnt[i] != 0:
                                    cnt = [0] * quadsNum
                                finished[individualTarget[i]] += 1
                                if leadfoll or finished[
                                        individualTarget[i]] == quadsNum:
                                    check = True
                                if individualTarget[i] < len(path) - 1:
                                    individualTarget[i] += 1
                                else:
                                    last[i] = True
                    else:
                        vec1 = ut.sub(path[individualTarget[i] + 1],
                                      path[individualTarget[i]])
                        vec2 = ut.sub(position[i], path[individualTarget[i]])
                        if nrm <= 1 or ut.angle(vec1, vec2) <= math.pi / 2:
                            finished[individualTarget[i]] += 1
                            if leadfoll or finished[
                                    individualTarget[i]] == quadsNum:
                                check = True
                            individualTarget[i] += 1
                    if check:
                        t2 = vrep.simxGetLastCmdTime(clientID)
                        ec.append((t2 - t1) / 1000)
                        print('Edge #' + str(number) + ': ' +
                              str((t2 - t1) / 1000) + 's')
                        number += 1
                        if number == len(path):
                            return ec
                        t1 = t2
                        if (leadfoll and finished[-1]
                                == 1) or finished[-1] == quadsNum:
                            end = True
                            individualTarget = [0] * quadsNum
                            finished = [0] * quadsNum
                destination[i] = ut.sub(path[individualTarget[i]], position[i])
                nrm = ut.norm(destination[i])
                if nrm != 0:
                    destination[i] = ut.mul(destination[i],
                                            kD[0] / (nrm**kD[1]))

            # compute output force without obstacle avoidance
            output[i] = separation[i]
            output[i] = ut.add(output[i], cohesion[i])
            output[i] = ut.add(output[i], alignment[i])
            output[i] = ut.add(output[i], destination[i])

            # compute obstacle avoidance force
            # angle = ut.angle(closest[i], output[i])
            # if angle > math.pi/2+0.3:
            #     avoidance[i] = [0, 0, 0]
            # else:
            avoidance[i] = ut.sub([0, 0, 0], closest[i])
            nrm = ut.norm(avoidance[i])
            if nrm != 0:
                avoidance[i] = ut.mul(avoidance[i], kO[0] / (nrm**kO[1]))

            # compute output force
            output[i] = ut.add(output[i], avoidance[i])
            if position[i][2] < 0.5:
                output[i][2] = 0.05

        # export output to VRep
        for i in range(quadsNum):
            vrep.simxSetObjectPosition(clientID, targets[i], quads[i],
                                       output[i], vrep.simx_opmode_streaming)
Example #22
0
# for i in range(1, len(vert)-1):
#     if costs[i] == -1:
#         _, temp = vrep.simxCreateDummy(clientID, 0.1, black, vrep.simx_opmode_oneshot_wait)
#     else:
#         color = ut.get_color(costs[i]/maxCost)+[0, 0, 0, 64, 64, 64, 0, 0, 0]
#         _, temp = vrep.simxCreateDummy(clientID, 0.1, color, vrep.simx_opmode_oneshot_wait)
#     vrep.simxSetObjectPosition(clientID, temp, -1, vert[i], vrep.simx_opmode_oneshot_wait)

# path visualisation in V-Rep
blue = [0, 0, 255, 0, 0, 0, 64, 64, 64, 0, 0, 0]
pathPoints = [0] * len(paths[0])
for i in range(len(paths[0])):
    _, pathPoints[i] = vrep.simxCreateDummy(clientID, 0.15, blue,
                                            vrep.simx_opmode_oneshot_wait)

temp = ut.sub(vert[-1], vert[0])
quadsEnd = [[0 for _ in range(3)] for _ in range(quadsNum)]
for i in range(quadsNum):
    quadsEnd[i] = ut.add(quadsStart[i], temp)

for i in range(K):
    print('Current path indices: ' + str(paths[i]))
    foundPath = [[0 for _ in range(3)] for _ in range(len(paths[i]))]
    estimated = 0
    for j in range(len(paths[i]) - 1):
        v1 = paths[i][j]
        v2 = paths[i][j + 1]
        if [v1, v2] in ridgeVert:
            idx = ridgeVert.index([v1, v2])
        else:
            idx = ridgeVert.index([v2, v1])
Example #23
0
 def _get_direction(self):
     assert len(self.coords) > 1
     return sub(self.coords[0], self.coords[1])
Example #24
0
 def potential_positions(self):
     return [add(self.head, d) for d in DIR_VECTORS if d != sub((0, 0), self.direction)]
Example #25
0
        for char in item[3]:
            if char == c:
                count += 1
        if count >= item[0] and count <= item[1]:
            valid += 1
    return valid


def part2(list) -> int:
    valid = 0
    for item in list:
        pos1 = item[0]
        pos2 = item[1]
        c = item[2]
        w = item[3]

        if (
            w[pos1 - 1] == c
            and w[pos2 - 1] != c
            or w[pos1 - 1] != c
            and w[pos2 - 1] == c
        ):
            valid += 1
    return valid


if __name__ == "__main__":
    get_input()
    sub(part1(readFile()), "a")
    sub(part2(readFile()), "b")
Example #26
0
from objects import GameMob


utils.title('MOBS')


###
#   GLOBALS
###
ITEMS = []
ITEMS_STR = []

###
#   LOOK FOR CORRECT JAVA FILES
###
utils.sub("Looking for java files...")
#utils.sub("Keywords: %s" % ', '.join(conf.ACHIEVEMENTS_JAVA_KEYWORDS))
for keyword in conf.MOBS_JAVA_KEYWORDS:
    cmd = run("grep '%s' ./classes/*" % keyword)
    for result in cmd:
        for line in result.split('\n'):
            if line and result is not '':
                java_file = os.path.basename(line.strip().split()[0][:-1])
                if java_file not in conf.MOBS_FILES:
                    utils.echo("%s " % java_file, end='')
                    conf.MOBS_FILES.append(java_file)

utils.echo('\r')

###
#   GET ITEMS INFO FROM CLASSFILE
def voro_start(clientID, obstacles, border):
    """
    Creates a Voronoi diagram around obstacles using vtk_voro
    :param clientID: ID of the VRep connection
    :param obstacles: list of obstacle handles
    :param border: scene border [width, height]
    :return: list of graph vertices, indices of edge vertices, gaps for each edge
    """

    border = [[-border[0] / 2, -border[1] / 2],
              [-border[0] / 2, border[1] / 2], [border[0] / 2, border[1] / 2],
              [border[0] / 2, -border[1] / 2]]
    obsNum = len(obstacles)
    output = []
    for i in range(obsNum):
        # get data from V-Rep
        _, position = vrep.simxGetObjectPosition(clientID, obstacles[i], -1,
                                                 vrep.simx_opmode_oneshot_wait)
        _, orientation = vrep.simxGetObjectOrientation(
            clientID, obstacles[i], -1, vrep.simx_opmode_oneshot_wait)
        orientation = orientation[2]

        _, minX = vrep.simxGetObjectFloatParameter(
            clientID, obstacles[i], 15, vrep.simx_opmode_oneshot_wait)
        _, minY = vrep.simxGetObjectFloatParameter(
            clientID, obstacles[i], 16, vrep.simx_opmode_oneshot_wait)
        _, maxX = vrep.simxGetObjectFloatParameter(
            clientID, obstacles[i], 18, vrep.simx_opmode_oneshot_wait)
        _, maxY = vrep.simxGetObjectFloatParameter(
            clientID, obstacles[i], 19, vrep.simx_opmode_oneshot_wait)

        corners = [[minX, minY], [minX, maxY], [maxX, minY], [maxX, maxY]]

        # compute bounding box corners for angled object
        center = ut.mul(ut.add(corners[0], corners[3]), 0.5)
        radius = ut.norm(ut.sub(corners[0], center))
        zero = ut.mul(ut.add(corners[0], corners[2]), 0.5)

        angle = ut.angle(ut.sub(corners[0], center), ut.sub(
            zero, center)) + orientation + math.pi / 2
        corners[0][0] = center[0] + radius * math.cos(angle)
        corners[0][1] = center[1] + radius * math.sin(angle)

        angle = ut.angle(ut.sub(corners[1], center), ut.sub(
            zero, center)) + orientation + math.pi / 2
        corners[1][0] = center[0] + radius * math.cos(angle)
        corners[1][1] = center[1] + radius * math.sin(angle)

        vec = ut.sub(center, corners[0])
        corners[2] = ut.add(center, vec)

        vec = ut.sub(center, corners[1])
        corners[3] = ut.add(center, vec)

        # move to obstacle position and convert to millimeters
        for j in range(4):
            corners[j] = ut.add(position[0:2], corners[j])
            for k in range(2):
                corners[j][k] = int(corners[j][k] * 1000)
        output.append(corners)

    # merge overlapping obstacles
    ignore = []
    merged = []
    for i in range(obsNum):
        if i not in ignore:
            tmp, visited = ut.merge_obstacles(i, output, ignore)
            ignore = ignore + visited
            for j in range(len(tmp)):
                for k in range(2):
                    tmp[j][k] = int(tmp[j][k])
            merged.append(tmp)

    # write to file to be used by vtk_voro
    file = open('voro_data.txt', 'wt', encoding='utf-8')
    file.write('[BORDER]\n' + str(border[0][0]) + ' ' + str(border[0][1]) +
               '\n' + str(border[1][0]) + ' ' + str(border[1][1]) + '\n' +
               str(border[2][0]) + ' ' + str(border[2][1]) + '\n' +
               str(border[3][0]) + ' ' + str(border[3][1]) + '\n\n')
    for i in range(len(merged)):
        file.write('[OBSTACLE]\n')
        for j in range(len(merged[i])):
            file.write(
                str(merged[i][j][0]) + ' ' + str(merged[i][j][1]) + '\n')
        file.write('\n')
    file.close()

    # execute vtk_voro
    command = "start /wait cmd /c cd " + os.getcwd(
    ) + " && .\\vtk_voro\\build\\Debug\\vtk_voro.exe voro_data.txt"
    os.system(command)

    # read vtk_voro output
    vertices = []
    edges = []
    mode = True
    with open('voro_output.txt', 'rt', encoding='utf-8') as f:
        for line in f:
            tmp = line.split()
            if tmp[0] == "---":
                mode = False
                continue
            if mode:
                for i in range(len(tmp)):
                    tmp[i] = float(tmp[i]) / 1000
                vertices.append(tmp)
            else:
                for i in range(len(tmp)):
                    tmp[i] = int(tmp[i])
                edges.append(tmp)

    # sample the obstacles for computing gaps
    merged.append(border)
    for i in range(len(merged)):
        for j in range(len(merged[i])):
            for k in range(len(merged[i][j])):
                merged[i][j][k] /= 1000

    for i in range(len(merged)):
        size = len(merged[i])
        for j in range(size):
            if j == size - 1:
                p0 = merged[i][j]
                p1 = merged[i][0]
            else:
                p0 = merged[i][j]
                p1 = merged[i][j + 1]
            vec = ut.sub(p1, p0)
            length = ut.norm(vec)
            vec = ut.mul(vec, 1 / length)

            for k in range(int(length / 0.1)):
                merged[i].append(ut.add(p0, ut.mul(vec, (k + 1) * 0.1)))

    # find size of the gap for each edge
    gaps = []
    for edge in edges:
        p0 = vertices[edge[0]]
        p1 = vertices[edge[1]]
        center = ut.mul(ut.add(p0, p1), 0.5)
        vec = ut.sub(p1, p0)
        norm = [-vec[1], vec[0]]
        length = ut.norm(vec)
        line = [norm[0], norm[1], -norm[0] * p0[0] - norm[1] * p0[1]]
        normal = [vec[0], vec[1], -vec[0] * center[0] - vec[1] * center[1]]

        mindist = [sys.maxsize, sys.maxsize]
        closest = [None, None]
        for obstacle in merged:
            for point in obstacle:
                if ut.point_line(point, normal) <= length / 2 + 0.01:
                    dist = ut.point_line(point, line)
                    if line[0] * point[0] + line[1] * point[1] + line[2] > 0:
                        if dist < mindist[0]:
                            mindist[0] = dist
                            closest[0] = point
                    elif dist < mindist[1]:
                        mindist[1] = dist
                        closest[1] = point
        if None in closest:
            gaps.append(None)
        else:
            gaps.append(ut.norm(ut.sub(closest[0], closest[1])))

    return vertices, edges, gaps
Example #28
0
def start(clientID,
          quads,
          targets,
          speed,
          proxs,
          path,
          endpos,
          leadfoll=False):
    """
    Boids model main program
    :param clientID: ID of the VRep connection
    :param quads: quadrotor handles
    :param targets: quadrotor target handles
    :param speed: speed of quadrotors
    :param proxs: proximity sensor handles
    :param path: quadrotor path coordinates
    :param endpos: ending position of quadrotors
    :param leadfoll: True - leader/followers mode, False - all boids following path (default)
    """

    # definition of constants
    quadsNum = len(quads)  # number of quadrotors
    viewRange = 3  # view range of quadrotors
    smp = 0.2  # sampling period
    kS = [0.30,
          2.0]  # separation constants [multiplication const, power const]
    kC = [0.30, 0.0]  # cohesion constants [multiplication const, power const]
    kA = [0.00, 0.0]  # alignment constants [multiplication const, power const]
    kD = [speed,
          1.0]  # path following constants [multiplication const, power const]
    kO = [0.20, 2.0
          ]  # obstacle avoidance constants [multiplication const, power const]

    # data stream init
    for i in range(quadsNum):
        vrep.simxGetObjectPosition(clientID, quads[i], -1,
                                   vrep.simx_opmode_streaming)
        vrep.simxGetObjectVelocity(clientID, quads[i],
                                   vrep.simx_opmode_streaming)
        vrep.simxReadProximitySensor(clientID, proxs[i],
                                     vrep.simx_opmode_streaming)

    # variables init
    position = [[0 for _ in range(3)]
                for _ in range(quadsNum)]  # position of quadrotors
    velocity = [[0 for _ in range(3)]
                for _ in range(quadsNum)]  # velocity of quadrotors
    closest = [[0 for _ in range(3)]
               for _ in range(quadsNum)]  # coords of closest obstacle to quads
    visibleQuads = [[0 for _ in range(quadsNum)]
                    for _ in range(quadsNum)]  # visible quadrotors
    individualTarget = [
        0
    ] * quadsNum  # current waypoint index for each quadrotor

    # get closest boid to starting point
    leader = 0
    _, tmp = vrep.simxGetObjectPosition(clientID, quads[0], -1,
                                        vrep.simx_opmode_buffer)
    dist = ut.norm(ut.sub(path[1], tmp))
    for i in range(1, quadsNum):
        _, tmp = vrep.simxGetObjectPosition(clientID, quads[i], -1,
                                            vrep.simx_opmode_buffer)
        nrm = ut.norm(ut.sub(path[1], tmp))
        if nrm < dist:
            dist = nrm
            leader = i

    # main boids program
    t1 = 0
    t2 = 0.0
    finished = [False] * quadsNum
    count = 0
    counting = False
    file = open('data.txt', 'wt', encoding='utf-8')
    while vrep.simxGetConnectionId(clientID) != -1:
        time.sleep(smp)

        separation = [[0 for _ in range(3)]
                      for _ in range(quadsNum)]  # separation force
        cohesion = [[0 for _ in range(3)]
                    for _ in range(quadsNum)]  # cohesion force
        alignment = [[0 for _ in range(3)]
                     for _ in range(quadsNum)]  # alignment force
        destination = [[0 for _ in range(3)]
                       for _ in range(quadsNum)]  # path following force
        avoidance = [[0 for _ in range(3)]
                     for _ in range(quadsNum)]  # obstacle avoidance force
        output = [[0 for _ in range(3)]
                  for _ in range(quadsNum)]  # output force

        # check if all quads finished
        if counting:
            if count >= 0:
                file.close()
                return (t2 - t1) / 1000
            count += 1
        else:
            for i in range(quadsNum):
                nrm = ut.norm(ut.sub(position[i][0:2], path[-1][0:2]))
                if nrm < 2 and not finished[i]:
                    finished[i] = True
                    print('Quad #' + str(i) + ' finished in ' +
                          str((vrep.simxGetLastCmdTime(clientID) - t1) /
                              1000) + 's')
                    if (leadfoll and finished[leader]) or (
                            not leadfoll and all(_ for _ in finished)):
                        counting = True
                        t2 = vrep.simxGetLastCmdTime(clientID)
                        if endpos is None:
                            file.close()
                            return (t2 - t1) / 1000

        # read data from VRep
        for i in range(quadsNum):
            _, position[i] = vrep.simxGetObjectPosition(
                clientID, quads[i], -1, vrep.simx_opmode_buffer)
            _, velocity[i], _ = vrep.simxGetObjectVelocity(
                clientID, quads[i], vrep.simx_opmode_buffer)
            _, res, closest[i], _, _ = vrep.simxReadProximitySensor(
                clientID, proxs[i], vrep.simx_opmode_buffer)
            if not res:
                closest[i] = [0, 0, 0]
            closest[i][2] = 0

        # write into data file
        ct = vrep.simxGetLastCmdTime(clientID)
        file.write(str(ct))
        for i in range(quadsNum):
            file.write(' ' + str(position[i][0]) + ' ' + str(position[i][1]) +
                       ' ' + str(position[i][2]))
            file.write(' ' + str(velocity[i][0]) + ' ' + str(velocity[i][1]) +
                       ' ' + str(velocity[i][2]))
            file.write(' ' + str(closest[i][0]) + ' ' + str(closest[i][1]))
        file.write('\n')

        # compute visible quadrotors
        for i in range(quadsNum):
            for j in range(quadsNum):
                if i != j:
                    temp = ut.sub(position[i], position[j])
                    if ut.norm(temp) < viewRange:
                        visibleQuads[i][j] = 1
                    else:
                        visibleQuads[i][j] = 0

        for i in range(quadsNum):
            # compute separation force
            for j in range(quadsNum):
                if i != j and visibleQuads[i][j] == 1:
                    temp = ut.sub(position[i], position[j])
                    nrm = ut.norm(temp)
                    if nrm != 0:
                        temp = ut.mul(temp, kS[0] / (nrm**kS[1]))
                        separation[i] = ut.add(separation[i], temp)

            # compute cohesion and alignment forces
            center = [0, 0, 0]  # center of the swarm
            if sum(visibleQuads[i]) != 0:
                for j in range(quadsNum):
                    if i != j and visibleQuads[i][j] == 1:
                        temp = ut.mul(position[j], 1 / sum(visibleQuads[i]))
                        center = ut.add(center, temp)
                        temp = ut.mul(velocity[j], 1 / sum(visibleQuads[i]))
                        alignment[i] = ut.add(alignment[i], temp)
                cohesion[i] = ut.sub(center, position[i])
            nrm = ut.norm(cohesion[i])
            if nrm != 0:
                cohesion[i] = ut.mul(cohesion[i], kC[0] / (nrm**kC[1]))
            nrm = ut.norm(alignment[i])
            if nrm != 0:
                alignment[i] = ut.mul(alignment[i], kA[0] / (nrm**kA[1]))

            # compute path following force
            if not leadfoll or i == leader or counting:
                if not counting:
                    nrm = ut.norm(
                        ut.sub(position[i][0:2],
                               path[individualTarget[i]][0:2]))
                    if individualTarget[i] != 0:
                        vec1 = ut.sub(path[individualTarget[i] - 1],
                                      path[individualTarget[i]])
                        vec2 = ut.sub(position[i], path[individualTarget[i]])
                        if individualTarget[i] < len(path) - 1 and (
                                nrm <= 1
                                or ut.angle(vec1, vec2) >= math.pi / 2):
                            individualTarget[i] += 1
                            # if individualTarget[i] == 2 and min(individualTarget) == 2:
                            #     print((vrep.simxGetLastCmdTime(clientID)-tt)/1000)
                    else:
                        vec1 = ut.sub(path[individualTarget[i] + 1],
                                      path[individualTarget[i]])
                        vec2 = ut.sub(position[i], path[individualTarget[i]])
                        if nrm <= 1 or ut.angle(vec1, vec2) <= math.pi / 2:
                            individualTarget[i] += 1
                            if t1 == 0 and min(individualTarget) == 1:
                                t1 = vrep.simxGetLastCmdTime(clientID)
                            # tt = vrep.simxGetLastCmdTime(clientID)
                    destination[i] = ut.sub(path[individualTarget[i]],
                                            position[i])
                else:
                    destination[i] = ut.sub(endpos[i], position[i])
                nrm = ut.norm(destination[i])
                if nrm != 0:
                    if finished[i]:
                        destination[i] = ut.mul(destination[i], 0.1)
                    else:
                        destination[i] = ut.mul(destination[i],
                                                kD[0] / (nrm**kD[1]))

            # compute output force without obstacle avoidance
            output[i] = separation[i]
            output[i] = ut.add(output[i], cohesion[i])
            output[i] = ut.add(output[i], alignment[i])
            output[i] = ut.add(output[i], destination[i])

            # compute obstacle avoidance force
            # angle = ut.angle(closest[i], output[i])
            # if angle > math.pi/2+0.3:
            #     avoidance[i] = [0, 0, 0]
            # else:
            avoidance[i] = ut.sub([0, 0, 0], closest[i])
            nrm = ut.norm(avoidance[i])
            if nrm != 0:
                avoidance[i] = ut.mul(avoidance[i], kO[0] / (nrm**kO[1]))

            # compute output force
            output[i] = ut.add(output[i], avoidance[i])
            if position[i][2] < 0.5:
                output[i][2] = 0.05

        # export output to VRep
        for i in range(quadsNum):
            vrep.simxSetObjectPosition(clientID, targets[i], quads[i],
                                       output[i], vrep.simx_opmode_streaming)
Example #29
0
if conf.SAVE:
    sys.path.append('../../minecraftcodex')
    os.environ['DJANGO_SETTINGS_MODULE'] = 'local_settings'
    #from database.models import Achievement

###
#   GLOBALS
###
ITEMS = []
ITEMS_STR = []

###
#   LOOK FOR CORRECT JAVA FILES
###
utils.sub("Looking for java files...")
#utils.sub("Keywords: %s" % ', '.join(conf.ACHIEVEMENTS_JAVA_KEYWORDS))
for keyword in conf.MOBS_JAVA_KEYWORDS:
    cmd = run("grep '%s' ./classes/*" % keyword)
    for result in cmd:
        for line in result.split('\n'):
            if line and result is not '':
                java_file = os.path.basename(line.strip().split()[0][:-1])
                if java_file not in conf.MOBS_FILES:
                    utils.echo("%s " % java_file, end='')
                    conf.MOBS_FILES.append(java_file)

utils.echo('\r')

###
#   GET ITEMS INFO FROM CLASSFILE
Example #30
0
def grn_solver(C,
               CRM,
               length,
               Idef,
               Iopt,
               R,
               E,
               typeT,
               solmax,
               KO,
               FE,
               uniqueness,
               limreg,
               P,
               Fixpoint,
               verbose=False,
               printSolutions=True,
               printmain=True,
               maximize=False):
    ## Selected interaction number limit                ##
    interaction_limit = 0
    if (not interaction_limit and Iopt):
        interaction_limit = len(Iopt)
    #____________________________________________________#
    #  Initialization of constants and variables         #
    #____________________________________________________#
    if (not solmax):
        solmax = 10
    if (maximize):
        s = Optimize()
    else:
        s = Solver()
    ngenes = len(C)
    zero, one = buildZERO(ngenes), buildONE(ngenes)
    mustHaveActivator = []
    UP, DOWN = [], []
    chiUP, chiDOWN = dict(), dict()
    for i in range(len(P)):
        if ("-" in P[i]):
            DOWN.append(C[i])
            chiDOWN.setdefault(i, len(DOWN) - 1)
        if ("+" in P[i]):
            UP.append(C[i])
            chiUP.setdefault(i, len(UP) - 1)
        if ("!" in P[i]):
            mustHaveActivator.append(i)
    ## Variable for the subset of optional interactions ##
    Is = BitVec("selected_interactions", len(Iopt)) if (Iopt) else false
    if (maximize and len(Iopt) > 0):
        from utils import sub
        lIs = BV2Int(sub(Is))
        s.add(lIs > 0)
        s.add(lIs <= len(Iopt))
        objective = s.maximize(lIs)
    intVar = [Is]
    ## Variables for the regulation functions           ##
    Rs = [BitVec("grf_%s" % node, 5) for node in C]
    regVar = Rs
    ## Variables for regulators                         ##
    regulators = [[
        BitVec("activators_%s" % gene, ngenes),
        BitVec("repressors_%s" % gene, ngenes)
    ] for gene in C]
    ## Variables for perturbations                      ##
    ko = [BitVec("ko_%s" % e[0], len(DOWN)) for e in E] if (DOWN) else []
    fe = [BitVec("fe_%s" % e[0], len(UP)) for e in E] if (UP) else []
    regInt = []
    stateVar = []
    exp_names = [e[0] for e in E]
    t = time()
    #____________________________________________________#
    #  Conditions on regulation functions                #
    #____________________________________________________#
    verboseIt("Conditions on regulation functions", verbose)
    s = regulation_condition(s, Rs, R, ngenes)
    #____________________________________________________#
    #  Conditions on perturbations                       #
    #____________________________________________________#
    s = perturbation_condition(s, KO, ko, exp_names, DOWN,
                               "KO") if (ko and KO) else s
    s = perturbation_condition(s, FE, fe, exp_names, UP,
                               "FE") if (fe and FE) else s
    #____________________________________________________#
    #  Conditions on regulators                          #
    #____________________________________________________#
    verboseIt("Computation of interactions", verbose)
    if (any([len(c) > 0 for c in CRM])):
        s = crmInteractions_condition(s, Is, Idef, Iopt, CRM, C)
    if (Iopt):
        s = interaction_condition(s, interaction_limit, Iopt, Is)
    for gene in C:
        idx = C.index(gene)
        ## Build lists of (indices of)    ##
        ## activators and                 ##
        ## repressors for input gene      ##
        ## For interaction edges in Iopt  ##
        ## Keep track of the regulatory   ##
        ## interactions for the gene      ##
        regIntActivators, regIntRepressors = None, None
        if (Iopt):
            [regIntActivators,
             regIntRepressors] = buildInteractionDict(Iopt, gene, C, opt=True)
        ## For interaction edges in Idef  ##
        if (Idef):
            [regIntActivators, regIntRepressors
             ] = buildInteractionDict(Idef,
                                      gene,
                                      C,
                                      regIntActivators=regIntActivators,
                                      regIntRepressors=regIntRepressors)
        regInt.append([regIntActivators, regIntRepressors])
        ## Potential regulator is a       ##
        ## regulator iff. the interaction ##
        ## where it is involved is        ##
        ## selected or definite           ##
        activators, repressors = regulators[idx]
        s = regulators_condition(s, Is, activators, regIntActivators, default)
        s = regulators_condition(s, Is, repressors, regIntRepressors, default)
        if (idx in mustHaveActivator):
            s = mustHaveActivator_condition(s, activators, ngenes)
        regulatorList = lambda regulators, regInt: [
            regulators + " of gene " + gene + ": "
        ] + [
            "gene " + C[i] + ", interaction " + str(regInt[i]) + "; "
            for i in regInt.keys()
        ]
        verboseIt(strList2Str(regulatorList("ACTIVATORS", regIntActivators)),
                  verbose)
        verboseIt(strList2Str(regulatorList("REPRESSORS", regIntRepressors)),
                  verbose)
    verboseIt("Computation of GRFs", verbose)
    prepreComputation = [
        prepreCompute(regulators[ci][0], regulators[ci][1])
        for ci in range(len(C))
    ]
    #____________________________________________________#
    #  Conditions on experiments                         #
    #____________________________________________________#
    verboseIt("Conditions on experiments", verbose)
    for exp in E:
        verboseIt("--------- EXPERIMENT \'" + exp[0] + "\'", verbose=printmain)
        ## State variables                  ##
        q = [BitVec(getState(n, exp[0]), ngenes) for n in range(length + 1)]
        stateVar += q
        ## Adding KO and FE constraints     ##
        if (KO and FE and ko and fe):
            [ko_e, s] = pert2full(s, ko[exp_names.index(exp[0])], chiDOWN,
                                  "ko_" + exp[0] + "_f", ngenes)
            [fe_e, s] = pert2full(s, fe[exp_names.index(exp[0])], chiUP,
                                  "fe_" + exp[0] + "_f", ngenes)
            res = lambda x: (x & ~ko_e) | fe_e
        elif (KO and ko):
            [ko_e, s] = pert2full(s, ko[exp_names.index(exp[0])], chiDOWN,
                                  "ko_" + exp[0] + "_f", ngenes)
            res = lambda x: x & ~ko_e
        elif (FE and fe):
            [fe_e, s] = pert2full(s, fe[exp_names.index(exp[0])], chiUP,
                                  "fe_" + exp[0] + "_f", ngenes)
            res = lambda x: x | fe_e
        else:
            res = lambda x: x
        #____________________________________#
        ## States must define a trajectory  ##
        ## in the search space              ##
        #____________________________________#
        existsFixpoint = filter(lambda x: x[1] == exp[0], Fixpoint)
        ## Finds the starting step point    ##
        ## for fix point                    ##
        if (existsFixpoint):
            sstep = existsFixpoint[0][0]
        else:
            sstep = None
## Enforces constraint for all i,   ##
## 0 <= i < sstep, T(q[i],q[i+1])   ##
        s = to_next_state(s, exp[0], prepreComputation, 0,
                          ifthenelse(sstep == None, length, sstep), q, typeT,
                          length, regulators, ngenes, R, Rs, res, verbose)
        ## Fixpoint constraint              ##
        ## for all i, sstep <= i <= length  ##
        ## T(q[i], q[i+1]) (synchronous) and##
        ## q[i] = q[i+1]                    ##
        s = fixpoint_condition(s, exp[0], prepreComputation,
                               ifthenelse(sstep == None, length + 1,
                                          sstep), q, typeT, length, regulators,
                               ngenes, R, Rs, res, verbose)
        #____________________________________#
        ## Experiment values should be      ##
        ## satisfied                        ##
        #____________________________________#
        ## For each observation in e        ##
        ## ee = { n, gene, value }          ##
        for [n, gene, value] in exp[1]:
            verboseIt(
                "Experiment=\'" + exp[0] + "\', Step=" + str(n) + ": grf(" +
                gene + ")=" + str(value), verbose)
            s = experiment_condition(s, q, n, C, gene, value)
    #____________________________________#
    ## Solution processing              ##
    #____________________________________#
    [resList, t, s, res] = getSolution(C,
                                       length,
                                       Iopt,
                                       ngenes,
                                       t,
                                       s,
                                       intVar,
                                       regVar,
                                       stateVar,
                                       regulators,
                                       chiDOWN,
                                       chiUP,
                                       R,
                                       uniqueness,
                                       verbose,
                                       resList=[],
                                       stopSol=(solmax == 1),
                                       printSolutions=printSolutions)
    if (not len(resList)):
        return ([resList, s, regInt])
    sol = 2
    while (sol <= solmax and not res):
        [resList, t, s, res] = getSolution(C,
                                           length,
                                           Iopt,
                                           ngenes,
                                           t,
                                           s,
                                           intVar,
                                           regVar,
                                           stateVar,
                                           regulators,
                                           chiDOWN,
                                           chiUP,
                                           R,
                                           uniqueness,
                                           verbose,
                                           resList=resList,
                                           solNB=sol,
                                           stopSol=(solmax == sol),
                                           printSolutions=printSolutions)
        if (res):
            return ([resList, s, regInt])
        sol += 1
    if (sol == solmax + 1):
        verboseIt("Maximum number of solutions reached.\n", printSolutions)
    if (sol > 0):
        verboseIt("There are solutions.\n", printSolutions)
    return ([resList, s, regInt])
Example #31
0
def rule19(q, a, r, c):
    return (UGT(sub(q & a), sub(q & r)))
Example #32
0
def showEdges():
    fig = plt.figure()
    fig.canvas.mpl_connect('button_press_event', onclick)

    #calculate smoothed normalmap
    smoothing = 3
    maxdepth = 0
    width = utils.getWidth()
    height = utils.getHeight()
    normalmap = np.zeros((width, height, 3))
    for x in range(1 + smoothing, width - 1 - smoothing):
        for y in range(1 + smoothing, height - 1 - smoothing):
            maxdepth = max(maxdepth, utils.parseDepth(x, y))
            cmx = utils.convert2Dto3D(
                calibration[1], x - 1, y,
                utils.parseDepthSmoothed(x - 1, y, smoothing))
            cmy = utils.convert2Dto3D(
                calibration[1], x, y - 1,
                utils.parseDepthSmoothed(x, y - 1, smoothing))
            cpx = utils.convert2Dto3D(
                calibration[1], x + 1, y,
                utils.parseDepthSmoothed(x + 1, y, smoothing))
            cpy = utils.convert2Dto3D(
                calibration[1], x, y + 1,
                utils.parseDepthSmoothed(x, y + 1, smoothing))
            n = utils.normalize(
                utils.cross(utils.sub(cpx, cmx), utils.sub(cpy, cmy)))
            normalmap[x][height - y - 1][0] = min(abs(n[0]), 1)
            normalmap[x][height - y - 1][1] = min(abs(n[1]), 1)
            normalmap[x][height - y - 1][2] = min(abs(n[2]), 1)

    #fade normalmap
    #for x in range(1, width):
    #  for y in range(1, height):
    #    factor = utils.parseDepth(x, y) / maxdepth
    #    normalmap[x][height - y - 1][0] *= (1 - factor)
    #    normalmap[x][height - y - 1][1] *= (1 - factor)
    #    normalmap[x][height - y - 1][2] *= (1 - factor)

    #calculate edgemap
    edgemap = np.zeros((width, height, 3))
    for x in range(2, width - 2):
        for y in range(2, height - 2):

            #calculate edge from depthmap
            d = utils.convert2Dto3D(calibration[1], x, y,
                                    utils.parseDepth(x, y))
            mx = utils.convert2Dto3D(calibration[1], x - 1, y,
                                     utils.parseDepth(x - 1, y))
            my = utils.convert2Dto3D(calibration[1], x, y - 1,
                                     utils.parseDepth(x, y - 1))
            px = utils.convert2Dto3D(calibration[1], x + 1, y,
                                     utils.parseDepth(x + 1, y))
            py = utils.convert2Dto3D(calibration[1], x, y + 1,
                                     utils.parseDepth(x, y + 1))
            edge = max(max(utils.length(d, mx), utils.length(d, my)),
                       max(utils.length(d, px), utils.length(d, py)))
            if edge > 0.1:  # difference of depth in meters
                edgemap[x][height - y - 1][1] = 1

            #calculate edge from normalmap
            d = normalmap[x][height - y - 1]
            mx = normalmap[x - 1][height - y - 1]
            my = normalmap[x][height - y - 1 - 1]
            px = normalmap[x + 1][height - y - 1]
            py = normalmap[x][height - y - 1 + 1]
            edge = max(max(utils.dot(d, mx), utils.dot(d, my)),
                       max(utils.dot(d, px), utils.dot(d, py)))
            if edge > 0.9:  # normal matching in percentage
                edgemap[x][height - y - 1][0] = 1

    #calculate output
    output = np.zeros((width, height, 3))
    for x in range(2, width - 2):
        for y in range(2, height - 2):
            if edgemap[x][height - y - 1][1] == 1:
                output[x][height - y - 1][2] = 1
            else:
                if edgemap[x][height - y - 1][0] == 0:
                    if edgemap[x - 1][height - y - 1][0] == 1:
                        output[x][height - y - 1][1] = 1
                    if edgemap[x][height - y - 1 - 1][0] == 1:
                        output[x][height - y - 1][1] = 1
                    if edgemap[x + 1][height - y - 1][0] == 1:
                        output[x][height - y - 1][1] = 1
                    if edgemap[x][height - y - 1 + 1][0] == 1:
                        output[x][height - y - 1][1] = 1

    #plt.imshow(normalmap, extent=[0, height, 0, width])
    #plt.imshow(edgemap, extent=[0, height, 0, width])
    plt.imshow(output, extent=[0, height, 0, width])
def load_map(shift, enlarge, include_border, clientID):
    """
    Loads map from voro_data.txt, creates Voronoi diagram and adjusts the output
    :param shift: shift the map by [x,y]
    :param enlarge: enlarge the map
    :param include_border: include border when computing size of gaps
    :param clientID: ID of the VRep connection (only for visualization)
    :return: list of graph vertices, indices of edge vertices, gaps for each edge
    """

    # read map file
    border = []
    obstacles = [[]]
    mode = True
    idx = 0
    with open('voro_data.txt', 'rt', encoding='utf-8') as f:
        for line in f:
            tmp = line.split()
            if tmp:
                if tmp[0].lower() == '[border]':
                    mode = True
                elif tmp[0].lower() == '[obstacle]':
                    obstacles.append([])
                    idx += 1
                    mode = False
                else:
                    if mode:
                        tmp[0] = float(tmp[0]) + shift[0]
                        tmp[1] = float(tmp[1]) + shift[1]
                        for i in range(len(tmp)):
                            tmp[i] = enlarge * float(tmp[i]) / 1000
                        border.append(tmp)
                    else:
                        tmp[0] = float(tmp[0]) + shift[0]
                        tmp[1] = float(tmp[1]) + shift[1]
                        for i in range(len(tmp)):
                            tmp[i] = enlarge * float(tmp[i]) / 1000
                        obstacles[idx].append(tmp)
    del obstacles[0]

    # execute vtk_voro
    command = "start /wait cmd /c cd " + os.getcwd(
    ) + " && .\\vtk_voro\\build\\Debug\\vtk_voro.exe voro_data.txt"
    os.system(command)

    # read vtk_voro output
    vertices = []
    edges = []
    mode = True
    with open('voro_output.txt', 'rt', encoding='utf-8') as f:
        for line in f:
            tmp = line.split()
            if tmp[0] == "---":
                mode = False
                continue
            if mode:
                tmp[0] = float(tmp[0]) + shift[0]
                tmp[1] = float(tmp[1]) + shift[1]
                for i in range(len(tmp)):
                    tmp[i] = enlarge * float(tmp[i]) / 1000
                vertices.append(tmp)
            else:
                for i in range(len(tmp)):
                    tmp[i] = int(tmp[i])
                edges.append(tmp)

    # for vertex in vertices:
    #     _, tmp = vrep.simxCreateDummy(clientID, 0.1, None, vrep.simx_opmode_oneshot_wait)
    #     vrep.simxSetObjectPosition(clientID, tmp, -1, vertex, vrep.simx_opmode_oneshot_wait)

    # sample the obstacles for computing gaps
    if include_border:
        obstacles.append(border)

    # for obstacle in obstacles:
    #     for point in obstacle:
    #         _, tmp = vrep.simxCreateDummy(clientID, 0.1, None, vrep.simx_opmode_oneshot_wait)
    #         vrep.simxSetObjectPosition(clientID, tmp, -1, point, vrep.simx_opmode_oneshot_wait)

    for i in range(len(obstacles)):
        size = len(obstacles[i])
        for j in range(size):
            if j == size - 1:
                p0 = obstacles[i][j]
                p1 = obstacles[i][0]
            else:
                p0 = obstacles[i][j]
                p1 = obstacles[i][j + 1]
            vec = ut.sub(p1, p0)
            length = ut.norm(vec)
            vec = ut.mul(vec, 1 / length)

            for k in range(int(length / 0.1)):
                obstacles[i].append(ut.add(p0, ut.mul(vec, (k + 1) * 0.1)))

    # for obstacle in obstacles:
    #     for point in obstacle:
    #         _, tmp = vrep.simxCreateDummy(clientID, 0.1, None, vrep.simx_opmode_oneshot_wait)
    #         vrep.simxSetObjectPosition(clientID, tmp, -1, point, vrep.simx_opmode_oneshot_wait)

    # find size of the gap for each edge
    gaps = []
    for edge in edges:
        p0 = vertices[edge[0]]
        p1 = vertices[edge[1]]
        center = ut.mul(ut.add(p0, p1), 0.5)
        vec = ut.sub(p1, p0)
        norm = [-vec[1], vec[0]]
        length = ut.norm(vec)
        line = [norm[0], norm[1], -norm[0] * p0[0] - norm[1] * p0[1]]
        normal = [vec[0], vec[1], -vec[0] * center[0] - vec[1] * center[1]]

        mindist = [sys.maxsize, sys.maxsize]
        found = [None, None]
        for obstacle in obstacles:
            for point in obstacle:
                if ut.point_line(point, normal) <= length / 2 + 0.01:
                    dist = ut.point_line(point, line)
                    if line[0] * point[0] + line[1] * point[1] + line[2] > 0:
                        if dist < mindist[0]:
                            mindist[0] = dist
                            found[0] = True
                    elif dist < mindist[1]:
                        mindist[1] = dist
                        found[1] = True
        if None in found:
            gaps.append(None)
        else:
            gaps.append(sum(mindist))

    return vertices, edges, gaps