Parcourir la source

Only run maxwell scenes

Jerome Buisine il y a 5 ans
Parent
commit
65e987c73e

+ 3 - 2
generateAndTrain_maxwell.sh

@@ -42,8 +42,9 @@ for nb_zones in {6,8,10,12,16}; do
                 echo $FILENAME
                 python generate_data_model_random.py --output ${FILENAME} --interval "${start},${end}" --kind ${mode} --metric ${metric} --scenes "${scenes}" --nb_zones "${nb_zones}" --percent 1 --sep ';' --rowindex '0'
                 python models/${model}_train.py --data ${FILENAME}.train --output ${MODEL_NAME}
-                python predict_seuil_expe.py --interval "${start}, ${end}" --model "./saved_models/${MODEL_NAME}.joblib" --mode "${mode}" --metric ${metric} --limit_detection '2'
-                python save_model_result_in_md.py --interval "${start}, ${end}" --model "./saved_models/${MODEL_NAME}.joblib" --mode "${mode}"
+                echo predict_seuil_expe_maxwell.py --interval "${start},${end}" --model "./saved_models/${MODEL_NAME}.joblib" --mode "${mode}" --metric ${metric} --limit_detection '2'
+                python predict_seuil_expe_maxwell.py --interval "${start},${end}" --model "./saved_models/${MODEL_NAME}.joblib" --mode "${mode}" --metric ${metric} --limit_detection '2'
+                python save_model_result_in_md_maxwell.py --interval "${start},${end}" --model "./saved_models/${MODEL_NAME}.joblib" --mode "${mode}" --metric ${metric}
             done
         done
     done

+ 3 - 3
models/ensemble_model_train.py

@@ -37,17 +37,17 @@ def main():
 
     if len(sys.argv) <= 1:
         print('Run with default parameters...')
-        print('python smv_model_train.py --data xxxx --output xxxx')
+        print('python ensemble_model_train.py --data xxxx --output xxxx')
         sys.exit(2)
     try:
         opts, args = getopt.getopt(sys.argv[1:], "hd:o", ["help=", "data=", "output="])
     except getopt.GetoptError:
         # print help information and exit:
-        print('python smv_model_train.py --data xxxx --output xxxx')
+        print('python ensemble_model_train.py --data xxxx --output xxxx')
         sys.exit(2)
     for o, a in opts:
         if o == "-h":
-            print('python smv_model_train.py --data xxxx --output xxxx')
+            print('python ensemble_model_train.py --data xxxx --output xxxx')
             sys.exit()
         elif o in ("-d", "--data"):
             p_data_file = a

+ 3 - 3
models/ensemble_model_train_v2.py

@@ -39,17 +39,17 @@ def main():
 
     if len(sys.argv) <= 1:
         print('Run with default parameters...')
-        print('python smv_model_train.py --data xxxx --output xxxx')
+        print('python ensemble_model_train_v2.py --data xxxx --output xxxx')
         sys.exit(2)
     try:
         opts, args = getopt.getopt(sys.argv[1:], "hd:o", ["help=", "data=", "output="])
     except getopt.GetoptError:
         # print help information and exit:
-        print('python smv_model_train.py --data xxxx --output xxxx')
+        print('python ensemble_model_train_v2.py --data xxxx --output xxxx')
         sys.exit(2)
     for o, a in opts:
         if o == "-h":
-            print('python smv_model_train.py --data xxxx --output xxxx')
+            print('python ensemble_model_train_v2.py --data xxxx --output xxxx')
             sys.exit()
         elif o in ("-d", "--data"):
             p_data_file = a

+ 11 - 5
predict_seuil_expe.py

@@ -64,8 +64,12 @@ def main():
     for id_scene, folder_scene in enumerate(scenes):
     
         print(folder_scene)
-        scene_path = scenes_path + "/" + folder_scene
-        with open(scene_path + "/" + config_filename, "r") as config_file:
+
+        scene_path = os.path.join(scenes_path, folder_scene)
+
+        config_path = os.path.join(scene_path, config_filename)
+
+        with open(config_path, "r") as config_file:
             last_image_name = config_file.readline().strip()
             prefix_image_name = config_file.readline().strip()
             start_index_image = config_file.readline().strip()
@@ -84,6 +88,8 @@ def main():
                 index_str = "0" + index_str
             zone_folder = "zone"+index_str
 
+            os.path.join(os.path.join(scene_path, zone_folder), threshold_expe_filename)
+
             with open(scene_path + "/" + zone_folder + "/" + threshold_expe_filename) as f:
                 threshold = int(f.readline())
                 threshold_expes.append(threshold)
@@ -106,7 +112,7 @@ def main():
             while len(start_index_image) > len(current_counter_index_str):
                 current_counter_index_str = "0" + current_counter_index_str
 
-            img_path = scene_path + "/" + prefix_image_name + current_counter_index_str + ".png"
+            img_path = os.path.join(scene_path, prefix_image_name + current_counter_index_str + ".png")
 
             current_img = Image.open(img_path)
             img_blocks = image_processing.divide_in_blocks(current_img, (200, 200))
@@ -155,14 +161,14 @@ def main():
         # end of scene => display of results
 
         # construct path using model name for saving threshold map folder
-        model_treshold_path = threshold_map_folder + '/' + p_model_file.split('/')[-1]
+        model_treshold_path = os.path.join(threshold_map_folder, p_model_file.split('/')[-1])
         
         if not os.path.exists(model_treshold_path):
             os.makedirs(model_treshold_path)
 
         abs_dist = []
 
-        map_filename = model_treshold_path + "/" + threshold_map_file_prefix + folder_scene
+        map_filename = os.path.join(model_treshold_path, threshold_map_file_prefix + folder_scene)
         f_map = open(map_filename, 'w')
 
         line_information = ""

+ 221 - 0
predict_seuil_expe_maxwell.py

@@ -0,0 +1,221 @@
+from sklearn.externals import joblib
+
+import numpy as np
+
+from ipfml import image_processing
+from PIL import Image
+
+import sys, os, getopt
+import subprocess
+import time
+
+current_dirpath = os.getcwd()
+
+config_filename   = "config"
+scenes_path = './fichiersSVD_light'
+min_max_filename = '_min_max_values'
+threshold_expe_filename = 'seuilExpe'
+tmp_filename = '/tmp/__model__img_to_predict.png'
+
+maxwell_scenes = ['Appart1opt02', 'Cuisine01', 'SdbCentre', 'SdbDroite']
+
+threshold_map_folder = "threshold_map"
+threshold_map_file_prefix = "treshold_map_"
+
+zones = np.arange(16)
+
+def main():
+
+    if len(sys.argv) <= 1:
+        print('Run with default parameters...')
+        print('python predict_seuil_expe_maxwell.py --interval "0,20" --model path/to/xxxx.joblib --mode svdn --metric lab --limit_detection xx')
+        sys.exit(2)
+    try:
+        opts, args = getopt.getopt(sys.argv[1:], "ht:m:o:l", ["help=", "interval=", "model=", "mode=", "metric=", "limit_detection="])
+    except getopt.GetoptError:
+        # print help information and exit:
+        print('python predict_seuil_expe_maxwell.py --interval "xx,xx" --model path/to/xxxx.joblib --mode svdn --metric lab --limit_detection xx')
+        sys.exit(2)
+    for o, a in opts:
+        if o == "-h":
+            print('python predict_seuil_expe_maxwell.py --interval "xx,xx" --model path/to/xxxx.joblib --mode svdn --metric lab --limit_detection xx')
+            sys.exit()
+        elif o in ("-t", "--interval"):
+            p_interval = a
+        elif o in ("-m", "--model"):
+            p_model_file = a
+        elif o in ("-o", "--mode"):
+            p_mode = a
+
+            if p_mode != 'svdn' and p_mode != 'svdne' and p_mode != 'svd':
+                assert False, "Mode not recognized"
+    
+        elif o in ("-m", "--metric"):
+            p_metric = a
+        elif o in ("-l", "--limit_detection"):
+            p_limit = int(a)
+        else:
+            assert False, "unhandled option"
+
+    scenes = os.listdir(scenes_path)
+    
+    if min_max_filename in scenes:
+        scenes.remove(min_max_filename)
+
+    # go ahead each scenes
+    for id_scene, folder_scene in enumerate(scenes):
+    
+        # only take in consideration maxwell scenes
+        if folder_scene in maxwell_scenes:
+    
+            print(folder_scene)
+
+            scene_path = os.path.join(scenes_path, folder_scene)
+
+            config_path = os.path.join(scene_path, config_filename)
+
+            with open(config_path, "r") as config_file:
+                last_image_name = config_file.readline().strip()
+                prefix_image_name = config_file.readline().strip()
+                start_index_image = config_file.readline().strip()
+                end_index_image = config_file.readline().strip()
+                step_counter = int(config_file.readline().strip())
+
+            threshold_expes = []
+            threshold_expes_detected = []
+            threshold_expes_counter = []
+            threshold_expes_found = []
+
+            # get zones list info
+            for index in zones:
+                index_str = str(index)
+                if len(index_str) < 2:
+                    index_str = "0" + index_str
+                zone_folder = "zone"+index_str
+
+                os.path.join(os.path.join(scene_path, zone_folder), threshold_expe_filename)
+
+                with open(scene_path + "/" + zone_folder + "/" + threshold_expe_filename) as f:
+                    threshold = int(f.readline())
+                    threshold_expes.append(threshold)
+
+                    # Initialize default data to get detected model threshold found
+                    threshold_expes_detected.append(False)
+                    threshold_expes_counter.append(0)
+                    threshold_expes_found.append(int(end_index_image)) # by default use max
+
+            current_counter_index = int(start_index_image)
+            end_counter_index = int(end_index_image)
+
+            print(current_counter_index)
+            check_all_done = False
+
+            while(current_counter_index <= end_counter_index and not check_all_done):
+                
+                current_counter_index_str = str(current_counter_index)
+
+                while len(start_index_image) > len(current_counter_index_str):
+                    current_counter_index_str = "0" + current_counter_index_str
+
+                img_path = os.path.join(scene_path, prefix_image_name + current_counter_index_str + ".png")
+
+                current_img = Image.open(img_path)
+                img_blocks = image_processing.divide_in_blocks(current_img, (200, 200))
+
+
+                check_all_done = all(d == True for d in threshold_expes_detected)
+
+                for id_block, block in enumerate(img_blocks):
+                    
+                    # check only if necessary for this scene (not already detected)
+                    if not threshold_expes_detected[id_block]:
+                        tmp_file_path = tmp_filename.replace('__model__',  p_model_file.split('/')[-1].replace('.joblib', '_'))
+                        block.save(tmp_file_path)
+
+                        python_cmd = "python predict_noisy_image_svd_" + p_metric + ".py --image " + tmp_file_path + \
+                                        " --interval '" + p_interval + \
+                                        "' --model " + p_model_file  + \
+                                        " --mode " + p_mode
+
+                        ## call command ##
+                        p = subprocess.Popen(python_cmd, stdout=subprocess.PIPE, shell=True)
+                        
+                        (output, err) = p.communicate()
+                        
+                        ## Wait for result ##
+                        p_status = p.wait()
+
+                        prediction = int(output)
+
+                        if prediction == 0:
+                            threshold_expes_counter[id_block] = threshold_expes_counter[id_block] + 1
+                        else:
+                            threshold_expes_counter[id_block] = 0
+                        
+                        if threshold_expes_counter[id_block] == p_limit:
+                            threshold_expes_detected[id_block] = True
+                            threshold_expes_found[id_block] = current_counter_index
+
+                        print(str(id_block) + " : " + str(current_counter_index) + "/" + str(threshold_expes[id_block]) + " => " + str(prediction))
+
+                current_counter_index += step_counter
+                print("------------------------")
+                print("Scene " + str(id_scene + 1) + "/" + str(len(scenes)))
+                print("------------------------")
+
+            # end of scene => display of results
+
+            # construct path using model name for saving threshold map folder
+            model_treshold_path = os.path.join(threshold_map_folder, p_model_file.split('/')[-1])
+            
+            if not os.path.exists(model_treshold_path):
+                os.makedirs(model_treshold_path)
+
+            abs_dist = []
+
+            map_filename = os.path.join(model_treshold_path, threshold_map_file_prefix + folder_scene)
+            f_map = open(map_filename, 'w')
+
+            line_information = ""
+
+            # default header
+            f_map.write('|  |    |    |  |\n')
+            f_map.write('---|----|----|---\n')
+            for id, threshold in enumerate(threshold_expes_found):
+
+                line_information += str(threshold) + " / " + str(threshold_expes[id]) + " | "
+                abs_dist.append(abs(threshold - threshold_expes[id]))
+
+                if (id + 1) % 4 == 0:
+                    f_map.write(line_information + '\n')
+                    line_information = ""
+            
+            f_map.write(line_information + '\n')
+
+            min_abs_dist = min(abs_dist)
+            max_abs_dist = max(abs_dist)
+            avg_abs_dist = sum(abs_dist) / len(abs_dist)
+
+            f_map.write('\nScene information : ')
+            f_map.write('\n- BEGIN : ' + str(start_index_image))
+            f_map.write('\n- END : ' + str(end_index_image))
+
+            f_map.write('\n\nDistances information : ')
+            f_map.write('\n- MIN : ' + str(min_abs_dist))
+            f_map.write('\n- MAX : ' + str(max_abs_dist))
+            f_map.write('\n- AVG : ' + str(avg_abs_dist))
+
+            f_map.write('\n\nOther information : ')
+            f_map.write('\n- Detection limit : ' + str(p_limit))
+
+            # by default print last line
+            f_map.close()
+
+            print("Scene " + str(id_scene + 1) + "/" + str(len(scenes)) + " Done..")
+            print("------------------------")
+
+            time.sleep(10)
+
+
+if __name__== "__main__":
+    main()

+ 101 - 0
save_model_result_in_md_maxwell.py

@@ -0,0 +1,101 @@
+from sklearn.externals import joblib
+
+import numpy as np
+
+from ipfml import image_processing
+from PIL import Image
+
+import sys, os, getopt
+import subprocess
+import time
+
+current_dirpath = os.getcwd()
+
+threshold_map_folder = "threshold_map"
+threshold_map_file_prefix = "treshold_map_"
+
+markdowns_folder = "models_info"
+
+zones = np.arange(16)
+
+def main():
+
+    if len(sys.argv) <= 1:
+        print('Run with default parameters...')
+        print('python save_model_result_in_md.py --interval "0,20" --model path/to/xxxx.joblib --mode ["svd", "svdn", "svdne"] --metric ["lab", "mscn"]')
+        sys.exit(2)
+    try:
+        opts, args = getopt.getopt(sys.argv[1:], "ht:m:o:l", ["help=", "interval=", "model=", "mode=", "metric="])
+    except getopt.GetoptError:
+        # print help information and exit:
+        print('python save_model_result_in_md.py --interval "xx,xx" --model path/to/xxxx.joblib --mode ["svd", "svdn", "svdne"] --metric ["lab", "mscn"]')
+        sys.exit(2)
+    for o, a in opts:
+        if o == "-h":
+            print('python save_model_result_in_md.py --interval "xx,xx" --model path/to/xxxx.joblib --mode ["svd", "svdn", "svdne"] --metric ["lab", "mscn"]')
+            sys.exit()
+        elif o in ("-t", "--interval"):
+            p_interval = list(map(int, a.split(',')))
+        elif o in ("-m", "--model"):
+            p_model_file = a
+        elif o in ("-o", "--mode"):
+            p_mode = a
+
+            if p_mode != 'svdn' and p_mode != 'svdne' and p_mode != 'svd':
+                assert False, "Mode not recognized"
+        elif o in ("-c", "--metric"):
+            p_metric = a
+        else:
+            assert False, "unhandled option"
+
+    
+    # call model and get global result in scenes
+
+    begin, end = p_interval
+
+    bash_cmd = "bash testModelByScene_maxwell.sh '" + str(begin) + "' '" + str(end) + "' '" + p_model_file + "' '" + p_mode + "' '" + p_metric + "'" 
+    print(bash_cmd)
+     
+    ## call command ##
+    p = subprocess.Popen(bash_cmd, stdout=subprocess.PIPE, shell=True)
+    
+    (output, err) = p.communicate()
+    
+    ## Wait for result ##
+    p_status = p.wait()
+
+    if not os.path.exists(markdowns_folder):
+        os.makedirs(markdowns_folder)
+        
+    # get model name to construct model
+    md_model_path = os.path.join(markdowns_folder, p_model_file.split('/')[-1].replace('.joblib', '.md'))
+
+    with open(md_model_path, 'w') as f:
+        f.write(output.decode("utf-8"))
+
+        # read each threshold_map information if exists
+        model_map_info_path = os.path.join(threshold_map_folder, p_model_file.replace('saved_models/', ''))
+
+        if not os.path.exists(model_map_info_path):
+            f.write('\n\n No threshold map information')
+        else:
+            maps_files = os.listdir(model_map_info_path)
+
+            # get all map information
+            for t_map_file in maps_files:
+                
+                file_path = os.path.join(model_map_info_path, t_map_file)
+                with open(file_path, 'r') as map_file:
+
+                    title_scene =  t_map_file.replace(threshold_map_file_prefix, '')
+                    f.write('\n\n## ' + title_scene + '\n')
+                    content = map_file.readlines()
+
+                    # getting each map line information
+                    for line in content:
+                        f.write(line)
+
+        f.close()
+
+if __name__== "__main__":
+    main()

+ 62 - 0
testModelByScene_maxwell.sh

@@ -0,0 +1,62 @@
+#! bin/bash
+
+if [ -z "$1" ]
+  then
+    echo "No first argument supplied"
+    echo "Need of begin vector index"
+    exit 1
+fi
+
+if [ -z "$2" ]
+  then
+    echo "No second argument supplied"
+    echo "Need of end vector index"
+    exit 1
+fi
+
+if [ -z "$3" ]
+  then
+    echo "No third argument supplied"
+    echo "Need of model input"
+    exit 1
+fi
+
+if [ -z "$4" ]
+  then
+    echo "No fourth argument supplied"
+    echo "Need of mode file : 'svd', 'svdn', svdne"
+    exit 1
+fi
+
+if [ -z "$5" ]
+  then
+    echo "No fifth argument supplied"
+    echo "Need of metric : 'lab', 'mscn'"
+    exit 1
+fi
+
+INPUT_BEGIN=$1
+INPUT_END=$2
+INPUT_MODEL=$3
+INPUT_MODE=$4
+INPUT_METRIC=$5
+
+zones="0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15"
+
+echo "**Model :** ${INPUT_MODEL}"
+echo "**Mode :** ${INPUT_MODE}"
+echo "**Vector range :** [${INPUT_BEGIN}, ${INPUT_END}]"
+echo ""
+echo " # | GLOBAL | NOISY | NOT NOISY"
+echo "---|--------|-------|----------"
+
+# only take maxwell scenes
+for scene in {"A","D","G","H"}; do
+
+  FILENAME="data/data_${INPUT_MODE}_${INPUT_METRIC}_B${INPUT_BEGIN}_E${INPUT_END}_scene${scene}"
+
+  python generate_data_model.py --output ${FILENAME} --interval "${INPUT_BEGIN},${INPUT_END}" --kind ${INPUT_MODE} --metric ${INPUT_METRIC} --scenes "${scene}" --zones "${zones}" --percent 1 --sep ";" --rowindex "0"
+
+  python prediction_scene.py --data "$FILENAME.train" --model ${INPUT_MODEL} --output "${INPUT_MODEL}_Scene${scene}_mode_${INPUT_MODE}_metric_${INPUT_METRIC}.prediction" --scene ${scene}
+
+done