first commit

This commit is contained in:
Johann Dreo 2018-12-08 19:40:22 +01:00
commit 27b52fef6c
5 changed files with 245 additions and 0 deletions

32
2018-2019/letters.py Normal file
View file

@ -0,0 +1,32 @@
letters = {
"alpha":("Α","α"),
"beta":("Β","β"),
"gamma":("Γ","γ"),
"delta":("Δ","δ"),
"epsilon":("Ε","ε"),
"zeta":("Ζ","ζ"),
"eta":("Η","η"),
"theta":("Θ","θ"),
"iota":("Ι","ι"),
"kappa":("Κ","κ"),
"lambda":("Λ","λ"),
"mu":("Μ","μ"),
"nu":("Ν","ν"),
"xi":("Ξ","ξ"),
"omicron":("Ο","ο"),
"pi":("Π","π"),
"rho":("Ρ","ρ"),
"sigma":("Σ","σ"),
"tau":("Τ","τ"),
"upsilon":("Υ","υ"),
"phi":("Φ","φ"),
"chi":("Χ","χ"),
"psi":("Ψ","ψ"),
"omega":("Ω","ω"),
"sampi":("Ͳ","ϡ")
}
if __name__=="__main__":
for key in letters:
print(key)

70
sho/api.py Normal file
View file

@ -0,0 +1,70 @@
import numpy as np
def sphere(x,offset=0.5):
"""Computes the square of a multi-dimensional vector x."""
f = 0
for i in range(len(x)):
f += (x[i]-offset)**2
return f
def square(sol,scale=1):
"""Gnerate a random vector close at thegiven scale to the given sol."""
return sol + np.random.random(len(sol))*scale
def greedy(objective_function, dimension, iterations, target=1e-3, neighborhood=square, scale=1/100, history=None):
"""Search the given objective_function of the given dimension,
during the given number of iterations, generating solution
with the given neighborhood.
Returns the best value of the function and the best solution."""
best_sol = np.random.random(dimension)
best_val = objective_function(best_sol)
for i in range(iterations):
sol = neighborhood(best_sol,scale)
val = objective_function(sol)
if val < best_val:
best_val = val
best_sol = sol
if history is not None:
history.append((val,sol))
if val < target: # Assume the optimum is zero
break
return best_val, best_sol
if __name__=="__main__":
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import argparse
import plot
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--dim", metavar="NB", default=2, type=int,
help="Number of dimensions")
functions = {"sphere":sphere}
parser.add_argument("-f", "--func", metavar="NAME", choices=functions, default="sphere",
help="Objective function")
parser.add_argument("-i", "--iter", metavar="NB", default=1000, type=int,
help="Maximum number of iterations")
parser.add_argument("-t", "--target", metavar="VAL", default=1e-3, type=float,
help="Function value target delta")
parser.add_argument("-s", "--seed", metavar="VAL", default=0, type=int,
help="Random pseudo-generator seed (0 for epoch)")
asked = parser.parse_args()
np.random.seed(asked.seed)
history = []
val,sol = greedy(functions[asked.func], asked.dim, asked.iter, asked.target, square, 0.03, history)
fig = plt.figure()
ax = fig.gca(projection='3d')
shape = (20,20)
plot.surface(ax, shape, sphere)
plot.path(ax, shape, history)
plt.show()

70
sho/basics.py Normal file
View file

@ -0,0 +1,70 @@
import numpy as np
def sphere(x,offset=0.5):
"""Computes the square of a multi-dimensional vector x."""
f = 0
for i in range(len(x)):
f += (x[i]-offset)**2
return f
def onemax(x):
"""Sum the given bitstring."""
s = 0
for i in x:
s += i
return s
def numerical_random(d):
"""Draw a random multi-dimensional vector in [0,1]**d"""
return np.random.random(d)
def bitstring_random(d):
"""Draw a random bistring of size d, with P(1)=0.5."""
return [int(round(i)) for i in np.random.random(d)]
def search(objective_function, dimension, iterations, generator, history=None):
"""Search the given objective_function of the given dimension,
during the given number of iterations, generating random solution
with the given generator.
Returns the best value of the function and the best solution."""
best_val = float("inf")
best_sol = None
for i in range(iterations):
sol = generator(dimension)
val = objective_function(sol)
if val < best_val:
best_val = val
best_sol = sol
if history is not None:
history.append((val,sol))
return best_val, best_sol
if __name__=="__main__":
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import plot
print("Random search over 10-OneMax")
print("After 10 iterations:")
val,sol = search(onemax, 10, 10, bitstring_random)
print("\t",val,sol)
print("After 1000 iterations:")
val,sol = search(onemax, 10, 1000, bitstring_random)
print("\t",val,sol)
print("Random search over 2-Sphere")
print("After 10 iterations:")
val,sol = search(sphere, 2, 10, numerical_random)
print("\t",val,sol)
print("After 50 iterations:")
history = []
val,sol = search(sphere, 2, 50, numerical_random, history)
print("\t",val,sol)
fig = plt.figure()
ax = fig.gca(projection='3d')
shape = (20,20)
plot.surface(ax, shape, sphere)
plot.path(ax, shape, history)
plt.show()

35
sho/plot.py Normal file
View file

@ -0,0 +1,35 @@
import numpy as np
from matplotlib import cm
import itertools
def surface(ax, shape, f):
Z = np.zeros( shape )
for y in range(shape[0]):
for x in range(shape[1]):
Z[y][x] = f( (x/shape[0],y/shape[1]), 0.5 )
X = np.arange(0,shape[0],1)
Y = np.arange(0,shape[1],1)
X,Y = np.meshgrid(X,Y)
ax.plot_surface(X, Y, Z, cmap=cm.viridis)
def path(ax, shape, history):
def pairwise(iterable):
a, b = itertools.tee(iterable)
next(b, None)
return zip(a, b)
k=0
for i,j in pairwise(range(len(history)-1)):
xi = history[i][1][0]*shape[0]
yi = history[i][1][1]*shape[1]
zi = history[i][0]
xj = history[j][1][0]*shape[0]
yj = history[j][1][1]*shape[1]
zj = history[j][0]
x = [xi, xj]
y = [yi, yj]
z = [zi, zj]
ax.plot(x,y,z, color=cm.RdYlBu(k))
k+=1

38
sho/snp.py Normal file
View file

@ -0,0 +1,38 @@
import matplotlib.pyplot as plt
import numpy as np
def x(p):
return p[0]
def y(p):
return p[1]
def distance(a,b):
return np.sqrt( (x(a)-x(b))**2 + (y(a)-y(b))**2 )
def count(domain_shape, sensors_positions, radius, output_domain = None):
s = 0
Y,X = domain_shape
for y in range(Y):
for x in range(X):
p = (x,y)
t = 0
for sensor in sensors_positions:
if distance( p, sensor ) < radius:
t += 1
# break
if output_domain is not None:
output_domain[y][x] = t
s += t
return s
if __name__=="__main__":
domain = np.zeros( (100,100) )
sensors = np.round(np.random.random( (3,2) ) * 100)
s = count(domain.shape, sensors, 40, domain)
plt.imshow(domain)
plt.show()