예제 #1
0
def worst_case_dynamic_attack(filepath, comp_filename, load_file_name, start_range, contingency_range, blackout_criterion, system_name, budget):
    from compiler.ast import flatten    
#    import greedy_hueristics_dynamic_attack_support
    import dynamic_outage_at_specific_stages_v2_testing
    import maptest_updated_outage_list_dynamic_attack_with_order_v1_testing
    import maptest_testing
    import time
    total_dynamic_ordering_exe_start_time = time.time();
    dynamic_initial_outage_temp = [];
    static_greedy_worst_case_outage = [];
    static_greedy_worst_case_load_loss = [];
    temp_dynamic_outage = [];
    temp_dynamic_outage_vec = [];
    temp_worst_dynamic_outage = [];
    temp_worst_dynamic_outage_vec = [];
    stage_vector = [1,2,3];
    static_greedy_worst_case_load_loss = 0;
#    static_greedy_worst_case_outage, static_greedy_worst_case_load_loss = greedy_hueristics_dynamic_attack_support.greedy_hueristics(filepath, comp_filename, load_file_name, start_range, contingency_range, blackout_criterion, system_name, budget);
    static_greedy_worst_case_outage = maptest_testing.maptest14bus_test_system(comp_filename, start_range, contingency_range);   
    static_greedy_worst_case_outage =  list(flatten(static_greedy_worst_case_outage)); 
#    static_greedy_worst_case_outage = ['Line.tl2122', 'Line.tl67', 'Line.tl2629'];
#    static_greedy_worst_case_load_loss = 70.74;
    worst_case_max_load_loss = static_greedy_worst_case_load_loss;
    temp_worst_dynamic_outage = static_greedy_worst_case_outage;
    for item in static_greedy_worst_case_outage:
        temp_worst_dynamic_outage_vec.append(0);
    for t in range(0, len(static_greedy_worst_case_outage)):
        print '================================================================================================='
        print 'ORDER NUMER %d FROM SELECTION' %t;
        dynamic_initial_outage_temp = [];
        dynamic_initial_outage_stage_vec = [0];
        temp_dynamic_initial_outage_stage_vec = dynamic_initial_outage_stage_vec;
        dynamic_initial_outage_temp.append(static_greedy_worst_case_outage[t]);
    #    print static_greedy_worst_case_load_loss
        for k in range(0, (budget-1)):
            dynamic_new_outage_list = maptest_updated_outage_list_dynamic_attack_with_order_v1_testing.maptest14bus_test_system(static_greedy_worst_case_outage, dynamic_initial_outage_temp);
    #        print dynamic_new_outage_list
            dynamic_temp_max_load_loss, temp_dynamic_outage, temp_dynamic_outage_vec = dynamic_outage_at_specific_stages_v2_testing.DSS_Python_Interface1(filepath, load_file_name, blackout_criterion, system_name, dynamic_new_outage_list, temp_dynamic_initial_outage_stage_vec,stage_vector);   
            dynamic_initial_outage_temp = temp_dynamic_outage;
            temp_dynamic_initial_outage_stage_vec = temp_dynamic_outage_vec;
    #        print dynamic_temp_max_load_loss
    #        print temp_dynamic_outage
    #        print temp_dynamic_outage_vec
            if (dynamic_temp_max_load_loss >= worst_case_max_load_loss):
                worst_case_max_load_loss = dynamic_temp_max_load_loss;
                temp_worst_dynamic_outage = temp_dynamic_outage;
                temp_worst_dynamic_outage_vec = temp_dynamic_outage_vec; 
        print '================================================================================================='
    total_dynamic_ordering_exe_end_time = time.time();
    total_dynamic_ordering_exe_time = (total_dynamic_ordering_exe_end_time - total_dynamic_ordering_exe_start_time);
    print '================================================================================================='
    print 'Worst Case Load Loss (in percent): %f' %worst_case_max_load_loss
    print 'Worst Case Outage: %s' %temp_worst_dynamic_outage
    print 'Worst Case Outage Vector (representing attacks at individual stages): %s' %temp_worst_dynamic_outage_vec
    print 'Total Execution Time in Seconds: %s' %total_dynamic_ordering_exe_time
    print '================================================================================================='
예제 #2
0
def greedy_hueristics(filepath, comp_filename, load_file_name, start_range,
                      contingency_range, blackout_criterion, system_name,
                      p_budget, s_budget, sub_name, protected_substation):
    import time
    import maptest_testing
    import maptest_testing_subs
    import static_attack_subs_support
    #    import maptest_testing_trimmed
    import trimmed_list
    tot_exe_time_start = time.time()
    temp_max_loadloss = 0
    worst_case_outage = []
    worst_case_sub = []
    loadloss_gain = 0
    for sub_budget in range(0, s_budget):
        if (worst_case_sub == []):
            subs_config_dict = maptest_testing.maptest14bus_test_system(
                comp_filename, start_range, contingency_range, sub_name,
                protected_substation)
        else:
            subs_config_dict = trimmed_list.maptest14bus_test_system(
                comp_filename, start_range, contingency_range, worst_case_sub,
                sub_name, protected_substation)
        subs_config_dict_keys = subs_config_dict.keys()
        for i in range(0, len(subs_config_dict)):
            #            print subs_config_dict_keys[i];
            temp_comp_list = subs_config_dict[subs_config_dict_keys[i]]
            #            print temp_comp_list
            temp_subs_elements = maptest_testing_subs.maptest14bus_test_system(
                temp_comp_list, start_range, contingency_range)
            max_load_loss_outage, max_loadloss = static_attack_subs_support.greedy_hueristics(
                filepath, temp_subs_elements, load_file_name, start_range,
                contingency_range, blackout_criterion, system_name, p_budget)
            if (max_loadloss > temp_max_loadloss):
                temp_max_loadloss = max_loadloss
                worst_case_outage = max_load_loss_outage
                worst_case_sub = subs_config_dict_keys[i]
                if sub_budget == 0:
                    worst_case_sub = tuple([worst_case_sub])
                else:
                    worst_case_sub = worst_case_sub
#            print worst_case_sub;
        if ((loadloss_gain - temp_max_loadloss) == 0):
            break
        else:
            loadloss_gain = temp_max_loadloss
    tot_exe_time_end = time.time()
    tot_exe_time = (tot_exe_time_end - tot_exe_time_start)
    print '@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@'
    print 'Worst case outage: %s' % worst_case_outage
    print 'Worst case loadloss: %s' % temp_max_loadloss
    print 'Worst case substation: {0}'.format(worst_case_sub)
    print 'Total execution time in seconds: %s' % tot_exe_time
    print '@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@'
    return worst_case_outage, temp_max_loadloss, worst_case_sub
def greedy_hueristics(filepath, comp_filename, load_file_name, start_range,
                      contingency_range, blackout_criterion, system_name,
                      p_budget):
    import cascade_algorithm
    import maptest_new_outage_list
    import cascade_algorithm_reduced_outages
    import time
    import maptest_testing
    import maptest_testing_subs
    import static_attack_subs_support
    #    tot_exe_time_start = time.time()
    temp_max_loadloss = 0
    worst_case_outage = []
    worst_case_sub = []
    budget = 0
    #    max_loadloss = 0;
    subs_config_dict = maptest_testing.maptest14bus_test_system(
        comp_filename, start_range, contingency_range)
    #    print subs_config_dict
    #    print len(subs_config_dict)
    #    temp_comp_list = subs_config_dict['S9']
    #    print temp_comp_list
    #    temp_subs_elements = maptest_testing_subs.maptest14bus_test_system(temp_comp_list, start_range, contingency_range);
    #    print temp_subs_elements
    subs_config_dict_keys = subs_config_dict.keys()
    for i in range(0, len(subs_config_dict)):
        print subs_config_dict_keys[i]
        temp_comp_list = subs_config_dict[subs_config_dict_keys[i]]
        print temp_comp_list
        #        if (len(temp_comp_list) <= p_budget):
        #            budget = len(temp_comp_list);
        #        else:
        #            budget = p_budget;
        temp_subs_elements = maptest_testing_subs.maptest14bus_test_system(
            temp_comp_list, start_range, contingency_range)
        max_load_loss_outage, max_loadloss = static_attack_subs_support.greedy_hueristics(
            filepath, temp_subs_elements, load_file_name, start_range,
            contingency_range, blackout_criterion, system_name, p_budget)
        if (max_loadloss > temp_max_loadloss):
            temp_max_loadloss = max_loadloss
            worst_case_outage = max_load_loss_outage
            worst_case_sub = subs_config_dict_keys[i]
    print '@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@'
    print 'Worst case outage: %s' % worst_case_outage
    print 'Worst case loadloss: %s' % temp_max_loadloss
    print 'Worst case substation: %s' % worst_case_sub
    #    print 'Total execution time in seconds: %s' %tot_exe_time
    print '@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@'
def maptest14bus_test_system(comp_filename, max_load_loss_contingency, start_range, contingency_range):
    import maptest_testing
    from compiler.ast import flatten    
# To generate all possible combinations itertools is needed
    CMB = [];
    CMB_new = [];
    temp_valueset = [];
    new_valueset = []
    valueset_new = []
    iter_max_load_loss_outage = [];
    valueset = maptest_testing.maptest14bus_test_system(comp_filename, start_range, contingency_range);
    valueset_new = list(flatten(valueset))
#    valueset_new = initial_static_worst_case_list;
#    valueset_new = list(flatten(valueset))
    iter_max_load_loss_outage.append(list(max_load_loss_contingency));
#    iter_max_load_loss_outage = [['Line.tl12', 'Line.tl1011']]
#    print iter_max_load_loss_outage
    max_load_loss_outage = iter_max_load_loss_outage
    max_load_loss_outage = list(flatten(max_load_loss_outage))
#    print len(iter_max_load_loss_outage)
#    print len(valueset[0])
#    print max_load_loss_outage[0]
#    print len(max_load_loss_outage)
    for elem in range(0, len(max_load_loss_outage)):
#        print max_load_loss_outage[elem]
        valueset_new.remove(max_load_loss_outage[elem])
    new_valueset = [valueset_new[i:i+1] for i in range(0, len(valueset_new), 1)]    
    for i in range(0, len(new_valueset)):
        temp_valueset = new_valueset[i];
#        print temp_valueset
        temp_iter_max_load_loss_outage = iter_max_load_loss_outage[0];
#        print temp_iter_max_load_loss_outage
        iter_temp_comb = temp_iter_max_load_loss_outage + temp_valueset;
#        print iter_temp_comb
        CMB.append(iter_temp_comb)
    CMB_new.append(CMB)
#    print CMB_new
    return CMB_new
def DSS_Python_Interface1(filepath, comp_filename, load_file_name, start_range, contingency_range, blackout_criterion, system_name):
    
# complete path of the dss file
# range of n-k contingency
# blackout_criterion in numbers
# name of topology for generated xml
    
# Setting up the com interface and the necessary files    
    import win32com.client
    import maptest_testing
    import load_maptest14bus1
    import numpy as np
    from xml.dom import minidom
#    import matplotlib.pyplot as plt
#    from compiler.ast import flatten
    import time
# ----------------- Instantiate the OpenDSS Object -------------------------
    total_execution_time_start = time.time()
    DSSObj = win32com.client.Dispatch("OpenDSSEngine.DSS");
    
# ----------------- Start the solver -----------------------------
    DSSStart = DSSObj.Start("0");
    if DSSStart:
        print("OpenDSS Engine started successfully")
    else:
        print("Unable to start the OpenDSS Engine")
        
# Set up the Text, Circuit, and Solution Interfaces
    DSSText = DSSObj.Text;
    DSSCircuit = DSSObj.ActiveCircuit;
    DSSSolution = DSSCircuit.Solution;
    
# Loading the circuit Using the Text Interface
    DSSText.Command = "clear";
    DSSText.Command = "Compile " + filepath;
    print("File compiled successfully")

# -------------------------------- Getting the contingency range -------------------------------
    contingencies = maptest_testing.maptest14bus_test_system(comp_filename, start_range, contingency_range);
#    contingencies = [[['Line.tl611','Line.tl1617','Line.tl414']]]
    num_n_minus_k_contingencies = len(contingencies);
#    Z_values_final = list(flatten(Z_values))
#    Median= 'Median:' + str(Median_Z);

# ----------------------- Lists and variable initialization ------------------------
    LC = [];
    load_c = [];
    load_loss = [];
    final_load_loss_list = [];
    iLines = DSSCircuit.FirstPDElement();
    curr_Line_Name = [];
    Line_Names = [];
    load_Names = [];
    normal_line_curr_values = [];
    maxcurline_limit1 = [];
    curr_Line_Current = [];
    Line_Currents = [];
    Total_line_loss_counter = 0;
    blackout_counter = 0;
    max_load_loss = 0;
    selected_outage = [];
    selected_outage_new = [];
#    blackout_list = [];
    
# Getting current values of each line and setting up the maximum threshold
    while(iLines > 0):
        line_curr_values = [];
        maxcurline_limit = [];
        curr_Line_Name = DSSCircuit.ActiveCktElement.Name;
        Line_Names.append(curr_Line_Name);
        curr_Line_Current = DSSCircuit.ActiveCktElement.CurrentsMagAng;
        LC = np.array(curr_Line_Current);
        Line_Currents.append(curr_Line_Current);
        for i in range(0,3):
            line_curr_values.append((LC[6+(2*i)]));
            maxcurline_limit.append((LC[6+(2*i)]*10/7));
        normal_line_curr_values.append(tuple(line_curr_values));
        maxcurline_limit1.append(tuple(maxcurline_limit));
        iLines = DSSCircuit.NextPDElement();
    #print "Line_Currents: %s" %normal_line_curr_values
    #print "Maximum line current limit: %s" %maxcurline_limit1
# --------------code for xml generation---------------------------- 
    root = minidom.Document();
    root_element = root.createElement('Contingencies');
    root.appendChild(root_element);
    xml_str = root.toprettyxml(indent="\t");
    data_path = system_name;
# -----------------------------------------------------------------        
# Getting all the contingencies and loop through it
    for i in range(0, num_n_minus_k_contingencies):

# --------------code for xml generation----------------------------         
        mykcontingency = root.createElement('N-' + str(i+1) );
# -----------------------------------------------------------------         
        contingency = contingencies[i];
        size_of_contingency = len(contingency);
#        size_of_contingency = 1
# ------------------ Disconnecting individual line(s) from the subset ------------------
        for j in range(0, size_of_contingency):
            perct_load_loss = 0;
            initial_loss = [];
            stagecounter = 0;
            prev_stage_counter = 0;
            print "OUTAGE SELECTION NUMBER: %s" %(j+1)
            print "------------------------------------------------------------------------------------------------------"
            print "Calling Solver"
            Total_line_loss_counter = len(contingency[j]);
#            contingency[j] = ['Line.tl49','Line.tl85']
#     --------------code for xml generation----------------------------------           
            my_path = root.createElement('Path');
            my_initial_outage = root.createElement('Initial_Stage');
            my_path.appendChild(my_initial_outage);
#     -----------------------------------------------------------------------
# ------------ Getting the initial outages and appending it to the list --------------            
            for k in range(0, len(contingency[j])):
#                DSSCircuit.CktElements(contingency[j][k]).Open(1,0);
#                DSSCircuit.CktElements(contingency[j][k]).Open(2,0);
                DSSText.Command = "Open " + contingency[j][k] + " 1"
                DSSText.Command = "Open " + contingency[j][k] + " 2"
                initial_loss.append(contingency[j][k]);

#     --------------code for xml generation----------------------------------                 
                my_outage = root.createElement('Outage');
                my_initial_outage.appendChild(my_outage);
                my_outage_text = root.createTextNode(str(contingency[j][k]));
                my_outage.appendChild(my_outage_text);
#     -----------------------------------------------------------------------                
            print "Initial outage: %s" %initial_loss
# Solving the circuit and updating line current values after initial outages
            DSSSolution.Solve();
            iLines = DSSCircuit.FirstPDElement();
            normal_line_curr_values = [];
            while(iLines > 0):
                line_curr_values = [];
                curr_Line_Name = DSSCircuit.ActiveCktElement.Name;
                Line_Names.append(curr_Line_Name);
                curr_Line_Current = DSSCircuit.ActiveCktElement.CurrentsMagAng;
                LC = np.array(curr_Line_Current);
                Line_Currents.append(np.array(curr_Line_Current));
                for k in range(0,3):
                    line_curr_values.append((LC[6+(2*k)]));
                normal_line_curr_values.append(tuple(line_curr_values));
                iLines = DSSCircuit.NextPDElement();
            overloadExists=1;
#     --------------code for xml generation----------------------------------             
            my_cascading_outage = root.createElement('Cascading_Stage');
            final_stage_text = 'Safe';
#     -----------------------------------------------------------------------
#     -------------- Check for overloads and blackout criterion -------------
            while(overloadExists == 1):
                overloadExists = 0;
                stagecounter = stagecounter + 1;
                line_loss = [];
                load_loss = [];
                load_Names = [];
                size = len(normal_line_curr_values);
                for k in range(0,size):
# ---------------------Removing overloaded lines-------------------------------------
                    if (normal_line_curr_values[k][1] >= maxcurline_limit1[k][1]):
#                        DSSCircuit.CktElements(Line_Names[k]).Open(1,0);
#                        DSSCircuit.CktElements(Line_Names[k]).Open(2,0);
                        DSSText.Command = "Open " + Line_Names[k] + " 1"
                        DSSText.Command = "Open " + Line_Names[k] + " 2"
                        line_loss.append(str(Line_Names[k]));
                        overloadExists = 1;
                        Total_line_loss_counter = Total_line_loss_counter + 1;
                line_loss_size = len(line_loss);
                if (line_loss_size != 0):
                    print "Stage {0}, Components Failed: {1} ".format(stagecounter, line_loss)
#     --------------code for xml generation-----------------------------------------                    
                    my_stage_num = root.createElement('Stage_Number');
                    my_stage_num_text = root.createTextNode(str(stagecounter));
                    my_stage_num.appendChild(my_stage_num_text);
                    for k in range(0, line_loss_size):
                        my_outage = root.createElement('Outage');
                        my_outage_text = root.createTextNode(line_loss[k]);
                        my_outage.appendChild(my_outage_text);
                        my_stage_num.appendChild(my_outage);
                    my_cascading_outage.appendChild(my_stage_num);
#     ------------------------------------------------------------------------------ 
# Solving the circuit and updating line currents after removal of overloaded lines
# to check for further overload                    
                DSSSolution.Solve();
                iLines = DSSCircuit.FirstPDElement();
                normal_line_curr_values = [];
                while(iLines > 0):
                    line_curr_values = [];
                    curr_Line_Name = DSSCircuit.ActiveCktElement.Name;
                    Line_Names.append(curr_Line_Name);
                    curr_Line_Current = DSSCircuit.ActiveCktElement.CurrentsMagAng;
                    LC = np.array(curr_Line_Current);
                    Line_Currents.append(np.array(curr_Line_Current));
                    for k in range(0,3):
                        line_curr_values.append((LC[6+(2*k)]));
                    normal_line_curr_values.append(tuple(line_curr_values));
                    iLines = DSSCircuit.NextPDElement();
#     ------------------------- Checking for load loss -----------------------                
                iLoads = DSSCircuit.FirstPCElement();
                load_curr_values = [];
                load_Names = [];
                load_loss = [];
                while(iLoads > 0):
                    load_i_values = [];
                    load_Name = DSSCircuit.ActiveCktElement.Name;
                    load_Names.append(load_Name);
                    load_current = DSSCircuit.ActiveCktElement.CurrentsMagAng;
                    load_c = np.array(load_current);
                    for k in range(0,3):
                        load_i_values.append((load_c[2*k]));
                    load_curr_values.append(tuple(load_i_values));
                    iLoads = DSSCircuit.NextPCElement();
                for k in range(0 , len(load_curr_values)):
                    if (load_curr_values[k][1] <= 1):
                        load_loss.append(load_Names[k]);
#    ---------------------------- Checking the blackout criterion ------------------------------------------------
                T_sys_load, amt_load_loss = load_maptest14bus1.load_maptest14bus(load_file_name, load_loss);
                perct_load_loss = (float(amt_load_loss)/float(T_sys_load))*100;
                if (( perct_load_loss >= blackout_criterion) and overloadExists==0):
#                if ((perct_load_loss = (float(amt_load_loss)/float(T_sys_load))*100) >= blackout_criterion):
#                    stagecounter = stagecounter + 1;
#                    blackout_list.append(contingency[j]);
                    prev_stage_counter = 1;
                    print '***********************************************************************'
                    print "%s percent of load has been lost" %perct_load_loss
#                    print "More than %s percent of the load has been lost" %blackout_criterion
                    print "System Blackout"
                    print "{0} MW load has been lost out of {1} MW total load".format(amt_load_loss, T_sys_load);
                    print '***********************************************************************'
#    ------------------------------------- text added for xml code -----------------------------------------------                    
                    final_stage_text = 'Blackout';
                    blackout_counter = blackout_counter + 1;
#                    break;
#            print load_Names
            if (prev_stage_counter != 1):
                print "%s percent of load has been lost" %perct_load_loss
            if (perct_load_loss > max_load_loss):
                max_load_loss = perct_load_loss;
                selected_outage = contingency[j];
#    --------------code for xml generation-----------------------------------------
            my_path.appendChild(my_cascading_outage);
            my_final_stage = root.createElement('Final_Stage');
            my_final_stage_text = root.createTextNode(final_stage_text);
            my_final_stage.appendChild(my_final_stage_text);
            my_path.appendChild(my_final_stage);
#    ------------------------------------------------------------------------------ 
            final_load_loss_list.append(perct_load_loss);
            print "Number of stages of failure = %s " %(stagecounter-1)
            print "Total number of components failed = %s " %Total_line_loss_counter
#    ----------------- Resetting the simulation back to normal -----------------------
            DSSText.Command = "Compile " + filepath;
#    ---------------------------- code for xml generation -------------------------------
            mykcontingency.appendChild(my_path);
        root_element.appendChild(mykcontingency);
        xml_str = root.toprettyxml(indent="\t");
#    with open(data_path, "w") as f:
#        f.write(xml_str);
    selected_outage_new.append(selected_outage)
    print '#######################################################################################################'
    print 'Maximum load loss causing outage: %s' %selected_outage
    print 'Maximum load loss causing outage: %s' %selected_outage_new
    print 'Maximum load loss (in percent): %s' %max_load_loss
    print '#######################################################################################################'
#    print "Number of Blackout cases = %d" %blackout_counter
    total_execution_time_end = time.time()
    total_execution_time = (total_execution_time_end - total_execution_time_start)
#    print 'Total execution time in seconds: %s' %total_execution_time
    return (selected_outage_new, max_load_loss) 
예제 #6
0
def greedy_hueristics(filepath, comp_filename, load_file_name, start_range, contingency_range, blackout_criterion, system_name, p_budget, s_budget):
# -----------------------------------------------------------------------------------------------------------------------------------
# Importing supporting methods
# -----------------------------------------------------------------------------------------------------------------------------------
    import time
    import maptest_testing
    import maptest_testing_subs
    import static_attack_subs_support
#    import maptest_testing_trimmed
    import trimmed_list
# -----------------------------------------------------------------------------------------------------------------------------------
# Initializing the method variables
# -----------------------------------------------------------------------------------------------------------------------------------
    tot_exe_time_start = time.time() # Starting the timer
    temp_max_loadloss = 0;
    worst_case_outage = [];
    worst_case_sub = [];
    loadloss_gain = 0;
# -----------------------------------------------------------------------------------------------------------------------------------
    for sub_budget in range(0, s_budget): # This loop runs for the value of s_budget and identifies the substations that maximizes the system damage
# -----------------------------------------------------------------------------------------------------------------------------------
# Attack Space generation
# ----------------------------------------------------------------------------------------------------------------------------------- 
        if (worst_case_sub == []):
            subs_config_dict = maptest_testing.maptest14bus_test_system(comp_filename, start_range, contingency_range);   			 # Depending upon the value of worst_case_sub, appropriate method is called. The inputs to both these methods maptest_testing,
        else:          																												 # trimmed_list are the comp_filename. Both of them returns a dictionary with substations as the keys and transmission lines 
            subs_config_dict = trimmed_list.maptest14bus_test_system(comp_filename, start_range, contingency_range, worst_case_sub); # associated with the respective protection assemblies as values which are then further used as attack points.
        subs_config_dict_keys = subs_config_dict.keys();
# -----------------------------------------------------------------------------------------------------------------------------------
# Finding the maximum load loss causing trasmission lines/protection assemblies
# -----------------------------------------------------------------------------------------------------------------------------------
        for i in range (0, len(subs_config_dict)):
            print subs_config_dict_keys[i];
            temp_comp_list = subs_config_dict[subs_config_dict_keys[i]]; # Identifies the transmission lines that are present in the respective substations
            print temp_comp_list
            temp_subs_elements = maptest_testing_subs.maptest14bus_test_system(temp_comp_list, start_range, contingency_range); # Converts temp_comp_list into the required input format for the static_attack_subs_support method using maptest_testing_subs
            max_load_loss_outage, max_loadloss = static_attack_subs_support.greedy_hueristics(filepath, temp_subs_elements, load_file_name, start_range, contingency_range, blackout_criterion, system_name, p_budget);  # Calls the method static_attack_subs_support for computing the worst case load loss caused by the transmission lines/protection assemblies 
# -----------------------------------------------------------------------------------------------------------------------------------
# Updating the solution																													
# -----------------------------------------------------------------------------------------------------------------------------------																									 # as per the budget constraints. The method returns the maximum load loss max_loadloss and corresponding transmission line max_load_loss_outage. 
            if (max_loadloss > temp_max_loadloss): # Checks if the current system damage is more than any previous damage
                temp_max_loadloss = max_loadloss;  # Updates load loss/damage
                worst_case_outage = max_load_loss_outage; # Updates transmission line
                worst_case_sub = subs_config_dict_keys[i]; # Updates Substations
                if sub_budget == 0:
                    worst_case_sub = tuple([worst_case_sub]);
                else:
                    worst_case_sub = worst_case_sub;
#            print worst_case_sub;
        if ((loadloss_gain - temp_max_loadloss) == 0): # Checks if there is a change in the solution for consecutive iterations. If not, the algorithm is terminated
            break;
        else:
            loadloss_gain = temp_max_loadloss; # Updates the change in damage
    tot_exe_time_end = time.time() # Stopping the timer
    tot_exe_time = (tot_exe_time_end - tot_exe_time_start) # Computes the actual run time of the algorithm
# -----------------------------------------------------------------------------------------------------------------------------------
# Prints the outputs on the console
# -----------------------------------------------------------------------------------------------------------------------------------
    print '@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@'
    print 'Worst case outage: %s' %worst_case_outage
    print 'Worst case loadloss: %s' %temp_max_loadloss
    print 'Worst case substation: {0}'.format(worst_case_sub)
    print 'Total execution time in seconds: %s' %tot_exe_time
    print '@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@'
def maptest14bus_test_system(comp_filename, start_range, contingency_range):
    import maptest_testing
    from compiler.ast import flatten
    # To generate all possible combinations itertools is needed
    #    import itertools
    #    a_list = [];
    #    a_list_2 = [];
    #    a_l = [];
    CMB = []
    CMB_new = []
    temp_valueset = []
    new_valueset = []
    valueset_new = []
    valueset = maptest_testing.maptest14bus_test_system(
        comp_filename, start_range, contingency_range)
    valueset_new = list(flatten(valueset))
    iter_max_load_loss_outage = [['Line.tl12', 'Line.tl1011']]
    print iter_max_load_loss_outage
    max_load_loss_outage = iter_max_load_loss_outage
    max_load_loss_outage = list(flatten(max_load_loss_outage))
    #    print len(iter_max_load_loss_outage)
    #    print len(valueset[0])
    #    print max_load_loss_outage[0]
    #    print len(max_load_loss_outage)
    for elem in range(0, len(max_load_loss_outage)):
        #        print max_load_loss_outage[elem]
        valueset_new.remove(max_load_loss_outage[elem])
#    print valueset_new
#    print len(valueset)
#    data_file = open(comp_filename, 'r');
#    line_data = data_file.readline();
#    valueset = eval(line_data);
#    data_file.close()
#    print len(valueset)
#    valueset = [['Line.tl23'], ['Line.tl1011'], ['Line.tl1213'], ['Line.tl25'], ['Line.tl34'], ['Line.tl24'], ['Line.tl47'], ['Line.tl15'], ['Line.tl914'], ['Line.tl49'], ['Line.tl612'], ['Line.tl1314'], ['Line.tl910'], ['Line.tl611'], ['Line.tl79'], ['Line.tl78'], ['Line.tl45'], ['Line.tl56'], ['Line.tl613']];
#    valueset = ['Line.tl1011', 'Line.tl1213', 'Line.tl25', 'Line.tl34', 'Line.tl24', 'Line.tl15', 'Line.tl914', 'Line.tl612', 'Line.tl1314', 'Line.tl910', 'Line.tl611', 'Line.tl79', 'Line.tl78', 'Line.tl45', 'Line.tl613'];
    new_valueset = [
        valueset_new[i:i + 1] for i in range(0, len(valueset_new), 1)
    ]
    print new_valueset
    #    print len(new_valueset)

    #    contingency_range = 1;
    #    valueset =[];
    #    transmission_line_impedance = [45,49,43,92,38,54];
    #    transmission_line_impedance = [12,40,57,35,35,35,44,57,54,39,74,17,42,21,34,8,28];
    # -------------- Open and read the text file and convert the content into a list ----------------
    #    data_file = open(comp_filename, 'r');
    #    line_data = data_file.readline();
    #    valueset = eval(line_data);
    #    data_file.close()
    #    print len(valueset)

    for i in range(0, len(new_valueset)):
        temp_valueset = new_valueset[i]
        #        print temp_valueset
        temp_iter_max_load_loss_outage = iter_max_load_loss_outage[0]
        #        print temp_iter_max_load_loss_outage
        iter_temp_comb = temp_valueset + temp_iter_max_load_loss_outage
        #        print iter_temp_comb
        CMB.append(iter_temp_comb)
    CMB_new.append(CMB)
    #    print CMB_new
    return CMB_new