-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsoft_computing_project.py
More file actions
83 lines (62 loc) · 2.62 KB
/
Copy pathsoft_computing_project.py
File metadata and controls
83 lines (62 loc) · 2.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# -*- coding: utf-8 -*-
"""Soft Computing Project
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1ou3XzPECyEjCs0gIAsiHxzWhKpgn6epE
"""
import random
NUM_DEVICES = int(input("Enter number of devices: ")) # Number of devices
energy_cost = []
print("Enter energy cost for each device:") # Here we are finding the energy cost for each device.
for i in range(NUM_DEVICES):
cost = float(input(f"Device {i + 1} cost: "))
energy_cost.append(cost)
# Creating an individual (device usage pattern) with at least one device ON.
def create_individual():
while True:
ind = [random.randint(0, 1) for _ in range(NUM_DEVICES)]
if sum(ind) >= 2: # Require at least 2 devices ON
return ind
# Creating the population
def create_population(size):
return [create_individual() for _ in range(size)]
# Calculating fitness
def fitness(individual):
total_cost = sum([individual[i] * energy_cost[i] for i in range(NUM_DEVICES)])
num_on = sum(individual)
if num_on < 2:
return 0 # Apply penalty if the number of active devices is less than 2.
return (num_on + 1) / (total_cost + 1)
# Selection
def selection(population):
weights = [fitness(ind) for ind in population]
return random.choices(population, weights=weights, k=2)
# Crossover
def crossover(parent1, parent2):
point = random.randint(1, NUM_DEVICES - 1)
return parent1[:point] + parent2[point:]
# Mutation
def mutate(individual, mutation_rate=0.3):
return [1 - gene if random.random() < mutation_rate else gene for gene in individual]
# Run the Genetic Algorithm
def genetic_algorithm(generations=50, population_size=100):
population = create_population(population_size)
for generation in range(generations):
new_population = []
for _ in range(population_size):
parent1, parent2 = selection(population)
child = crossover(parent1, parent2)
child = mutate(child)
if sum(child) >= 2: # Checking at least 2 devices ON
new_population.append(child)
else:
new_population.append(create_individual())
population = new_population
best = max(population, key=fitness)
print(f"Generation {generation + 1}: Best Fitness = {fitness(best):.4f}")
best_individual = max(population, key=fitness)
best_cost = sum([best_individual[i] * energy_cost[i] for i in range(NUM_DEVICES)])
print("\n✅ Best Device Usage Pattern (1=On, 0=Off):", best_individual)
print("💡 Corresponding Energy Cost:", best_cost)
# Run the program
genetic_algorithm()