Commit c9e3fb4a authored by Amelie Royer's avatar Amelie Royer

ls

parent f2adf891
from __future__ import print_function
#!/usr/bin/env python
# -*- coding: utf-8 -*-
......@@ -12,6 +13,10 @@ import sys
import argparse
import numpy as np
from shutil import rmtree
from utils import iteritems
if sys.version_info[0] == 3:
xrange = range
def isWall(i,j,direction):
"""
......@@ -34,7 +39,7 @@ def turnLeft(orient):
global left
return left[orient]
right = {v: k for (k, v) in left.iteritems()}
right = {v: k for (k, v) in iteritems(left)}
def turnRight(orient):
"""
Returns the orientation to the right of ``orient``.
......@@ -42,7 +47,6 @@ def turnRight(orient):
global right
return right[orient]
def mazeBoundaries(maze):
"""
Returns the reachable boundaries of the maze.
......@@ -91,23 +95,23 @@ if __name__ == "__main__":
# Hyperparameters
actions = ['F','L','R']
failures = [0.2, 0.1, 0.1] # Probability of staying still after action forward, left and right respectively.
wall_failure = args.wall_failure # Probability of being trapped when going forward towards a wall
wall_failure = args.wall_failure # Probability of being trapped when going forward towards a wall
goal_reward = 1.0
min_x, max_x, min_y, max_y = sys.maxint, 0, sys.maxint, 0
min_x, max_x, min_y, max_y = sys.maxsize, 0, sys.maxsize, 0
changeMap = {'N':[-1,0],'S':[1,0],'E':[0,1],'W':[0,-1]}
###### 1. Create mazes
print "\n\n\033[91m-----> Maze creation\033[0m"
print("\n\n\033[91m-----> Maze creation\033[0m")
mazes = []
# From file
# load from file
if args.fin is not None:
base_name = os.path.basename(args.fin).rsplit('.', 1)[0]
maze = []
with open(args.fin, 'r') as fIn:
for line in fIn.read().splitlines():
if not line.strip():
# Change env
print "\r Maze %d" % len(mazes),
# change env
print("\r Maze %d" % len(mazes), end=' ')
mazes.append(maze)
x1, x2, y1, y2 = mazeBoundaries(maze)
min_x = min(min_x, x1); max_x = max(max_x, x2);
......@@ -115,15 +119,15 @@ if __name__ == "__main__":
maze = []
else:
maze.append(line.split())
# Add last maze if not done
# add last maze (no empty last line)
if len(maze) > 1:
mazes.append(maze)
x1, x2, y1, y2 = mazeBoundaries(maze)
min_x = min(min_x, x1); max_x = max(max_x, x2);
min_y = min(min_y, y1); max_y = max(max_y, y2);
# OR generate mazes
# or generate mazes
else:
base_name = "gen_%dx%d_%d%d%d%d_%d" % (args.size, args.size, args.init, args.trap, args.goal, args.wall, args.env)
base_name = "gen_%d_%d_%d_%d_%d_%d" % (args.size, args.init, args.trap, args.goal, args.wall, args.env)
maze = np.pad(np.zeros((args.size - 1, args.size - 1), dtype=int) + 48, 1, 'constant', constant_values=49)
n_cases = (args.size - 1) * (args.size - 1)
n_choices = args.goal + args.init + args.trap + args.wall
......@@ -131,7 +135,7 @@ if __name__ == "__main__":
assert(n_choices <= n_cases)
# for each environment
for e in xrange(args.env):
print "\r Maze %d/%d" % (e + 1, args.env),
print("\r Maze %d/%d" % (e + 1, args.env), end=' ')
# choose cases
current = np.array(maze)
cases = np.random.choice(choices, n_choices, replace=False)
......@@ -140,11 +144,11 @@ if __name__ == "__main__":
c = cases[i]
current[c / (args.size - 1) + 1, c % (args.size - 1) + 1] = 60 if i < args.init else 120 if i < args.init + args.trap else 103 if i < args.init + args.trap + args.goal else 49
# append new environment
str_maze = [[str(unichr(x)) for x in line] for line in current]
str_maze = [[str(chr(x)) for x in line] for line in current]
mazes.append(str_maze)
x1, x2, y1, y2 = mazeBoundaries(str_maze)
min_x = min(min_x, x1); max_x = max(max_x, x2);
min_y = min(min_y, y1); max_y = max(max_y, y2);
min_x = min(min_x, x1); max_x = max(max_x, x2)
min_y = min(min_y, y1); max_y = max(max_y, y2)
# Check that mazes shape are consistent
aux = [(len(maze), len(maze[0])) for maze in mazes]
......@@ -158,21 +162,31 @@ if __name__ == "__main__":
os.makedirs(output_dir)
f_rewards = open(os.path.join(output_dir, "%s.rewards" % base_name), 'w')
f_transitions = open(os.path.join(output_dir, "%s.transitions" % base_name), 'w')
f_summary = open(os.path.join(output_dir, "%s.summary" % base_name), 'w')
f_summary.write("%d min x\n%d max x\n%d min y\n%d max y\n%d environments\n" % (min_x, max_x, min_y, max_y, len(mazes)))
f_summary.write("%d inits\n%d goals\n%d traps\n%d walls\n%.3f wall failure\n" % (args.init, args.goal, args.trap, args.wall, args.wall_failure))
f_summary.write("\nFailure rates for each environment:\n")
###### 1. Create transitions function
print "\n\n\033[91m-----> Transitions generation\033[0m"
# Store mazes if not loading from file
if args.fin is None:
with open(os.path.join(output_dir, "%s.mazes" % base_name), 'w') as f_mazes:
f_mazes.write('\n\n'.join('\n'.join(' '.join(line) for line in m) for m in mazes))
###### 2. Create transitions function
print("\n\n\033[91m-----> Transitions generation\033[0m")
# Parse each maze
from collections import Counter
for e, maze in enumerate(mazes):
print "\n > Maze %d/%d \n" % (e + 1, len(mazes)),
print("\n > Maze %d/%d \n" % (e + 1, len(mazes)), end=' ')
if args.rdf:
failures = np.random.rand(3) / 2. # uniformly random sampling in [0; 0.5)
print " sampled failures:", failures
failures = np.random.rand(3) / 2. # failure rates, sampled in [0; 0.5)
f_summary.write("%s\n" % (' '.join("%.3f" % x for x in failures)))
print(" sampled failures:", failures)
c = Counter([x for y in maze for x in y])
n_init = c['v'] + c['>'] + c['^'] + c['<']
for i in range(0, width):
for j in range(0, height):
print "\r state %d/%d" % (4 * (i * height + j + 1), 4 * width * height), #4 * = all orientations
print("\r state %d/%d" % (4 * (i * height + j + 1), 4 * width * height), end=' ')
element = maze[i][j]
# I.N.I.T
......@@ -181,7 +195,7 @@ if __name__ == "__main__":
for action in actions:
f_transitions.write("%s %s %s %f\n" % ('S', action, current_state, 1.0 / n_init))
# Other states
# other states
for orient in ['N','E','S','W']:
current_state = "%dx%dx%s" % (i, j, orient)
# T.R.A.P
......@@ -216,11 +230,9 @@ if __name__ == "__main__":
f_transitions.close()
f_rewards.close()
###### 3. Summary
f_summary = open(os.path.join(output_dir, "%s.summary" % base_name), 'w')
f_summary.write("%d min x\n%d max x\n%d min y\n%d max y\n%d environments" % (min_x, max_x, min_y, max_y, len(mazes)))
f_summary.close()
###### 3. End
print("\n\n\033[92m-----> End\033[0m")
print(" Output directory: %s" % output_dir)
# End
......@@ -15,8 +15,24 @@ try:
except ImportError:
from io import StringIO
# Python 2 - 3 compatibility
if sys.version_info[0] == 3:
xrange = range
try:
dict.iteritems
except AttributeError:
# Python 3
def itervalues(d):
return iter(d.values())
def iteritems(d):
return iter(d.items())
else:
# Python 2
def itervalues(d):
return d.itervalues()
def iteritems(d):
return d.iteritems()
class Logger:
"""
......@@ -93,6 +109,7 @@ def assign_customer_cluster(user, ulevel):
status = int(user[17] == 'M')
house = int(user[26] == 'Y')
ncars = int(user[27])
#return n_children_home
# Ulevel 0, distinguish on 5 age category and gender
if ulevel == 0:
return gender + 2 * age_category
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment