Exemplo n.º 1
0
def test_circuit_resistance():
    circuit = Circuit()
    battery = VoltageSource(circuit, 9)  # 9 volts
    resistor = Resistor(circuit, 10)  # 1 ohm
    battery.negative = resistor.positive
    battery.positive = resistor.negative = circuit._ground
    print circuit.graph.edges()
    mna = circuit.assemble_mna_equation()
    stuff = mna.simulate(10.0, 0.1)

    circuit.draw()
    plt.savefig('crkt1.png')
Exemplo n.º 2
0
def test_circuit_parallel_resistor_capacitor():
    circuit = Circuit()
    battery = VoltageSource(circuit, 9)
    resistor = Resistor(circuit, 1)
    capacitor = Capacitor(circuit, 1e-1)  # 1 microFarad
    battery.negative = resistor.positive = capacitor.positive
    battery.positive = resistor.negative = capacitor.negative = circuit._ground

    mna = circuit.assemble_mna_equation()
    stuff = mna.simulate_be(1e0, 1e-3, vars=[Var(battery.id, 'i')])

    print mna.rev_idict

    plt.plot(stuff)
    plt.savefig('cap_par.png')

    plt.figure()
    circuit.draw()
    plt.savefig('crkt3.png')
Exemplo n.º 3
0
def test_circuit_capacitance():
    circuit = Circuit()
    battery = VoltageSource(circuit, 9)
    resistor = Resistor(circuit, 1)
    capacitor = Capacitor(circuit, 1e-1)
    battery.positive = resistor.positive
    resistor.negative = capacitor.positive
    capacitor.negative = battery.negative = circuit._ground

    mna = circuit.assemble_mna_equation()
    stuff = mna.simulate_be(
        1e0,
        1e-3,
        vars=[Var(resistor.negative, 'v'),
              Var(resistor.positive, 'v')])

    plt.plot(stuff)
    plt.savefig('cap.png')

    plt.figure()
    circuit.draw()
    plt.savefig('crkt2.png')
Exemplo n.º 4
0
class Game:
    def __init__(self):
        pygame.init()
        pygame.display.set_caption("Car tutorial")
        width = 1280
        height = 720

        self.screen = pygame.display.set_mode((width, height))
        self.clock = pygame.time.Clock()
        self.ticks = 60
        self.exit = False
        self.circuit = Circuit(self.screen)

    def run(self):
        # current_dir = os.path.dirname(os.path.abspath(__file__))
        # image_path = os.path.join(current_dir, "car.png")
        # car_image = pygame.image.load(image_path)

        Evo.setLearningPhase(1)

        # MODIFIER LE NOMBRE DE VOITURE ICI POUR EN AVOIR QU UNE
        NombreVoiture = 20
        TabCar = []

        populationNN = Evo.initPopulation(NombreVoiture)
        generationCount = 1
        while not self.exit:
            allCarsCrashed = False

            print(generationCount)
            generationCount += 1

            #  REMPLACER RANDOM PAR LES COORD DE LA VOITURE SI UNIQUE VOITURE, SINON LES 5 AURONT LE MEME COMPORTEMENT ET SERONT INDIFFERENCIABLE
            for i in range(0, NombreVoiture):
                # TabCar.append(Car.Car(random.randint(70, 110), random.randint(80, 120)))
                TabCar.append(Car.Car(100, 100, -90))

            for j in range(0, NombreVoiture):
                TabCar[j].setNeuralNetwork(populationNN[j])

            self.clock = pygame.time.Clock()

            Evo.setLearningPhase(0)
            while (allCarsCrashed == False):
                dt = self.clock.get_time() / 1000

                # Event queue
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        self.exit = True

                # Mouvement de la voiture par IA
                for c in TabCar:
                    if (c.canRun):
                        c.run(self.circuit.listObstacle, dt)
                        if (c.testCollision(self.circuit.listObstacle)):
                            c.stop(False)
                        elif (
                                self.isOutOfBounds(c)
                        ):  #si une voiture est sortie du circuit et de l'écran on la discalifie
                            c.stop(True)

                # Mouvement de la voiture par l'utilisateur
                """
                # User input
                pressed = pygame.key.get_pressed()
    
                if pressed[pygame.K_UP]:
                    if car.velocity.x < 0:
                        car.acceleration = car.brake_deceleration
                    else:
                        car.acceleration += 640 * dt
                elif pressed[pygame.K_DOWN]:
                    if car.velocity.x > 0:
                        car.acceleration = -car.brake_deceleration
                    else:
                        car.acceleration -= 640 * dt
                # elif pressed[pygame.K_SPACE]:
                # if abs(car.velocity.x) > dt * car.brake_deceleration:
                # car.acceleration = -copysign(car.brake_deceleration, car.velocity.x)
                # else:
                # car.acceleration = -car.velocity.x / dt'''
                else:
                    if abs(car.velocity.x) > dt * car.free_deceleration:
                        car.acceleration = -copysign(car.free_deceleration, car.velocity.x)
                    else:
                        if dt != 0:
                            car.acceleration = -car.velocity.x / dt
                car.acceleration = max(-car.max_acceleration, min(car.acceleration, car.max_acceleration))
    
                if pressed[pygame.K_RIGHT]:
                    car.steering -= 300 * dt
                elif pressed[pygame.K_LEFT]:
                    car.steering += 300 * dt
                else:
                    car.steering = 0
                car.steering = max(-car.max_steering, min(car.steering, car.max_steering))
                """

                # Logic
                allCarsCrashed = True
                for c in TabCar:
                    c.update(dt)
                    if c.canRun == True:
                        allCarsCrashed = False

                # Drawing
                self.screen.fill((0, 0, 0))
                for c in TabCar:
                    rotated = pygame.transform.rotate(c.image, c.angle)
                    # print (car.angle % 360)
                    # print(car.angle)
                    # print(car.position[0], car.position[1])
                    # Test des Sensor >>>
                    # print(self.circuit.listObstacle)
                    # print(car.sensors(self.circuit.listObstacle))
                    # car.sensors(self.circuit.listObstacle)
                    # car.testCollision(self.circuit.listObstacle)
                    rect = rotated.get_rect()
                    self.screen.blit(
                        rotated,
                        c.position - (rect.width / 2, rect.height / 2))
                self.circuit.draw()

                pygame.display.flip()

                self.clock.tick(self.ticks)

            Evo.setLearningPhase(1)

            for x in range(0, NombreVoiture):
                populationNN[x].setFitness(TabCar[x].getFitness())

            populationNN = Evo.updateGeneration(populationNN, 0.4, 0.1, 0.4,
                                                0.2)

            TabCar.clear()

        pygame.quit()

    def isOutOfBounds(self, aCar):
        if aCar.position.x < 0 or aCar.position.x > self.screen.get_width() \
                or aCar.position.y < 0 or aCar.position.y > self.screen.get_height():
            return True
# Verify correctness of the SUM3 circuit
from itertools import product

for x1, x2, x3 in product(range(2), repeat=3):
    w0, w1 = sum3(x1, x2, x3)
    assert x1 + x2 + x3 == w0 + 2 * w1

# Build a circuit for SUM5 out of SUM2 and SUM3 blocks
circuit = Circuit(input_labels=['x1', 'x2', 'x3', 'x4', 'x5'])
x1, x2, x3, x4, x5 = circuit.input_labels
a0, a1 = add_sum3(circuit, [x1, x2, x3])
b0, b1 = add_sum3(circuit, [a0, x4, x5])
w1, w2 = add_sum2(circuit, [a1, b1])
circuit.outputs = [b0, w1, w2]
check_sum_circuit(circuit)
circuit.draw('sum5')


# Find an optimum circuit for SUM3 using SAT-solvers
def sum_n(x):
    return [(sum(x) >> i) & 1 for i in range(ceil(log2(len(x) + 1)))]


circuit_finder = CircuitFinder(dimension=3, number_of_gates=5, function=sum_n)
circuit = circuit_finder.solve_cnf_formula()
circuit.draw('sum3')

# Improve the SUM5 circuit of size 12
circuit = Circuit(input_labels=[f'x{i}' for i in range(1, 6)], gates={})
circuit.outputs = add_sum5_suboptimal(circuit, circuit.input_labels)
improved_circuit = improve_circuit(circuit, subcircuit_size=5, connected=True)