generate_data_model.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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. config_filename = "config"
  14. zone_folder = "zone"
  15. min_max_filename = "_min_max_values"
  16. generic_output_file_svd = '_random.csv'
  17. output_data_folder = 'data'
  18. # define all scenes values
  19. scenes = ['Appart1opt02', 'Bureau1', 'Cendrier', 'Cuisine01', 'EchecsBas', 'PNDVuePlongeante', 'SdbCentre', 'SdbDroite', 'Selles']
  20. scenes_indexes = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
  21. choices = ['svd', 'svdn', 'svdne']
  22. path = './fichiersSVD_light'
  23. zones = np.arange(16)
  24. seuil_expe_filename = 'seuilExpe'
  25. def construct_new_line(path_seuil, interval, line, sep, index):
  26. begin, end = interval
  27. line_data = line.split(';')
  28. seuil = line_data[0]
  29. metrics = line_data[begin+1:end+1]
  30. with open(path_seuil, "r") as seuil_file:
  31. seuil_learned = int(seuil_file.readline().strip())
  32. if seuil_learned > int(seuil):
  33. line = '1'
  34. else:
  35. line = '0'
  36. for idx, val in enumerate(metrics):
  37. if index:
  38. line += " " + str(idx + 1)
  39. line += sep
  40. line += val
  41. line += '\n'
  42. return line
  43. def generate_data_model(_filename, _interval, _choice, _metric, _scenes = scenes, _zones = zones, _percent = 1, _sep=':', _index=True):
  44. output_train_filename = _filename + ".train"
  45. output_test_filename = _filename + ".test"
  46. if not '/' in output_train_filename:
  47. raise Exception("Please select filename with directory path to save data. Example : data/dataset")
  48. # create path if not exists
  49. if not os.path.exists(output_data_folder):
  50. os.makedirs(output_data_folder)
  51. train_file = open(output_train_filename, 'w')
  52. test_file = open(output_test_filename, 'w')
  53. scenes = os.listdir(path)
  54. # remove min max file from scenes folder
  55. scenes = [s for s in scenes if min_max_filename not in s]
  56. for id_scene, folder_scene in enumerate(scenes):
  57. scene_path = os.path.join(path, folder_scene)
  58. zones_folder = []
  59. # create zones list
  60. for index in zones:
  61. index_str = str(index)
  62. if len(index_str) < 2:
  63. index_str = "0" + index_str
  64. zones_folder.append("zone"+index_str)
  65. for id_zone, zone_folder in enumerate(zones_folder):
  66. zone_path = os.path.join(scene_path, zone_folder)
  67. data_filename = _metric + "_" + _choice + generic_output_file_svd
  68. data_file_path = os.path.join(zone_path, data_filename)
  69. # getting number of line and read randomly lines
  70. f = open(data_file_path)
  71. lines = f.readlines()
  72. num_lines = len(lines)
  73. lines_indexes = np.arange(num_lines)
  74. random.shuffle(lines_indexes)
  75. path_seuil = os.path.join(zone_path, seuil_expe_filename)
  76. counter = 0
  77. # check if user select current scene and zone to be part of training data set
  78. for index in lines_indexes:
  79. line = construct_new_line(path_seuil, _interval, lines[index], _sep, _index)
  80. percent = counter / num_lines
  81. if id_zone in _zones and folder_scene in _scenes and percent <= _percent:
  82. train_file.write(line)
  83. else:
  84. test_file.write(line)
  85. counter += 1
  86. f.close()
  87. train_file.close()
  88. test_file.close()
  89. def main():
  90. if len(sys.argv) <= 1:
  91. print('Run with default parameters...')
  92. print('python generate_data_model.py --output xxxx --interval 0,20 --kind svdne --metric lab --scenes "A, B, D" --zones "1, 2, 3" --percent 0.7 --sep ":" --rowindex "1"')
  93. sys.exit(2)
  94. try:
  95. opts, args = getopt.getopt(sys.argv[1:], "ho:i:k:s:z:p:r", ["help=", "output=", "interval=", "kind=", "metric=", "scenes=", "zones=", "percent=", "sep=", "rowindex="])
  96. except getopt.GetoptError:
  97. # print help information and exit:
  98. print('python generate_data_model.py --output xxxx --interval 0,20 --kind svdne --metric lab --scenes "A, B, D" --zones "1, 2, 3" --percent 0.7 --sep ":" --rowindex "1"')
  99. sys.exit(2)
  100. for o, a in opts:
  101. if o == "-h":
  102. print('python generate_data_model.py --output xxxx --interval 0,20 --kind svdne --metric lab --scenes "A, B, D" --zones "1, 2, 3" --percent 0.7 --sep ":" --rowindex "1"')
  103. sys.exit()
  104. elif o in ("-o", "--output"):
  105. p_filename = a
  106. elif o in ("-i", "--interval"):
  107. p_interval = list(map(int, a.split(',')))
  108. elif o in ("-k", "--kind"):
  109. p_kind = a
  110. elif o in ("-m", "--metric"):
  111. p_metric = a
  112. elif o in ("-s", "--scenes"):
  113. p_scenes = a.split(',')
  114. elif o in ("-z", "--zones"):
  115. if ',' in a:
  116. p_zones = list(map(int, a.split(',')))
  117. else:
  118. p_zones = [a.strip()]
  119. elif o in ("-p", "--percent"):
  120. p_percent = float(a)
  121. elif o in ("-s", "--sep"):
  122. p_sep = a
  123. elif o in ("-r", "--rowindex"):
  124. if int(a) == 1:
  125. p_rowindex = True
  126. else:
  127. p_rowindex = False
  128. else:
  129. assert False, "unhandled option"
  130. # getting scenes from indexes user selection
  131. scenes_selected = []
  132. for scene_id in p_scenes:
  133. index = scenes_indexes.index(scene_id.strip())
  134. scenes_selected.append(scenes[index])
  135. # create database using img folder (generate first time only)
  136. generate_data_model(p_filename, p_interval, p_kind, p_metric, scenes_selected, p_zones, p_percent, p_sep, p_rowindex)
  137. if __name__== "__main__":
  138. main()