generate_data_model_random_center.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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, argparse
  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, utils
  15. from modules.utils import config as cfg
  16. from modules.utils import data as dt
  17. # getting configuration information
  18. config_filename = cfg.config_filename
  19. learned_folder = cfg.learned_zones_folder
  20. min_max_filename = cfg.min_max_filename_extension
  21. # define all scenes values
  22. all_scenes_list = cfg.scenes_names
  23. all_scenes_indices = cfg.scenes_indices
  24. normalization_choices = cfg.normalization_choices
  25. path = cfg.dataset_path
  26. zones = cfg.zones_indices
  27. seuil_expe_filename = cfg.seuil_expe_filename
  28. renderer_choices = cfg.renderer_choices
  29. metric_choices = cfg.metric_choices_labels
  30. output_data_folder = cfg.output_data_folder
  31. custom_min_max_folder = cfg.min_max_custom_folder
  32. min_max_ext = cfg.min_max_filename_extension
  33. generic_output_file_svd = '_random.csv'
  34. min_value_interval = sys.maxsize
  35. max_value_interval = 0
  36. abs_gap_data = 150
  37. def construct_new_line(seuil_learned, interval, line, choice, each, norm):
  38. begin, end = interval
  39. line_data = line.split(';')
  40. seuil = line_data[0]
  41. metrics = line_data[begin+1:end+1]
  42. # keep only if modulo result is 0 (keep only each wanted values)
  43. metrics = [float(m) for id, m in enumerate(metrics) if id % each == 0]
  44. # TODO : check if it's always necessary to do that (loss of information for svd)
  45. if norm:
  46. if choice == 'svdne':
  47. metrics = utils.normalize_arr_with_range(metrics, min_value_interval, max_value_interval)
  48. if choice == 'svdn':
  49. metrics = utils.normalize_arr(metrics)
  50. if seuil_learned > int(seuil):
  51. line = '1'
  52. else:
  53. line = '0'
  54. for idx, val in enumerate(metrics):
  55. line += ';'
  56. line += str(val)
  57. line += '\n'
  58. return line
  59. def get_min_max_value_interval(_scenes_list, _interval, _metric):
  60. global min_value_interval, max_value_interval
  61. scenes = os.listdir(path)
  62. # remove min max file from scenes folder
  63. scenes = [s for s in scenes if min_max_filename not in s]
  64. for id_scene, folder_scene in enumerate(scenes):
  65. # only take care of maxwell scenes
  66. if folder_scene in _scenes_list:
  67. scene_path = os.path.join(path, folder_scene)
  68. zones_folder = []
  69. # create zones list
  70. for index in zones:
  71. index_str = str(index)
  72. if len(index_str) < 2:
  73. index_str = "0" + index_str
  74. zones_folder.append("zone"+index_str)
  75. for id_zone, zone_folder in enumerate(zones_folder):
  76. zone_path = os.path.join(scene_path, zone_folder)
  77. # if custom normalization choices then we use svd values not already normalized
  78. data_filename = _metric + "_svd"+ 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. # check if user select current scene and zone to be part of training data set
  84. for line in lines:
  85. begin, end = _interval
  86. line_data = line.split(';')
  87. metrics = line_data[begin+1:end+1]
  88. metrics = [float(m) for m in metrics]
  89. min_value = min(metrics)
  90. max_value = max(metrics)
  91. if min_value < min_value_interval:
  92. min_value_interval = min_value
  93. if max_value > max_value_interval:
  94. max_value_interval = max_value
  95. def generate_data_model(_scenes_list, _filename, _interval, _choice, _metric, _scenes, _nb_zones = 4, _percent = 1, _random=0, _step=1, _each=1, _custom = False):
  96. output_train_filename = _filename + ".train"
  97. output_test_filename = _filename + ".test"
  98. if not '/' in output_train_filename:
  99. raise Exception("Please select filename with directory path to save data. Example : data/dataset")
  100. # create path if not exists
  101. if not os.path.exists(output_data_folder):
  102. os.makedirs(output_data_folder)
  103. train_file_data = []
  104. test_file_data = []
  105. for id_scene, folder_scene in enumerate(_scenes_list):
  106. scene_path = os.path.join(path, folder_scene)
  107. zones_indices = zones
  108. # shuffle list of zones (=> randomly choose zones)
  109. # only in random mode
  110. if _random:
  111. random.shuffle(zones_indices)
  112. # store zones learned
  113. learned_zones_indices = zones_indices[:_nb_zones]
  114. # write into file
  115. folder_learned_path = os.path.join(learned_folder, _filename.split('/')[1])
  116. if not os.path.exists(folder_learned_path):
  117. os.makedirs(folder_learned_path)
  118. file_learned_path = os.path.join(folder_learned_path, folder_scene + '.csv')
  119. with open(file_learned_path, 'w') as f:
  120. for i in learned_zones_indices:
  121. f.write(str(i) + ';')
  122. for id_zone, index_folder in enumerate(zones_indices):
  123. index_str = str(index_folder)
  124. if len(index_str) < 2:
  125. index_str = "0" + index_str
  126. current_zone_folder = "zone" + index_str
  127. zone_path = os.path.join(scene_path, current_zone_folder)
  128. # if custom normalization choices then we use svd values not already normalized
  129. if _custom:
  130. data_filename = _metric + "_svd"+ generic_output_file_svd
  131. else:
  132. data_filename = _metric + "_" + _choice + generic_output_file_svd
  133. data_file_path = os.path.join(zone_path, data_filename)
  134. # getting number of line and read randomly lines
  135. f = open(data_file_path)
  136. lines = f.readlines()
  137. num_lines = len(lines)
  138. # randomly shuffle image
  139. if _random:
  140. random.shuffle(lines)
  141. path_seuil = os.path.join(zone_path, seuil_expe_filename)
  142. with open(path_seuil, "r") as seuil_file:
  143. seuil_learned = int(seuil_file.readline().strip())
  144. counter = 0
  145. # check if user select current scene and zone to be part of training data set
  146. for data in lines:
  147. percent = counter / num_lines
  148. image_index = int(data.split(';')[0])
  149. if image_index % _step == 0:
  150. with open(path_seuil, "r") as seuil_file:
  151. seuil_learned = int(seuil_file.readline().strip())
  152. gap_threshold = abs(seuil_learned - image_index)
  153. # only keep data near to threshold of zone image
  154. if gap_threshold <= abs_gap_data:
  155. line = construct_new_line(seuil_learned, _interval, data, _choice, _each, _custom)
  156. if id_zone < _nb_zones and folder_scene in _scenes and percent <= _percent:
  157. train_file_data.append(line)
  158. else:
  159. test_file_data.append(line)
  160. counter += 1
  161. f.close()
  162. train_file = open(output_train_filename, 'w')
  163. test_file = open(output_test_filename, 'w')
  164. for line in train_file_data:
  165. train_file.write(line)
  166. for line in test_file_data:
  167. test_file.write(line)
  168. train_file.close()
  169. test_file.close()
  170. def main():
  171. # getting all params
  172. parser = argparse.ArgumentParser(description="Generate data for model using correlation matrix information from data")
  173. parser.add_argument('--output', type=str, help='output file name desired (.train and .test)')
  174. parser.add_argument('--interval', type=str, help='Interval value to keep from svd', default='"0, 200"')
  175. parser.add_argument('--kind', type=str, help='Kind of normalization level wished', choices=normalization_choices)
  176. parser.add_argument('--metric', type=str, help='Metric data choice', choices=metric_choices)
  177. parser.add_argument('--scenes', type=str, help='List of scenes to use for training data')
  178. parser.add_argument('--nb_zones', type=int, help='Number of zones to use for training data set')
  179. parser.add_argument('--random', type=int, help='Data will be randomly filled or not', choices=[0, 1])
  180. parser.add_argument('--percent', type=float, help='Percent of data use for train and test dataset (by default 1)')
  181. parser.add_argument('--step', type=int, help='Photo step to keep for build datasets', default=1)
  182. parser.add_argument('--each', type=int, help='Each features to keep from interval', default=1)
  183. parser.add_argument('--renderer', type=str, help='Renderer choice in order to limit scenes used', choices=renderer_choices, default='all')
  184. parser.add_argument('--custom', type=str, help='Name of custom min max file if use of renormalization of data', default=False)
  185. args = parser.parse_args()
  186. p_filename = args.output
  187. p_interval = list(map(int, args.interval.split(',')))
  188. p_kind = args.kind
  189. p_metric = args.metric
  190. p_scenes = args.scenes.split(',')
  191. p_nb_zones = args.nb_zones
  192. p_random = args.random
  193. p_percent = args.percent
  194. p_step = args.step
  195. p_each = args.each
  196. p_renderer = args.renderer
  197. p_custom = args.custom
  198. # list all possibles choices of renderer
  199. scenes_list = dt.get_renderer_scenes_names(p_renderer)
  200. scenes_indices = dt.get_renderer_scenes_indices(p_renderer)
  201. # getting scenes from indexes user selection
  202. scenes_selected = []
  203. for scene_id in p_scenes:
  204. index = scenes_indices.index(scene_id.strip())
  205. scenes_selected.append(scenes_list[index])
  206. # find min max value if necessary to renormalize data
  207. if p_custom:
  208. get_min_max_value_interval(scenes_list, p_interval, p_metric)
  209. # write new file to save
  210. if not os.path.exists(custom_min_max_folder):
  211. os.makedirs(custom_min_max_folder)
  212. min_max_folder_path = os.path.join(os.path.dirname(__file__), custom_min_max_folder)
  213. min_max_filename_path = os.path.join(min_max_folder_path, p_custom)
  214. with open(min_max_filename_path, 'w') as f:
  215. f.write(str(min_value_interval) + '\n')
  216. f.write(str(max_value_interval) + '\n')
  217. # create database using img folder (generate first time only)
  218. generate_data_model(scenes_list, p_filename, p_interval, p_kind, p_metric, scenes_selected, p_nb_zones, p_percent, p_random, p_step, p_each, p_custom)
  219. if __name__== "__main__":
  220. main()