generate_data_model_random.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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, sep, index):
  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. if index:
  51. line += " " + str(idx + 1)
  52. line += sep
  53. line += str(val)
  54. line += '\n'
  55. return line
  56. def get_min_max_value_interval(_filename, _interval, _choice, _metric):
  57. global min_value_interval, max_value_interval
  58. scenes = os.listdir(path)
  59. # remove min max file from scenes folder
  60. scenes = [s for s in scenes if min_max_filename not in s]
  61. # remove calibration mire from images
  62. scenes = [s for s in scenes if calibration_folder not in s]
  63. for id_scene, folder_scene in enumerate(scenes):
  64. # only take care of synthesis scenes
  65. if folder_scene in scenes_list:
  66. scene_path = os.path.join(path, folder_scene)
  67. zones_folder = []
  68. # create zones list
  69. for index in zones:
  70. index_str = str(index)
  71. if len(index_str) < 2:
  72. index_str = "0" + index_str
  73. zones_folder.append("zone"+index_str)
  74. # shuffle list of zones (=> randomly choose zones)
  75. random.shuffle(zones_folder)
  76. for id_zone, zone_folder in enumerate(zones_folder):
  77. zone_path = os.path.join(scene_path, zone_folder)
  78. data_filename = _metric + "_" + _choice + generic_output_file_svd
  79. data_file_path = os.path.join(zone_path, data_filename)
  80. # getting number of line and read randomly lines
  81. f = open(data_file_path)
  82. lines = f.readlines()
  83. counter = 0
  84. # check if user select current scene and zone to be part of training data set
  85. for line in lines:
  86. begin, end = _interval
  87. line_data = line.split(';')
  88. metrics = line_data[begin+1:end+1]
  89. metrics = [float(m) for m in metrics]
  90. min_value = min(metrics)
  91. max_value = max(metrics)
  92. if min_value < min_value_interval:
  93. min_value_interval = min_value
  94. if max_value > max_value_interval:
  95. max_value_interval = max_value
  96. counter += 1
  97. def generate_data_model(_filename, _interval, _choice, _metric, _scenes = scenes_list, _nb_zones = 4, _percent = 1, _norm = False, _sep=':', _index=True):
  98. output_train_filename = _filename + ".train"
  99. output_test_filename = _filename + ".test"
  100. if not '/' in output_train_filename:
  101. raise Exception("Please select filename with directory path to save data. Example : data/dataset")
  102. # create path if not exists
  103. if not os.path.exists(output_data_folder):
  104. os.makedirs(output_data_folder)
  105. train_file = open(output_train_filename, 'w')
  106. test_file = open(output_test_filename, 'w')
  107. scenes = os.listdir(path)
  108. # remove min max file from scenes folder
  109. scenes = [s for s in scenes if min_max_filename not in s]
  110. for id_scene, folder_scene in enumerate(scenes):
  111. # only take care of maxwell scenes
  112. if folder_scene in scenes_list:
  113. scene_path = os.path.join(path, folder_scene)
  114. zones_folder = []
  115. # create zones list
  116. for index in zones:
  117. index_str = str(index)
  118. if len(index_str) < 2:
  119. index_str = "0" + index_str
  120. zones_folder.append("zone"+index_str)
  121. # shuffle list of zones (=> randomly choose zones)
  122. random.shuffle(zones_folder)
  123. path_seuil = os.path.join(zone_path, seuil_expe_filename)
  124. for id_zone, zone_folder in enumerate(zones_folder):
  125. zone_path = os.path.join(scene_path, zone_folder)
  126. data_filename = _metric + "_" + _choice + generic_output_file_svd
  127. data_file_path = os.path.join(zone_path, data_filename)
  128. # getting number of line and read randomly lines
  129. f = open(data_file_path)
  130. lines = f.readlines()
  131. num_lines = len(lines)
  132. lines_indexes = np.arange(num_lines)
  133. random.shuffle(lines_indexes)
  134. counter = 0
  135. # check if user select current scene and zone to be part of training data set
  136. for index in lines_indexes:
  137. line = construct_new_line(path_seuil, _interval, lines[index], _norm, _sep, _index)
  138. percent = counter / num_lines
  139. if id_zone < _nb_zones and folder_scene in _scenes and percent <= _percent:
  140. train_file.write(line)
  141. else:
  142. test_file.write(line)
  143. counter += 1
  144. f.close()
  145. train_file.close()
  146. test_file.close()
  147. def main():
  148. p_custom = False
  149. if len(sys.argv) <= 1:
  150. print('Run with default parameters...')
  151. 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 --sep : --rowindex 1 --custom min_max_filename')
  152. sys.exit(2)
  153. try:
  154. opts, args = getopt.getopt(sys.argv[1:], "ho:i:k:s:n:p:r:c", ["help=", "output=", "interval=", "kind=", "metric=","scenes=", "nb_zones=", "percent=", "sep=", "rowindex=", "custom="])
  155. except getopt.GetoptError:
  156. # print help information and exit:
  157. 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 --sep : --rowindex 1 --custom min_max_filename')
  158. sys.exit(2)
  159. for o, a in opts:
  160. if o == "-h":
  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 --sep : --rowindex 1 --custom min_max_filename')
  162. sys.exit()
  163. elif o in ("-o", "--output"):
  164. p_filename = a
  165. elif o in ("-i", "--interval"):
  166. p_interval = list(map(int, a.split(',')))
  167. elif o in ("-k", "--kind"):
  168. p_kind = a
  169. elif o in ("-m", "--metric"):
  170. p_metric = a
  171. elif o in ("-s", "--scenes"):
  172. p_scenes = a.split(',')
  173. elif o in ("-n", "--nb_zones"):
  174. p_nb_zones = int(a)
  175. elif o in ("-p", "--percent"):
  176. p_percent = float(a)
  177. elif o in ("-s", "--sep"):
  178. p_sep = a
  179. elif o in ("-r", "--rowindex"):
  180. if int(a) == 1:
  181. p_rowindex = True
  182. else:
  183. p_rowindex = False
  184. elif o in ("-c", "--custom"):
  185. p_custom = a
  186. else:
  187. assert False, "unhandled option"
  188. # getting scenes from indexes user selection
  189. scenes_selected = []
  190. for scene_id in p_scenes:
  191. index = scenes_indexes.index(scene_id.strip())
  192. scenes_selected.append(scenes_list[index])
  193. # find min max value if necessary to renormalize data
  194. if p_custom:
  195. get_min_max_value_interval(p_filename, p_interval, p_kind, p_metric)
  196. # write new file to save
  197. if not os.path.exists(custom_min_max_folder):
  198. os.makedirs(custom_min_max_folder)
  199. min_max_folder_path = os.path.join(os.path.dirname(__file__), custom_min_max_folder)
  200. min_max_filename_path = os.path.join(min_max_folder_path, p_custom)
  201. with open(min_max_filename_path, 'w') as f:
  202. f.write(str(min_value_interval) + '\n')
  203. f.write(str(max_value_interval) + '\n')
  204. # create database using img folder (generate first time only)
  205. generate_data_model(p_filename, p_interval, p_kind, p_metric, scenes_selected, p_nb_zones, p_percent, p_custom, p_sep, p_rowindex)
  206. if __name__== "__main__":
  207. main()