generate_data_model_random.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Fri Sep 14 21:02:42 2018
  5. @author: jbuisine
  6. """
  7. from __future__ import print_function
  8. import sys, os, getopt
  9. import numpy as np
  10. import random
  11. import time
  12. import json
  13. from PIL import Image
  14. from ipfml import processing, metrics
  15. from modules.utils import config as cfg
  16. # getting configuration information
  17. zone_folder = cfg.zone_folder
  18. min_max_filename = cfg.min_max_filename_extension
  19. # define all scenes values
  20. scenes_list = cfg.scenes_folders
  21. scenes_indexes = cfg.scenes_indices
  22. choices = cfg.normalization_choices
  23. path = cfg.dataset_path
  24. zones = cfg.zones_indices
  25. seuil_expe_filename = cfg.seuil_expe_filename
  26. metric_choices = cfg.metric_choices_labels
  27. output_data_folder = cfg.output_data_folder
  28. custom_min_max_folder = cfg.min_max_custom_folder
  29. min_max_ext = cfg.min_max_filename_extension
  30. calibration_folder = 'calibration'
  31. generic_output_file_svd = '_random.csv'
  32. min_value_interval = sys.maxsize
  33. max_value_interval = 0
  34. def construct_new_line(path_seuil, interval, line, norm):
  35. begin, end = interval
  36. line_data = line.split(';')
  37. seuil = line_data[0]
  38. metrics = line_data[begin+1:end+1]
  39. metrics = [float(m) for m in metrics]
  40. # TODO : check if it's always necessary to do that (loss of information for svd)
  41. if norm:
  42. metrics = processing.normalize_arr_with_range(metrics, min_value_interval, max_value_interval)
  43. with open(path_seuil, "r") as seuil_file:
  44. seuil_learned = int(seuil_file.readline().strip())
  45. if seuil_learned > int(seuil):
  46. line = '1'
  47. else:
  48. line = '0'
  49. for idx, val in enumerate(metrics):
  50. line += ';'
  51. line += str(val)
  52. line += '\n'
  53. return line
  54. def get_min_max_value_interval(_filename, _interval, _choice, _color, _metric):
  55. global min_value_interval, max_value_interval
  56. scenes = os.listdir(path)
  57. # remove min max file from scenes folder
  58. scenes = [s for s in scenes if min_max_filename not in s]
  59. # remove calibration mire from images
  60. scenes = [s for s in scenes if calibration_folder not in s]
  61. for id_scene, folder_scene in enumerate(scenes):
  62. # only take care of synthesis scenes
  63. if folder_scene in scenes_list:
  64. scene_path = os.path.join(path, folder_scene)
  65. zones_folder = []
  66. # create zones list
  67. for index in zones:
  68. index_str = str(index)
  69. if len(index_str) < 2:
  70. index_str = "0" + index_str
  71. zones_folder.append("zone"+index_str)
  72. # shuffle list of zones (=> randomly choose zones)
  73. random.shuffle(zones_folder)
  74. for id_zone, zone_folder in enumerate(zones_folder):
  75. zone_path = os.path.join(scene_path, zone_folder)
  76. if _color:
  77. data_filename = _metric + "_color_" + _choice + generic_output_file_svd
  78. else:
  79. data_filename = _metric + "_" + _choice + generic_output_file_svd
  80. data_file_path = os.path.join(zone_path, data_filename)
  81. # getting number of line and read randomly lines
  82. f = open(data_file_path)
  83. lines = f.readlines()
  84. counter = 0
  85. # check if user select current scene and zone to be part of training data set
  86. for line in lines:
  87. begin, end = _interval
  88. line_data = line.split(';')
  89. metrics = line_data[begin+1:end+1]
  90. metrics = [float(m) for m in metrics]
  91. min_value = min(metrics)
  92. max_value = max(metrics)
  93. if min_value < min_value_interval:
  94. min_value_interval = min_value
  95. if max_value > max_value_interval:
  96. max_value_interval = max_value
  97. counter += 1
  98. def generate_data_model(_filename, _interval, _choice, _metric, _scenes = scenes_list, _nb_zones = 4, _percent = 1, _color=False, _norm = False):
  99. output_train_filename = _filename + ".train"
  100. output_test_filename = _filename + ".test"
  101. if not '/' in output_train_filename:
  102. raise Exception("Please select filename with directory path to save data. Example : data/dataset")
  103. # create path if not exists
  104. if not os.path.exists(output_data_folder):
  105. os.makedirs(output_data_folder)
  106. train_file = open(output_train_filename, 'w')
  107. test_file = open(output_test_filename, 'w')
  108. scenes = os.listdir(path)
  109. # remove min max file from scenes folder
  110. scenes = [s for s in scenes if min_max_filename not in s]
  111. for id_scene, folder_scene in enumerate(scenes):
  112. # only take care of maxwell scenes
  113. if folder_scene in scenes_list:
  114. scene_path = os.path.join(path, folder_scene)
  115. zones_folder = []
  116. # create zones list
  117. for index in zones:
  118. index_str = str(index)
  119. if len(index_str) < 2:
  120. index_str = "0" + index_str
  121. zones_folder.append("zone"+index_str)
  122. # shuffle list of zones (=> randomly choose zones)
  123. random.shuffle(zones_folder)
  124. path_seuil = os.path.join(scene_path, seuil_expe_filename)
  125. for id_zone, zone_folder in enumerate(zones_folder):
  126. zone_path = os.path.join(scene_path, zone_folder)
  127. if _color:
  128. data_filename = _metric + "_color_" + _choice + generic_output_file_svd
  129. else:
  130. data_filename = _metric + "_" + _choice + generic_output_file_svd
  131. data_file_path = os.path.join(zone_path, data_filename)
  132. # getting number of line and read randomly lines
  133. f = open(data_file_path)
  134. lines = f.readlines()
  135. num_lines = len(lines)
  136. lines_indexes = np.arange(num_lines)
  137. random.shuffle(lines_indexes)
  138. counter = 0
  139. # check if user select current scene and zone to be part of training data set
  140. for index in lines_indexes:
  141. line = construct_new_line(path_seuil, _interval, lines[index], _norm)
  142. percent = counter / num_lines
  143. if id_zone < _nb_zones and folder_scene in _scenes and percent <= _percent:
  144. train_file.write(line)
  145. else:
  146. test_file.write(line)
  147. counter += 1
  148. f.close()
  149. train_file.close()
  150. test_file.close()
  151. def main():
  152. p_custom = False
  153. if len(sys.argv) <= 1:
  154. print('Run with default parameters...')
  155. print('python generate_data_model_random.py --output xxxx --interval 0,20 --kind svdne --metric lab --scenes "A, B, D" --nb_zones 5 --percent 0.7 --color 0 --custom min_max_filename')
  156. sys.exit(2)
  157. try:
  158. opts, args = getopt.getopt(sys.argv[1:], "ho:i:k:s:n:p:r:c:c", ["help=", "output=", "interval=", "kind=", "metric=","scenes=", "nb_zones=", "percent=", "color=", "custom="])
  159. except getopt.GetoptError:
  160. # print help information and exit:
  161. print('python generate_data_model_random.py --output xxxx --interval 0,20 --kind svdne --metric lab --scenes "A, B, D" --nb_zones 5 --percent 0.7 --color 0 --custom min_max_filename')
  162. sys.exit(2)
  163. for o, a in opts:
  164. if o == "-h":
  165. print('python generate_data_model_random.py --output xxxx --interval 0,20 --kind svdne --metric lab --scenes "A, B, D" --nb_zones 5 --percent 0.7 --color 0 --custom min_max_filename')
  166. sys.exit()
  167. elif o in ("-o", "--output"):
  168. p_filename = a
  169. elif o in ("-i", "--interval"):
  170. p_interval = list(map(int, a.split(',')))
  171. elif o in ("-k", "--kind"):
  172. p_kind = a
  173. elif o in ("-m", "--metric"):
  174. p_metric = a
  175. elif o in ("-s", "--scenes"):
  176. p_scenes = a.split(',')
  177. elif o in ("-n", "--nb_zones"):
  178. p_nb_zones = int(a)
  179. elif o in ("-p", "--percent"):
  180. p_percent = float(a)
  181. elif o in ("-c", "--color"):
  182. p_color = int(a)
  183. elif o in ("-c", "--custom"):
  184. p_custom = a
  185. else:
  186. assert False, "unhandled option"
  187. # getting scenes from indexes user selection
  188. scenes_selected = []
  189. for scene_id in p_scenes:
  190. index = scenes_indexes.index(scene_id.strip())
  191. scenes_selected.append(scenes_list[index])
  192. # find min max value if necessary to renormalize data
  193. if p_custom:
  194. get_min_max_value_interval(p_filename, p_interval, p_kind, p_color, p_metric)
  195. # write new file to save
  196. if not os.path.exists(custom_min_max_folder):
  197. os.makedirs(custom_min_max_folder)
  198. min_max_folder_path = os.path.join(os.path.dirname(__file__), custom_min_max_folder)
  199. min_max_filename_path = os.path.join(min_max_folder_path, p_custom)
  200. with open(min_max_filename_path, 'w') as f:
  201. f.write(str(min_value_interval) + '\n')
  202. f.write(str(max_value_interval) + '\n')
  203. # create database using img folder (generate first time only)
  204. generate_data_model(p_filename, p_interval, p_kind, p_metric, scenes_selected, p_nb_zones, p_percent, p_color, p_custom)
  205. if __name__== "__main__":
  206. main()