pythonfuzzyskfuzzy

How to prevents a AssertionError from stop Python code?


I want to do a system using a Autorules fuzzy controller where i create rules from process real data. My problem is when i use the new data to simulate the fuzzy controller with the rules extracted of the older data, i get a error about the crisp output that cannot be calculated because do not exist rules enough, what is totally normal because my fuzzy system needs more rules and that's my point! I want to implement a new routine that analyses the crisp input/output and create new rules from this data, after that, i want to go back in my code and simulate again.

Is there a function that blocks the AssertionError from stop the code and redirect to another def or to a previously code line?

I tried to find some lib with a function that allows me to redirect the error steady to stop the code but no sucess. I think i will have to change the skfuzzy defuzz def code to allow to make it.

Thank you very much.

''' python

step = stp_ini
k = 0
delay = stp_ini
end = stp_fim - stp_ini
Tout_sim = pd.DataFrame(columns=['val'])
Vent_sim = pd.DataFrame(columns=['val'])

start = timeit.default_timer()

for step in range(end-k):
    clear_output(wait=True)
    simulation.input['PCA1'] = comp1n[step+delay]
    simulation.input['PCA2'] = comp2n[step+delay]
    simulation.input['PCA3'] = comp3n[step+delay]
    simulation.input['PCA4'] = comp4n[step+delay]
    simulation.input['Vent'] = dataoutf.NumVentOn[step+delay]
    simulation.compute()
    Tout_sim = Tout_sim.append({'val':simulation.output['Tout']},ignore_index=True)

    stop = timeit.default_timer()
    if ((step/(stp_fim-k-1))*100) < 5:
        expected_time = "Calculating..."
    else:
        time_perc = timeit.default_timer()
        expected_time = np.round( ( (time_perc-start)/(step/(end-k-1)) )/60,2)

'''

~\AppData\Local\Continuum\anaconda3\lib\site-packages\skfuzzy\control\controlsystem.py in defuzz(self) 587 self.var.defuzzify_method) 588 except AssertionError: --> 589 raise ValueError("Crisp output cannot be calculated, likely " 590 "because the system is too sparse. Check to " 591 "make sure this set of input values will "

ValueError: Crisp output cannot be calculated, likely because the system is too sparse. Check to make sure this set of input values will activate at least one connected Term in each Antecedent via the current set of Rules.

edit: I try to wrap the line code ValueError by try but the ValueError is activated yet

def defuzz(self):
    """Derive crisp value based on membership of adjective(s)."""
    if not self.sim._array_inputs:
        ups_universe, output_mf, cut_mfs = self.find_memberships()

        if len(cut_mfs) == 0:
            raise ValueError("No terms have memberships.  Make sure you "
                             "have at least one rule connected to this "
                             "variable and have run the rules calculation.")

        try:
            return defuzz(ups_universe, output_mf,
                          self.var.defuzzify_method)
        except AssertionError:
            try:
                new_c1 = []
                new_c2 = []
                new_c3 = []
                new_c4 = []
                new_vent = []
                new_tout = []
                newcondition1 = []
                newcondition2 = []
                newcondition3 = []
                newcondition4 = []
                newcondition5 = []
                newcondition6 = []

                #input
                n = 0
                for n in range(len(namespca)):
                    new_c1.append(fuzz.interp_membership(PCA1.universe, PCA1[namespcapd.name.loc[n]].mf, comp1n[step]))
                    new_c2.append(fuzz.interp_membership(PCA2.universe, PCA2[namespcapd.name.loc[n]].mf, comp2n[step]))
                    new_c3.append(fuzz.interp_membership(PCA3.universe, PCA3[namespcapd.name.loc[n]].mf, comp3n[step]))
                    new_c4.append(fuzz.interp_membership(PCA4.universe, PCA4[namespcapd.name.loc[n]].mf, comp4n[step]))

                n = 0
                for n in range(len(namesvent)):    
                    new_vent.append(fuzz.interp_membership(Vent.universe, Vent[namesventpd.name.loc[n]].mf, dataoutf.NumVentOn[step]))

                #output
                n = 0
                for n in range(len(namestemp)):
                    new_tout.append(fuzz.interp_membership(Tout.universe, Tout[namestemppd.name.loc[n]].mf, dataoutf.TsaidaHT[step]))

                #new_c1 = np.transpose(new_c1)
                new_c1_conv = pd.DataFrame(new_c1)
                #new_c2 = np.transpose(new_c2)
                new_c2_conv = pd.DataFrame(new_c2)
                #new_c3 = np.transpose(new_c3)
                new_c3_conv = pd.DataFrame(new_c3)
                #new_c4 = np.transpose(new_c4)
                new_c4_conv = pd.DataFrame(new_c4)
                #new_vent = np.transpose(new_vent)
                new_vent_conv = pd.DataFrame(new_vent)
                #new_tout = np.transpose(new_tout)
                new_tout_conv = pd.DataFrame(new_tout)

                i=0
                for i in range(pcamf):
                    newcondition1.append([new_c1_conv.idxmax(axis=0) == i])
                    newcondition2.append([new_c2_conv.idxmax(axis=0) == i])
                    newcondition3.append([new_c3_conv.idxmax(axis=0) == i])
                    newcondition4.append([new_c4_conv.idxmax(axis=0) == i])

                i=0
                for i in range(ventmf):
                    newcondition5.append([new_vent_conv.idxmax(axis=0) == i])

                i=0
                for i in range(tempmf):
                    newcondition6.append([new_tout_conv.idxmax(axis=0) == i])

                choicelistpca = namespca
                choicelistvent = namesvent
                choicelisttout = namestemp

                new_c1_rules = np.select(newcondition1, choicelistpca)
                new_c2_rules = np.select(newcondition2, choicelistpca)
                new_c3_rules = np.select(newcondition3, choicelistpca)
                new_c4_rules = np.select(newcondition4, choicelistpca)
                new_vent_rules = np.select(newcondition5, choicelistvent)
                new_tout_rules = np.select(newcondition6, choicelisttout)

                new_rules = np.vstack([new_c1_rules,new_c2_rules,new_c3_rules,new_c4_rules,new_vent_rules,new_tout_rules])
                new_rules = new_rules.T

                new_rulespd = pd.DataFrame(new_rules,columns=['PCA1','PCA2','PCA3','PCA4','Vent','Tout'])

                #Checar se a nova regra está dentro do conjunto de regras fuzzy atual
                if pd.merge(new_rulespd,AutoRules, on=['PCA1','PCA2','PCA3','PCA4','Vent','Tout'],how='inner').empty:
                    print('Nova regra não encontrada no conjunto atual de regras fuzzy!')
                else:
                    pd.merge(new_rulespd,AutoRules, on=['PCA1','PCA2','PCA3','PCA4','Vent','Tout'],how='inner')

        """except AssertionError:
            raise ValueError("Crisp output cannot be calculated, likely "
                             "because the system is too sparse. Check to "
                             "make sure this set of input values will "
                             "activate at least one connected Term in each "
                             "Antecedent via the current set of Rules.")"""
    else:
        # Calculate using array-aware version, one cut at a time.
        output = np.zeros(self.sim._array_shape, dtype=np.float64)

        it = np.nditer(output, ['multi_index'], [['writeonly', 'allocate']])

        for out in it:
            universe, mf = self.find_memberships_nd(it.multi_index)
            out[...] = defuzz(universe, mf, self.var.defuzzify_method)

        return output

Solution

  • Wrap the line of code that raises ValueError in a try. And decide what to do in its except ValueError: clause. Perhaps continue-ing on to the next iteration might be reasonable.