コード例 #1
0
ファイル: ga.py プロジェクト: Kobrs/TheCreatureProject
    def decode(self, DNA):
        # First 26 bits are encoding of global dopamine parameters, so we treat
        #   them separately.
        dop = b.b_to_int(DNA[0:10]) / 100.
        dopdr = b.b_to_int(DNA[10:26]) / 655360.
        self.DNA = DNA[26:]
        frames_id = self._find_frames()
        self._decode_frame(frames_id)

        return self.Cells, dop, dopdr
コード例 #2
0
ファイル: ga.py プロジェクト: Kobrs/TheCreatureProject
    def _interpret_frame(self, frame):
        """First 8 bits will be the cell id, next 8 bits will be dendrite len,
        further 8 bits will be dendrite passive current(int8). Everything after
        that will be target id, weight and delay triple - id have 8bits,
        weight have 16 divided to two parts: 1 bit for weight sign and 15 bits
        for value multiplied by 10 000 bit and delay 4. This triplet will
        have 28 bit"""

        i0 = 0
        i1 = self.id_len
        cell_id = frame[i0:i1]
        cell_id = b.b_to_int(cell_id)

        i0 = i1
        i1 += self.coord_len
        x = frame[i0:i1]
        x = b.b_to_int(x)

        # i0 = i1
        # i1 += self.coord_len
        # y = frame[i0:i1]
        # y = b.b_to_int(y)

        i0 = i1
        i1 += 8  # dend len
        dend_len = frame[i0:i1]
        dend_len = b.b_to_int(dend_len) + 1  # it cannot be 0

        i0 = i1
        i1 += 8
        dend_pas = frame[i0:i1]
        dend_pas = b.b_to_int(dend_pas) - 127

        # Scan for (index, weight, delay) triples
        iwd_len = self.id_len + 1 + self.w_len + self.d_len  # 1 is w_type
        iwd_triples = []
        i = i1
        while i < len(frame)-(iwd_len-1):
            iwd_frame = frame[i: i+iwd_len]
            iwd_triples.append(self._decode_iwd_triple(iwd_frame))

            i+=iwd_len

        cell_dict = {"x": x, "dend_len": dend_len, "dend_pas": dend_pas,
                     "connections": iwd_triples}
        # Overwrite existing settings or create new
        self.Cells[cell_id] = cell_dict
コード例 #3
0
ファイル: ga.py プロジェクト: Kobrs/TheCreatureProject
    def _decode_iwd_triple(self, iwd_frame):
        i0 = 0
        i1 = self.id_len
        c_id = iwd_frame[i0:i1]
        c_id = b.b_to_int(c_id)

        i0 = i1
        i1 += 1
        w_type = int(iwd_frame[i0:i1])

        i0 = i1
        i1 += self.w_len
        w = iwd_frame[i0:i1]
        # Weights can only be positive
        w = float(b.b_to_int(w)) / 10000.

        i0 = i1
        i1 += self.d_len
        d = iwd_frame[i0:i1]
        d = b.b_to_int(d)

        return c_id, (w_type, w), d
コード例 #4
0
ファイル: algorithms.py プロジェクト: optNGUI/Projekt-KI
def genetic2(self, i_length, generations=50, pop_size=10):
    generations = int(generations)
    pop_size = int(pop_size)
    i_length = int(i_length)
    import binstr, random
    t = self
    logger.info("Started vernünftigen genetischen Algorithmus")

    def ind_to_params(ind):
        params = [None for i in range(i_length)]
        for i in range(i_length):
            params[i] = ind[8 * i:8 * (i + 1)]
        return params

    def params_to_ind(params):
        ind = ''
        for i in params:
            ind += binstr.b_bin_to_gray(binstr.int_to_b(i))
        return ind

    def individuum():
        return params_to_ind([random.randint(0, 256) for i in range(i_length)])

    population = [individuum() for i in range(pop_size)]

    def mutate(ind):
        if len(ind) < 2:
            raise TypeError("Individuum too short")
        for i in range(len(ind)):
            if random.random() < 1 / len(ind):
                if ind[i] == '0':
                    replace = '1'
                else:
                    replace = '0'
                ind = ind[:i] + replace + ind[i + 1:]

    def crossover(ind1, ind2):
        point1, point2 = 0, 255
        while point1 == 0:
            point1 = random.randint(0, 255)
        while point2 == 255:
            point2 = random.randint(0, 255)
        if point1 > point2:  # make sure point1 <= point2
            point1, point2 = point2, point1

        child0 = ind1[:point1] + ind2[point1:point2] + ind1[point2:]
        child1 = ind2[:point1] + ind1[point1:point2] + ind2[point2:]
        return (child0, child1)

    def select():
        cnt = 2
        sum_fit = sum([fitness(ind) for ind in population])
        pop = population[:]
        random.shuffle(pop)
        pairs = []
        for i in range(cnt):
            n = random.uniform(0, sum_fit)
            m = random.uniform(0, sum_fit)
            tmp_sum = 0
            first, second = None, None
            for ind in pop:
                tmp_sum += fitness(ind)
                if tmp_sum >= n:
                    first = ind
                    break
            tmp_sum = 0
            for ind in pop:
                tmp_sum += fitness(ind)
                if tmp_sum >= m:
                    second = ind
                    break
            if first is None or second is None:
                print("FAILED")
                raise RuntimeError("Ooops")
            pairs.append((first, second))
        print(str(pairs))
        return pairs

    def fitness(ind):
        params = ind_to_params(ind)
        params = [int(x) for x in params]
        return t.fitness(*params)

    for i in range(generations):
        logger.debug("Generation {i}".format(i=i))
        parents = select()
        children = []
        for p in parents:
            ind1, ind2 = p
            children.extend(crossover(ind1, ind2))
        n = len(population)
        for child in children:
            if child not in population:
                population.append(child)
        #print(str(len(population)))
        while len(population) > n:  # O(|children|)
            population.remove(min(population, key=fitness))
        for i, ind in enumerate(population):
            new_ind = (ind + '.')[:-1]
            mutate(new_ind)
            if fitness(new_ind) >= fitness(ind) and new_ind not in population:
                population[i] = new_ind
        if (algkill[t.msg.id] is not None):
            break

    best = max(population, key=fitness)

    bestfit = fitness(best)
    best = ind_to_params(best)
    best = [binstr.b_to_int(i) for i in best]
    return (best, bestfit)
コード例 #5
0
ファイル: mmfe.py プロジェクト: alacrities/MMFE8Readout
    def daq_readOut(self):
        data       = None
        fifo_count = 0
        attempts   = 10
        while fifo_count == 0 and attempts > 0:
            attempts -= 1
            message = "r 0x44A10014 1" # word count of data fifo
            data = self.udp.udp_client(message, self.UDP_IP, self.UDP_PORT)
            if data != None:
                data_list  = data.split(" ")
                fifo_count = int(data_list[2], 16)
            time.sleep(1)

        print "FIFOCNT ", fifo_count
        if data == None or fifo_count == 0:
            print "Warning: Did not receive data. Stop readout."
            return
        if fifo_count == 0:
            print "Warning: found 0 FIFO counts. Stop readout."
            return
        if fifo_count % 2 != 0:
            print "Warning: Lost one count in fifo reading."
            fifo_count -= 1

        peeks_per_cycle = 10
        cycles    = fifo_count / peeks_per_cycle
        remainder = fifo_count % peeks_per_cycle

        for cycle in reversed(xrange(1+cycles)):
            
            peeks     = peeks_per_cycle if cycle > 0 else remainder
            message   = "k 0x44A10010 %s" % (peeks)
            data      = self.udp.udp_client(message, self.UDP_IP, self.UDP_PORT)
            data_list = data.split()

            for iword in xrange(2, peeks+1, 2):

                word0 = int(data_list[iword],   16)
                word1 = int(data_list[iword+1], 16)

                if not word0 > 0:
                    print "Out of order or no data."
                    continue

                word0 = word0 >> 2       # get rid of first 2 bits (threshold)
                addr  = (word0 & 63) + 1 # get channel number as on GUI
                word0 = word0 >> 6       # get rid of address
                amp   = word0 & 1023     # get amplitude

                word0  = word0 >> 10     # ?
                timing = word0 & 255     # 
                word0  = word0 >> 8      # we will later check for vmm number
                vmm    = word0 &  7      # get vmm number

                bcid_gray = int(word1 & 4095)
                bcid_bin  = binstr.b_gray_to_bin(binstr.int_to_b(bcid_gray, 16))
                bcid_int  = binstr.b_to_int(bcid_bin)

                word1 = word1 >> 12      # later we will get the turn number   
                word1 = word1 >> 4       # 4 bits of zeros?
                immfe = int(word1 & 255) # do we need to convert this?

                to_print = "word0 = %s word1 = %s addr = %s amp = %s time = %s bcid = %s vmm = %s mmfe = %s"
                print to_print % (data_list[iword], data_list[iword+1],
                                  str(addr),     str(amp), str(timing), 
                                  str(bcid_int), str(vmm), str(immfe))

                with open('mmfe8Test.dat', 'a') as myfile:
                    myfile.write(str(int(addr))+'\t'+ str(int(amp))+'\t'+ str(int(timing))+'\t'+ str(bcid_int) +'\t'+ str(vmm) +'\n')
コード例 #6
0
ファイル: algorithms.py プロジェクト: optNGUI/Projekt-KI
def genetic2(self, i_length, generations=50, pop_size=10):
    generations = int(generations)
    pop_size = int(pop_size)
    i_length = int(i_length)
    import binstr, random
    t = self
    logger.info("Started vernünftigen genetischen Algorithmus")
    
    
    def ind_to_params(ind):
        params = [None for i in range(i_length)]
        for i in range(i_length):
            params[i] = ind[8*i:8*(i+1)]
        return params
    
    def params_to_ind(params):
        ind = ''
        for i in params:
            ind+=binstr.b_bin_to_gray(binstr.int_to_b(i))
        return ind
    
    def individuum():
        return params_to_ind([random.randint(0,256) for i in range(i_length)])
    
    population = [individuum() for i in range(pop_size)]
    
    def mutate(ind):
        if len(ind) < 2:
            raise TypeError("Individuum too short")
        for i in range(len(ind)):
            if random.random() < 1/len(ind):
                if ind[i] == '0':
                    replace = '1'
                else:
                    replace = '0'
                ind = ind[:i] + replace + ind[i+1:]
    
    def crossover(ind1, ind2):
        point1, point2 = 0, 255
        while point1 == 0:
            point1 = random.randint(0,255)
        while point2 == 255:
            point2 = random.randint(0,255)
        if point1 > point2: # make sure point1 <= point2
            point1, point2 = point2, point1
        

        child0 = ind1[:point1] + ind2[point1:point2] + ind1[point2:]
        child1 = ind2[:point1] + ind1[point1:point2] + ind2[point2:]
        return (child0,child1)
    
    def select():
        cnt = 2
        sum_fit = sum([fitness(ind) for ind in population])
        pop = population[:]
        random.shuffle(pop)
        pairs = []
        for i in range(cnt):
            n = random.uniform(0, sum_fit)
            m = random.uniform(0, sum_fit)
            tmp_sum = 0
            first, second = None, None
            for ind in pop:
                tmp_sum += fitness(ind)
                if tmp_sum >= n:
                    first = ind
                    break
            tmp_sum = 0
            for ind in pop:
                tmp_sum += fitness(ind)
                if tmp_sum >= m:
                    second = ind
                    break
            if first is None or second is None:
                print("FAILED")
                raise RuntimeError("Ooops")
            pairs.append((first, second))
        print(str(pairs))
        return pairs
    
    def fitness(ind):
        params = ind_to_params(ind)
        params = [int(x) for x in params]
        return t.fitness(*params)
    
    for i in range(generations):
        logger.debug("Generation {i}".format(i=i))
        parents = select()
        children = []
        for p in parents:
            ind1, ind2 = p
            children.extend(crossover(ind1, ind2))
        n = len(population)
        for child in children:
            if child not in population:
                population.append(child)
        #print(str(len(population)))
        while len(population) > n:  # O(|children|)
            population.remove(min(population, key=fitness))
        for i, ind in enumerate(population):
            new_ind = (ind+'.')[:-1]
            mutate(new_ind)
            if fitness(new_ind) >= fitness(ind) and new_ind not in population:
                population[i] = new_ind
        if(algkill[t.msg.id] is not None):
            break
        
    best = max(population, key=fitness)
    
    bestfit = fitness(best)
    best = ind_to_params(best)
    best = [binstr.b_to_int(i) for i in best]
    return (best,bestfit)