1
0
mirror of git://projects.qi-hardware.com/nn-usb-fpga.git synced 2025-04-21 12:27:27 +03:00

Adding evolvable hardware example

This commit is contained in:
Carlos Camargo
2010-10-01 09:03:07 -05:00
parent 5459532f07
commit 1f2712e4de
44 changed files with 4424 additions and 1047 deletions

View File

@@ -0,0 +1,75 @@
DESIGN = ehw
PINS = $(DESIGN).ucf
DEVICE = xc3s500e-VQ100-4
BGFLAGS = -g TdoPin:PULLNONE -g DonePin:PULLUP \
-g CRC:enable -g StartUpClk:CCLK
SIM_CMD = /opt/cad/modeltech/bin/vsim
SIM_COMP_SCRIPT = simulation/$(DESIGN)_TB.do
#SIM_INIT_SCRIPT = simulation/$(DESIGN)_init.do
SIMGEN_OPTIONS = -p $(FPGA_ARCH) -lang $(LANGUAGE)
SAKC_IP = 192.168.254.101
SRC = $(DESIGN).v reg_bank.v
SRC_HDL = evalfit_peripheral.vhd counters.vhd mt.vhd
all: bits
remake: clean-build all
clean:
rm -f *~ */*~ a.out *.log *.key *.edf *.ps trace.dat
clean-build: clean
rm -rf build
cleanall: clean
rm -rf build $(DESIGN).bit
bits: $(DESIGN).bit
#
# Synthesis
#
build/project.src:
@[ -d build ] || mkdir build
@rm -f $@
#If you don't have logicores disable this line
cp *ngc build/
for i in $(SRC); do echo verilog work ../$$i >> $@; done
for i in $(SRC_HDL); do echo VHDL work ../$$i >> $@; done
build/project.xst: build/project.src
echo "run" > $@
echo "-top $(DESIGN) " >> $@
echo "-p $(DEVICE)" >> $@
echo "-opt_mode Area" >> $@
echo "-opt_level 1" >> $@
echo "-ifn project.src" >> $@
echo "-ifmt mixed" >> $@
echo "-ofn project.ngc" >> $@
echo "-ofmt NGC" >> $@
echo "-rtlview yes" >> $@
build/project.ngc: build/project.xst $(SRC)
cd build && xst -ifn project.xst -ofn project.log
build/project.ngd: build/project.ngc $(PINS)
cd build && ngdbuild -p $(DEVICE) project.ngc -uc ../$(PINS)
build/project.ncd: build/project.ngd
cd build && map -pr b -p $(DEVICE) project
build/project_r.ncd: build/project.ncd
cd build && par -w project project_r.ncd
build/project_r.twr: build/project_r.ncd
cd build && trce -v 25 project_r.ncd project.pcf
$(DESIGN).bit: build/project_r.ncd build/project_r.twr
cd build && bitgen project_r.ncd -l -w $(BGFLAGS)
@mv -f build/project_r.bit $@
sim:
cd simulation; $(SIM_CMD) -do $(DESIGN)_TB.do
upload: $(DESIGN).bit
scp $(DESIGN).bit root@$(SAKC_IP):

147
Examples/ehw4/logic/counters.vhd Executable file
View File

@@ -0,0 +1,147 @@
-------------------------------------------------------------------------------
-- --
-- MT32 - Mersenne Twister --
-- Copyright (C) 2007 HT-LAB --
-- --
-- Contact : Use feedback form on the website. --
-- Web: http://www.ht-lab.com --
-- --
-- MT32 files are released under the GNU General Public License. --
-- --
-------------------------------------------------------------------------------
-- --
-- This library is free software; you can redistribute it and/or --
-- modify it under the terms of the GNU Lesser General Public --
-- License as published by the Free Software Foundation; either --
-- version 2.1 of the License, or (at your option) any later version. --
-- --
-- This library is distributed in the hope that it will be useful, --
-- but WITHOUT ANY WARRANTY; without even the implied warranty of --
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU --
-- Lesser General Public License for more details. --
-- --
-- Full details of the license can be found in the file "copying.txt". --
-- --
-- You should have received a copy of the GNU Lesser General Public --
-- License along with this library; if not, write to the Free Software --
-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA --
-- --
-------------------------------------------------------------------------------
-- --
-- Counters, instantiated in top level --
-------------------------------------------------------------------------------
LIBRARY ieee;
USE ieee.std_logic_1164.all;
USE ieee.std_logic_arith.all;
USE ieee.std_logic_unsigned.all;
ENTITY counters IS
GENERIC(
M : integer := 397;
N : integer := 623
);
PORT(
clk : IN std_logic;
resetn : IN std_logic;
ena : IN std_logic;
wea : OUT std_logic;
kk_cnt : OUT std_logic_vector (9 DOWNTO 0);
km_cnt : OUT std_logic_vector (9 DOWNTO 0);
kp_cnt : OUT std_logic_vector (9 DOWNTO 0);
wr_cnt : OUT std_logic_vector (9 DOWNTO 0)
);
END counters ;
--
ARCHITECTURE rtl OF counters IS
signal kk_cnt_s : std_logic_vector (9 DOWNTO 0);
signal km_cnt_s : std_logic_vector (9 DOWNTO 0);
signal kp_cnt_s : std_logic_vector (9 DOWNTO 0);
signal wr_cnt_s : std_logic_vector (9 DOWNTO 0);
BEGIN
process (clk,resetn)
begin
if (resetn='0') then
wea <= '0';
elsif (rising_edge(clk)) then
wea <= ena; -- wea is delayed by 1 clock cycle to
end if; -- prevent writing outside the dpram address
end process; -- address range (0..623)
-------------------------------------------------------------------------------
-- Write counter which is equal to kk-1
-- Required to achieve single cycle read/write
-------------------------------------------------------------------------------
process (clk,resetn)
begin
if (resetn='0') then
wr_cnt_s <= (others => '1');
elsif (rising_edge(clk)) then
if (wr_cnt_s = CONV_STD_LOGIC_VECTOR(N,10)) then
wr_cnt_s <= (others => '0');
elsif ena='1' then
wr_cnt_s <= wr_cnt_s + '1';
end if;
end if;
end process;
wr_cnt <= wr_cnt_s;
-------------------------------------------------------------------------------
-- kk Counter
-------------------------------------------------------------------------------
process (clk,resetn)
begin
if (resetn='0') then
kk_cnt_s <= (others => '0');
elsif (rising_edge(clk)) then
if (kk_cnt_s = CONV_STD_LOGIC_VECTOR(N,10)) then
kk_cnt_s <= (others => '0');
elsif ena='1' then
kk_cnt_s <= kk_cnt_s + '1';
end if;
end if;
end process;
kk_cnt <= kk_cnt_s;
-------------------------------------------------------------------------------
-- kp Counter
-------------------------------------------------------------------------------
process (clk,resetn)
begin
if (resetn='0') then
kp_cnt_s <= "0000000001";
elsif (rising_edge(clk)) then
if (kp_cnt_s = CONV_STD_LOGIC_VECTOR(N,10)) then
kp_cnt_s <= (others => '0');
elsif ena='1' then
kp_cnt_s <= kp_cnt_s + '1';
end if;
end if;
end process;
kp_cnt <= kp_cnt_s;
-------------------------------------------------------------------------------
-- km Counter
-------------------------------------------------------------------------------
process (clk,resetn)
begin
if (resetn='0') then
km_cnt_s <= CONV_STD_LOGIC_VECTOR(M,10);
elsif (rising_edge(clk)) then
if (km_cnt_s = CONV_STD_LOGIC_VECTOR(N,10)) then
km_cnt_s <= (others => '0');
elsif ena='1' then
km_cnt_s <= km_cnt_s + '1';
end if;
end if;
end process;
km_cnt <= km_cnt_s;
end architecture rtl;

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,37 @@
NET clk LOC = "P38";
NET reset LOC = "P30"; #WARNING change to another pin
NET led LOC = "P44";
NET irq_pin LOC = "P71";
#ADDRESS BUS
NET "addr<12>" LOC = "P90";
NET "addr<11>" LOC = "P91";
NET "addr<10>" LOC = "P85";
NET "addr<9>" LOC = "P92";
NET "addr<8>" LOC = "P94";
NET "addr<7>" LOC = "P95";
NET "addr<6>" LOC = "P98";
NET "addr<5>" LOC = "P3";
NET "addr<4>" LOC = "P2";
NET "addr<3>" LOC = "P78";
NET "addr<2>" LOC = "P79";
NET "addr<1>" LOC = "P83";
NET "addr<0>" LOC = "P84";
#DATA BUS
NET "sram_data<7>" LOC = "P4";
NET "sram_data<6>" LOC = "P5";
NET "sram_data<5>" LOC = "P9";
NET "sram_data<4>" LOC = "P10";
NET "sram_data<3>" LOC = "P11";
NET "sram_data<2>" LOC = "P12";
NET "sram_data<1>" LOC = "P15";
NET "sram_data<0>" LOC = "P16";
#CONTROL BUS
NET "nwe" LOC = "P88";
NET "noe" LOC = "P86";
NET "ncs" LOC = "P69";

278
Examples/ehw4/logic/ehw.v Normal file
View File

@@ -0,0 +1,278 @@
`timescale 1ns / 1ps
module ehw(clk, sram_data, addr, nwe, ncs, noe, reset, led,
irq_pin);
parameter B = (7);
input clk, addr, nwe, ncs, noe, reset;
inout [B:0] sram_data;
output led;
output irq_pin;
// synchronize signals
reg sncs, snwe;
reg [12:0] buffer_addr;
reg [B:0] buffer_data;
wire led;
// bram-cpu interfaz
reg we;
reg w_st=0;
reg [B:0] wdBus;
reg [B:0] rdBus;
wire [12:0] addr;
reg [7:0] bae;
// bram-evalfit interfaz
wire we_eval, en_ev;
wire [63:0] ev_do;
wire [63:0] ev_di;
// Interconnection
wire [31:0] mt_rnd;
wire [31:0] reg0;
wire [31:0] reg1;
wire [31:0] reg2;
wire [31:0] reg3;
wire [31:0] reg4;
wire [7:0] status;
wire [15:0] error;
wire [8:0] evalfit_addr;
wire en_fit;
wire [15:0] max_com;
wire [3:0] max_lev;
wire [7:0] control;
reg [7:0] reg_bank [31:0];
wire enReg;
wire [4:0] address;
// Test : LED blinking
reg [25:0] counter;
always @(posedge clk) begin
if (~reset)
counter <= {25{1'b0}};
else
counter <= counter + 1;
end
assign led = counter[24];
// Data Bus direction control
wire T = ~noe | ncs;
assign sram_data = T?8'bZ:rdBus;
// synchronize assignment
always @(negedge clk)
begin
sncs <= ncs;
snwe <= nwe;
buffer_data <= sram_data;
buffer_addr <= addr;
end
// write access cpu to bram
always @(posedge clk)
if(~reset) {w_st, we, wdBus} <= 0;
else begin
wdBus <= buffer_data;
case (w_st)
0: begin
we <= 0;
if(sncs | snwe) w_st <= 1;
end
1: begin
if(~(sncs | snwe)) begin
we <= 1;
w_st <= 0;
end
else we <= 0;
end
endcase
end
// Address Decoder
// We have 2 memory blocks 1: 512 x 64 bits memory 32kb = 4kB 0000 - 0FFF buffer_addr[12] = 0
// 2: Register Bank 1000 - 101F buffer_addr[12] = 1
// SIE has an eight bits data bus, this module generate the required signals to create a 64 bits word.
always @(buffer_addr)
begin
if(~buffer_addr[12]) begin
case (buffer_addr[2:0])
0: bae <= 8'h01;
1: bae <= 8'h02;
2: bae <= 8'h04;
3: bae <= 8'h08;
4: bae <= 8'h10;
5: bae <= 8'h20;
6: bae <= 8'h40;
7: bae <= 8'h80;
endcase
end
else
bae <= 8'h00;
end
wire en1, en2; // enable memory signals
assign en0 = bae[0] | bae[1] | bae[2] | bae[3];
assign en1 = bae[4] | bae[5] | bae[6] | bae[7];
reg[31:0] DIA_Aux;
always @ (posedge clk) begin
if (bae[0]) DIA_Aux[7:0] = wdBus[7:0];
if (bae[1]) DIA_Aux[15:8] = wdBus[7:0];
if (bae[2]) DIA_Aux[23:16] = wdBus[7:0];
if (bae[3]) DIA_Aux[31:24] = wdBus[7:0];
if (bae[4]) DIA_Aux[7:0] = wdBus[7:0];
if (bae[5]) DIA_Aux[15:8] = wdBus[7:0];
if (bae[6]) DIA_Aux[23:16] = wdBus[7:0];
if (bae[7]) DIA_Aux[31:24] = wdBus[7:0];
end
reg [2:0] state, nextstate; //FSM for write in 32bit mode to memory
wire we0, we1;
wire nreset;
assign nreset = ~reset;
parameter S0 = 3'b000;
parameter S1 = 3'b001;
parameter S2 = 3'b010;
always @ (posedge clk, posedge nreset)
if (nreset) state <= S0;
else state <= nextstate;
// next state logic
always@(*)
case (state)
S0:if (bae[3]&we) nextstate = S1;
else
if (bae[7]&we) nextstate = S2;
else nextstate = S0;
S1: nextstate = S0;
S2: nextstate = S0;
default: nextstate = S0;
endcase
// output logic
assign we0 = (state == S1);
assign we1 = (state == S2);
// Read control
reg [7:0] MemDOA;
wire [63:0] DOA_Aux;
always @(posedge clk)
if(~reset)begin
rdBus = 8'h00;
end
else begin
if(enReg)
rdBus = reg_bank[address];
else
rdBus = MemDOA[7:0];
end
// memory output mux
always @(buffer_addr[2:0])
case (buffer_addr[2:0])
0 : MemDOA = DOA_Aux[7:0];
1 : MemDOA = DOA_Aux[15:8];
2 : MemDOA = DOA_Aux[23:16];
3 : MemDOA = DOA_Aux[31:24];
4 : MemDOA = DOA_Aux[39:32];
5 : MemDOA = DOA_Aux[47:40];
6 : MemDOA = DOA_Aux[55:48];
7 : MemDOA = DOA_Aux[63:56];
default: MemDOA = 8'h00;
endcase
// Store Inputs
always @(posedge clk)
begin
if(enReg) begin
reg_bank[20] = error[7:0];
reg_bank[21] = error[15:8];
reg_bank[22] = status[7:0];
reg_bank[24] = mt_rnd[7:0];
reg_bank[25] = mt_rnd[15:8];
reg_bank[26] = mt_rnd[23:16];
reg_bank[27] = mt_rnd[31:24];
end
end
assign address[4:0] = buffer_addr[4:0];
assign enReg = buffer_addr[12];
assign reg0[7:0] = reg_bank[0];
assign reg0[15:8] = reg_bank[1];
assign reg0[23:16] = reg_bank[2];
assign reg0[31:24] = reg_bank[3];
assign reg1[7:0] = reg_bank[4];
assign reg1[15:8] = reg_bank[5];
assign reg1[23:16] = reg_bank[6];
assign reg1[31:24] = reg_bank[7];
assign reg2[7:0] = reg_bank[8];
assign reg2[15:8] = reg_bank[9];
assign reg2[23:16] = reg_bank[10];
assign reg2[31:24] = reg_bank[11];
assign reg3[7:0] = reg_bank[12];
assign reg3[15:8] = reg_bank[13];
assign reg3[23:16] = reg_bank[14];
assign reg3[31:24] = reg_bank[15];
assign reg4[7:0] = reg_bank[16];
assign reg4[15:8] = reg_bank[17];
assign reg4[23:16] = reg_bank[18];
assign reg4[31:24] = reg_bank[19];
assign max_lev = reg_bank[28];
assign control = reg_bank[29];
assign max_com[7:0] = reg_bank[30];
assign max_com[15:8] = reg_bank[31];
// Write control
always @(negedge clk)
if(we & enReg) begin
case (address)
0: reg_bank[0] = wdBus;
1: reg_bank[1] = wdBus;
2: reg_bank[2] = wdBus;
3: reg_bank[3] = wdBus;
4: reg_bank[4] = wdBus;
5: reg_bank[5] = wdBus;
6: reg_bank[6] = wdBus;
7: reg_bank[7] = wdBus;
8: reg_bank[8] = wdBus;
9: reg_bank[9] = wdBus;
10: reg_bank[10] = wdBus;
11: reg_bank[11] = wdBus;
12: reg_bank[12] = wdBus;
13: reg_bank[13] = wdBus;
14: reg_bank[14] = wdBus;
15: reg_bank[15] = wdBus;
16: reg_bank[16] = wdBus;
17: reg_bank[17] = wdBus;
18: reg_bank[18] = wdBus;
19: reg_bank[19] = wdBus;
28: reg_bank[28] = wdBus;
29: reg_bank[29] = wdBus;
30: reg_bank[30] = wdBus;
31: reg_bank[31] = wdBus;
endcase
end
RAMB16_S36_S36 #(.INIT_00(256'hABCDEF00_00000000_00000000_00000000_00000000_00000000_00000000_76543210) )
mem0 ( .CLKA(~clk), .ENA(en0), .SSRA(1'b0), .ADDRA(buffer_addr[11:3]), .WEA(we0), .DIA(DIA_Aux[31:0]), .DIPA(0'b0), .DOA(DOA_Aux[31:0]),
.CLKB(~clk), .ENB(en_ev), .SSRB(1'b0), .ADDRB(evalfit_addr), .WEB(we_eval), .DIB(ev_do[31:0]), .DIPB(0'b0), .DOB(ev_di[31:0]));
RAMB16_S36_S36 mem1( .CLKA(~clk), .ENA(en1), .SSRA(1'b0), .ADDRA(buffer_addr[11:3]), .WEA(we1), .DIA(DIA_Aux[31:0]), .DIPA(0'b0), .DOA(DOA_Aux[63:32]),
.CLKB(~clk), .ENB(en_ev),.SSRB(1'b0), .ADDRB(evalfit_addr), .WEB(we_eval), .DIB(ev_do[63:32]), .DIPB(0'b0), .DOB(ev_di[63:32]));
// evalfit_peripheral
evalfit_peripheral evalfit( .clk(clk), .reset(~reset), .habilita(control[0]), .maxcombs(max_com), .nivel_max(max_lev),
.peripheral_mem_in(ev_di), .peripheral_mem_en(en_eval), .peripheral_mem_out(ev_do), .peripheral_mem_we(we_eval),
.peripheral_mem_addr(evalfit_addr), .evalfit3_estado(status), .errores(error),
.fin_ack(irq_pin), .reg0_s(reg0), .reg1_s(reg1), .reg2_s(reg2), .reg3_s(reg3), .reg4_s(reg4));
// MersenneTwister
mt_mem random( .clk(clk), .ena(1'b1), .resetn(reset), .random(mt_rnd));
endmodule

View File

@@ -0,0 +1,482 @@
-- 07/11/08
-- Evalfit_peripheral
-- Evalua un arbol de 5 pentarboles, por ahora es valido hasta para *** 14 variables ***
-- Funciona hasta con 14 vars.
-- mapa:
-- 0 - 0x3F Cromosoma
-- 0x40 - 0x13F Objetivo. 16384 bits. Se empieza por el bit 0 MSB.
-- Cromosoma en memoria
-- bit bit Contenido
-- 28 a 31 Nivel del arbol
-- 32 a 47 LUT o tabla del arbol
-- 48 a 63 Variables de entrada del arbol (4 bits por variable)
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;---- Uncomment the following library declaration if instantiating
---- any Xilinx primitives in this code.
library UNISIM;
use UNISIM.VComponents.all;
entity evalfit_peripheral is
Port ( clk, reset, habilita: in STD_LOGIC;
maxcombs : in STD_LOGIC_VECTOR (0 to 15);
nivel_max : in STD_LOGIC_VECTOR (0 to 3);
peripheral_mem_in : in STD_LOGIC_VECTOR (0 to 63);
peripheral_mem_en : out std_logic;
peripheral_mem_out : out STD_LOGIC_VECTOR (0 to 63);
peripheral_mem_we : out STD_LOGIC;
peripheral_mem_addr : out STD_LOGIC_VECTOR (0 to 8);
evalfit3_estado : out std_logic_vector(0 to 7);
errores : out STD_LOGIC_VECTOR (0 to 15);
fin_ack : out std_logic;
reg0_s : out STD_LOGIC_VECTOR (0 to 31);
reg1_s : out STD_LOGIC_VECTOR (0 to 31);
reg2_s : out STD_LOGIC_VECTOR (0 to 31);
reg3_s : out STD_LOGIC_VECTOR (0 to 31);
reg4_s : out STD_LOGIC_VECTOR (0 to 31)
);
end evalfit_peripheral;
architecture Behavioral of evalfit_peripheral is
function mux16(sel: in std_logic_vector(0 to 3); ent: in std_logic_vector(0 to 15)) return std_logic is
begin
case sel is
when "0000" => return ent(15);
when "0001" => return ent(14);
when "0010" => return ent(13);
when "0011" => return ent(12);
when "0100" => return ent(11);
when "0101" => return ent(10);
when "0110" => return ent(9);
when "0111" => return ent(8);
when "1000" => return ent(7);
when "1001" => return ent(6);
when "1010" => return ent(5);
when "1011" => return ent(4);
when "1100" => return ent(3);
when "1101" => return ent(2);
when "1110" => return ent(1);
when others => return ent(0);
end case;
end mux16;
function mux4(sel: in std_logic_vector(0 to 1); ent: in std_logic_vector(0 to 3)) return std_logic is
begin
case sel is
when "00" => return ent(3);
when "01" => return ent(2);
when "10" => return ent(1);
when others => return ent(0);
end case;
end mux4;
-- senales para evaluar funciones
signal reg0, reg1, reg2, reg3, reg4, regn3, regn4:STD_LOGIC_VECTOR (0 to 31);
signal reg0_sig, reg1_sig, reg2_sig, reg3_sig, reg4_sig, regn3_sig, regn4_sig :STD_LOGIC_VECTOR (0 to 31);
signal sel_aux0, sel_aux1, sel_aux2, sel_aux3, sel_aux4, sel_auxn3, sel_auxn4, sal_arbol, minter_n3, minter_n4 : std_logic_vector(0 to 3);
signal salida_s, fin_ack_sig, fifow_wrreq_sig: std_logic;
signal entrada, errores_aux, errores_sig, salida_nivel : STD_LOGIC_VECTOR (0 to 15);
-- senales para las memorias, guardan resultados de arboles intermedios
signal DO_n2, DI_n2, DO_n3, DI_n3, DO_n4, DI_n4: std_logic_vector(3 downto 0);
signal ADDR_n2, ADDR_n3, ADDR_n4: std_logic_vector(0 to 13);
signal WE_n2, WE_n3, WE_n4: std_logic_vector(3 downto 0);
signal WE_n2_sig, WE_n3_sig, WE_n4_sig: std_logic_vector(3 downto 0);
signal EN_n2, SSR, EN_n3, EN_n4: std_logic;
-- senales para el control
type estado is (reset1, reset2, inicio, proceso, n1, n2, n3, n4, precuenta, cuenta, final, final2);
signal ep, es: estado;
signal nivel, nivel_sig, nivel_reg: std_logic_vector(0 to 3);
signal c1, c1_sig, c2, c2_sig, c3, c3_sig, c4, c4_sig: std_logic_vector(0 to 1);
signal conta, conta_sig, conta2, conta2_sig: std_logic_vector(0 to 15);
signal estado_evalf3, estado_evalf3_sig: std_logic_vector(0 to 7);
signal peripheral_mem_addr_aux, peripheral_mem_addr_sig, peripheral_mem_addr_crom_sig,peripheral_mem_addr_crom : STD_LOGIC_VECTOR (0 to 8);
begin
process(ep, habilita, reg0, reg1, reg2, reg3, reg4, regn3, regn4, nivel, c1, c2, c3, c4, conta,
salida_s, salida_nivel, WE_n2, WE_n3, WE_n4, nivel_max,
maxcombs, peripheral_mem_in, peripheral_mem_addr_crom, peripheral_mem_addr_aux)
begin
es <= reset1;
WE_n2_sig <= "0000";
WE_n3_sig <= "0000";
WE_n4_sig <= "0000";
reg0_sig <= reg0;
reg1_sig <= reg1;
reg2_sig <= reg2;
reg3_sig <= reg3;
reg4_sig <= reg4;
regn3_sig <= regn3;
regn4_sig <= regn4;
conta_sig <= conta;
conta2_sig <= conta2;
c1_sig <= c1;
c2_sig <= c2;
c3_sig <= c3;
c4_sig <= c4;
DI_n2 <= "0000";
DI_n3 <= "0000";
DI_n4 <= "0000";
fin_ack_sig <= '0';
peripheral_mem_addr_sig <= peripheral_mem_addr_aux;
peripheral_mem_addr_crom_sig <= peripheral_mem_addr_crom;
peripheral_mem_we <= '0';
peripheral_mem_en <= '0';
errores_sig <= errores_aux;
nivel_sig <= nivel_reg;
estado_evalf3_sig <= x"FF";
case ep is
when reset1 => --poner la memoria a 0000
WE_n2_sig <= "1111";
WE_n3_sig <= "1111";
WE_n4_sig <= "1111";
conta2_sig <= (others => '0');
es <= reset2;
when reset2 =>
DI_n2 <= "0000";
DI_n3 <= "0000";
DI_n4 <= "0000";
if(conta2 = maxcombs)then
WE_n2_sig <= "0000";
WE_n3_sig <= "0000";
WE_n4_sig <= "0000";
conta2_sig <= (others => '0');
es <= inicio;
else
WE_n2_sig <= "1111";
WE_n3_sig <= "1111";
WE_n4_sig <= "1111";
conta2_sig <= conta2 + 1;
es <= reset2;
end if;
when inicio =>
if(habilita = '0') then
es <= inicio;
conta_sig <= (others => '0');
conta2_sig <= (others => '0');
peripheral_mem_addr_sig <= (others => '0');
c1_sig <= "00";
c2_sig <= "00";
c3_sig <= "00";
c4_sig <= "00";
errores_sig <= x"0000";
else
es <= proceso;
peripheral_mem_en <= '1';
end if;
estado_evalf3_sig <= x"01";
when proceso =>
peripheral_mem_en <= '1';
if(nivel = "0001")then
case c1 is
when "00" => reg0_sig <= peripheral_mem_in(32 to 63);
when "01" => reg1_sig <= peripheral_mem_in(32 to 63);
when "10" => reg2_sig <= peripheral_mem_in(32 to 63);
when others => reg3_sig <= peripheral_mem_in(32 to 63);
end case;
es <= n1;
elsif(nivel = "0010")then
reg4_sig <= peripheral_mem_in(32 to 63);
WE_n2_sig(conv_integer(c2)) <= '1';
DI_n2(conv_integer(c2)) <= salida_nivel(2);
es <= n2;
elsif(nivel = "0011")then
regn3_sig <= peripheral_mem_in(32 to 63);
WE_n3_sig(conv_integer(c3)) <= '1';
DI_n3(conv_integer(c3)) <= salida_nivel(3);
es <= n3;
elsif(nivel = "0100")then
regn4_sig <= peripheral_mem_in(32 to 63);
WE_n4_sig(conv_integer(c4)) <= '1';
DI_n4(conv_integer(c4)) <= salida_nivel(4);
es <= n4;
elsif(nivel = "1111")then
es <= final2;
end if;
peripheral_mem_addr_sig <= peripheral_mem_addr_aux + 1;
peripheral_mem_addr_crom_sig <= peripheral_mem_addr_aux + 1;
nivel_sig <= nivel;
estado_evalf3_sig <= x"02";
when n1 =>
peripheral_mem_en <= '1';
c1_sig <= c1 + 1;
peripheral_mem_addr_sig <= peripheral_mem_addr_aux;
es <= proceso;
estado_evalf3_sig <= x"03";
when n2 =>
WE_n2_sig(conv_integer(c2)) <= '1';
DI_n2(conv_integer(c2)) <= salida_nivel(2);
peripheral_mem_en <= '1';
peripheral_mem_addr_sig <= "001000000" + ('0' & conta(2 to 9));-- esto es para que evalue el pentarbol y guarde en memoria la salida
es <= precuenta;
conta2_sig <= (others => '0');
estado_evalf3_sig <= x"04";
when n3 =>
WE_n3_sig(conv_integer(c3)) <= '1';
DI_n3(conv_integer(c3)) <= salida_nivel(3);
peripheral_mem_en <= '1';
peripheral_mem_addr_sig <= "001000000" + ('0' & conta(2 to 9));--
es <= precuenta;
conta2_sig <= (others => '0');
estado_evalf3_sig <= x"05";
when n4 =>
WE_n4_sig(conv_integer(c4)) <= '1';
DI_n4(conv_integer(c4)) <= salida_nivel(4);
peripheral_mem_en <= '1';
peripheral_mem_addr_sig <= "001000000" + ('0' & conta(2 to 9));--
es <= precuenta;
conta2_sig <= (others => '0');
estado_evalf3_sig <= x"06";
when precuenta =>
WE_n2_sig <= WE_n2;
WE_n3_sig <= WE_n3;
WE_n4_sig <= WE_n4;
DI_n2(conv_integer(c2)) <= salida_nivel(2);
DI_n3(conv_integer(c3)) <= salida_nivel(3);
DI_n4(conv_integer(c4)) <= salida_nivel(4);
peripheral_mem_en <= '1';
peripheral_mem_addr_sig <= "001000000" + ('0' & conta2(2 to 9));
conta_sig <= conta;
conta2_sig <= conta + 1;
es <= cuenta;
estado_evalf3_sig <= x"07";
when cuenta =>
DI_n2(conv_integer(c2)) <= salida_nivel(2);
DI_n3(conv_integer(c3)) <= salida_nivel(3);
DI_n4(conv_integer(c4)) <= salida_nivel(4);
peripheral_mem_en <= '1';
if(conta = maxcombs)then
WE_n2_sig <= "0000";
WE_n3_sig <= "0000";
WE_n4_sig <= "0000";
conta_sig <= (others => '0');
conta2_sig <= (others => '0');
peripheral_mem_addr_sig <= peripheral_mem_addr_crom; --direccion de mem donde esta el cromosoma
es <= final;
else
WE_n2_sig <= WE_n2;
WE_n3_sig <= WE_n3;
WE_n4_sig <= WE_n4;
conta_sig <= conta + 1;
conta2_sig <= conta2 + 1;
peripheral_mem_addr_sig <= "001000000" + ('0' & conta2(2 to 9));--crear señal conta futura
if(conta(10 to 15) = "111111")then
es <= precuenta;
else
es <= cuenta;
end if;
end if;
if(nivel_reg = nivel_max)then
if(salida_nivel(conv_integer(nivel_max)) = peripheral_mem_in(conv_integer(conta(10 to 15))))then
errores_sig <= errores_aux;
else
errores_sig <= errores_aux + 1;
end if;
else
errores_sig <= errores_aux;
end if;
estado_evalf3_sig <= x"08";
when final =>
if(nivel_reg = "0010")then
c2_sig <= c2 + 1;
elsif(nivel_reg = "0011")then
c3_sig <= c3 + 1;
elsif(nivel_reg = "0100")then
c4_sig <= c4 + 1;
end if;
peripheral_mem_en <= '1';
peripheral_mem_addr_sig <= peripheral_mem_addr_crom;
es <= proceso;
estado_evalf3_sig <= x"09";
when final2 =>
if(habilita = '1') then
es <= final2;
else
es <= inicio;
end if;
fin_ack_sig <= '1';
estado_evalf3_sig <= x"0A";
when others => es <= inicio;
end case;
end process;
process(clk, reset)
begin
if(reset = '1')then
ep <= reset1;
c1 <= "00";
c2 <= "00";
c3 <= "00";
c4 <= "00";
WE_n2 <= "0000";
WE_n3 <= "0000";
WE_n4 <= "0000";
reg0 <= x"00000000";
reg1 <= x"00000000";
reg2 <= x"00000000";
reg3 <= x"00000000";
reg4 <= x"00000000";
regn3 <= x"00000000";
regn4 <= x"00000000";
conta <= (others => '0');
conta2 <= (others => '0');
fin_ack <= '0';
peripheral_mem_addr_aux <= "000000000";
peripheral_mem_addr_crom <= "000000000";
errores_aux <= (others => '0');
nivel_reg <= "0000";
estado_evalf3 <= x"00";
elsif(rising_edge(clk))then
ep <= es;
c1 <= c1_sig;
c2 <= c2_sig;
c3 <= c3_sig;
c4 <= c4_sig;
WE_n2 <= WE_n2_sig;
WE_n3 <= WE_n3_sig;
WE_n4 <= WE_n4_sig;
reg0 <= reg0_sig;
reg1 <= reg1_sig;
reg2 <= reg2_sig;
reg3 <= reg3_sig;
reg4 <= reg4_sig;
regn3 <= regn3_sig;
regn4 <= regn4_sig;
conta <= conta_sig;
conta2 <= conta2_sig;
fin_ack <= fin_ack_sig;
peripheral_mem_addr_aux <= peripheral_mem_addr_sig;
peripheral_mem_addr_crom <= peripheral_mem_addr_crom_sig;
errores_aux <= errores_sig;
nivel_reg <= nivel_sig;
estado_evalf3 <= estado_evalf3_sig;
end if;
end process;
process(nivel_reg, conta, conta2)
begin
case nivel_reg is
when "0000" =>
ADDR_n2 <= conta(2 to 15);
ADDR_n3 <= conta(2 to 15);
ADDR_n4 <= conta(2 to 15);
when "0010" =>
ADDR_n2 <= conta(2 to 15);
ADDR_n3 <= conta(2 to 15);
ADDR_n4 <= conta(2 to 15);
when "0011" =>
ADDR_n2 <= conta2(2 to 15);
ADDR_n3 <= conta(2 to 15);
ADDR_n4 <= conta(2 to 15);
when "0100" =>
ADDR_n2 <= conta(2 to 15);
ADDR_n3 <= conta2(2 to 15);
ADDR_n4 <= conta(2 to 15);
when others =>
ADDR_n2 <= conta2(2 to 15);
ADDR_n3 <= conta2(2 to 15);
ADDR_n4 <= conta2(2 to 15);
end case;
end process;
errores <= errores_aux;
peripheral_mem_addr <= peripheral_mem_addr_aux;
nivel <= peripheral_mem_in(28 to 31);
EN_n2 <= '1';
EN_n3 <= '1';
EN_n4 <= '1';
SSR <= '0';
minter_n3 <= DO_n2;
minter_n4 <= DO_n3;
entrada <= conta;
evalfit3_estado <= estado_evalf3;
reg0_s <= reg0;
reg1_s <= reg1;
reg2_s <= reg2;
reg3_s <= reg3;
reg4_s <= reg4;
salida_nivel(1) <= sal_arbol(3);
sel_aux0(3) <= mux16(reg0(28 to 31), entrada);
sel_aux0(2) <= mux16(reg0(24 to 27), entrada);
sel_aux0(1) <= mux16(reg0(20 to 23), entrada);
sel_aux0(0) <= mux16(reg0(16 to 19), entrada);
sal_arbol(3) <= mux16(sel_aux0, reg0(0 to 15)); -- reg0(0 to 15) = dato_lut
sel_aux1(3) <= mux16(reg1(28 to 31), entrada);
sel_aux1(2) <= mux16(reg1(24 to 27), entrada);
sel_aux1(1) <= mux16(reg1(20 to 23), entrada);
sel_aux1(0) <= mux16(reg1(16 to 19), entrada);
sal_arbol(2) <= mux16(sel_aux1, reg1(0 to 15));
sel_aux2(3) <= mux16(reg2(28 to 31), entrada);
sel_aux2(2) <= mux16(reg2(24 to 27), entrada);
sel_aux2(1) <= mux16(reg2(20 to 23), entrada);
sel_aux2(0) <= mux16(reg2(16 to 19), entrada);
sal_arbol(1) <= mux16(sel_aux2, reg2(0 to 15));
sel_aux3(3) <= mux16(reg3(28 to 31), entrada);
sel_aux3(2) <= mux16(reg3(24 to 27), entrada);
sel_aux3(1) <= mux16(reg3(20 to 23), entrada);
sel_aux3(0) <= mux16(reg3(16 to 19), entrada);
sal_arbol(0) <= mux16(sel_aux3, reg3(0 to 15));
sel_aux4(3) <= mux4(reg4(30 to 31), sal_arbol); --arbol de 2do nivel
sel_aux4(2) <= mux4(reg4(26 to 27), sal_arbol);
sel_aux4(1) <= mux4(reg4(22 to 23), sal_arbol);
sel_aux4(0) <= mux4(reg4(18 to 19), sal_arbol);
salida_nivel(2) <= mux16(sel_aux4, reg4(0 to 15));
sel_auxn3(3) <= mux4(regn3(30 to 31), minter_n3); --arboles de 3er nivel
sel_auxn3(2) <= mux4(regn3(26 to 27), minter_n3);
sel_auxn3(1) <= mux4(regn3(22 to 23), minter_n3);
sel_auxn3(0) <= mux4(regn3(18 to 19), minter_n3);
salida_nivel(3) <= mux16(sel_auxn3, regn3(0 to 15));
sel_auxn4(3) <= mux4(regn4(30 to 31), minter_n4); --arboles de 4to nivel
sel_auxn4(2) <= mux4(regn4(26 to 27), minter_n4);
sel_auxn4(1) <= mux4(regn4(22 to 23), minter_n4);
sel_auxn4(0) <= mux4(regn4(18 to 19), minter_n4);
salida_nivel(4) <= mux16(sel_auxn4, regn4(0 to 15));
ram_nivel20:RAMB16_S1 port map(DO => DO_n2(3 downto 3), ADDR => ADDR_n2, CLK => clk, DI => DI_n2(3 downto 3), EN => EN_n2, SSR => SSR, WE => WE_n2(3));
ram_nivel21:RAMB16_S1 port map(DO => DO_n2(2 downto 2), ADDR => ADDR_n2, CLK => clk, DI => DI_n2(2 downto 2), EN => EN_n2, SSR => SSR, WE => WE_n2(2));
ram_nivel22:RAMB16_S1 port map(DO => DO_n2(1 downto 1), ADDR => ADDR_n2, CLK => clk, DI => DI_n2(1 downto 1), EN => EN_n2, SSR => SSR, WE => WE_n2(1));
ram_nivel23:RAMB16_S1 port map(DO => DO_n2(0 downto 0), ADDR => ADDR_n2, CLK => clk, DI => DI_n2(0 downto 0), EN => EN_n2, SSR => SSR, WE => WE_n2(0));
ram_nivel30:RAMB16_S1 port map(DO => DO_n3(3 downto 3), ADDR => ADDR_n3, CLK => clk, DI => DI_n3(3 downto 3), EN => EN_n3, SSR => SSR, WE => WE_n3(3));
ram_nivel31:RAMB16_S1 port map(DO => DO_n3(2 downto 2), ADDR => ADDR_n3, CLK => clk, DI => DI_n3(2 downto 2), EN => EN_n3, SSR => SSR, WE => WE_n3(2));
ram_nivel32:RAMB16_S1 port map(DO => DO_n3(1 downto 1), ADDR => ADDR_n3, CLK => clk, DI => DI_n3(1 downto 1), EN => EN_n3, SSR => SSR, WE => WE_n3(1));
ram_nivel33:RAMB16_S1 port map(DO => DO_n3(0 downto 0), ADDR => ADDR_n3, CLK => clk, DI => DI_n3(0 downto 0), EN => EN_n3, SSR => SSR, WE => WE_n3(0));
ram_nivel40:RAMB16_S1 port map(DO => DO_n4(3 downto 3), ADDR => ADDR_n4, CLK => clk, DI => DI_n4(3 downto 3), EN => EN_n4, SSR => SSR, WE => WE_n4(3));
ram_nivel41:RAMB16_S1 port map(DO => DO_n4(2 downto 2), ADDR => ADDR_n4, CLK => clk, DI => DI_n4(2 downto 2), EN => EN_n4, SSR => SSR, WE => WE_n4(2));
ram_nivel42:RAMB16_S1 port map(DO => DO_n4(1 downto 1), ADDR => ADDR_n4, CLK => clk, DI => DI_n4(1 downto 1), EN => EN_n4, SSR => SSR, WE => WE_n4(1));
ram_nivel43:RAMB16_S1 port map(DO => DO_n4(0 downto 0), ADDR => ADDR_n4, CLK => clk, DI => DI_n4(0 downto 0), EN => EN_n4, SSR => SSR, WE => WE_n4(0));
end Behavioral;

191
Examples/ehw4/logic/mt.vhd Executable file
View File

@@ -0,0 +1,191 @@
-------------------------------------------------------------------------------
-- --
-- MT32 - Mersenne Twister --
-- Copyright (C) 2007 HT-LAB --
-- --
-- Contact : Use feedback form on the website. --
-- Web: http://www.ht-lab.com --
-- --
-- MT32 files are released under the GNU General Public License. --
-- --
-------------------------------------------------------------------------------
-- --
-- This library is free software; you can redistribute it and/or --
-- modify it under the terms of the GNU Lesser General Public --
-- License as published by the Free Software Foundation; either --
-- version 2.1 of the License, or (at your option) any later version. --
-- --
-- This library is distributed in the hope that it will be useful, --
-- but WITHOUT ANY WARRANTY; without even the implied warranty of --
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU --
-- Lesser General Public License for more details. --
-- --
-- Full details of the license can be found in the file "copying.txt". --
-- --
-- You should have received a copy of the GNU Lesser General Public --
-- License along with this library; if not, write to the Free Software --
-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA --
-- --
-------------------------------------------------------------------------------
-- --
-- Top Level (Synthesis) --
-------------------------------------------------------------------------------
LIBRARY ieee;
USE ieee.std_logic_1164.all;
USE ieee.std_logic_unsigned.all;
USE ieee.std_logic_arith.all;
ENTITY mt_mem IS
PORT(
clk : IN std_logic;
ena : IN std_logic;
resetn : IN std_logic;
random : OUT std_logic_vector (31 DOWNTO 0)
);
END mt_mem ;
LIBRARY ieee;
ARCHITECTURE struct OF mt_mem IS
-- Architecture declarations
-- internal signal declarations
signal kk_cnt : std_logic_vector(9 downto 0);
signal km_cnt : std_logic_vector(9 downto 0);
signal kp_cnt : std_logic_vector(9 downto 0);
signal mt_kk31 : std_logic_vector(0 downto 0);
signal mt_kk_s : std_logic_vector(31 downto 0);
signal mt_km : std_logic_vector(31 downto 0);
signal mt_kp : std_logic_vector(30 downto 0);
signal wea : std_logic;
signal wea_s : std_logic_vector(0 downto 0);
signal wr_cnt : std_logic_vector(9 downto 0);
signal xor1_s : std_logic_vector(31 downto 0);
signal xor2_s : std_logic_vector(31 downto 0);
signal xor3_s : std_logic_vector(31 downto 0);
signal y_s : std_logic_vector(31 downto 0);
signal mag01_s : std_logic_vector(31 downto 0);
-- Component Declarations
COMPONENT counters
GENERIC (
M : integer := 397;
N : integer := 623
);
PORT (
clk : IN std_logic ;
resetn : IN std_logic ;
ena : IN std_logic ;
wea : OUT std_logic ;
kk_cnt : OUT std_logic_vector (9 DOWNTO 0);
km_cnt : OUT std_logic_vector (9 DOWNTO 0);
kp_cnt : OUT std_logic_vector (9 DOWNTO 0);
wr_cnt : OUT std_logic_vector (9 DOWNTO 0)
);
END COMPONENT;
COMPONENT dpram624x1
PORT (
addra : IN std_logic_VECTOR (9 DOWNTO 0);
addrb : IN std_logic_VECTOR (9 DOWNTO 0);
clka : IN std_logic;
clkb : IN std_logic;
dina : IN std_logic_VECTOR (0 DOWNTO 0);
wea : IN std_logic_VECTOR (0 DOWNTO 0);
doutb : OUT std_logic_VECTOR (0 DOWNTO 0)
);
END COMPONENT;
COMPONENT dpram624x31
PORT (
addra : IN std_logic_VECTOR (9 DOWNTO 0);
addrb : IN std_logic_VECTOR (9 DOWNTO 0);
clka : IN std_logic;
clkb : IN std_logic;
dina : IN std_logic_VECTOR (30 DOWNTO 0);
wea : IN std_logic_VECTOR (0 DOWNTO 0);
doutb : OUT std_logic_VECTOR (30 DOWNTO 0)
);
END COMPONENT;
COMPONENT dpram624x32
PORT (
addra : IN std_logic_VECTOR (9 DOWNTO 0);
addrb : IN std_logic_VECTOR (9 DOWNTO 0);
clka : IN std_logic;
clkb : IN std_logic;
dina : IN std_logic_VECTOR (31 DOWNTO 0);
wea : IN std_logic_VECTOR (0 DOWNTO 0);
doutb : OUT std_logic_VECTOR (31 DOWNTO 0)
);
END COMPONENT;
BEGIN
-- Architecture concurrent statements
-- HDL Embedded Text Block 1 eb1
-- eb1 1
wea_s(0) <= wea; -- wonderful VHDL
-- HDL Embedded Text Block 2 XOR_CHAIN1
-- eb1 1
xor1_s <= mt_kk_s XOR ("00000000000"&mt_kk_s(31 downto 11));
xor2_s <= xor1_s XOR (xor1_s(24 downto 0)&"0000000" AND X"9D2C5680");
xor3_s <= xor2_s XOR (xor2_s(16 downto 0)&"000000000000000" AND X"EFC60000");
random <= xor3_s XOR "000000000000000000"&xor3_s(31 downto 18);
-- HDL Embedded Text Block 3 eb3
y_s <= mt_kk31(0)&mt_kp(30 downto 0);
mag01_s <= X"00000000" when y_s(0)='0' else X"9908B0DF";
mt_kk_s <= mt_km XOR ('0'&y_s(31 downto 1)) XOR mag01_s;
-- Instance port mappings.
U_7 : counters
GENERIC MAP (
M => 397,
N => 623
)
PORT MAP (
clk => clk,
resetn => resetn,
ena => ena,
wea => wea,
kk_cnt => kk_cnt,
km_cnt => km_cnt,
kp_cnt => kp_cnt,
wr_cnt => wr_cnt
);
U_0 : dpram624x1
PORT MAP (
clka => clk,
dina => mt_kk_s(31 DOWNTO 31),
addra => wr_cnt,
wea => wea_s,
clkb => clk,
addrb => kk_cnt,
doutb => mt_kk31
);
U_1 : dpram624x31
PORT MAP (
clka => clk,
dina => mt_kk_s(30 DOWNTO 0),
addra => wr_cnt,
wea => wea_s,
clkb => clk,
addrb => kp_cnt,
doutb => mt_kp
);
U_2 : dpram624x32
PORT MAP (
clka => clk,
dina => mt_kk_s,
addra => wr_cnt,
wea => wea_s,
clkb => clk,
addrb => km_cnt,
doutb => mt_km
);
END struct;

View File

@@ -0,0 +1,96 @@
`timescale 1ns / 1ps
module reg_bank(clk, reset, en, we, wdBus, rdBus, address, reg0, reg1, reg2, reg3, reg4, regMT, error, status, max_lev, max_com, control);
input clk, reset, en, we;
input [7:0] wdBus;
output [7:0] rdBus;
input [4:0] address;
input [31:0] reg0;
input [31:0] reg1;
input [31:0] reg2;
input [31:0] reg3;
input [31:0] reg4;
input [31:0] regMT;
input [16:0] error;
input [7:0] status;
output [15:0] max_com;
output [7:0] max_lev;
output [7:0] control;
reg [7:0] reg_bank [31:0];
reg [7:0] rdBus;
// Read control
always @(posedge clk)
if(reset)
rdBus = 8'h00;
else begin
rdBus = reg_bank[address];
end
// Store Inputs
always @(posedge clk)
begin
if(en) begin
reg_bank[0] = reg0[7:0];
reg_bank[1] = reg0[15:8];
reg_bank[2] = reg0[23:16];
reg_bank[3] = reg0[31:24];
reg_bank[4] = reg1[7:0];
reg_bank[5] = reg1[15:8];
reg_bank[6] = reg1[23:16];
reg_bank[7] = reg1[31:24];
reg_bank[8] = reg2[7:0];
reg_bank[9] = reg2[15:8];
reg_bank[10] = reg2[23:16];
reg_bank[11] = reg2[31:24];
reg_bank[12] = reg3[7:0];
reg_bank[13] = reg3[15:8];
reg_bank[14] = reg3[23:16];
reg_bank[15] = reg3[31:24];
reg_bank[16] = reg4[7:0];
reg_bank[17] = reg4[15:8];
reg_bank[18] = reg4[23:16];
reg_bank[19] = reg4[31:24];
reg_bank[20] = error[7:0];
reg_bank[21] = error[15:8];
reg_bank[22] = { 4'b0, status};
// reg_bank[23] = regMT[7:0];
// reg_bank[24] = regMT[15:8];
// reg_bank[25] = regMT[23:16];
// reg_bank[26] = regMT[31:24];
end
end
assign max_com[7:0] = reg_bank[26];
assign max_com[15:8] = reg_bank[27];
assign max_lev = reg_bank[28];
assign control = reg_bank[29];
// Write control
always @(negedge clk)
if(we & en) begin
case (address)
27: reg_bank[26] = wdBus;
28: reg_bank[27] = wdBus;
29: reg_bank[28] = wdBus;
30: reg_bank[29] = wdBus;
endcase
end
endmodule

View File

@@ -0,0 +1,33 @@
CC = mipsel-openwrt-linux-gcc
all: jz_init_sram jz_test_gpio enable_rx enable_irq
DEBUG = -O3 -g0
COMMON_SOURCES = jz47xx_gpio.c jz47xx_mmap.c
H_SOURCES = jz47xx_gpio.h jz47xx_mmap.h
INCLUDE = -I.
WARNINGS= -Wcast-align -Wpacked -Wpadded -Wall
CCFLAGS = ${INCLUDE} ${DEBUG} ${WARNINGS}
LDFLAGS =
COMMON_OBJECTS = $(COMMON_SOURCES:.c=.o)
NANO_IP = 192.168.254.101
genetic.o: genetic.c genetic.h
${CC} -lm -I. -c genetic.c -o genetic.o
client: sintesishw_client.c genetic.o sintesishw_client.h
${CC} sintesishw_client.c genetic.o -o sintesishw_client -lm -I.
server: sintesishw_server.c genetic.o
${CC} sintesishw_server.c genetic.o -o sintesishw_server -lm -lpthread -I.
clean:
rm -f *.o sintesishw_client sintesishw_server ${EXEC} *~

Binary file not shown.

816
Examples/ehw4/src/genetic.c Normal file
View File

@@ -0,0 +1,816 @@
#include "stdio.h"
#include "termios.h"
#include "sys/mman.h"
#include "stdlib.h"
#include "sys/types.h"
#include "sys/stat.h"
#include "fcntl.h"
#include "time.h"
#include "math.h"
#include "pthread.h"
#include "sys/socket.h"
#include "netinet/in.h"
#include "netdb.h"
#include "errno.h"
#include "sys/un.h"
#include "genetic.h"
/**************************************************************************************************************************************
imprime un cromosoma completo */
void mostrar_indiv(char *cromo, int pentarboles, int vars)
{
char *ap, i, fn[8] = {'!', '&', '^', '|', '_'}; //NOT, AND, XOR, OR, NADA o YES
char vn[] = {'A', 'B', 'C', 'D', 'E' , 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', '.'};
char f1,f2,f3;
char a;
ap = cromo;
for(i = 0; i < ARBOLES_INDIV; i++){
if(*(cromo + 7) == 1)
{
vn[vars] = '.';
printf("%0x%c%c%c%c %i ", *(unsigned short int *)ap, vn[(*(ap+2) >> 4) & 0xF], vn[*(ap+2) & 0xF], vn[(*(ap+3) >> 4) & 0xF], vn[*(ap+3) & 0xF], *(ap+6));
}
else
{
vn[4] = '.';
printf("%0x%c%c%c%c %i", *(unsigned short int *)ap, vn[(*(ap+2) >> 4) & 0xF], vn[*(ap+2) & 0xF], vn[(*(ap+3) >> 4) & 0xF], vn[*(ap+3) & 0xF], *(ap+6));
}
// printf("\t %0x %0x ", *(short int *)(ap+2), *(ap+6) );
ap = ap + LONG_ARBOL;
}
printf(" ");
for(i = 0; i < LONG_INDIV; i++)
{ a=*(char *)(cromo+i) & 0xff;
printf("%hhu,",a);
}
//fflush(stdout);
}
/**************************************************************************************************************************************
imprime un arbol completo */
mostrar_arbol(char *cromo, int vars)
{
char *ap, i, fn[8] = {'!', '&', '^', '|', '_'}; //NOT, AND, XOR, OR, NADA o YES
char vn[] = {'A', 'B', 'C', 'D', 'E' , 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', '.'};
ap = cromo;
if(*(cromo + 7) == 1)
{
vn[vars] = '.';
printf("LUT:%04x VARS:%c%c%c%c %0x", *(unsigned short int *)ap, vn[*(ap+2) >> 4], vn[*(ap+2) & 0xF], vn[*(ap+3) >> 4], vn[*(ap+3) & 0xF], *(ap+6));
}
else
{
vn[4] = '.';
printf("LUT:%04x VARS:%c%c%c%c %0x", *(unsigned short int *)ap, vn[*(ap+2) >> 4], vn[*(ap+2) & 0xF], vn[*(ap+3) >> 4], vn[*(ap+3) & 0xF], *(ap+6));
}
printf("\tVARS:%04x \tLUT_index:%0x \t", *(unsigned short int *)(ap+2), *(ap+6) );
for(i = 0; i < LONG_ARBOL; i++)
{
printf("%0x,",*(cromo+i));
}
printf("\n");
}
/**************************************************************************************************************************************
genera un numero de forma aleatoria hasta max inclusive*/
char random_var(int max)
{
char variable, mascara;
int i;
mascara = 1;
do
{
mascara = (mascara << 1) + 1;
}while(max > mascara);
if(HW_ENABLE == 1) variable = (*(int *)(evalfit_ptr1 + EVALFIT_RDREG8)) & mascara;
else variable = random() & mascara;
while(variable > max)
{
variable = variable - max;
}
return variable;
}
/**************************************************************************************************************************************
Genera un arbol de forma aleatoria
Las funciones y variables son representadas por enteros del 0 al 3 o mas...
- el arbol se encuentra compuesto de tres funciones, dos de entrada y una de salida.
*/
void gen_arbol(char *ap, int variables)
{
int lut;
short int dato_lut;
lut = (random_var(FUNCIONES)*25) + (random_var(FUNCIONES) * 5) + random_var(FUNCIONES);//random_var(FUNCOMBS-1);
dato_lut = (*(funlut_ap+(lut*2)) << 8) + (*(funlut_ap+(lut*2)+1));
*(short int *)ap = ntohs(dato_lut); //Se cambia endianismo para cuando se ejecute en 386, que es distinto a PPC
*(ap+2) = *(ap+3) = 0;
*(ap+2) = random_var(variables) + (random_var(variables) << 4);
*(ap+3) = random_var(variables) + (random_var(variables) << 4);
*(ap+6) = lut;
// mostrar_arbol(ap);
}
/**************************************************************************************************************************************
genera un individuo de forma aleatoria */
void gen_indiv(char *cromo, int pentarboles, int vars)
{
char i=0;
int n1, n2, n3, n4, n5, c1, c2, c3, c4, c5, sig, indice;
n1 = n2 = n3 = n4 = n5 = 0;
c1 = c2 = c3 = c4 = c5 = 0;
indice = 0;
sig=1;
do
{
if((sig == 1) && (c1 < nivel1))
{
gen_arbol(cromo + (indice * LONG_ARBOL), vars-1);
*(cromo +(indice*LONG_ARBOL) + 7) = 1;
n1 ++;
c1 ++;
indice ++;
if(n1 < 4)
sig = 1;
else
{
sig = 2;
n1 = 0;
}//printf("1");
}
else
{
if((sig == 2) && (c2 < *(nivel2+pentarboles)))
{
gen_arbol(cromo + (indice*LONG_ARBOL), 3);
*(cromo +(indice*LONG_ARBOL) + 7) = 2;
n2++;
c2 ++;
indice ++;
if(c2 == *(nivel2+pentarboles))
sig = 3;
else
{
if(n2 < 4)
sig = 1;
else
{
sig = 3;
n2 = 0;
}
}//printf("2");
}
else
{
if((sig == 3) && (c3 < *(nivel3+pentarboles)))
{
gen_arbol(cromo + (indice*LONG_ARBOL), 3);
*(cromo +(indice*LONG_ARBOL) + 7) = 3;
n3++;
c3++;
indice++;
if(c3 == *(nivel3+pentarboles))
sig = 4;
else
{
if(n3 < 4)
sig = 1;
else
{
sig = 4;
n3 = 0;
}
}//printf("3");
}
else
{
if((sig == 4) && (c4 < *(nivel4+pentarboles)))
{
gen_arbol(cromo + (indice*LONG_ARBOL), 3);
*(cromo +(indice*LONG_ARBOL) + 7) = 4;
n4++;
c4++;
indice++;
if(c4 == *(nivel4+pentarboles))
sig = 5;
else
{
if(n4 < 4)
sig = 1;
else
{
sig = 5;
n4 = 0;
}
}//printf("4");
}
else
{
if((sig == 5) && (c5 < *(nivel5+pentarboles)))
{
gen_arbol(cromo + (indice*LONG_ARBOL), 3);
*(cromo +(indice*LONG_ARBOL) + 7) = 5;
c5++;
indice++;
if(c5 == *(nivel5+pentarboles))
sig = 1;
else
sig = 1;
}
}
}
}
}
/* mostrar_indiv(cromo, 1,vars); //*/
}while(indice < ARBOLES_INDIV);
}
/**************************************************************************************************************************************
genera una poblacion completa */
void gen_poblacion(char *cromo, int pentarboles, int vars, int indivs)
{
int i;
for(i=0; i < indivs; i++)
{
gen_indiv(cromo + ( i * LONG_INDIV), pentarboles, vars);
}
}
/**************************************************************************************************************************************
halla la salida de un arbol para una entrada de x de un cromo basado en LUT*/
int eval_func_lut(char *ap, int x, int vars ) //var apunta al valor de las variables
{
char Y;
char var[vars], i, a, b, c, d;
int lut;
for(i=0;i <= vars-1;i++)
{
var[i] = (x >> i) & 0x1;
// printf("-%i",var[i]);
}
var[vars] = 0;
a = *(ap + 3) & 0xF;
b = (*(ap + 3) >> 4) & 0xF;
c = *(ap + 2) & 0xF;
d = (*(ap + 2) >> 4) & 0xF;
i = var[a] + (var[b]*2) + (var[c]*4) + (var[d]*8);
lut = *(short int *)ap;
Y = (lut >> i) & 0x1;
return Y;
}
/**************************************************************************************************************************************
retorna las salidas de un cromosoma de 5 arboles*/
void eval_pentarbol_sw(char *ap, int *salida, int *entrada, int vars)
{
int i, k ;
char salidas[ARBOLES][COMBS], aux[COMBS];
for(i=0; i <= ARBOLES-2; i++){ //se evaluan las salidas de los primeros arboles y se almacenan en salidas
for(k=0; k<= (COMBS-1); k++)
{
salidas[i][k] = eval_func_lut((ap+(i*LONG_ARBOL)), k, vars);
}
}
//se calculan los minterminos para el arbol de salida
for(k=0; k <= (COMBS-1); k++)
{
aux[k] = ((salidas[0][k])*1) + ((salidas[1][k])*2) + ((salidas[2][k])*4) + ((salidas[3][k])*8);
}
for(i=0; i <= (COMBS-1); i++)
{
*(salida + i) = eval_func_lut(ap + ((ARBOLES-1) * LONG_ARBOL), aux[i], vars);
}
}
/**************************************************************************************************************************************
retorna el numero de errores y las salidas de un cromosoma de 1 o mas pentarboles*/
int eval_fit_sw(char *ap, int *objetivo, int num_min, int pentarboles, int vars )
{
int *obj_min, *med_min2, *med_min3, *med_min4, *med_min5, *entrada, i, j, errores, puertas;
int *salida, n2, n3, n4, n5, x;
obj_min = malloc(sizeof(obj_min)*COMBS);
med_min2 = malloc(sizeof(med_min2)*COMBS);
med_min3 = malloc(sizeof(med_min3)*COMBS);
med_min4 = malloc(sizeof(med_min4)*COMBS);
med_min5 = malloc(sizeof(med_min5)*COMBS);
entrada = malloc(sizeof(entrada)*COMBS);
salida = malloc(sizeof(salida)*COMBS);
errores = 0;
for(i=0; i < COMBS; i++)
{
*(obj_min+i) = 0;
*(entrada+i) = i;
*(med_min2 + i) = 0;
*(med_min3 + i) = 0;
*(med_min4 + i) = 0;
*(med_min5 + i) = 0;
}
for(i = 0; i < num_min; i++)
{
*(obj_min + (*(objetivo + i))) = 1; //se convierte el objetivo a un arreglo
}
i = 0;
n2 = 0;
n3 = 0;
n4 = 0;
n5 = 0;
do
{
if(*(ap + (i * LONG_ARBOL) + 7) == 1)
{
eval_pentarbol_sw(ap + (i * LONG_ARBOL), salida, entrada, vars);
for(j = 0; j < COMBS; j++)
{
*(med_min2 + j) = *(med_min2 + j) + (*(salida + j) << n2);
}
if(n2 == 3) n2 = 0; else n2++;
i = i + 5;
}
else
{
if(*(ap + (i * LONG_ARBOL) + 7) == 3)
{
for(j = 0; j < COMBS; j++)
{
*(salida + j) = eval_func_lut(ap + (i * LONG_ARBOL), *(med_min2 + j), vars);
}
for(j = 0; j < COMBS; j++)
{
*(med_min3 + j) = *(med_min3 + j) + (*(salida + j) << n3);
}
if(n3 == 3) n3 = 0; else n3++;
i++;
}
else
{
if(*(ap + (i * LONG_ARBOL) + 7) == 4)
{
for(j = 0; j < COMBS; j++)
{
*(salida + j) = eval_func_lut(ap + (i * LONG_ARBOL), *(med_min3 + j), vars);
}
for(j = 0; j < COMBS; j++)
{
*(med_min4 + j) = *(med_min4 + j) + (*(salida + j) << n4);
}
if(n4 == 3) n4 = 0; else n4++;
i++;
}
}
}
}while(i <= (ARBOLES_INDIV-1));
if(*(ap + ((ARBOLES_INDIV-1) * LONG_ARBOL) + 7) == 2)
{
for(j = 0; j < COMBS; j++) //se evalua el arbol de salida
{
errores = errores + abs(*(med_min2 + j) - *(obj_min + j)); //errores
/* printf("[%i]",*(med_min2 + j));*/
}
}
if(*(ap + ((ARBOLES_INDIV-1) * LONG_ARBOL) + 7) == 3)
{
for(j = 0; j < COMBS; j++) //se evalua el arbol de salida
{
errores = errores + abs(*(med_min3 + j) - *(obj_min + j)); //errores
}
}
if(*(ap + ((ARBOLES_INDIV-1) * LONG_ARBOL) + 7) == 4)
{
for(j = 0; j < COMBS; j++) //se evalua el arbol de salida
{
errores = errores + abs(*(med_min4 + j) - *(obj_min + j)); //errores
}
}
if(*(ap + ((ARBOLES_INDIV-1) * LONG_ARBOL) + 7) == 5)
{
for(j = 0; j < COMBS; j++) //se evalua el arbol de salida
{
errores = errores + abs(*(med_min5 + j) - *(obj_min + j)); //errores
}
}
free(obj_min);
free(med_min2);
free(med_min3);
free(med_min4);
free(med_min5);
free(entrada);
free(salida);
puertas = 0;
return ((errores * PESO_SALIDA) + puertas);
}
/**************************************************************************************************************************************
inicia la evaluacion de un cromosoma en un periferico*/
int evalfit_hw_init(char *cromo, int pentarboles, int nivel_max, void *evalfit_ptr )
{
int i;
/** insertar cromosoma en periferico **/
for(i = 0; i < ARBOLES_INDIV; i++)
{
*(int *)((evalfit_ptr) + EVALFIT_MEMOFFSET + (LONG_ARBOL*i)) = *(char *)(cromo +(LONG_ARBOL*i)+7);
// printf("\n%i: %0x",i,*(int *)(evalfit_ptr + EVALFIT_MEMOFFSET + (LONG_ARBOL*i)));
*(int *)((evalfit_ptr) + EVALFIT_MEMOFFSET + (LONG_ARBOL*i) + 4) = *(int *)(cromo +(LONG_ARBOL*i));
// printf(": %0x",*(int *)(evalfit_ptr + EVALFIT_MEMOFFSET + (LONG_ARBOL*i)+4));
}
*(int *)((evalfit_ptr) + EVALFIT_MEMOFFSET + (LONG_ARBOL*i)) = 0xF; //para terminar
i++;
*(int *)((evalfit_ptr) + EVALFIT_MEMOFFSET + (LONG_ARBOL*i)) = 0xF; //para terminar
/** Iniciar **/
*(int *)(evalfit_ptr + EVALFIT_CONTROL_OFFSET) = CONTROL_START_MASK;
}
/**************************************************************************************************************************************
espera y retorna el numero de errores y las salidas de un cromosoma de 1 o mas pentarboles*/
int evalfit_hw_wait(char *cromo, int pentarboles, int nivel_max, void *evalfit_ptr )
{
int errores, puertas, i;
// tiempo1 = get_timestamp();
do{ }while((*(int *)(evalfit_ptr + EVALFIT_RDREG1) & DONE_MASK) != 1);
// tiempo2 = get_timestamp();
errores = *(int *)(evalfit_ptr + EVALFIT_RDREG2) & ERRORS_MASK; //errores
*(int *)(evalfit_ptr + EVALFIT_CONTROL_OFFSET) = 0; //terminar, bajar habilita
puertas = 0;
for(i = 0; i < ARBOLES_INDIV; i++)
{
puertas = puertas + *(puertas_ap + *(char *)(cromo +(LONG_ARBOL*i)+6));
}
return ((errores * PESO_SALIDA) + (PESO_PUERTAS * puertas) + (PESO_NIVELES * nivel_max));
}
/**************************************************************************************************************************************
cruza dos cromosomas y almacena en destino. */
void cruzar(char *padre1, char *padre2, char *destino1, char *destino2, int pentarboles)
{
int a, i;
a = (random() & 0x1F) + 1; //punto de corte, es un numero de arbol
while(a > (ARBOLES_INDIV))
{
a = a - ARBOLES_INDIV;//(pentarboles * ARBOLES);
}
a = a-1;
// printf("\n%i",a);
for(i = 0; i < (a * LONG_ARBOL); i++)
{
*(destino1 + i) = *(padre1 + i); //padre1
*(destino2 + i) = *(padre2 + i); //padre1
}
for(i = (a * LONG_ARBOL); i < LONG_INDIV; i++) // +1 para el arbol de salida
{
*(destino1 + i) = *(padre2 + i); //padre2
*(destino2 + i) = *(padre1 + i); //padre2
}
}
/**************************************************************************************************************************************
cruza dos cromosomas y almacena en destino. */
void cross2point(char *padre1, char *padre2, char *destino1, char *destino2, int pentarboles)
{
int a, b, i;
a = random_var((pentarboles*ARBOLES)-3);
b = random_var((pentarboles*ARBOLES)-a-2)+a;
a++;
b++;
// printf("\n%i %i %i",a,b,pentarboles*ARBOLES);fflush(stdout);
for(i = 0; i < (a*LONG_ARBOL) ; i++)
{
*(destino1 + i) = *(padre1 + i); //
*(destino2 + i) = *(padre2 + i); //
}
for(i = a; i < (b*LONG_ARBOL) ; i++)
{
*(destino2 + i) = *(padre1 + i); //
*(destino1 + i) = *(padre2 + i); //
}
for(i = (b*LONG_ARBOL); i < LONG_INDIV; i++) // +1 para el arbol de salida
{
*(destino1 + i) = *(padre1 + i); //padre2
*(destino2 + i) = *(padre2 + i); //padre2
}
}
/**************************************************************************************************************************************
muta un cromosoma y almacena en destino. */
void muta_indiv(char *padre, char *destino, int pentarboles, int vars)
{
int a, i;
gen_indiv(destino, pentarboles, vars);
a = (random() & 0x1F) + 1; //punto de corte, es un numero de arbol
while(a > (ARBOLES_INDIV))
{
a = a - ARBOLES_INDIV;
}
for(i = 0; i < (a * LONG_ARBOL); i++)
{
*(destino + i) = *(padre + i); //padre1
}
}
/**************************************************************************************************************************************
Introducir minterminos **/
void minterm2peripheral(int *fun_obj, int tamano, void *evalfit_ptr)
{
int i, j, a;
for(i = 0; i < 512; i++) //rellenar con 0
{
*(int *)(evalfit_ptr + EVALFIT_OBJOFFSET + (i*4)) = 0;
}
for(i = 0; i < tamano; i++) //insertar 1's en segmento de mem objetivo
{
j=0;
a=fun_obj[i];
while(a > 31)
{
a -= 32;
j++;
}
*(int *)(evalfit_ptr + EVALFIT_OBJOFFSET + (j*4)) += (1 << (31-a));
}
}
/**************************************************************************************************************************************
inicializar periferico **/
int init_peripheral(int offset_int, int basemem)
{
/* Variables para periferico*/
int *aux, base_periferico, *evalfit_ptr;
off_t offset = offset_int; //Direccion base del periferico
base_periferico = (int *)mmap(NULL, MAP_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, basemem, offset & ~MAP_MASK);
evalfit_ptr = base_periferico + (offset & MAP_MASK);
printf("\r\nPeripheral_ptr: %0x", evalfit_ptr);
if( (int *)evalfit_ptr == (int *)MAP_FAILED)
{ printf("error mmap!\n");
fflush(stdout);
return -1;
}
*(int *)(evalfit_ptr + EVALFIT_CONTROL_OFFSET) = CONTROL_RESET_MASK; //reset
*(int *)(evalfit_ptr + EVALFIT_CONTROL_OFFSET) = 0;
printf("\nDate + Status: %0x\n", *(int *)(evalfit_ptr + EVALFIT_STATUS_OFFSET));
return evalfit_ptr;
}
/**************************************************************************************************************************************
cerrar periferico **/
int close_peripheral(char *evalfit_ptr)
{
if(munmap(evalfit_ptr, MAP_SIZE)==-1)
perror("munmap");
printf("Error en unmap() (close_peripheral)\n");
exit(-1);
}
/**************************************************************************************************************************************
cambiar endianismo **/
int big2little(int x)
{
int y, i, r;
y=0;
r=0;
for(i=0 ; i<=3; i++){
x = x >> r;
y = y << r;
y = y | (x & 0xFF);
r = 8;
}
return y;
}
/**************************************************************************************************************************************
crea y evoluciona un cromosoma a partir de una funcion objetivo*/
evolucionar(struct gen_datos_tipo *gen_datos)
{
int *generacion, k, a, i, j = 0, tamacromo, vars, aux, *aux_sal, T;
int conta=0, aux1, aux2, *fitness, *fitness2, *entrada, *objetivo, tamaobj, pentarboles, *fitness_sal, fitness_entrada, nivel_max;
char o, *ap, *cromo, *ordenpoblacion, *cromo_sal, *cromo_entrada;
long int tiempo1, tiempo2;
float tiempof1, tiempof2, tiempof3;
/* Variables para almacenar datos para graficar*/
int *datos, x, puntos;
char ruta[]="sarsar.dat";
FILE *fich;
/* datos = malloc(sizeof(datos)*maxgeneraciones*2); if(datos==0) printf("Error en malloc");*/
/* x=0;*/
objetivo = gen_datos -> objetivo;
tamaobj = gen_datos -> tamaobj;
pentarboles = gen_datos -> pentarboles;
tamacromo = gen_datos -> tamacrom;
cromo_sal = gen_datos -> cromo_sal;
fitness_sal = gen_datos -> fitness;
cromo_entrada = gen_datos -> cromo_entrada;
fitness_entrada = gen_datos -> fitness_entrada;
nivel_max = gen_datos -> nivel_max;
vars = gen_datos -> vars;
generacion = gen_datos->generacion;
aux = gen_datos->aux;
aux_sal = gen_datos->aux_sal;
cromo = malloc(sizeof(cromo) * (poblacion + 2) * LONG_INDIV); if(cromo==0) printf("Error en malloc");
fitness = malloc(sizeof(fitness) * (poblacion+1)); if(fitness==0) printf("Error en malloc");
fitness2 = malloc(sizeof(fitness2) * (poblacion+1)); if(fitness2==0) printf("Error en malloc");
ordenpoblacion = malloc(sizeof(ordenpoblacion) * (poblacion+1)); if(ordenpoblacion==0) printf("Error en malloc");
if(gen_datos->en_cromo_entrada == 1)
{
for(i = 0; i < LONG_INDIV; i++ )
{
*(char *)(cromo + i) = *(char *)(cromo_entrada + i);
}
}
if(gen_datos->en_cromo_entrada==0) gen_poblacion(cromo, pentarboles, vars, poblacion);
else gen_poblacion(cromo + LONG_INDIV, pentarboles, vars, poblacion-1);
for(i = 0; i < poblacion; i++)
{
*(ordenpoblacion + i) = i; //se inicializa el stream para el orden poblacional
*(fitness + i) = 100000;
*(fitness2 + i) = 100000;
}
/** copiar miniterminos a periferico **/
if(HW_ENABLE == 1) {
minterm2peripheral(objetivo, tamaobj, (int *)(evalfit_ptr1));
minterm2peripheral(objetivo, tamaobj, (int *)(evalfit_ptr2));
minterm2peripheral(objetivo, tamaobj, (int *)(evalfit_ptr3));
minterm2peripheral(objetivo, tamaobj, (int *)(evalfit_ptr4));
}
/** Insertar maxcombs y nivel_max **/
if(HW_ENABLE == 1) {
*(int *)(evalfit_ptr1 + EVALFIT_WREG4) = (COMBS-1) + (nivel_max << 16);
*(int *)(evalfit_ptr2 + EVALFIT_WREG4) = (COMBS-1) + (nivel_max << 16);
*(int *)(evalfit_ptr3 + EVALFIT_WREG4) = (COMBS-1) + (nivel_max << 16);
*(int *)(evalfit_ptr4 + EVALFIT_WREG4) = (COMBS-1) + (nivel_max << 16);
}
o=0;
*generacion = 0;
T = aux >> 16;
do{
// cruzar
for(i = ((poblacion*T)/8); i < ((poblacion*(T+1))/8); i=i+4) //salvar los primeros 4 y cruzar
{
cross2point(cromo+INDICE_PADRE1, cromo+INDICE_PADRE2, cromo+(*(ordenpoblacion+i)*LONG_INDIV), cromo+(*(ordenpoblacion+i+1)*LONG_INDIV), pentarboles);
cross2point(cromo+INDICE_PADRE1, cromo+INDICE_PADRE2, cromo+(*(ordenpoblacion+i+2)*LONG_INDIV), cromo+(*(ordenpoblacion+i+3)*LONG_INDIV), pentarboles);
}//cruzar
// Mutacion
for(i = ((poblacion*(T+1))/8); i < ((poblacion*(T+2))/8); i++)
{
muta_indiv(cromo + INDICE_PADRE1, cromo + ((*(ordenpoblacion + i )) * LONG_INDIV), pentarboles, vars);
}
for(i = ((poblacion*(T+2))/8); i < ((poblacion*(T+3))/8); i++)
{
muta_indiv(cromo + INDICE_PADRE2, cromo + ((*(ordenpoblacion + i )) * LONG_INDIV), pentarboles, vars);
}
//crear nuevos indiv reemplazar por taras
for(i = ((poblacion*(T+3))/8); i < poblacion; i++)
{
gen_indiv((cromo + ((*(ordenpoblacion + i)) * LONG_INDIV)), pentarboles, vars);
}
// evaluar cromosomas de poblacion
o=0;
// tiempo1 = get_timestamp();
for(i = 0; i < poblacion; i=i+4)
{
if(HW_ENABLE == 1)
{
evalfit_hw_init((cromo + (i * LONG_INDIV)), pentarboles, nivel_max, (int *)evalfit_ptr1);
evalfit_hw_init((cromo + ((i+1) * LONG_INDIV)), pentarboles, nivel_max, (int *)evalfit_ptr2);
evalfit_hw_init((cromo + ((i+2) * LONG_INDIV)), pentarboles, nivel_max, (int *)evalfit_ptr3);
evalfit_hw_init((cromo + ((i+3) * LONG_INDIV)), pentarboles, nivel_max, (int *)evalfit_ptr4);
*(fitness + i) = evalfit_hw_wait((cromo + (i * LONG_INDIV)), pentarboles, nivel_max, (int *)evalfit_ptr1);
*(fitness + i+1) = evalfit_hw_wait((cromo + ((i+1) * LONG_INDIV)), pentarboles,nivel_max, (int *)evalfit_ptr2);
*(fitness + i+2) = evalfit_hw_wait((cromo + ((i+2) * LONG_INDIV)), pentarboles,nivel_max, (int *)evalfit_ptr3);
*(fitness + i+3) = evalfit_hw_wait((cromo + ((i+3) * LONG_INDIV)), pentarboles, nivel_max, (int *)evalfit_ptr4);
}else{
*(fitness + i) = eval_fit_sw((cromo + (i * LONG_INDIV)), objetivo, tamaobj, pentarboles, vars);
*(fitness + i+1) = eval_fit_sw((cromo + ((i+1) * LONG_INDIV)), objetivo, tamaobj, pentarboles, vars);
*(fitness + i+2) = eval_fit_sw((cromo + ((i+2) * LONG_INDIV)), objetivo, tamaobj, pentarboles, vars);
*(fitness + i+3) = eval_fit_sw((cromo + ((i+3) * LONG_INDIV)), objetivo, tamaobj, pentarboles, vars);
}
*(fitness2 + i) = *(fitness + i);
*(fitness2 + i+1) = *(fitness + i+1);
*(fitness2 + i+2) = *(fitness + i+2);
*(fitness2 + i+3) = *(fitness + i+3);
if(*(fitness + i) < PESO_SALIDA)
{
o++; //incrementar numero de aciertos
}
}
// tiempo2 = get_timestamp();
x++;
//seleccionar cromosomas para mutar y cruzar y para eliminar, se realiza una ordenacion en ordenpoblacion, solo se ordena el indice del cromosoma
for(i = 0; i < poblacion; i++)
{
*(ordenpoblacion + i) = i; //se inicializa el stream para el orden poblacional
}
for(i=0; i < poblacion; i++)
{
for(j=i+1; j < poblacion; j++)
{
if(*(fitness2 + j) < *(fitness2 + i))
{
aux1 = *(ordenpoblacion + i);
*(ordenpoblacion + i) = *(ordenpoblacion + j);
*(ordenpoblacion + j) = aux1;
aux2 = *(fitness2 + i);
*(fitness2 + i) = *(fitness2 + j);
*(fitness2 + j) = aux2;
}
}
}
//Se mide la evolucion del fitness en las generaciones, se saca la media por generacion
aux1 = 0;
for(i = 0; i < poblacion; i++)
{
aux1 = aux1 + *(fitness + i);
}
*(aux_sal + *generacion) = aux1 / poblacion;
*(aux_sal + maxgeneraciones + *generacion) = *fitness2;
(*generacion)++;
// for(i=0; i < RESULTADOS; i++)
// {
// printf("\nfit%i: %i ", i, *(fitness+*(ordenpoblacion+i)), *(generacion+*(ordenpoblacion+i)));
// mostrar_indiv(cromo + ( *(ordenpoblacion + i) * LONG_INDIV), pentarboles, vars);
// }
}while(/* (o < RESULTADOS) && */ (*generacion < maxgeneraciones));
for(i = 0; i < RESULTADOS; i++)
{
for(j=0; j< LONG_INDIV;j++)
{
*(cromo_sal + (i*LONG_INDIV) + j) = *(cromo + (*(ordenpoblacion + i)*LONG_INDIV) + j);
}
*(fitness_sal + i) = *(fitness + *(ordenpoblacion + i));
}
free(cromo);
free(fitness);
free(fitness2);
free(ordenpoblacion);
}

126
Examples/ehw4/src/genetic.h Normal file
View File

@@ -0,0 +1,126 @@
/** Genetic definitions **/
#define HW_ENABLE 1 //cambiar en sintesishw_server.h habilitar hw, 0 se hace por SW
#define PAR_ONLYFIT 0 //paralelizacion, 0 ALGORITMO ENTERO, 1 SOLO FITNESS
#define FUNCIONES 4
#define COMBS (int) pow(2,vars)
#define FUNCOMBS (int) pow(FUNCIONES + 1, 3)
#define FUN_NOT 0
#define FUN_AND 1
#define FUN_XOR 2
#define FUN_OR 3
#define YES FUNCIONES
#define NOVAR vars
#define PESO_SALIDA 100
#define PESO_PUERTAS 5
#define PESO_NIVELES 0
#define RESULTADOS 2
/* Numero de generaciones en el que se amplia la logitud del cromosoma*/
#define UMBRAL_GENERACION (int) pow(3, pentarboles) * 33
#define MAX_PENTARBOLES 16
#define ARBOLES 5
#define LONG_ARBOL 8
int nivel2[]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
int nivel3[]={0,0,1,1,1,2,2,2,2,3,3, 3, 3, 4, 4, 4};
int nivel4[]={0,0,0,0,0,1,1,1,1,1,1, 1, 1, 1, 1, 1};
int nivel5[]={0,0,0,0,0,0,0,0,0,0,0, 0, 0, 0, 0, 0};
#define nivel1 pentarboles * 4
#define ARBOLES_INDIV (int)(nivel1 + *(nivel2+pentarboles) + *(nivel3+pentarboles) + *(nivel4+pentarboles) + *(nivel5+pentarboles))
#define LONG_INDIV (int)(ARBOLES_INDIV * LONG_ARBOL)
#define INDICE_PADRE1 ((*ordenpoblacion) * LONG_INDIV)
#define INDICE_PADRE2 ((*(ordenpoblacion+1)) * LONG_INDIV)
#define INDICE_TARA1 ((*(ordenpoblacion+poblacion-1)) * LONG_INDIV)
#define INDICE_TARA2 ((*(ordenpoblacion+poblacion-2)) * LONG_INDIV)
#define INDICE_TARA3 ((*(ordenpoblacion+poblacion-3)) * LONG_INDIV)
#define INDICE_TARA4 ((*(ordenpoblacion+poblacion-4)) * LONG_INDIV)
/************************** peripheral Definitions ***************************/
#define USR_REGS 0x10
#define MAP_SIZE 0x4000Ul
#define MAP_MASK (MAP_SIZE - 1)
#define DONE_MASK 0x1
#define ERRORS_MASK 0xFFFF
/** CONTROL REGISTERS **/
#define EVALFIT_REGBASE_OFFSET 0
#define EVALFIT_CONTROL_OFFSET EVALFIT_REGBASE_OFFSET + 0
#define CONTROL_RESET_MASK 0x80000000
#define CONTROL_START_MASK 0x40000000
#define EVALFIT_STATUS_OFFSET EVALFIT_REGBASE_OFFSET + 0
#define EVALFIT_SRCADDR_OFFSET EVALFIT_REGBASE_OFFSET + 4
#define EVALFIT_DSTADDR_OFFSET EVALFIT_REGBASE_OFFSET + 8
#define EVALFIT_TRANSFERSIZE_OFFSET EVALFIT_REGBASE_OFFSET + 12
#define EVALFIT_REG_OFFSET EVALFIT_REGBASE_OFFSET + 16
/** WRITE REGISTERS **/
#define EVALFIT_WREG4 (EVALFIT_REGBASE_OFFSET + (4*4))
#define EVALFIT_WREG5 (EVALFIT_REGBASE_OFFSET + (4*5))
#define EVALFIT_wREG6 (EVALFIT_REGBASE_OFFSET + (4*6))
#define EVALFIT_wREG7 (EVALFIT_REGBASE_OFFSET + (4*7))
#define EVALFIT_wREG8 (EVALFIT_REGBASE_OFFSET + (4*8))
/** READ REGISTERS **/
#define EVALFIT_RDREG0 (EVALFIT_REGBASE_OFFSET)
#define EVALFIT_RDREG1 (EVALFIT_REGBASE_OFFSET + (4*1))
#define EVALFIT_RDREG2 (EVALFIT_REGBASE_OFFSET + (4*2))
#define EVALFIT_RDREG3 (EVALFIT_REGBASE_OFFSET + (4*3))
#define EVALFIT_RDREG4 (EVALFIT_REGBASE_OFFSET + (4*4))
#define EVALFIT_RDREG5 (EVALFIT_REGBASE_OFFSET + (4*5))
#define EVALFIT_RDREG6 (EVALFIT_REGBASE_OFFSET + (4*6))
#define EVALFIT_RDREG7 (EVALFIT_REGBASE_OFFSET + (4*7))
#define EVALFIT_RDREG8 (EVALFIT_REGBASE_OFFSET + (4*8))
/** MEMORY **/
#define EVALFIT_MEMOFFSET 0x1000
#define EVALFIT_OBJOFFSET EVALFIT_MEMOFFSET + (0x40 * 8)
/** CROMOSOMA **/
#define CROMO_NIVEL_OFFSET
/* Variables globales */
char *funlut_ap, *puertas_ap;
void *evalfit_ptr1, *evalfit_ptr4, *evalfit_ptr3, *evalfit_ptr2;
int maxgeneraciones, poblacion;
typedef long long timestamp_t;
static timestamp_t
get_timestamp ()
{
struct timeval now;
gettimeofday (&now, NULL);
return now.tv_usec + (timestamp_t)now.tv_sec *1000000 ;
}
struct gen_datos_tipo
{
int *objetivo;
int tamaobj;
int pentarboles;
int vars;
int tamacrom;
int maxgen;
char *cromo_sal;
int *fitness;
char *cromo_entrada;
int fitness_entrada;
int nivel_max;
int en_cromo_entrada;
int *generacion;
int *tiempo;
int aux;
int *aux_sal;
};

Binary file not shown.

View File

@@ -0,0 +1,97 @@
/** Genetic definitions **/
#define HW_ENABLE 0 //habilitar hw, 0 se hace por SW
#define VARS 8
#define FUNCIONES 4
#define COMBS (int) pow(2,VARS)
#define FUNCOMBS (int) pow(FUNCIONES + 1, 3)
#define FUN_NOT 0
#define FUN_AND 1
#define FUN_XOR 2
#define FUN_OR 3
#define YES FUNCIONES
#define NOVAR VARS
#define PESO_SALIDA 1
#define PESO_PUERTAS 1
#define MAXGENERACIONES 32
#define RESULTADOS 4
/* Numero de generaciones en el que se amplia la logitud del cromosoma*/
#define UMBRAL_GENERACION (int) pow(3, pentarboles) * 5000
#define MAX_PENTARBOLES 16
#define POBLACION 4
#define ARBOLES 5
#define LONG_ARBOL 8
/*
POBLACION define el numero de individuos. minimo 6. 2 padres 4 taras
ARBOLES define el numero de arboles en un individuo. Cada arbol tiene 3 funciones 4 variables.
INDICES_XXX define el desplazamiento de un individuo en el cromosoma completo de la poblacion, cromo
*/
#define nivel1 pentarboles * 4
#define ARBOLES_INDIV (int)(nivel1 + nivel2(pentarboles) + nivel3(pentarboles) + nivel4(pentarboles) + nivel5(pentarboles))
#define LONG_INDIV (int)(ARBOLES_INDIV * LONG_ARBOL)
#define INDICE_PADRE1 ((*ordenpoblacion) * LONG_INDIV)
#define INDICE_PADRE2 ((*(ordenpoblacion+1)) * LONG_INDIV)
#define INDICE_TARA1 ((*(ordenpoblacion+POBLACION-1)) * LONG_INDIV)
#define INDICE_TARA2 ((*(ordenpoblacion+POBLACION-2)) * LONG_INDIV)
#define INDICE_TARA3 ((*(ordenpoblacion+POBLACION-3)) * LONG_INDIV)
#define INDICE_TARA4 ((*(ordenpoblacion+POBLACION-4)) * LONG_INDIV)
/************************** peripheral Definitions ***************************/
#define EVALFIT_PHYSBASE 0xcd800000
#define USR_REGS 0x10
#define MAP_SIZE 0x4000Ul
#define MAP_MASK (MAP_SIZE - 1)
#define DONE_MASK 0x1
#define ERRORS_MASK 0xFFFF
/** CONTROL REGISTERS **/
#define EVALFIT_REGBASE_OFFSET 0
#define EVALFIT_CONTROL_OFFSET EVALFIT_REGBASE_OFFSET + 0
#define CONTROL_RESET_MASK 0x80000000
#define CONTROL_START_MASK 0x40000000
#define EVALFIT_STATUS_OFFSET EVALFIT_REGBASE_OFFSET + 0
#define EVALFIT_SRCADDR_OFFSET EVALFIT_REGBASE_OFFSET + 4
#define EVALFIT_DSTADDR_OFFSET EVALFIT_REGBASE_OFFSET + 8
#define EVALFIT_TRANSFERSIZE_OFFSET EVALFIT_REGBASE_OFFSET + 12
#define EVALFIT_REG_OFFSET EVALFIT_REGBASE_OFFSET + 16
/** WRITE REGISTERS **/
#define EVALFIT_WREG4 (EVALFIT_REGBASE_OFFSET + (4*4))
#define EVALFIT_WREG5 (EVALFIT_REGBASE_OFFSET + (4*5))
#define EVALFIT_wREG6 (EVALFIT_REGBASE_OFFSET + (4*6))
#define EVALFIT_wREG7 (EVALFIT_REGBASE_OFFSET + (4*7))
#define EVALFIT_wREG8 (EVALFIT_REGBASE_OFFSET + (4*8))
/** READ REGISTERS **/
#define EVALFIT_RDREG0 (EVALFIT_REGBASE_OFFSET)
#define EVALFIT_RDREG1 (EVALFIT_REGBASE_OFFSET + (4*1))
#define EVALFIT_RDREG2 (EVALFIT_REGBASE_OFFSET + (4*2))
#define EVALFIT_RDREG3 (EVALFIT_REGBASE_OFFSET + (4*3))
#define EVALFIT_RDREG4 (EVALFIT_REGBASE_OFFSET + (4*4))
#define EVALFIT_RDREG5 (EVALFIT_REGBASE_OFFSET + (4*5))
#define EVALFIT_RDREG6 (EVALFIT_REGBASE_OFFSET + (4*6))
#define EVALFIT_RDREG7 (EVALFIT_REGBASE_OFFSET + (4*7))
/** MEMORY **/
#define EVALFIT_MEMOFFSET 0x1000
#define EVALFIT_OBJOFFSET EVALFIT_MEMOFFSET + (0x40 * 8)
/** CROMOSOMA **/
#define CROMO_NIVEL_OFFSET

View File

@@ -0,0 +1,461 @@
/*********************************************************************************************************
** Programa para probar la sintesis combinacional mediante programacion genetica,
** se usan sockets para repartir carga de trabajo a otros clientes
** Se usa periferico evalfit del proyecto ehw3
** se aceleran 5 arboles, que en el presente codigo se llama pentarbol
** compilar con math.h -lm
** compilar con threads: -lpthread
** gcc sintesishw_client.c -lm -lpthread -o sintesishw_client_ppc
** ejecutar:
** ./sintesishw_client_386 vars poblacion generaciones pentarboles sar.dat sar2.dat
**
**********************************************************************************************************/
#include <stdio.h>
#include <termios.h>
#include <sys/mman.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>
#include <math.h>
#include <pthread.h>
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <errno.h>
#include <sys/un.h>
#include <sintesishw_client.h>
/**************************************************************************************************************************************
*/
create_connect_socket(char *addr, int *fd_ap)
{
int fd;
struct sockaddr_in input_addr;
struct sockaddr_in server;
if (inet_aton(addr, &input_addr.sin_addr)==-1)
{ perror("inet_aton");
exit(-1);
}
if ((fd=socket(AF_INET, SOCK_STREAM, 0))==-1){
printf("socket() error\n");
exit(-1);
}
server.sin_family = AF_INET;
server.sin_port = htons(PORT);
server.sin_addr = input_addr.sin_addr;
bzero(&(server.sin_zero),8);
if(connect(fd, (struct sockaddr *)&server, sizeof(struct sockaddr))==-1)
{
// printf("connect() error en %s\n",addr);
perror("connect");
exit(-1);
}
/* printf(".");*/
*fd_ap = fd;
}
rx_cromo(int fd, void *data_socket_rx_ap, char *cromo_sal, int *fitness, int pentarboles, int *generacion, int *tiempo, int *aux_sal)
{
void *ap1;
int i, j, numbytes_rx;
int nivel2[]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
int nivel3[]={0,0,1,1,1,2,2,2,2,3,3, 3, 3, 4, 4, 4};
int nivel4[]={0,0,0,0,0,1,1,1,1,1,1, 1, 1, 1, 1, 1};
int nivel5[]={0,0,0,0,0,0,0,0,0,0,0, 0, 0, 0, 0, 0};
if ((numbytes_rx=recv(fd,data_socket_rx_ap,MAXDATASIZE,0)) == -1){
printf("Error en recv() \n");
perror("recv");
exit(-1);
}
ap1 = data_socket_rx_ap;
/* printf("Rx:%i ",ntohl(*(int *)ap1));*/
ap1 = ap1 + 4;
for(i=0; i < RESULTADOS ;i++)
{
for(j=0; j < LONG_INDIV ;j++)
{
*(cromo_sal + j + (LONG_INDIV*i)) = *(char *)ap1;
ap1 ++;
}
*(fitness + i) = ntohl(*(int *)ap1) & 0xFFFF;
*(generacion + i) = ntohl(*(int *)ap1) >> 16;
ap1 = ap1 + 4;
*(tiempo+i) = ntohl(*(int *)ap1);
ap1 = ap1 + 4;
}
for(i = 0; i < maxgeneraciones*2 ;i++)
{
*(aux_sal + i) = ntohl(*(int *)ap1);
ap1 = ap1 + 4;
}
}
tx_cromo(struct gen_datos_tipo *gen_datos, int fd)
{
void *data_socket_tx_ap, *ap1;
int *objetivo, i, numbytes_tx;
data_socket_tx_ap = malloc((gen_datos->tamaobj)*sizeof(int) + gen_datos->tamacrom + 0xFF);
ap1= data_socket_tx_ap;
*(int *)ap1 = htonl(gen_datos->tamaobj | (maxgeneraciones << 16));
ap1 = ap1 + 4;
objetivo = gen_datos->objetivo;
for(i=0; i < (gen_datos->tamaobj); i++)
{
*(int *)ap1 = htonl(objetivo[i]);
ap1 = ap1 + 4;
}
*(int *)ap1 = htonl(gen_datos->pentarboles | (gen_datos->vars << 16));
ap1 = ap1 + 4;
*(int *)ap1 = htonl(gen_datos->tamacrom | (poblacion << 16));
ap1 = ap1 + 4;
for(i = 0; i < (gen_datos->tamacrom); i++)
{
*(char *)(ap1) = *(char *)(gen_datos->cromo_entrada + i);
ap1 = ap1 + 1;
}
*(int *)ap1 = htonl(gen_datos->fitness_entrada); //fitness de entrada?
ap1 = ap1 + 4;
*(int *)ap1 = htonl((gen_datos->en_cromo_entrada<<16) | gen_datos->nivel_max);
ap1 = ap1 + 4;
*(int *)ap1 = htonl(gen_datos->aux); //datos varios
ap1 = ap1 + 4;
*(int *)ap1 = htonl(0xa55a9669); //datos varios
ap1 = ap1 + 4;
numbytes_tx = ap1 - data_socket_tx_ap;
send(fd, data_socket_tx_ap, numbytes_tx ,0); //enviar
free(data_socket_tx_ap);
}
/**************************************************************************************************************************************
crea una poblacion, y envia a placas para evolucionar */
iniciar_evol(struct gen_datos_tipo *gen_datos)
{
int *generacion, k, a, i, j = 0, vars;
int conta=0, aux1, aux2, *fitness, *fitness2, *entrada, *objetivo, tamaobj, pentarboles, maxgens, *fitness_sal, fitness_entrada, nivel_max, *aux_sal;
char o, *ap, *cromo, *ordenpoblacion, *cromo_sal, *cromo_entrada;
int *tiempo;
int nivel2[]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
int nivel3[]={0,0,1,1,1,2,2,2,2,3,3, 3, 3, 4, 4, 4};
int nivel4[]={0,0,0,0,0,1,1,1,1,1,1, 1, 1, 1, 1, 1};
int nivel5[]={0,0,0,0,0,0,0,0,0,0,0, 0, 0, 0, 0, 0};
/* variables para sockets */
int fds[8],fd1, fd2, fd3, fd4, fd5, fd6, fd7, fd8, numbytes_tx, numbytes_rx; /* ficheros descriptores para sockets*/
void *data_socket_rx_ap;
char server[][16] = {IP0, IP1, IP2, IP3, IP4, IP5, IP6, IP7};
pentarboles = gen_datos->pentarboles;
vars = gen_datos->vars;
generacion = gen_datos->generacion;
tiempo = gen_datos->tiempo;
aux_sal = gen_datos->aux_sal;
cromo = malloc(sizeof(cromo) * (poblacion + 2) * LONG_INDIV); if(cromo==0) printf("Error en malloc");
fitness = malloc(sizeof(fitness) * (poblacion+1)); if(fitness==0) printf("Error en malloc");
fitness2 = malloc(sizeof(fitness2) * (poblacion+1)); if(fitness2==0) printf("Error en malloc");
ordenpoblacion = malloc(sizeof(ordenpoblacion) * (poblacion+1)); if(ordenpoblacion==0) printf("Error en malloc");
for(i=0; i < nodos; i++) //enviar a nodos
{
create_connect_socket(server[i], &fds[i]);
}
/* preparar socket para recibir */
data_socket_rx_ap = malloc(10000);
if(PAR_ONLYFIT==1)
{
gen_poblacion(cromo, pentarboles, vars);
// cruzar
for(i = ((poblacion*1)/8); i < ((poblacion*2)/8); i=i+4) //salvar los primeros 4 y cruzar
{
cross2point(cromo+i*LONG_INDIV, cromo + i*LONG_INDIV, cromo+((i)*LONG_INDIV), cromo+((i+1)*LONG_INDIV), pentarboles);
cross2point(cromo+i*LONG_INDIV, cromo + i*LONG_INDIV, cromo+((i+2)*LONG_INDIV), cromo+((i+3)*LONG_INDIV), pentarboles);
}//cruzar
// Mutacion
for(i = ((poblacion*2)/8); i < ((poblacion*3)/8); i++)
{
muta_indiv(cromo + i*LONG_INDIV, cromo + ((( i )) * LONG_INDIV), pentarboles, vars);
}
for(i = ((poblacion*3)/8); i < ((poblacion*4)/8); i++)
{
muta_indiv(cromo + i*LONG_INDIV, cromo + ((( i )) * LONG_INDIV), pentarboles, vars);
}
//crear nuevos indiv reemplazar por taras
for(i = ((poblacion*4)/8); i < poblacion; i++)
{
gen_indiv((cromo + ((( i)) * LONG_INDIV)), pentarboles, vars);
}
*generacion++;
}
gen_datos->tamacrom = LONG_INDIV;
for(j=0;j<1;j++)
{
for(i=0; i<nodos;i++) //enviar a nodos
{
tx_cromo(gen_datos, fds[i]);
}
cromo_sal = gen_datos->cromo_sal;
for(i=0; i<nodos;i++) //recoger fitness o cromosomas resultantes
{
rx_cromo(fds[i], data_socket_rx_ap, cromo_sal+(LONG_INDIV*RESULTADOS*i), gen_datos->fitness+(RESULTADOS*i), pentarboles,generacion + (RESULTADOS*i),tiempo+(RESULTADOS*i), aux_sal+(maxgeneraciones*2*i));
}
}
free(cromo);
free(fitness);
free(fitness2);
free(ordenpoblacion);
free(data_socket_rx_ap);
for(i=0; i<nodos;i++) close(fds[i]);
}
/*******************************************************************************************************************************/
/*******************************************************************************************************************************/
/*******************************************************************************************************************************/
/*******************************************************************************************************************************/
int main( int argc, char** argv )
{
int *generacion, k, a, b, z, i, j= 0, error, nivel_max, vars, *tiempo, poblacion_total, m, p, iteraciones, T;
int conta=0, aux1, aux2, pentarboles, *fitness1, *fitness2, *entrada, *orderesult, aux, *aux_sal;
char o, *ap, *valor_devuelto;;
char *cromo_sal1, *cromo_sal2, *cromo_entrada;
int tamaobj, objetivo[8192], obj_combs;//= {0,254,123,16,87,56,34,76,89,155,199};
long int tiempo1, tiempo2;
float tiempof, tiempof2, Tfloat, float1, float2;
int nivel2[]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
int nivel3[]={0,0,1,1,1,2,2,2,2,3,3, 3, 3, 4, 4, 4};
int nivel4[]={0,0,0,0,0,1,1,1,1,1,1, 1, 1, 1, 1, 1};
int nivel5[]={0,0,0,0,0,0,0,0,0,0,0, 0, 0, 0, 0, 0};
/* Estructuras para datos de cromosomas*/
struct gen_datos_tipo data_struct1, data_struct2;
struct gen_datos_tipo *data_struct_ap1, *data_struct_ap2;
data_struct_ap1 = &data_struct1;
data_struct_ap2 = &data_struct2;
/* Variables para tablas de lut*/
FILE *f1;
int size1;
srand ( (time(NULL)) );
/* Variables para almacenar datos para graficar*/
int *datos, *datos2, x, media=4, puntos;
FILE *fich, *fich2;
char output_file_name[128], output_file_fitness_name[128];
sscanf(argv[1], "%i",&vars);
sscanf(argv[2], "%i", &poblacion_total);
sscanf(argv[3], "%i", &maxgeneraciones);
sscanf(argv[4], "%i", &nodos);
sscanf(argv[5], "%s", output_file_name);
sscanf(argv[6], "%s", output_file_fitness_name);
// printf("\nvars: %i indivs:%i generations:%i nodos:%i ", vars, poblacion_total, maxgeneraciones, nodos);
fflush(stdout);
pentarboles = 1; //MODIFIQUE NIVEL_MAX
nivel_max = 2;
poblacion = poblacion_total/nodos;
m = 1; //datos a migrar
p = 8; //frecuencia de migracion
T = 4; //temperatura para crear nuevos indiv. A mayor T menor temperatura
i=0;
tamaobj=0;
aux = (T << 16) | p;
iteraciones = maxgeneraciones/p;
maxgeneraciones = p;
obj_combs = pow(2, (vars/2));
/*Armar funcion objetivo comparador*/ /* OJO, SE ESTÁN METIENDO VALORES DE 1EXX EN LAS LUT Y ESOS INDIVIDUOS AL PARECER QUEDAN MAL */
for(a=0; a < obj_combs ;a++)
{
for(b=0; b < obj_combs ;b++)
{
if(a > b)z=1; if(a < b)z=2; if(a == b)z=4;
if((z & 0x4) != 0 )
{
objetivo[tamaobj] = i;
printf("%i ",objetivo[tamaobj]);
tamaobj++;
}
i++;
}
}
// printf("Tama:%i ",tamaobj);
/* Tabla para las LUT*/
f1 = fopen("funlut.dat","r");
if(f1 == NULL){
printf("\nError de lectura de archivo!");
return 0;}
fseek (f1, 0, SEEK_END);
size1 = ftell(f1);
funlut_ap = malloc(size1); if(funlut_ap==0) printf("Error en malloc");
rewind (f1);
fread(funlut_ap,1,size1,f1);
fclose(f1);
puntos = 16; /*numero de puntos para la grafica*/
datos = malloc(sizeof(datos)*puntos*3); if(datos==0) printf("Error en malloc");
fich=fopen(output_file_name,"wb");
datos2 = malloc(sizeof(datos2) * maxgeneraciones * p * nodos); if(datos2==0) printf("Error en malloc");
fich2=fopen(output_file_fitness_name,"wb");
cromo_sal1 = malloc(sizeof(cromo_sal1) * RESULTADOS * LONG_INDIV * nodos); if(cromo_sal1==0) printf("Error en malloc");
fitness1 = malloc(sizeof(fitness1) * RESULTADOS * nodos); if(fitness1==0) printf("Error en malloc");
cromo_sal2 = malloc(sizeof(cromo_sal2) * RESULTADOS * LONG_INDIV * nodos); if(cromo_sal2==0) printf("Error en malloc");
fitness2 = malloc(sizeof(fitness2) * RESULTADOS * nodos); if(fitness2==0) printf("Error en malloc");
cromo_sal2 = malloc(sizeof(cromo_sal2) * RESULTADOS * LONG_INDIV * nodos); if(cromo_sal2==0) printf("Error en malloc");
generacion = malloc(sizeof(generacion)* RESULTADOS * nodos); if(generacion==0) printf("Error en malloc");
tiempo = malloc(sizeof(tiempo)* RESULTADOS * nodos); if(tiempo==0) printf("Error en malloc");
cromo_entrada = malloc(sizeof(cromo_entrada)* LONG_INDIV * m); if(cromo_entrada==0) printf("Error en malloc");
orderesult = malloc(sizeof(orderesult) * nodos*RESULTADOS); if(orderesult==0) printf("Error en malloc");
aux_sal = malloc(sizeof(aux_sal) * nodos * maxgeneraciones * 2); if(aux_sal==0) printf("Error en malloc");
data_struct_ap1->objetivo = objetivo;
data_struct_ap1->tamaobj = tamaobj;
data_struct_ap1->pentarboles = pentarboles;
data_struct_ap1->maxgen = maxgeneraciones;
data_struct_ap1->cromo_sal = cromo_sal1;
data_struct_ap1->fitness = fitness1;
data_struct_ap1->cromo_entrada = cromo_entrada;
data_struct_ap1->fitness_entrada = 0;
data_struct_ap1->nivel_max = nivel_max;
data_struct_ap1->vars= vars;
data_struct_ap1->en_cromo_entrada = 0;
data_struct_ap1->generacion = generacion;
data_struct_ap1->tiempo = tiempo;
data_struct_ap1->aux = aux;
data_struct_ap1->aux_sal = aux_sal;
/* printf("\npentarboles:%i nivel_max%i ", pentarboles ,nivel_max);*/
/* fflush(stdout); */
/* Iniciar evolucion */
x = 0;
fflush(stdout);
for(k = 0; k < iteraciones ; k++)
{
tiempo1 = get_timestamp();
iniciar_evol(data_struct_ap1);
tiempo2 = get_timestamp();
*tiempo = tiempo2 - tiempo1;
tiempof2 = *tiempo;
tiempof = tiempof2/(1000000);
// printf("\n%i %i %i %5f",nodos, vars, poblacion_total, tiempof);
fprintf(fich, "\n%i %i %i %5f",nodos, vars, poblacion_total, tiempof);
for(i = 0; i < nodos*RESULTADOS; i++) //Organizar lo q llego, ¡solo se indexa orderesult, que dice en q orden estan los cromosomas!
{
*(orderesult + i) = i; //se inicializa el stream para el orden
}
for(i=0; i< nodos*RESULTADOS; i++)
{
for(j=i+1; j< nodos*RESULTADOS; j++)
{
if(*(fitness1 + j) < *(fitness1 + i))
{
aux1 = *(orderesult + i);
*(orderesult + i) = *(orderesult + j);
aux2 = *(fitness1 + i);
*(fitness1 + i) = *(fitness1 + j);
*(orderesult + j) = aux1;
*(fitness1 + j) = aux2;
aux1 = *(generacion + i);
*(generacion + i) = *(generacion + j);
*(generacion + j) = aux1;
}
}
}
for(i = 0; i < maxgeneraciones; i=i+maxgeneraciones) //revisar mediciones
{
aux1 = 0;
aux2 = 0;
for(j = 0; j < nodos; j++)
{
aux1 = aux1 + *(aux_sal + (maxgeneraciones * 2 * j) + i);
aux2 = aux2 + *(aux_sal + (maxgeneraciones * 2 * j) + maxgeneraciones + i);
}
aux1 = aux1 / nodos;
aux2 = aux2 / nodos;
if((x&(((iteraciones*p)/puntos)-1)) == 0x0)
fprintf(fich2, "%i %i %i\n",(k*p)+i, aux1, aux2);
// printf("%i %i %i %i\n",(k*p)+i, aux1, aux2, T);
}
for(i = 0; i < LONG_INDIV; i++ )
{
*(char *)(cromo_entrada + i) = *(char *)(cromo_sal1 + (*(orderesult)*LONG_INDIV) + i);
}
data_struct_ap1->en_cromo_entrada = 1;
x = x + p;
float1 = k;
float2 = iteraciones;
Tfloat = (float1/float2)*4;
T = 1 + (int)Tfloat;
aux = (T << 16) | p;
data_struct_ap1->aux = aux;
}
for(i=0; i < RESULTADOS-1 ;i++)
{
printf("\nfit%i:%i gnrcn:%i ", i, *(fitness1), *(generacion + *(orderesult + i)));
mostrar_indiv(cromo_sal1 + ( *orderesult * LONG_INDIV ), pentarboles, vars);
}
x++;
free(cromo_sal1);
free(fitness1);
free(cromo_sal2);
free(fitness2);
free(cromo_entrada);
free(orderesult);
free(generacion);
free(tiempo);
free(aux_sal);
fclose(fich);
fclose(fich2);
free(datos);
free(datos2);
free(funlut_ap);
return 0;
}

View File

@@ -0,0 +1,64 @@
/** Genetic definitions **/
#define PAR_ONLYFIT 0 //paralelizacion, 0 ALGORITMO ENTERO, 1 SOLO FITNESS
#define RESULTADOS 2
/* Numero de generaciones en el que se amplia la logitud del cromosoma*/
#define ARBOLES 5
#define LONG_ARBOL 8
#define nivel1 pentarboles * 4
#define ARBOLES_INDIV (int)(nivel1 + *(nivel2+pentarboles) + *(nivel3+pentarboles) + *(nivel4+pentarboles) + *(nivel5+pentarboles))
#define LONG_INDIV (int)(ARBOLES_INDIV * LONG_ARBOL)
//sockets defs
#define PORT 3550 /* El puerto que sera abierto */
#define BACKLOG 2 /* El numero de conexiones permitidas */
#define MAXDATASIZE 10000 /* El numero maximo de datos en bytes */
#define IP0 "192.168.0.4"
#define IP1 "192.168.0.6"
#define IP2 "192.168.0.7"
#define IP3 "192.168.0.8"
#define IP4 "192.168.0.9"
#define IP5 "192.168.0.10"
#define IP6 "192.168.0.11"
#define IP7 "192.168.0.12"
//#define IP0 "193.147.52.150"
//#define IP1 "193.147.52.139"
/* Variables globales */
char *funlut_ap, *puertas_ap;
void *evalfit_ptr1, *evalfit_ptr4, *evalfit_ptr3, *evalfit_ptr2;
int maxgeneraciones, poblacion, nodos;
typedef long long timestamp_t;
static timestamp_t
get_timestamp ()
{
struct timeval now;
gettimeofday (&now, NULL);
return now.tv_usec + (timestamp_t)now.tv_sec *1000000 ;
}
struct gen_datos_tipo
{
int *objetivo;
int tamaobj;
int pentarboles;
int vars;
int tamacrom;
int maxgen;
char *cromo_sal;
int *fitness;
char *cromo_entrada;
int fitness_entrada;
int nivel_max;
int en_cromo_entrada;
int *generacion;
int *tiempo;
int aux;
int *aux_sal;
};

View File

@@ -0,0 +1,283 @@
/*********************************************************************************************************
** Programa para probar la sintesis combinacional mediante programacion genetica,
** se usan sockets para repartir carga de trabajo a otros clientes
** Se usa periferico evalfit del proyecto ehw3
** se aceleran 5 arboles, que en el presente codigo se llama pentarbol
** compilar con math.h -lm
** compilar con threads: -lpthread
** powerpc-405-linux-gnu-gcc sintesishw_server.c -lm -lpthread -o sintesishw_server_ppc
**
**
**********************************************************************************************************/
#include <stdio.h>
#include <termios.h>
#include <sys/mman.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>
#include <math.h>
#include <pthread.h>
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <errno.h>
#include <sys/un.h>
#include <sintesishw_server.h>
/**************************************************************************************************************************************
crea socket */
int crear_socket()
{
int fd;
struct sockaddr_in server;
if ((fd=socket(AF_INET, SOCK_STREAM, 0)) == -1 ) /* Crear socket */
{
perror("socket");
exit(-1);
}
server.sin_family = AF_INET;
server.sin_port = htons(PORT); /* cambiar endianismo */
server.sin_addr.s_addr = INADDR_ANY; /* INADDR_ANY coloca nuestra direccion IP */
bzero(&(server.sin_zero),8); /* escribimos ceros en el resto de la estructura */
if (setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,&server,sizeof(struct sockaddr)) == -1) /* permite reutilizar el puerto */
{
perror("setsockopt");
exit(1);
}
if(bind(fd,(struct sockaddr*) & server, sizeof(struct sockaddr))==-1) //se asigna el socket
{
perror("bind");
exit(EXIT_FAILURE);
}
return fd;
}
/*******************************************************************************************************************************/
/*******************************************************************************************************************************/
/*******************************************************************************************************************************/
/*******************************************************************************************************************************/
int main()
{
int k, a, i, j = 0, error, vars = 4, *tiempo;
int conta=0, aux1, aux2, pentarboles, *fitness1, *fitness2, *entrada, *generacion, aux, *aux_sal;
char o, *ap, *valor_devuelto;;
char *cromo_sal1, *cromo_sal2, *cromo_entrada, *cromo_ap_aux;
int objetivo[8192];//= {0,254,123,16,87,56,34,76,89,155,199};
struct gen_datos_tipo data_struct1, data_struct2;
struct gen_datos_tipo *data_struct_ap1, *data_struct_ap2;
int nivel2[]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
int nivel3[]={0,0,1,1,1,2,2,2,2,3,3, 3, 3, 4, 4, 4};
int nivel4[]={0,0,0,0,0,1,1,1,1,1,1, 1, 1, 1, 1, 1};
int nivel5[]={0,0,0,0,0,0,0,0,0,0,0, 0, 0, 0, 0, 0};
/* Variables para tablas de lut*/
FILE *f1, *f2;
int size1, size2;
/* Variables para los sockets */
int fd, fd2, numbytes; /* punteros para sockets */
struct sockaddr_in server;
struct sockaddr_in client;
void *data_socket_rx_ap, *data_socket_tx_ap, *ap1;
int sin_size;
/*para periferico*/
int basemem;
srand ( (time(NULL)) );
/* Tabla para las LUT*/
f1 = fopen("funlut.dat","r");
if(f1 == NULL){ printf("\nError de lectura de archivo!");return 0;}
fseek (f1, 0, SEEK_END);
size1 = ftell(f1);
funlut_ap = malloc(size1); if(funlut_ap==0) printf("Error en malloc");
rewind (f1);
fread(funlut_ap,1,size1,f1);
fclose(f1);
f2 = fopen("puertas.dat","r");
if(f2 == NULL){ printf("\nError de lectura de archivo!");return 0;}
fseek (f2, 0, SEEK_END);
size2 = ftell(f2);
puertas_ap = malloc(size2); if(puertas_ap==0) printf("Error en malloc");
rewind (f2);
fread(puertas_ap,1,size2,f2);
fclose(f2);
basemem = open("/dev/mem", (O_RDWR | O_SYNC)); //abrir dispositivo memoria para mapear dir del periferico
if(basemem == -1)
{ printf("Error al abrir /dev/mem \n");
return -1;}
/** iniciar periferico **/
if(HW_ENABLE == 1){
evalfit_ptr1 = (int *)init_peripheral(EVALFIT_PHYSBASE1, basemem);
evalfit_ptr2 = (int *)init_peripheral(EVALFIT_PHYSBASE2, basemem);
evalfit_ptr3 = (int *)init_peripheral(EVALFIT_PHYSBASE3, basemem);
evalfit_ptr4 = (int *)init_peripheral(EVALFIT_PHYSBASE4, basemem);
}
data_struct_ap1 = &data_struct1;
data_struct_ap2 = &data_struct2;
/* preparar socket para recibir */
data_socket_rx_ap = malloc(100000);
data_socket_tx_ap = malloc(100000);
fd = crear_socket();
if(listen(fd, BACKLOG) == -1)
{ printf("error en listen()\n");
exit(-1);
}
//int err, sndsize=8192;
//err = setsockopt(fd2, SOL_SOCKET, SO_RCVBUF, (char *)&sndsize, (int)sizeof(sndsize));
while(1)
{
sin_size=sizeof(struct sockaddr_in);
if ((fd2 = accept(fd,(struct sockaddr *)&client, &sin_size))==-1) /* llamada a accept() */
{
printf("error en accept()\n");
exit(-1);
}
/* printf("Se obtuvo una conexion desde %s\n", inet_ntoa(client.sin_addr) ); //mostrara la IP del cliente QUITAR PARA GANAR VELOCIDAD*/
numbytes=0;
do
{
if ((aux1=recv(fd2,data_socket_rx_ap+numbytes,8192,0)) == -1){ /* recibir datos del cliente*/
perror("recv");
printf("Error en recv() \n");
exit(-1);
}
numbytes = numbytes+aux1;
}while(*(int *)(data_socket_rx_ap+numbytes-4)!=htonl(0xa55a9669));
ap1 = data_socket_rx_ap; /* Cargar datos en la estructura para la evolucion */
data_struct_ap1->tamaobj = htonl(*(int *)ap1) & 0xFFFF;
maxgeneraciones = htonl(*(int *)ap1) >> 16;
// printf("\ntama obj:%0x maxgens:%i numbytes:%i-- ", data_struct_ap1->tamaobj, maxgeneraciones,numbytes);
fflush(stdout);
ap1 = ap1 + 4;
for(i=0;i < (data_struct_ap1->tamaobj); i++)
{
objetivo[i] =htonl(*(int *)ap1); //XX
// printf("obj:%i %i ",i,objetivo[i]);
ap1 = ap1 + 4;
}
data_struct_ap1->objetivo = objetivo;
data_struct_ap1->pentarboles = htonl(*(int *)ap1) & 0XFF;
pentarboles = data_struct_ap1->pentarboles;
vars = htonl(*(int *)ap1) >> 16;
data_struct_ap1->vars = vars;
ap1 = ap1 + 4;
data_struct_ap1->tamacrom = htonl(*(int *)ap1) & 0xFFFF;
poblacion = htonl(*(int *)ap1) >> 16;
// printf("\ntamacrom:%0x poblacion:%i vars:%i pentarboles:%i maxgeneraciones:%i ", data_struct_ap1->tamacrom, poblacion,vars,pentarboles,maxgeneraciones);
ap1 = ap1 + 4;
cromo_entrada = malloc(sizeof(cromo_entrada) * RESULTADOS * LONG_INDIV); if(cromo_entrada==0) printf("Error en malloc");
data_struct_ap1->cromo_entrada = cromo_entrada;
for(i = 0; i < (data_struct_ap1 -> tamacrom); i++)
{
*(char *)(cromo_entrada + i) = *(char *)ap1;
ap1 = ap1 + 1;
}
data_struct_ap1->fitness_entrada = htonl(*(int *)ap1);
ap1 = ap1 + 4;
data_struct_ap1->nivel_max = htonl(*(int *)ap1) & 0xFFFF;
data_struct_ap1->en_cromo_entrada = htonl(*(int *)ap1) >> 16; //han enviado un cromosoma?
ap1 = ap1 + 4;
data_struct_ap1->aux = htonl(*(int *)ap1);
/* printf("\nnivel_max:%0x-- ", data_struct_ap1->nivel_max);*/
data_struct_ap1->maxgen = maxgeneraciones;
cromo_sal1 = malloc(sizeof(cromo_sal1) * RESULTADOS * LONG_INDIV); if(cromo_sal1==0) printf("Error en malloc"); /* reservar para cromosomas */
fitness1 = malloc(sizeof(fitness1) * RESULTADOS); if(fitness1==0) printf("Error en malloc");
cromo_sal2 = malloc(sizeof(cromo_sal2) * RESULTADOS * LONG_INDIV); if(cromo_sal2==0) printf("Error en malloc");
fitness2 = malloc(sizeof(fitness2) * RESULTADOS); if(fitness2==0) printf("Error en malloc");
generacion = malloc(sizeof(generacion)); if(generacion==0) printf("Error en malloc");
tiempo = malloc(sizeof(tiempo)* RESULTADOS ); if(tiempo==0) printf("Error en malloc");
aux_sal = malloc(sizeof(aux_sal)* maxgeneraciones * 2 ); if(aux_sal==0) printf("Error en malloc");
data_struct_ap1->generacion = generacion;
data_struct_ap1->cromo_sal = cromo_sal1;
data_struct_ap1->fitness = fitness1;
data_struct_ap1->fitness_entrada = 0;
data_struct_ap1->tiempo = tiempo;
data_struct_ap1->aux_sal = aux_sal;
*generacion = 0;
evolucionar(data_struct_ap1); // evolucionar
/* for(i=0; i < RESULTADOS ;i++)*/
/* {*/
/* printf(" %i-- fit:%i \t",i , *(fitness1 + i));*/
/* mostrar_indiv(cromo_sal1 + (i*LONG_INDIV), pentarboles, vars);*/
/* }*/
ap1 = data_socket_tx_ap; /* devolver resultados */
*(int *)ap1 = ntohl(LONG_INDIV);
ap1 = ap1 + 4;
for(i=0; i < RESULTADOS ;i++)
{
for(j=0; j < LONG_INDIV ;j++)
{
*(char *)ap1 = *(cromo_sal1 + j + (LONG_INDIV * i));
ap1 ++;
}
*(int *)ap1 = ntohl(((*generacion) << 16) | (*(fitness1 + i)));
ap1 = ap1 + 4;
*(int *)ap1 = ntohl(*tiempo);
ap1 = ap1 + 4;
}
for(i=0; i < maxgeneraciones*2 ;i++) //devolver mediciones
{
*(int *)ap1 = ntohl(*(aux_sal+i));
ap1 = ap1 + 4;
}
numbytes = ap1 - data_socket_tx_ap;
send(fd2, data_socket_tx_ap, numbytes, 0); /* devuelve cromosoma y fitness al cliente */
/* printf("\n");*/
close(fd2);
free(cromo_entrada);
free(cromo_sal1);
free(fitness1);
free(cromo_sal2);
free(fitness2);
free(generacion);
free(tiempo);
free(aux_sal);
}
if(HW_ENABLE == 1){
close_peripheral(evalfit_ptr1);
close_peripheral(evalfit_ptr2);
close_peripheral(evalfit_ptr3);
close_peripheral(evalfit_ptr4);
}
close(basemem);
free(funlut_ap);
free(puertas_ap);
free(data_socket_rx_ap);
free(data_socket_tx_ap);
shutdown(fd, SHUT_RDWR);
close(fd);
return 0;
}

View File

@@ -0,0 +1,58 @@
/** Genetic definitions **/
#define HW_ENABLE 1 //cambiar en genetic.h habilitar hw, 0 se hace por SW
#define RESULTADOS 2
#define ARBOLES 5
#define LONG_ARBOL 8
#define nivel1 pentarboles * 4
#define ARBOLES_INDIV (int)(nivel1 + *(nivel2+pentarboles) + *(nivel3+pentarboles) + *(nivel4+pentarboles) + *(nivel5+pentarboles))
#define LONG_INDIV (int)(ARBOLES_INDIV * LONG_ARBOL)
#define EVALFIT_PHYSBASE1 0xcd800000
#define EVALFIT_PHYSBASE2 0xcd820000
#define EVALFIT_PHYSBASE3 0xcd840000
#define EVALFIT_PHYSBASE4 0xcd860000
//sockets defs
#define PORT 3550 /* El puerto que sera abierto */
#define BACKLOG 2 /* El numero de conexiones permitidas */
#define MAXDATASIZE 10000 /* El numero maximo de datos en bytes */
/* Variables globales */
char *funlut_ap, *puertas_ap;
void *evalfit_ptr1, *evalfit_ptr4, *evalfit_ptr3, *evalfit_ptr2;
int maxgeneraciones, poblacion;
typedef long long timestamp_t;
static timestamp_t
get_timestamp ()
{
struct timeval now;
gettimeofday (&now, NULL);
return now.tv_usec + (timestamp_t)now.tv_sec *1000000 ;
}
struct gen_datos_tipo
{
int *objetivo;
int tamaobj;
int pentarboles;
int vars;
int tamacrom;
int maxgen;
char *cromo_sal;
int *fitness;
char *cromo_entrada;
int fitness_entrada;
int nivel_max;
int en_cromo_entrada;
int *generacion;
int *tiempo;
int aux;
int *aux_sal;
};

29
Examples/ehw4/src/test/Makefile Executable file
View File

@@ -0,0 +1,29 @@
#OBJS := start.o main.o jz_serial.o
CROSS := mipsel-openwrt-linux-
INCLUDE = -I. -lm
CCFLAGS = ${INCLUDE} ${DEBUG} ${WARNINGS}
#CFLAGS := -O2 -G 0 -mno-abicalls -fno-pic -mips32 -Iinclude
AFLAGS = -D__ASSEMBLY__ $(CFLAGS)
LDFLAGS := -T ld.script -nostdlib -EL
COMMON_SOURCES = jz47xx_gpio.c jz47xx_mmap.c
COMMON_OBJECTS = $(COMMON_SOURCES:.c=.o)
H_SOURCES = jz47xx_gpio.h jz47xx_mmap.h
NANO_IP = 192.168.254.101
all: xburst
xburst: xburst.c xburst.h $(COMMON_OBJECTS)
$(CROSS)gcc $(COMMON_OBJECTS) xburst.c -o xburst ${CCFLAGS}
.c.o:
$(CROSS)gcc $(CCFLAGS) -c $< -o $@
.S.o:
$(CROSS)gcc $(AFLAGS) -c $< -o $@
indent:
indent -bad -bap -nbc -bl -nce -i2 --no-tabs --line-length120 $(COMMON_SOURCES) $(H_SOURCES)
upload: xburst
scp xburst root@$(NANO_IP):binaries

View File

@@ -0,0 +1,40 @@
/*
JZ47xx test gpio
Copyright (C) 2010 Andres Calderon andres.calderon@emqbit.com
Carlos Camargo cicamargoba@unal.edu.co
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#include <stdio.h>
#include <unistd.h>
#include "jz47xx_gpio.h"
#define IRQ_PORT JZ_GPIO_PORT_C
#define IRQ_PIN 15
int
main ()
{
JZ_PIO *pio = jz_gpio_map (IRQ_PORT);
if (!pio)
return -1;
jz_gpio_as_irq (pio, IRQ_PIN);
return 0;
}

View File

@@ -0,0 +1,40 @@
/*
JZ47xx test gpio
Copyright (C) 2010 Andres Calderon andres.calderon@emqbit.com
Carlos Camargo cicamargoba@unal.edu.co
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#include <stdio.h>
#include <unistd.h>
#include "jz47xx_gpio.h"
#define RXD_PORT JZ_GPIO_PORT_D
#define RXD_PIN 26
int
main ()
{
JZ_PIO *pio = jz_gpio_map (RXD_PORT);
if (!pio)
return -1;
jz_gpio_as_func (pio, RXD_PIN, 1);
return 0;
}

View File

@@ -0,0 +1,119 @@
/*
JZ47xx GPIO at userspace
Copyright (C) 2010 Andres Calderon andres.calderon@emqbit.com
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <jz47xx_gpio.h>
#include <jz47xx_mmap.h>
#define JZ_GPIO_BASE 0x10010000
void
jz_gpio_as_output (JZ_PIO * pio, unsigned int o)
{
pio->PXFUNC = (1 << (o));
pio->PXSELC = (1 << (o));
pio->PXDIRS = (1 << (o));
}
void
jz_gpio_as_input (JZ_PIO * pio, unsigned int o)
{
pio->PXFUNC = (1 << (o));
pio->PXSELC = (1 << (o));
pio->PXDIRC = (1 << (o));
}
void
jz_gpio_as_irq (JZ_PIO * pio, unsigned int o)
{
pio->PXFUNC = (1 << (o));
pio->PXSELS = (1 << (o));
pio->PXDIRC = (1 << (o));
}
void
jz_gpio_set_pin (JZ_PIO * pio, unsigned int o)
{
pio->PXDATS = (1 << (o));
}
void
jz_gpio_clear_pin (JZ_PIO * pio, unsigned int o)
{
pio->PXDATC = (1 << (o));
}
void
jz_gpio_out (JZ_PIO * pio, unsigned int o, unsigned int val)
{
if (val == 0)
pio->PXDATC = (1 << (o));
else
pio->PXDATS = (1 << (o));
}
unsigned int
jz_gpio_get_pin (JZ_PIO * pio, unsigned int o)
{
return (pio->PXPIN & (1 << o)) ? 1 : 0;
}
int
jz_gpio_as_func (JZ_PIO * pio, unsigned int o, int func)
{
switch (func)
{
case 0:
pio->PXFUNS = (1 << o);
pio->PXTRGC = (1 << o);
pio->PXSELC = (1 << o);
pio->PXPES = (1 << o);
return 1;
case 1:
pio->PXFUNS = (1 << o);
pio->PXTRGC = (1 << o);
pio->PXSELS = (1 << o);
pio->PXPES = (1 << o);
return 1;
case 2:
pio->PXFUNS = (1 << o);
pio->PXTRGS = (1 << o);
pio->PXSELC = (1 << o);
pio->PXPES = (1 << o);
return 1;
}
return 0;
}
JZ_PIO *
jz_gpio_map (int port)
{
JZ_PIO *pio;
pio = (JZ_PIO *) jz_mmap (JZ_GPIO_BASE);
pio = (JZ_PIO *) ((unsigned int) pio + port * 0x100);
return pio;
}

View File

@@ -0,0 +1,84 @@
/*
JZ47xx GPIO at userspace
Copyright (C) 2010 Andres Calderon andres.calderon@emqbit.com
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#ifndef __jz47xx_gpio_h__
#define __jz47xx_gpio_h__
#define JZ_GPIO_PORT_A 0
#define JZ_GPIO_PORT_B 1
#define JZ_GPIO_PORT_C 2
#define JZ_GPIO_PORT_D 3
typedef volatile unsigned int JZ_REG; /* Hardware register definition */
typedef struct _JZ_PIO
{
JZ_REG PXPIN; /* PIN Level Register */
JZ_REG Reserved0;
JZ_REG Reserved1;
JZ_REG Reserved2;
JZ_REG PXDAT; /* Port Data Register */
JZ_REG PXDATS; /* Port Data Set Register */
JZ_REG PXDATC; /* Port Data Clear Register */
JZ_REG Reserved3;
JZ_REG PXIM; /* Interrupt Mask Register */
JZ_REG PXIMS; /* Interrupt Mask Set Reg */
JZ_REG PXIMC; /* Interrupt Mask Clear Reg */
JZ_REG Reserved4;
JZ_REG PXPE; /* Pull Enable Register */
JZ_REG PXPES; /* Pull Enable Set Reg. */
JZ_REG PXPEC; /* Pull Enable Clear Reg. */
JZ_REG Reserved5;
JZ_REG PXFUN; /* Function Register */
JZ_REG PXFUNS; /* Function Set Register */
JZ_REG PXFUNC; /* Function Clear Register */
JZ_REG Reserved6;
JZ_REG PXSEL; /* Select Register */
JZ_REG PXSELS; /* Select Set Register */
JZ_REG PXSELC; /* Select Clear Register */
JZ_REG Reserved7;
JZ_REG PXDIR; /* Direction Register */
JZ_REG PXDIRS; /* Direction Set Register */
JZ_REG PXDIRC; /* Direction Clear Register */
JZ_REG Reserved8;
JZ_REG PXTRG; /* Trigger Register */
JZ_REG PXTRGS; /* Trigger Set Register */
JZ_REG PXTRGC; /* Trigger Set Register */
JZ_REG Reserved9;
JZ_REG PXFLG; /* Port Flag Register */
JZ_REG PXFLGC; /* Port Flag clear Register */
} JZ_PIO, *PJZ_PIO;
void jz_gpio_as_output (JZ_PIO * pio, unsigned int o);
void jz_gpio_as_input (JZ_PIO * pio, unsigned int o);
void jz_gpio_set_pin (JZ_PIO * pio, unsigned int o);
void jz_gpio_clear_pin (JZ_PIO * pio, unsigned int o);
void jz_gpio_out (JZ_PIO * pio, unsigned int o, unsigned int val);
unsigned int jz_gpio_get_pin (JZ_PIO * pio, unsigned int o);
int jz_gpio_as_func (JZ_PIO * pio, unsigned int o, int func);
JZ_PIO *jz_gpio_map (int port);
#endif

Binary file not shown.

View File

@@ -0,0 +1,64 @@
/*
* JZ47xx GPIO lines
*
* Written 2010 by Andres Calderon andres.calderon@emqbit.com
*/
#include <stdio.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h>
#include <jz47xx_mmap.h>
void *
jz_mmap (off_t address)
{
int fd;
void *pio;
if ((fd = open ("/dev/mem", O_RDWR | O_SYNC)) == -1)
{
fprintf (stderr, "Cannot open /dev/mem.\n");
return 0;
}
pio = (void *) mmap (0, getpagesize (), PROT_READ | PROT_WRITE, MAP_SHARED, fd, address);
if (pio == (void *) -1)
{
fprintf (stderr, "Cannot mmap.\n");
return 0;
}
return pio;
}
void *
jz_fpga_map (off_t address)
{
int fd;
void *fpga;
if ((fd = open ("/dev/mem", O_RDWR | O_SYNC)) == -1)
{
fprintf (stderr, "Cannot open /dev/mem.\n");
return 0;
}
fpga = (void *) mmap (0, FPGA_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, address);
if (fpga == (void *) -1)
{
fprintf (stderr, "Cannot mmap.\n");
return 0;
}
return fpga;
}

View File

@@ -0,0 +1,17 @@
/*
* JZ47xx GPIO lines
*
* Written 2010 by Andres Calderon andres.calderon@emqbit.com
*/
#ifndef __jz47xx_mmap_h__
#define __jz47xx_mmap_h__
#include <sys/mman.h>
#define FPGA_SIZE (1 << 15)
void *jz_mmap (off_t address);
void *jz_fpga_map (off_t address);
#endif

Binary file not shown.

View File

@@ -0,0 +1,75 @@
/* SAKC FPGA/SRAM interface test
Copyright (C) 2010 Carlos Camargo cicamargoba@unal.edu.co
Andres Calderon andres.calderon@emqbit.com
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include "jz47xx_gpio.h"
#include "jz47xx_mmap.h"
#define CS2_PORT JZ_GPIO_PORT_B
#define CS2_PIN 26
int
main ()
{
int i;
JZ_PIO *pio;
int *virt_addr;
pio = jz_gpio_map (CS2_PORT);
jz_gpio_as_func (pio, CS2_PIN, 0);
virt_addr = (int *) jz_mmap (0x13010000) + 0x18/sizeof(int);
if (*virt_addr != 0xFFF7700)
{ // 0 WS, 8 bits
*virt_addr = 0xFFF7700;
printf ("Configuring CS2 8 bits \n");
}
else
printf ("CS3, already configured\n");
virt_addr = (int *) jz_fpga_map (0x15000000);
printf ("Writing Memory..\n");
srand48(0x3c);
for (i = 0; i < FPGA_SIZE/4; i++)
virt_addr[i] = (lrand48() & 0x00ff);
printf ("Reading Memory..\n");
srand48(0x3c);
for (i = 0; i < FPGA_SIZE/4; i++){
printf("%X\n", virt_addr[i]);
if (virt_addr[i] != (lrand48() & 0x00ff)){
printf ("FPGA - Xburst connection test failed on Address:0x%x\n", i);
return 1; /* Error */
}
}
printf ("%d\n", i);
printf ("FPGA - Xburst connection test passed\n");
return 0;
}

View File

@@ -0,0 +1,59 @@
/*
JZ47xx test gpio
Copyright (C) 2010 Andres Calderon andres.calderon@emqbit.com
Carlos Camargo cicamargoba@unal.edu.co
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#include <stdio.h>
#include <unistd.h>
#include "jz47xx_gpio.h"
//#define TEST_PORT JZ_GPIO_PORT_C
//#define TEST_PIN 17
int
main (int argc,char *argv[])
{
int TEST_PORT, TEST_PIN;
if(argc != 3){
fprintf(stderr,"\nUsage: %s TEST_PIN_PORT(A=0, B=1, C=2, D=3) TEST_PIN \n",argv[0]);
}
TEST_PORT = JZ_GPIO_PORT_C;
TEST_PIN = 17;
JZ_PIO *pio = jz_gpio_map (TEST_PORT);
if (!pio)
return -1;
jz_gpio_as_output (pio, TEST_PIN);
int tg = 1;
while (1)
{
jz_gpio_out (pio, TEST_PIN, tg);
printf ("[%d]", jz_gpio_get_pin (pio, TEST_PIN));
fflush (stdout);
usleep (500 * 1000);
tg = !tg;
}
return 0;
}

BIN
Examples/ehw4/src/test/xburst Executable file

Binary file not shown.

70
Examples/ehw4/src/test/xburst.c Executable file
View File

@@ -0,0 +1,70 @@
#include <stdio.h>
#include <stdlib.h>
#include "fcntl.h"
#include <sys/mman.h>
#include <xburst.h>
#include "jz47xx_gpio.h"
#include <jz47xx_mmap.h>
#define CS2_PORT JZ_GPIO_PORT_B
#define CS2_PIN 26
int periph_map(off_t offset)
{
int basemem, baseperiph;
basemem = open("/dev/mem", (O_RDWR | O_SYNC)); //abrir dispositivo memoria para mapear dir del periferico
if(basemem == -1)
{
printf("Error to open /dev/mem \n");
return -1;
}
baseperiph = (int )mmap(NULL, MAP_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, basemem, offset);// & ~MAP_MASK);
if (baseperiph == -1)
{
printf ("Cannot mmap.\n");
return -1;
}
return baseperiph;
}
int main(){
int i, j;
int basemem, base_periferico, *ConfigRegsBase_ptr;
void *peripheral1_ptr;
void *pio;
printf("Xburst Test...");
basemem = open("/dev/mem", (O_RDWR | O_SYNC)); //abrir dispositivo memoria para mapear dir del periferico
if(basemem == -1)
{
printf("Error al abrir /dev/mem \n");
return -1;
}
pio = jz_gpio_map(CS2_PORT);
jz_gpio_as_func (pio, CS2_PIN, 0);
ConfigRegsBase_ptr = (int *)periph_map(CONFIG_REGS_BASE);// + SACR2_OFFSET/sizeof(int);//SMCR2_OFFSET/sizeof(int);
printf("\n%0x ", *(ConfigRegsBase_ptr + SMCR2_OFFSET/sizeof(int)));
munmap(ConfigRegsBase_ptr, MAP_SIZE);
peripheral1_ptr = (int *)periph_map(0x14000000);
for(i = 0; i < 0xfff; i=i+4){
j = rand();
// *(int *)(peripheral1_ptr + i) = j;
// if(j != *(int *)(peripheral1_ptr + i)){
// printf("\nError at %0x offset:%i\n", (int *)(peripheral1_ptr + i), i); exit(0);
// }
printf("\nReg %i: write:%0x read:%0x", i, j, *(int *)(peripheral1_ptr + i) );
}
printf("\nPassed Test\n");
munmap(peripheral1_ptr, MAP_SIZE);
//munmap(base_periferico, MAP_SIZE);
close(basemem);
exit(0);
}

10
Examples/ehw4/src/test/xburst.h Executable file
View File

@@ -0,0 +1,10 @@
#define CONFIG_REGS_BASE 0x13010000
#define SMCR2_OFFSET 0x18
#define SACR2_OFFSET 0x38
#define MAP_SIZE 0x10000Ul
#define MAP_MASK (MAP_SIZE - 1)
#define XBURST_PHYSBASE1 0x14000000
//SMCR2 reset:0x0FFF7700 Address: 0x13010018