generate_data_model_random.py 10 KB

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