Example #1
0
 def create_control_system(self):
     # create control system and simulation
     self.control_system = ctrl.ControlSystem(self.rulebase)
     self.simulation = ctrl.ControlSystemSimulation(self.control_system)
Example #2
0
def inicializaFuzzy():
    global autonomy

    #INPUTS
    MyoValue = ctrl.Antecedent(np.arange(40, 100, 0.005), 'MyoValue')
    JoyLinear = ctrl.Antecedent(np.arange(-1, 1, 0.005), 'JoyLinear')
    JoyAngular = ctrl.Antecedent(np.arange(-2, 2, 0.005), 'JoyTheta')
    WeldPos = ctrl.Antecedent(np.arange(-1, 1, 0.005), 'WeldPos')

    #OUTPUTS
    LoA = ctrl.Consequent(np.arange(1, 4, 1), 'LoA')

    #MEMBERSHIP FUNCTIONS
    #myo emg rms mean value
    MyoValue['Low'] = fuzz.trimf(MyoValue.universe, [40, 40, 60])
    MyoValue['Medium'] = fuzz.trimf(MyoValue.universe, [40, 60, 80])
    MyoValue['High'] = fuzz.trimf(MyoValue.universe, [80, 100, 100])

    #velocity linear - joystick
    JoyLinear['NegHigh'] = fuzz.trimf(JoyLinear.universe, [-1, -1, -0.5])
    JoyLinear['NegMedium'] = fuzz.trimf(JoyLinear.universe, [-1, -0.5, -0.1])
    JoyLinear['NegLow'] = fuzz.trimf(JoyLinear.universe, [-0.5, -0.1, 0])
    JoyLinear['Zero'] = fuzz.trimf(JoyLinear.universe, [-0.1, 0, 0.1])
    JoyLinear['PosLow'] = fuzz.trimf(JoyLinear.universe, [0, 0.1, 0.5])
    JoyLinear['PosMedium'] = fuzz.trimf(JoyLinear.universe, [0.1, 0.5, 1])
    JoyLinear['PosHigh'] = fuzz.trimf(JoyLinear.universe, [0.5, 1, 1])

    #velocity angular - joystick
    JoyAngular['LeftHigh'] = fuzz.trimf(JoyAngular.universe, [-2, -2, -1])
    JoyAngular['LeftMedium'] = fuzz.trimf(JoyAngular.universe, [-2, -1, -0.5])
    JoyAngular['LeftLow'] = fuzz.trimf(JoyAngular.universe, [-1, -0.5, 0])
    JoyAngular['Center'] = fuzz.trimf(JoyAngular.universe, [-0.5, 0, 0.5])
    JoyAngular['RightLow'] = fuzz.trimf(JoyAngular.universe, [0, 0.5, 1])
    JoyAngular['RightMedium'] = fuzz.trimf(JoyAngular.universe, [0.5, 1, 2])
    JoyAngular['RightHigh'] = fuzz.trimf(JoyAngular.universe, [1, 2, 2])

    #weld position
    WeldPos['LeftHigh'] = fuzz.trimf(WeldPos.universe, [-1, -1, -0.5])
    WeldPos['LeftMedium'] = fuzz.trimf(WeldPos.universe, [-1, -0.5, -0.1])
    WeldPos['LeftLow'] = fuzz.trimf(WeldPos.universe, [-0.5, -0.1, 0])
    WeldPos['Center'] = fuzz.trimf(WeldPos.universe, [-0.5, 0, 0.5])
    WeldPos['RightLow'] = fuzz.trimf(WeldPos.universe, [0, 0.1, 0.5])
    WeldPos['RightMedium'] = fuzz.trimf(WeldPos.universe, [0.1, 0.5, 1])
    WeldPos['RightHigh'] = fuzz.trimf(WeldPos.universe, [0.5, 1, 1])

    #Level of Autonomy - LoA
    LoA['Manual'] = fuzz.trimf(LoA.universe, [1, 1, 2])
    LoA['Shared'] = fuzz.trimf(LoA.universe, [1, 2, 3])
    LoA['Supervisory'] = fuzz.trimf(LoA.universe, [2, 3, 4])
    LoA['Autonomous'] = fuzz.trimf(LoA.universe, [3, 4, 4])

    #RULES

    rule9 = ctrl.Rule(JoyAngular['LeftHigh'] & WeldPos['LeftHigh'],
                      LoA['Manual'])
    rule10 = ctrl.Rule(JoyAngular['LeftHigh'] & WeldPos['LeftMedium'],
                       LoA['Manual'])
    rule11 = ctrl.Rule(JoyAngular['LeftHigh'] & WeldPos['LeftLow'],
                       LoA['Shared'])
    rule12 = ctrl.Rule(JoyAngular['LeftHigh'] & WeldPos['Center'],
                       LoA['Shared'])
    rule13 = ctrl.Rule(JoyAngular['LeftHigh'] & WeldPos['RightLow'],
                       LoA['Supervisory'])
    rule14 = ctrl.Rule(JoyAngular['LeftHigh'] & WeldPos['RightMedium'],
                       LoA['Supervisory'])
    rule15 = ctrl.Rule(JoyAngular['LeftHigh'] & WeldPos['RightHigh'],
                       LoA['Autonomous'])

    rule16 = ctrl.Rule(JoyAngular['LeftMedium'] & WeldPos['LeftHigh'],
                       LoA['Manual'])
    rule17 = ctrl.Rule(JoyAngular['LeftMedium'] & WeldPos['LeftMedium'],
                       LoA['Manual'])
    rule18 = ctrl.Rule(JoyAngular['LeftMedium'] & WeldPos['LeftLow'],
                       LoA['Manual'])
    rule19 = ctrl.Rule(JoyAngular['LeftMedium'] & WeldPos['Center'],
                       LoA['Shared'])
    rule20 = ctrl.Rule(JoyAngular['LeftMedium'] & WeldPos['RightLow'],
                       LoA['Shared'])
    rule21 = ctrl.Rule(JoyAngular['LeftMedium'] & WeldPos['RightMedium'],
                       LoA['Supervisory'])
    rule22 = ctrl.Rule(JoyAngular['LeftMedium'] & WeldPos['RightHigh'],
                       LoA['Autonomous'])

    rule23 = ctrl.Rule(JoyAngular['LeftLow'] & WeldPos['LeftHigh'],
                       LoA['Shared'])
    rule24 = ctrl.Rule(JoyAngular['LeftLow'] & WeldPos['LeftMedium'],
                       LoA['Manual'])
    rule25 = ctrl.Rule(JoyAngular['LeftLow'] & WeldPos['LeftLow'],
                       LoA['Manual'])
    rule26 = ctrl.Rule(JoyAngular['LeftLow'] & WeldPos['Center'],
                       LoA['Manual'])
    rule27 = ctrl.Rule(JoyAngular['LeftLow'] & WeldPos['RightLow'],
                       LoA['Shared'])
    rule28 = ctrl.Rule(JoyAngular['LeftLow'] & WeldPos['RightMedium'],
                       LoA['Supervisory'])
    rule29 = ctrl.Rule(JoyAngular['LeftLow'] & WeldPos['RightHigh'],
                       LoA['Autonomous'])

    rule30 = ctrl.Rule(JoyAngular['Center'] & WeldPos['LeftHigh'],
                       LoA['Autonomous'])
    rule31 = ctrl.Rule(JoyAngular['Center'] & WeldPos['LeftMedium'],
                       LoA['Supervisory'])
    rule32 = ctrl.Rule(JoyAngular['Center'] & WeldPos['LeftLow'],
                       LoA['Shared'])
    rule33 = ctrl.Rule(JoyAngular['Center'] & WeldPos['Center'], LoA['Manual'])
    rule34 = ctrl.Rule(JoyAngular['Center'] & WeldPos['RightLow'],
                       LoA['Shared'])
    rule35 = ctrl.Rule(JoyAngular['Center'] & WeldPos['RightMedium'],
                       LoA['Supervisory'])
    rule36 = ctrl.Rule(JoyAngular['Center'] & WeldPos['RightHigh'],
                       LoA['Autonomous'])

    rule37 = ctrl.Rule(JoyAngular['RightLow'] & WeldPos['LeftHigh'],
                       LoA['Autonomous'])
    rule38 = ctrl.Rule(JoyAngular['RightLow'] & WeldPos['LeftMedium'],
                       LoA['Supervisory'])
    rule39 = ctrl.Rule(JoyAngular['RightLow'] & WeldPos['LeftLow'],
                       LoA['Shared'])
    rule40 = ctrl.Rule(JoyAngular['RightLow'] & WeldPos['Center'],
                       LoA['Manual'])
    rule41 = ctrl.Rule(JoyAngular['RightLow'] & WeldPos['RightLow'],
                       LoA['Manual'])
    rule42 = ctrl.Rule(JoyAngular['RightLow'] & WeldPos['RightMedium'],
                       LoA['Manual'])
    rule43 = ctrl.Rule(JoyAngular['RightLow'] & WeldPos['RightHigh'],
                       LoA['Shared'])

    rule44 = ctrl.Rule(JoyAngular['RightMedium'] & WeldPos['LeftHigh'],
                       LoA['Autonomous'])
    rule45 = ctrl.Rule(JoyAngular['RightMedium'] & WeldPos['LeftMedium'],
                       LoA['Supervisory'])
    rule46 = ctrl.Rule(JoyAngular['RightMedium'] & WeldPos['LeftLow'],
                       LoA['Shared'])
    rule47 = ctrl.Rule(JoyAngular['RightMedium'] & WeldPos['Center'],
                       LoA['Shared'])
    rule48 = ctrl.Rule(JoyAngular['RightMedium'] & WeldPos['RightLow'],
                       LoA['Manual'])
    rule49 = ctrl.Rule(JoyAngular['RightMedium'] & WeldPos['RightMedium'],
                       LoA['Manual'])
    rule50 = ctrl.Rule(JoyAngular['RightMedium'] & WeldPos['RightHigh'],
                       LoA['Manual'])

    rule51 = ctrl.Rule(JoyAngular['RightHigh'] & WeldPos['LeftHigh'],
                       LoA['Autonomous'])
    rule52 = ctrl.Rule(JoyAngular['RightHigh'] & WeldPos['LeftMedium'],
                       LoA['Supervisory'])
    rule53 = ctrl.Rule(JoyAngular['RightHigh'] & WeldPos['LeftLow'],
                       LoA['Supervisory'])
    rule54 = ctrl.Rule(JoyAngular['RightHigh'] & WeldPos['Center'],
                       LoA['Shared'])
    rule55 = ctrl.Rule(JoyAngular['RightHigh'] & WeldPos['RightLow'],
                       LoA['Shared'])
    rule56 = ctrl.Rule(JoyAngular['RightHigh'] & WeldPos['RightMedium'],
                       LoA['Manual'])
    rule57 = ctrl.Rule(JoyAngular['RightHigh'] & WeldPos['RightHigh'],
                       LoA['Manual'])

    #CONTROL
    autonomy_ctrl = ctrl.ControlSystem([
        rule1, rule2, rule3, rule4, rule5, rule6, rule7, rule8, rule9, rule10,
        rule11, rule12, rule13, rule14, rule15, rule16, rule17, rule18, rule19,
        rule20, rule21, rule22, rule23, rule24, rule25, rule26, rule27, rule28,
        rule29, rule30, rule31, rule32, rule33, rule34, rule35, rule36, rule37,
        rule38, rule39, rule40, rule41, rule42, rule43, rule44, rule45, rule46,
        rule47, rule48, rule49, rule50, rule51, rule52, rule53, rule54, rule55,
        rule56, rule57
    ])
    autonomy = ctrl.ControlSystemSimulation(autonomy_ctrl)

    return
Example #3
0
rule40i = ctrl.Rule(valence['very high'] & arousal['very high'],
                    intensity['high'])
rule41i = ctrl.Rule(valence['very high'] & arousal['high'], intensity['high'])
rule42i = ctrl.Rule(valence['very high'] & arousal['mid low'],
                    intensity['high'])
rule43i = ctrl.Rule(valence['very high'] & arousal['mid high'],
                    intensity['high'])
rule44i = ctrl.Rule(valence['very high'] & arousal['very low'],
                    intensity['high'])
# rule1a.view()

#### Control system ####
angle_ctrl = ctrl.ControlSystem([
    rule1a, rule2a, rule3a, rule4a, rule5a, rule6a, rule7a, rule8a, rule9a,
    rule10a, rule11a, rule12a, rule13a, rule14a, rule15a, rule16a, rule17a,
    rule18a, rule19a, rule20a, rule21a, rule22a, rule23a, rule24a, rule25a,
    rule26a, rule27a, rule28a, rule29a, rule30a, rule31a, rule32a, rule33a,
    rule34a, rule35a, rule36a, rule37a, rule38a, rule39a, rule40a, rule41a,
    rule42a, rule43a, rule44a, rule45a, rule46a, rule47a, rule48a
])
intensity_ctrl = ctrl.ControlSystem([
    rule1i, rule2i, rule3i, rule4i, rule5i, rule6i, rule7i, rule8i, rule9i,
    rule10i, rule11i, rule12i, rule13i, rule14i, rule15i, rule16i, rule17i,
    rule18i, rule19i, rule20i, rule21i, rule22i, rule23i, rule24i, rule25i,
    rule26i, rule27i, rule28i, rule29i, rule30i, rule31i, rule32i, rule33i,
    rule34i, rule35i, rule36i, rule37i, rule38i, rule39i, rule40i, rule41i,
    rule42i, rule43i, rule44i
])

#### simulation ####
angle_value = ctrl.ControlSystemSimulation(angle_ctrl)
intensity_value = ctrl.ControlSystemSimulation(intensity_ctrl)
Example #4
0
                (error['pp'] & delta['pm']) | (error['pp'] & delta['pg'])),
    consequent=output['pp'],
    label='output pp')

rule5 = ctrl.Rule(
    antecedent=((error['nm'] & delta['ng']) | (error['np'] & delta['ng']) |
                (error['pg'] & delta['pm']) | (error['pm'] & delta['pm']) |
                (error['pm'] & delta['pg'])),
    consequent=output['pm'],
    label='output pm')

rule6 = ctrl.Rule(antecedent=(error['pg'] & delta['pg']),
                  consequent=output['pg'],
                  label='output pg')

system = ctrl.ControlSystem(
    rules=[rule0, rule1, rule2, rule3, rule4, rule5, rule6])

sim = ctrl.ControlSystemSimulation(system, flush_after_run=21 * 21 + 1)

area_base = 10
referencia = 50
altura_atual = 10
delta_erro = 0
erro_anterior = 0
controle_anterior = 0
vazao_saida = 5
ts = 5

altura_vec = []
controle_vec = []
tempo = []
Example #5
0
def fuzzy_contrast(folder, image_file, figsize=(10, 10),
                   channel=None, show=False):
    """Increase the contrast of input image by using fuzzy logic.

    Parameters
    ----------
    folder : string
        Directory containing image_file
    image_file : string
        Filename of image to be analyzed
    figsize : tuple of int or float
        Size of output image
    show : bool
        If True, outputs image to Jupyter notebook display.
    channel : int
        Channel of image to read in for multichannel images e.g.
        testim[:, :, channel]

    Returns
    -------
    rf_image : numpy.ndarray
        Output image

    Examples
    --------

    """

    # Build fuzzy logic system.
    dark = ctrl.Antecedent(np.linspace(0, 1, 101), 'dark')
    darker = ctrl.Consequent(np.linspace(0, 1, 101), 'darker')

    w = 90
    dark['dark'] = 1 - fuzz.sigmf(dark.universe, 0.425, w)
    dark['gray'] = fuzz.trimf(dark.universe, [0.35, 0.5, 0.65])
    dark['bright'] = fuzz.sigmf(dark.universe, 0.575, w)

    slope = 3.7
    width = 0.04
    darker['darker'] = fuzz.gbellmf(darker.universe, width, slope, 0.1)
    darker['midgray'] = fuzz.gbellmf(darker.universe, width, slope, 0.5)
    darker['brighter'] = fuzz.gbellmf(darker.universe, width, slope, 0.9)

    rule1 = ctrl.Rule(dark['dark'], darker['darker'])
    rule2 = ctrl.Rule(dark['gray'], darker['midgray'])
    rule3 = ctrl.Rule(dark['bright'], darker['brighter'])

    Fctrl = ctrl.ControlSystem([rule1, rule2, rule3])
    F = ctrl.ControlSystemSimulation(Fctrl)

    # Apply to image
    fname = '{}/{}'.format(folder, image_file)
    test_image = sio.imread(fname)
    if channel is None:
        test_image = test_image / test_image.max()
    else:
        test_image = test_image[:, :, channel] / test_image[:, :, channel].max()
    F.input['dark'] = test_image
    F.compute()
    fuzzy_image = F.output['darker']
    rf_image = (255.0 / fuzzy_image.max() * (fuzzy_image - fuzzy_image.min())
                ).astype(np.uint8)

    if show:
        fig, ax = plt.subplots(figsize=figsize)
        ax.imshow(rf_image, cmap='gray', vmin=0, vmax=255.0)
        ax.axis('off')

    output = "fuzzy_{}.png".format(image_file.split('.')[0])
    sio.imsave(folder+'/'+output, rf_image)

    return rf_image
Example #6
0
def fuzzing(vel, dis, flag=0):
    # Fuzzificacao
    velocidade = ctrl.Antecedent(np.arange(0, 101, 1), 'velocidade')
    distancia = ctrl.Antecedent(np.arange(0, 101, 1), 'distancia')
    pressao = ctrl.Consequent(np.arange(0, 101, 1), 'pressao')

    velocidade.automf(5)
    distancia.automf(5)

    # pressao['low'] = fuzz.trimf(pressao.universe, [0, 0, 50])
    # pressao['medium'] = fuzz.trimf(pressao.universe, [0, 50, 100])
    # pressao['high'] = fuzz.trimf(pressao.universe, [50, 100, 100])

    pressao['poor'] = fuzz.gaussmf(pressao.universe, 0, 10)
    pressao['mediocre'] = fuzz.gaussmf(pressao.universe, 25, 10)
    pressao['average'] = fuzz.gaussmf(pressao.universe, 50, 10)
    pressao['decent'] = fuzz.gaussmf(pressao.universe, 75, 10)
    pressao['good'] = fuzz.gaussmf(pressao.universe, 100, 10)

    # Regras
    regras = []

    regras.append(
        ctrl.Rule(velocidade['mediocre'] & distancia['average'],
                  pressao['poor']))
    regras.append(
        ctrl.Rule(velocidade['mediocre'] & distancia['mediocre'],
                  pressao['mediocre']))
    regras.append(
        ctrl.Rule(velocidade['mediocre'] & distancia['poor'],
                  pressao['average']))
    regras.append(
        ctrl.Rule(velocidade['average'] & distancia['average'],
                  pressao['average']))
    regras.append(
        ctrl.Rule(velocidade['average'] & distancia['mediocre'],
                  pressao['decent']))
    regras.append(
        ctrl.Rule(velocidade['average'] & distancia['poor'], pressao['good']))
    regras.append(
        ctrl.Rule(velocidade['decent'] & distancia['good'],
                  pressao['average']))
    regras.append(
        ctrl.Rule(velocidade['decent'] & distancia['decent'],
                  pressao['decent']))

    regras.append(ctrl.Rule(velocidade['poor'], pressao['poor']))
    # regras.append(ctrl.Rule(velocidade['mediocre'] | distancia['good'], pressao['decent']))
    regras.append(ctrl.Rule(velocidade['good'], pressao['good']))

    pressao_ctrl = ctrl.ControlSystem(regras)
    pressao_sim = ctrl.ControlSystemSimulation(pressao_ctrl)

    pressao_sim.input['velocidade'] = vel
    pressao_sim.input['distancia'] = dis

    pressao_sim.compute()
    print(pressao_sim.output['pressao'])

    # distancia.view()
    # velocidade.view()
    pressao.view(sim=pressao_sim)
    plt.show()
light =ctrl.Antecedent(np.arange(0, 11, 1), 'light')
hum =ctrl.Antecedent(np.arange(20, 81, 1), 'hum')
switch_power = ctrl.Consequent(np.arange(0, 11, 1), 'switch_power')
temp.automf(3)
light.automf(3)
hum.automf(3)
#switch_power.automf(3)
switch_power['low'] = fuzz.trimf(switch_power.universe, [0, 0, 5])
switch_power['medium'] = fuzz.trimf(switch_power.universe, [0, 5, 10])
switch_power['high'] = fuzz.trimf(switch_power.universe, [5, 10, 10])

rule1 = ctrl.Rule(temp['good'],switch_power['high'])
rule2 = ctrl.Rule(temp['average'] | hum['good'] ,switch_power['high'])
rule3 = ctrl.Rule(temp['poor'], switch_power['low'])
rule4 = ctrl.Rule(light['poor'], switch_power['low'])
tipping_ctrl = ctrl.ControlSystem([rule1, rule2, rule3,rule4])
tipping = ctrl.ControlSystemSimulation(tipping_ctrl)


#temp['average'].view()
#light['average'].view()
#hum['average'].view()
#switch_power.view()
##----------------Fuzzy End-----------------------------#

cnx = mysql.connector.connect(user='******', password='******',host='120.110.7.27',database='smarttimersocket')
cursor = cnx.cursor()
#My SQL Command
cursor.execute("SELECT * FROM `socket` ")
row = cursor.fetchone()
while row is not None:
temp_sense.view()
gas_sense.view()

#RULE base
rule1 = ctrl.Rule(temp_sense['Normal'] & gas_sense['Normal'], fire_gasLeak_sense['sec1'])
rule2 = ctrl.Rule(temp_sense['Normal'] & gas_sense['High'], fire_gasLeak_sense['sec2'])
rule3 = ctrl.Rule(temp_sense['Normal'] & gas_sense['Explosive Leak'], fire_gasLeak_sense['sec3'])
rule4 = ctrl.Rule(temp_sense['Hot'] & gas_sense['Normal'], fire_gasLeak_sense['sec1'])
rule5 = ctrl.Rule(temp_sense['Hot'] & gas_sense['High'] , fire_gasLeak_sense['sec2'])
rule6 = ctrl.Rule(temp_sense['Hot'] & gas_sense['Explosive Leak'], fire_gasLeak_sense['sec3'])
rule7 = ctrl.Rule(temp_sense['Critically Hot'] & gas_sense['Normal'], fire_gasLeak_sense['sec3'])
rule8 = ctrl.Rule(temp_sense['Critically Hot'] & gas_sense['High'], fire_gasLeak_sense['sec3'])
rule9 = ctrl.Rule(temp_sense['Critically Hot'] & gas_sense['Explosive Leak'], fire_gasLeak_sense['sec3'])

#Creating a fuzzy control system using the rule base
FireGasLeak_ctrlSys = ctrl.ControlSystem([rule1, rule2, rule3, rule4, rule5 , rule6, rule7, rule8, rule9])

#Creating a simulation for our Iot systems using the above created FCS
FgcsIot = ctrl.ControlSystemSimulation(FireGasLeak_ctrlSys)

periodic_work(55)

###
def periodic_work(interval):
    while True:
        # (GET requests) to retrieve temperature and gas field values . '/last' in request indicates most recent values
        tempField_data=urllib.urlopen("https://api.thingspeak.com/channels/484808/fields/1/last?api_key=FT93ZS9HFBJCY06V&results=1");
        gasField_data=urllib.urlopen("https://api.thingspeak.com/channels/484808/fields/2/last?api_key=FT93ZS9HFBJCY06V&results=1");
        
        x=float(tempField_data.read())
        y=float(gasField_data.read())
Example #9
0
def buildFuzzySystem(showDescription=False):
    """ 
    ===========================================================================
    Build Fuzzy Sistem for variable: memory  
    ===========================================================================   
    
    **Args**:
        showDescription: (boolean)
    **Returns**:
        None
    """
    #==========================================================================
    # Set labels of inputs and outputs
    #==========================================================================

    var_in1_label = 'net_err_rate'
    var_out_label = 'out'

    logger.info("buildFuzzySystem:" + var_in1_label)

    #==========================================================================
    # Set numerical range of inputs and outputs
    #==========================================================================

    in1_max = 1000.0

    var_in1_universe = np.arange(0, in1_max, in1_max / 1000.0)
    var_out_universe = np.arange(0, 1, 0.01)

    #==========================================================================
    # Set inputs(Antecedent) and outputs (Consequent)
    #==========================================================================

    var_in1 = ctrl.Antecedent(var_in1_universe, var_in1_label)
    var_out = ctrl.Consequent(var_out_universe, var_out_label)

    #==========================================================================
    # Set membership functions of fuzzy set
    #==========================================================================

    var_in1['low'] = fuzz.zmf(var_in1.universe, in1_max * 0.01, in1_max * 0.1)
    var_in1['high'] = fuzz.smf(var_in1.universe, in1_max * 0.01, in1_max * 0.1)

    var_out['low'] = fuzz.zmf(var_out.universe, 0.4, 0.8)
    var_out['high'] = fuzz.smf(var_out.universe, 0.7, 0.9)

    #==========================================================================
    # Set fuzzy rules
    #==========================================================================

    rule1 = ctrl.Rule(var_in1['high'], var_out['high'])
    rule2 = ctrl.Rule(var_in1['low'], var_out['low'])

    #==========================================================================
    # Build fuzzy control system and simulation
    #==========================================================================

    var_ctrl = ctrl.ControlSystem([rule1, rule2])
    var_fuzzysim = ctrl.ControlSystemSimulation(var_ctrl)

    #==========================================================================
    # Set fuzzy rules
    #==========================================================================

    if showDescription:
        fig = plt.figure(figsize=(12, 12))
        plt.subplot(3, 1, 1)
        plt.title('Input: ' + var_in1_label)
        plt.plot(var_in1_universe, var_in1['low'].mf, label='low')
        plt.plot(var_in1_universe, var_in1['high'].mf, label='high')
        plt.legend()

        plt.subplot(3, 1, 2)
        plt.title('Output: ' + var_out_label)
        plt.plot(var_out_universe, var_out['low'].mf, label='low')
        plt.plot(var_out_universe, var_out['high'].mf, label='high')
        plt.legend()

        var_fuzzysim.input[var_in1_label] = var_in1_universe
        var_fuzzysim.compute()
        y = var_fuzzysim.output[var_out_label]
        plt.subplot(3, 1, 3)
        plt.plot(var_in1_universe,
                 y,
                 label='Fuzzy transform of ' + var_in1_label)

        #plt.show()
        plt.savefig('/tmp/fuzzy_' + var_in1_label + '.png')

    return var_fuzzysim
Example #10
0
##out roda kiri (susur kiri)

rule1 = ctrl.Rule(left['jauh']   | right['dekat'],    out['cepat'])  
rule2 = ctrl.Rule(left['jauh']   | right['sedang'],   out['cepat'])
rule3 = ctrl.Rule(left['jauh']   | right['jauh'],    out['lambat'])   

rule4 = ctrl.Rule(left['sedang'] | right['dekat'],   out['sedang']) 
rule5 = ctrl.Rule(left['sedang'] | right['sedang'],   out['lambat']) #center 
rule6 = ctrl.Rule(left['sedang'] | right['jauh'],    out['sed_cep']) 

rule7 = ctrl.Rule(left['dekat']  | right['dekat'],  out['lambat'])  
rule8 = ctrl.Rule(left['dekat']  | right['sedang'],   out['lambat'])
rule9 = ctrl.Rule(left['dekat']  | right['jauh'],     out['sed_cep'])

outing_ctrl = ctrl.ControlSystem([rule1,rule2,rule3,rule4,rule5,rule6,rule7,rule8,rule9])
outing = ctrl.ControlSystemSimulation(outing_ctrl)


#-----------------------------Remote Api---------------------------------------


vrep.simxFinish(-1) 
clientID=vrep.simxStart ('127.0.0.1',19997,True,True,5000,5)
if clientID!=-1:
    print ("Connected to remote API server") 
    vrep.simxAddStatusbarMessage(clientID,"Program Loaded!",vrep.simx_opmode_oneshot)
else: 
    print ("Connection not successful")
    sys.exit("Could not connect")
    
Example #11
0
    def init_fuzzy(self):
        """
        Make fuzzy setup by defining membership functions and rules
        """

        # Set the difference between the right front sensor and the right back sensor
        difference_right_sensors = ctrl.Antecedent(np.arange(-1.0, 1.0, 0.001),
                                                   'difference_right_sensors')
        difference_right_sensors['negative'] = fuzz.gaussmf(
            difference_right_sensors.universe, -1, 0.25)
        difference_right_sensors['zero'] = fuzz.gaussmf(
            difference_right_sensors.universe, 0, 0.015)
        difference_right_sensors['positive'] = fuzz.gaussmf(
            difference_right_sensors.universe, 1, 0.25)

        # Set the distances of the front sensors
        distances_front_sensors = list()
        for i in range(3):
            distances_front_sensors.append(
                ctrl.Antecedent(np.arange(0, 5.0, self.steps),
                                'distance_front_sensor_' + str(i + 1)))
            distances_front_sensors[i]['close'] = fuzz.trapmf(
                distances_front_sensors[i].universe, [0.0, 0.0, 0.3, 0.8])
            distances_front_sensors[i]['away'] = fuzz.trapmf(
                distances_front_sensors[i].universe, [0.3, 0.8, 5.0, 5.0])

        # Define available velocities for each wheel
        v_left = ctrl.Consequent(
            np.arange(-self.max_speed, 1.0 + self.max_speed, 0.01), 'vl')
        v_right = ctrl.Consequent(
            np.arange(-self.max_speed, 1.0 + self.max_speed, 0.01), 'vr')

        # Define the membership functions for the wheels speed
        v_left['fast'] = fuzz.trimf(v_left.universe,
                                    [2.0, 2.0, self.max_speed])
        v_left['regular'] = fuzz.trimf(v_left.universe, [0.0, 2.0, 2.0])
        v_left['zero'] = fuzz.trimf(v_left.universe, [-0.1, 0.0, 0.1])
        v_right['fast'] = fuzz.trimf(v_right.universe,
                                     [2.0, 2.0, self.max_speed])
        v_right['regular'] = fuzz.trimf(v_left.universe, [0.0, 2.0, 2.0])
        v_right['zero'] = fuzz.trimf(v_right.universe, [-0.1, 0.0, 0.1])

        # Rules to make the robot follow the wall by turning left, right or going forward
        # Turn left
        rule_l1 = ctrl.Rule(
            distances_front_sensors[0]['close']
            | distances_front_sensors[1]['close']
            | distances_front_sensors[2]['close'], v_left['zero'])
        rule_r1 = ctrl.Rule(
            distances_front_sensors[0]['close']
            | distances_front_sensors[1]['close']
            | distances_front_sensors[2]['close'], v_right['fast'])

        # Turn right
        rule_l2 = ctrl.Rule(
            difference_right_sensors['positive']
            & distances_front_sensors[0]['away']
            & distances_front_sensors[1]['away'], v_left['fast'])
        rule_r2 = ctrl.Rule(difference_right_sensors['positive'],
                            v_right['zero'])

        # Go forward, next to the wall
        rule_l3 = ctrl.Rule(
            difference_right_sensors['zero']
            & distances_front_sensors[0]['away']
            & distances_front_sensors[1]['away'], v_left['regular'])
        rule_r3 = ctrl.Rule(
            difference_right_sensors['zero']
            & distances_front_sensors[0]['away']
            & distances_front_sensors[1]['away'], v_right['regular'])
        rule_l4 = ctrl.Rule(
            difference_right_sensors['negative']
            & distances_front_sensors[0]['away']
            & distances_front_sensors[1]['away'], v_left['regular'])
        rule_r4 = ctrl.Rule(
            difference_right_sensors['negative']
            & distances_front_sensors[0]['away']
            & distances_front_sensors[1]['away'], v_right['regular'])

        vel_ctrl = ctrl.ControlSystem([
            rule_l1, rule_l2, rule_l3, rule_l4, rule_r1, rule_r2, rule_r3,
            rule_r4
        ])
        self.fuzzy_system = ctrl.ControlSystemSimulation(vel_ctrl)
Example #12
0
from skfuzzy import control as ctrl

q = ctrl.Antecedent(np.arange(0, 11, 1), 'Quality')
s = ctrl.Antecedent(np.arange(0, 11, 1), 'Service')
t = ctrl.Consequent(np.arange(0, 26, 1), 'Tip')

q['Low'] = fuzzy.trimf(q.universe, [0, 0, 5])
q['Medium'] = fuzzy.trimf(q.universe, [0, 5, 10])
q['High'] = fuzzy.trimf(q.universe, [5, 10, 10])

s['Low'] = fuzzy.trimf(s.universe, [0, 0, 5])
s['Medium'] = fuzzy.trimf(s.universe, [0, 5, 10])
s['High'] = fuzzy.trimf(s.universe, [5, 10, 10])

t['Low'] = fuzzy.trimf(t.universe, [0, 0, 12.5])
t['Medium'] = fuzzy.trimf(t.universe, [0, 12.5, 25])
t['High'] = fuzzy.trimf(t.universe, [12.5, 25, 25])

r1 = ctrl.Rule(q['Low'] | s['Low'], t['Low'])
r2 = ctrl.Rule(s['Medium'], t['Medium'])
r3 = ctrl.Rule(s['High'] | q['High'], t['High'])

t_ctrl = ctrl.ControlSystem([r1, r2, r3])
t_cal = ctrl.ControlSystemSimulation(t_ctrl)

t_cal.input['Quality'] = 6.5
t_cal.input['Service'] = 9.5
t_cal.compute()
print(t_cal.output['Tip'])
t.view(sim=t_cal)
Example #13
0
def inicializaFuzzy():
    global autonomy

    #INPUTS
    MyoValue = ctrl.Antecedent(np.arange(20, 180, 0.005), 'MyoValue')
    MyoRoll = ctrl.Antecedent(np.arange(-2, 2, 0.005), 'MyoRoll')
    #MyoPitch = ctrl.Antecedent(np.arange(-0.5,0.5,0.005),'MyoPitch')
    #MyoYaw = ctrl.Antecedent(np.arange(-0.5,0.5,0.005),'MyoYaw')
    #JoyLinear = ctrl.Antecedent(np.arange(-1,1,0.005),'JoyLinear')
    JoyAngular = ctrl.Antecedent(np.arange(-5, 5, 0.005), 'JoyAngular')
    WeldPos = ctrl.Antecedent(np.arange(-1, 1, 0.005), 'WeldPos')

    #OUTPUTS
    LoA = ctrl.Consequent(np.arange(0, 4, 0.1), 'LoA')

    #MEMBERSHIP FUNCTIONS
    #myo emg rms mean value
    MyoValue['Low'] = fuzz.trimf(MyoValue.universe, [20.000, 20.000, 60.000])
    MyoValue['MedLow'] = fuzz.trimf(MyoValue.universe,
                                    [20.000, 60.000, 100.000])
    MyoValue['Medium'] = fuzz.trimf(MyoValue.universe,
                                    [60.000, 100.000, 140.000])
    MyoValue['MedHigh'] = fuzz.trimf(MyoValue.universe,
                                     [100.000, 140.000, 180.000])
    MyoValue['High'] = fuzz.trimf(MyoValue.universe,
                                  [140.000, 180.000, 180.000])

    #myo roll
    MyoRoll['ACWHigh'] = fuzz.trapmf(MyoRoll.universe,
                                     [-2.000, -2.000, -0.500, -0.250])
    MyoRoll['ACWLow'] = fuzz.trimf(MyoRoll.universe, [-0.500, -0.250, 0.000])
    MyoRoll['Zero'] = fuzz.trimf(MyoRoll.universe, [-0.250, 0.000, 0.250])
    MyoRoll['CWLow'] = fuzz.trimf(MyoRoll.universe, [0.000, 0.250, 0.500])
    MyoRoll['CWHigh'] = fuzz.trapmf(MyoRoll.universe,
                                    [0.250, 0.500, 2.000, 2.000])

    #MyoPitch['DownHigh'] = fuzz.trimf(MyoPitch.universe,[-0.500, -0.500, -0.250])
    #MyoPitch['DownLow'] = fuzz.trimf(MyoPitch.universe,[-0.500, -0.250, 0.000])
    #MyoPitch['Center'] = fuzz.trimf(MyoPitch.universe,[-0.250, 0.000, 0.250])
    #MyoPitch['UpLow'] = fuzz.trimf(MyoPitch.universe,[0.000, 0.250, 0.500])
    #MyoPitch['UpHigh'] = fuzz.trimf(MyoPitch.universe,[0.250, 0.500, 0.500])

    #MyoYaw['LeftHigh'] = fuzz.trimf(MyoYaw.universe,[-0.500, -0.500, -0.250])
    #MyoYaw['LeftLow'] = fuzz.trimf(MyoYaw.universe,[-0.500, -0.250, 0.000])
    #MyoYaw['Center'] = fuzz.trimf(MyoYaw.universe,[-0.250, 0.000, 0.250])
    #MyoYaw['RightLow'] = fuzz.trimf(MyoYaw.universe,[0.000, 0.250, 0.500])
    #MyoYaw['RightHigh'] = fuzz.trimf(MyoYaw.universe,[0.250, 0.500, 0.500])

    #velocity linear - joystick
    #JoyLinear['NegHigh'] = fuzz.trimf(JoyLinear.universe,[-1, -1, -0.5])
    #JoyLinear['NegLow'] = fuzz.trimf(JoyLinear.universe,[-0.5, -0.1, 0])
    #JoyLinear['Zero'] = fuzz.trimf(JoyLinear.universe,[-0.1, 0, 0.1])
    #JoyLinear['PosLow'] = fuzz.trimf(JoyLinear.universe,[0, 0.1, 0.5])
    #JoyLinear['PosHigh'] = fuzz.trimf(JoyLinear.universe,[0.5, 1, 1])

    #velocity angular - joystick
    JoyAngular['LeftHigh'] = fuzz.trapmf(JoyAngular.universe,
                                         [-5.000, -5.000, -2.000, -1.000])
    JoyAngular['LeftLow'] = fuzz.trimf(JoyAngular.universe,
                                       [-2.000, -1.000, 0.000])
    JoyAngular['Center'] = fuzz.trimf(JoyAngular.universe,
                                      [-1.000, 0.000, 1.000])
    JoyAngular['RightLow'] = fuzz.trimf(JoyAngular.universe,
                                        [0.000, 1.000, 2.000])
    JoyAngular['RightHigh'] = fuzz.trapmf(JoyAngular.universe,
                                          [1.000, 2.000, 5.000, 5.000])

    #weld position
    WeldPos['LeftHigh'] = fuzz.trimf(WeldPos.universe,
                                     [-1.000, -1.000, -0.500])
    WeldPos['LeftLow'] = fuzz.trimf(WeldPos.universe, [-1.000, -0.500, 0.000])
    WeldPos['Center'] = fuzz.trimf(WeldPos.universe, [-0.500, 0.000, 0.500])
    WeldPos['RightLow'] = fuzz.trimf(WeldPos.universe, [0.000, 0.500, 1.000])
    WeldPos['RightHigh'] = fuzz.trimf(WeldPos.universe, [0.500, 1.000, 1.000])

    #Level of Autonomy - LoA
    LoA['Manual'] = fuzz.trapmf(LoA.universe, [0.000, 0.000, 0.500, 1.500])
    LoA['Shared'] = fuzz.trimf(LoA.universe, [0.500, 1.500, 2.500])
    LoA['Supervisory'] = fuzz.trimf(LoA.universe, [1.500, 2.500, 3.500])
    LoA['Autonomous'] = fuzz.trapmf(LoA.universe, [2.500, 3.500, 4.000, 4.000])

    #RULES
    #Joy Angular e Weld Position

    rule1 = ctrl.Rule(JoyAngular['LeftHigh'] & WeldPos['LeftHigh'],
                      LoA['Manual'])
    rule2 = ctrl.Rule(JoyAngular['LeftHigh'] & WeldPos['LeftLow'],
                      LoA['Shared'])
    rule3 = ctrl.Rule(JoyAngular['LeftHigh'] & WeldPos['Center'],
                      LoA['Supervisory'])
    rule4 = ctrl.Rule(JoyAngular['LeftHigh'] & WeldPos['RightLow'],
                      LoA['Autonomous'])
    rule5 = ctrl.Rule(JoyAngular['LeftHigh'] & WeldPos['RightHigh'],
                      LoA['Autonomous'])

    rule6 = ctrl.Rule(JoyAngular['LeftLow'] & WeldPos['LeftHigh'],
                      LoA['Shared'])
    rule7 = ctrl.Rule(JoyAngular['LeftLow'] & WeldPos['LeftLow'],
                      LoA['Manual'])
    rule8 = ctrl.Rule(JoyAngular['LeftLow'] & WeldPos['Center'], LoA['Shared'])
    rule9 = ctrl.Rule(JoyAngular['LeftLow'] & WeldPos['RightLow'],
                      LoA['Supervisory'])
    rule10 = ctrl.Rule(JoyAngular['LeftLow'] & WeldPos['RightHigh'],
                       LoA['Autonomous'])

    rule11 = ctrl.Rule(JoyAngular['Center'] & WeldPos['LeftHigh'],
                       LoA['Supervisory'])
    rule12 = ctrl.Rule(JoyAngular['Center'] & WeldPos['LeftLow'],
                       LoA['Shared'])
    rule13 = ctrl.Rule(JoyAngular['Center'] & WeldPos['Center'], LoA['Manual'])
    rule14 = ctrl.Rule(JoyAngular['Center'] & WeldPos['RightLow'],
                       LoA['Shared'])
    rule15 = ctrl.Rule(JoyAngular['Center'] & WeldPos['RightHigh'],
                       LoA['Supervisory'])

    rule16 = ctrl.Rule(JoyAngular['RightLow'] & WeldPos['LeftHigh'],
                       LoA['Autonomous'])
    rule17 = ctrl.Rule(JoyAngular['RightLow'] & WeldPos['LeftLow'],
                       LoA['Supervisory'])
    rule18 = ctrl.Rule(JoyAngular['RightLow'] & WeldPos['Center'],
                       LoA['Shared'])
    rule19 = ctrl.Rule(JoyAngular['RightLow'] & WeldPos['RightLow'],
                       LoA['Manual'])
    rule20 = ctrl.Rule(JoyAngular['RightLow'] & WeldPos['RightHigh'],
                       LoA['Shared'])

    rule21 = ctrl.Rule(JoyAngular['RightHigh'] & WeldPos['LeftHigh'],
                       LoA['Autonomous'])
    rule22 = ctrl.Rule(JoyAngular['RightHigh'] & WeldPos['LeftLow'],
                       LoA['Autonomous'])
    rule23 = ctrl.Rule(JoyAngular['RightHigh'] & WeldPos['Center'],
                       LoA['Supervisory'])
    rule24 = ctrl.Rule(JoyAngular['RightHigh'] & WeldPos['RightLow'],
                       LoA['Shared'])
    rule25 = ctrl.Rule(JoyAngular['RightHigh'] & WeldPos['RightHigh'],
                       LoA['Manual'])

    # Myo Roll e Weld Position

    rule26 = ctrl.Rule(MyoRoll['ACWHigh'] & WeldPos['LeftHigh'], LoA['Manual'])
    rule27 = ctrl.Rule(MyoRoll['ACWHigh'] & WeldPos['LeftLow'], LoA['Shared'])
    rule28 = ctrl.Rule(MyoRoll['ACWHigh'] & WeldPos['Center'],
                       LoA['Supervisory'])
    rule29 = ctrl.Rule(MyoRoll['ACWHigh'] & WeldPos['RightLow'],
                       LoA['Autonomous'])
    rule30 = ctrl.Rule(MyoRoll['ACWHigh'] & WeldPos['RightHigh'],
                       LoA['Autonomous'])

    rule31 = ctrl.Rule(MyoRoll['ACWLow'] & WeldPos['LeftHigh'], LoA['Shared'])
    rule32 = ctrl.Rule(MyoRoll['ACWLow'] & WeldPos['LeftLow'], LoA['Manual'])
    rule33 = ctrl.Rule(MyoRoll['ACWLow'] & WeldPos['Center'], LoA['Shared'])
    rule34 = ctrl.Rule(MyoRoll['ACWLow'] & WeldPos['RightLow'],
                       LoA['Supervisory'])
    rule35 = ctrl.Rule(MyoRoll['ACWLow'] & WeldPos['RightHigh'],
                       LoA['Autonomous'])

    rule36 = ctrl.Rule(MyoRoll['Zero'] & WeldPos['LeftHigh'],
                       LoA['Supervisory'])
    rule37 = ctrl.Rule(MyoRoll['Zero'] & WeldPos['LeftLow'], LoA['Shared'])
    rule38 = ctrl.Rule(MyoRoll['Zero'] & WeldPos['Center'], LoA['Manual'])
    rule39 = ctrl.Rule(MyoRoll['Zero'] & WeldPos['RightLow'], LoA['Shared'])
    rule40 = ctrl.Rule(MyoRoll['Zero'] & WeldPos['RightHigh'],
                       LoA['Supervisory'])

    rule41 = ctrl.Rule(MyoRoll['CWLow'] & WeldPos['LeftHigh'],
                       LoA['Autonomous'])
    rule42 = ctrl.Rule(MyoRoll['CWLow'] & WeldPos['LeftLow'],
                       LoA['Supervisory'])
    rule43 = ctrl.Rule(MyoRoll['CWLow'] & WeldPos['Center'], LoA['Shared'])
    rule44 = ctrl.Rule(MyoRoll['CWLow'] & WeldPos['RightLow'], LoA['Manual'])
    rule45 = ctrl.Rule(MyoRoll['CWLow'] & WeldPos['RightHigh'], LoA['Shared'])

    rule46 = ctrl.Rule(MyoRoll['CWHigh'] & WeldPos['LeftHigh'],
                       LoA['Autonomous'])
    rule47 = ctrl.Rule(MyoRoll['CWHigh'] & WeldPos['LeftLow'],
                       LoA['Autonomous'])
    rule48 = ctrl.Rule(MyoRoll['CWHigh'] & WeldPos['Center'],
                       LoA['Supervisory'])
    rule49 = ctrl.Rule(MyoRoll['CWHigh'] & WeldPos['RightLow'], LoA['Shared'])
    rule50 = ctrl.Rule(MyoRoll['CWHigh'] & WeldPos['RightHigh'], LoA['Manual'])

    rule51 = ctrl.Rule(MyoValue['Low'], LoA['Manual'])
    rule52 = ctrl.Rule(MyoValue['MedLow'], LoA['Manual'])
    rule53 = ctrl.Rule(MyoValue['Medium'], LoA['Shared'])
    rule54 = ctrl.Rule(MyoValue['MedHigh'], LoA['Supervisory'])
    rule55 = ctrl.Rule(MyoValue['High'], LoA['Autonomous'])

    #CONTROL
    autonomy_ctrl = ctrl.ControlSystem([
        rule1, rule2, rule3, rule4, rule5, rule6, rule7, rule8, rule9, rule10,
        rule11, rule12, rule13, rule14, rule15, rule16, rule17, rule18, rule19,
        rule20, rule21, rule22, rule23, rule24, rule25, rule26, rule27, rule28,
        rule29, rule30, rule31, rule32, rule33, rule34, rule35, rule36, rule37,
        rule38, rule39, rule40, rule41, rule42, rule43, rule44, rule45, rule46,
        rule47, rule48, rule49, rule50, rule51, rule52, rule53, rule54, rule55
    ])
    autonomy = ctrl.ControlSystemSimulation(autonomy_ctrl)

    return
Example #14
0
                        house['medium'])
house_rule9 = ctrl.Rule(location['fair'] & market_value['high'], house['high'])
house_rule10 = ctrl.Rule(location['fair'] & market_value['veryhigh'],
                         house['very high'])
house_rule11 = ctrl.Rule(location['excellent'] & market_value['low'],
                         house['medium'])
house_rule12 = ctrl.Rule(location['excellent'] & market_value['medium'],
                         house['very high'])
house_rule13 = ctrl.Rule(location['excellent'] & market_value['high'],
                         house['very high'])
house_rule14 = ctrl.Rule(location['excellent'] & market_value['veryhigh'],
                         house['very high'])

house_ctrl = ctrl.ControlSystem([
    house_rule1, house_rule2, house_rule3, house_rule4, house_rule5,
    house_rule6, house_rule7, house_rule8, house_rule9, house_rule10,
    house_rule11, house_rule12, house_rule13, house_rule14
])

house_value = ctrl.ControlSystemSimulation(house_ctrl)

house_value.input['market_value'] = MARKET_VALUE
house_value.input['location'] = LOCATION

house_value.compute()
#input
house_out = house_value.output['house']

print(house_value.output['house'])
house.view(sim=house_value)
Example #15
0
rule2 = ctrl.Rule(direction['error_left'] & goal_distance['longe'],
                  vel_right['pos'])
rule3 = ctrl.Rule(direction['error_right'] & goal_distance['longe'],
                  vel_right['neg'])
rule4 = ctrl.Rule(direction['error_right'] & goal_distance['longe'],
                  vel_left['pos'])
rule5 = ctrl.Rule(direction['no_error'] & goal_distance['longe'],
                  vel_left['pos'])
rule6 = ctrl.Rule(direction['no_error'] & goal_distance['longe'],
                  vel_right['pos'])
rule7 = ctrl.Rule(goal_distance['perto'], vel_right['pos'])
rule8 = ctrl.Rule(goal_distance['perto'], vel_right['neg'])
rule9 = ctrl.Rule(goal_distance['perto'], vel_left['neg'])
rule10 = ctrl.Rule(goal_distance['perto'], vel_left['pos'])

go_to_goal_ctrl = ctrl.ControlSystem(
    [rule1, rule2, rule3, rule4, rule5, rule6, rule7, rule8, rule9, rule10])
go_to_goal = ctrl.ControlSystemSimulation(go_to_goal_ctrl)

positions = [[], []]
velocities_left = []
velocities_right = []
distances = []


def get_info_to_plot(vel, distance, it):
    if it % 150 == 0:
        position = robot.get_current_position()
        positions[0].append(position[0])
        positions[1].append(position[1])
        velocities_left.append(vel[0])
        velocities_right.append(vel[1])
Example #16
0
# Auto-membership function population is possible with .automf(3, 5, or 7)
curr.automf(7)
extracurr.automf(7)

# Custom membership functions can be built interactively with a familiar,
# Pythonic API
grade['fail'] = fuzz.trimf(grade.universe, [0, 0, 4])
grade['promoted'] = fuzz.trimf(grade.universe, [4, 4, 7])
grade['merit-list'] = fuzz.trimf(grade.universe, [7, 10, 10])

rule1 = ctrl.Rule(curr['poor'] | extracurr['poor'], grade['fail'])
rule2 = ctrl.Rule(curr['average'] | extracurr['average'], grade['promoted'])
rule3 = ctrl.Rule(extracurr['good'] | curr['good'], grade['merit-list'])

grading_ctrl = ctrl.ControlSystem([rule1, rule2, rule3])

grading = ctrl.ControlSystemSimulation(grading_ctrl)
# Pass inputs to the ControlSystem using Antecedent labels with Pythonic API
# Note: if you like passing many inputs all at once, use .inputs(dict_of_data)
grading.input['Curricular Grade'] = 7
grading.input['Extra-Curricular Grade'] = 8

# Crunch the numbers

grading.compute()
print("Resulting Grade :", round(grading.output['Result'] * 10, 3), "%")
print("SGPA =", round(grading.output['Result'], 2))
alphagrade = grading.output['Result']
if alphagrade <= 4:
    print("F")
performace['ganteng'] = fuzzy.trapmf(performace.universe, [25,75,100,100])

performace.view()

""" rules """

rules1 = system.Rule(tinggi_badan['tinggi'] & berat_badan['berat_banget'], performace['ganteng'])
rules1.view()

rules2 = system.Rule(tinggi_badan['tinggi'] & berat_badan['berat_banget'], performace['ganteng'])
rules3 = system.Rule(tinggi_badan['sedang'] & berat_badan['berat_banget'], performace['ganteng'])
rules4 = system.Rule(tinggi_badan['sedang'] & berat_badan['ringan'], performace['jelek'])
rules5 = system.Rule(tinggi_badan['pendek'] & berat_badan['berat_banget'], performace['jelek'])
rules6 = system.Rule(tinggi_badan['pendek'] & berat_badan['ringan'], performace['jelek'])

""" input decision (keputusan)"""

performace_control_udin = system.ControlSystem([rules1,rules2,rules3,rules4,rules5,rules6])
performace_control_udin.view()

performacepointsimulasi = system.ControlSystemSimulation(performace_control_udin)

performacepointsimulasi.input['berat_badan'] = 40
performacepointsimulasi.input['tinggi_badan'] = 110

performacepointsimulasi.compute()

performace.view(sim=performacepointsimulasi)
print("performance si udin : ", performacepointsimulasi.output['performance'])
Example #18
0
rule7 = ctrl.Rule(
    Investigative['poor'] | Social['good'] | Artistic['poor']
    | Realistic['good'] | Enterprising['good'], Interest['medium'])
rule8 = ctrl.Rule(
    Investigative['good'] | Social['good'] | Artistic['good']
    | Realistic['good'] | Enterprising['average'], Interest['high'])
rule9 = ctrl.Rule(
    Investigative['average'] | Social['good'] | Artistic['poor']
    | Realistic['good'] | Enterprising['average'], Interest['high'])
rule10 = ctrl.Rule(
    Investigative['average'] | Social['poor'] | Artistic['poor']
    | Realistic['good'] | Enterprising['good'], Interest['high'])

rule1.view()

inter_ctrl = ctrl.ControlSystem(
    [rule1, rule2, rule3, rule4, rule5, rule6, rule7, rule8, rule9, rule10])

inter = ctrl.ControlSystemSimulation(inter_ctrl)

print("\n Value 1-3 = Low , 4-7 = Medium , 8-10 = High\n")
print("Enter the value for each skill for suggestion.")

inter.input['Investigative'] = int(
    input("Enter the value for Investigative : "))
inter.input['Social'] = int(input("Enter the value for Social : "))
inter.input['Artistic'] = int(input("Enter the value for Artistic : "))
inter.input['Realistic'] = int(input("Enter the value for Realistic : "))
inter.input['Enterprising'] = int(input("Enter the value for Enterprising : "))
inter.compute()

print("\nOutput - ")
Example #19
0
fcm_gr.view()
plt.show()

#plt.subplot(133)
fcm_sl.view()
plt.show()

rl = []

for i in range(ncenters):
    s1 = "ce" + str(i)
    s2 = "sl" + str(i)
    rule = ctrl.Rule(fcm_gr[s1], fcm_sl[s2])
    rl.append(rule)

sist = ctrl.ControlSystem(rl)
sist1 = ctrl.ControlSystemSimulation(sist)

#im_gauss = np.zeros_like(Im)

Im2 = np.zeros_like(Im)

#for i in range(fil*col):
#print Im[0,i]
#    sist1.input['grupos'] = Im[0,i]
#    sist1.compute()
#    Im2[0,i] = sist1.output['salida']

# for i in range(len(Im)):
#    ims = 0.01
# ims2 = 0.01
Example #20
0
#from mitigation_rules_demo import rule_list_generator
from mitigation_rules import rule_list_generator
rule_list=rule_list_generator(object_distance,object_direction, object_risk,left_speed,right_speed)



"""

Control System Creation and Simulation
---------------------------------------

Now that we have our rules defined, we can simply create a control system via:
"""

risk_mitigation_fls = ctrl.ControlSystem(rule_list)

"""
In order to simulate this control system, we will create a
``ControlSystemSimulation``.  Think of this object representing our controller
applied to a specific set of cirucmstances. 
"""

risk_mitigation_instance = ctrl.ControlSystemSimulation(risk_mitigation_fls)

"""
We can now simulate our control system by simply specifying the inputs
and calling the ``compute`` method.  
"""
# Pass inputs to the ControlSystem using Antecedent labels with Pythonic API
# Note: if you like passing many inputs all at once, use .inputs(dict_of_data)
Example #21
0
food.view()
tips.view()

# create your rulebase including at least 4 rules
rule_1 = control.Rule(service['poor'] & food['poor'], tips['poor'])
rule_2 = control.Rule(service['average'] & food['average'], tips['average'])
rule_3 = control.Rule(service['good'] & food['good'], tips['good'])
rule_4 = control.Rule(service['average'] & food['poor'], tips['average'])
rule_5 = control.Rule(service['poor'] & food['average'], tips['poor'])
rule_6 = control.Rule(service['good'] & food['poor'], tips['average'])
rule_7 = control.Rule(service['poor'] & food['good'], tips['average'])

# create a control system
control_system = control.ControlSystem([rule_1,
                                        rule_2,
                                        rule_3,
                                        rule_4,
                                        rule_5,
                                        rule_6,
                                        rule_7])
# create a simulation
simulation = control.ControlSystemSimulation(control_system)

# run the fuzzy machine
simulation.input['service'] = 10
simulation.input['food'] = 80
simulation.compute()
# show the result
tips.view(sim = simulation)
print(simulation.output['tips'])
    def willing2ask_fuzzy(self, inputs):
        # Define some parameters
        hmin = 400
        hmax = 4500
        hdiff = 10

        unitmin = 0
        unitmax = 1
        unitdiff = 0.1

        # Define antecedents (inputs): holds variables and membership functions
        # Health represents an aggregation of the values for battery, sensor, actuator and motor condition
        health = ctrl.Antecedent(np.arange(hmin, hmax, hdiff), 'health')

        # Best known agent to ask, in which helpfulness and success rate are combined beforehand, using a dot product
        best_agent = ctrl.Antecedent(np.arange(unitmin, unitmax, unitdiff),
                                     'best_agent')

        # The environment represents a combined value of the danger associated with physical obstacles, and the general culture of the population
        # as in the case of the best known agent, these can be combined using a dot product
        environment = ctrl.Antecedent(np.arange(unitmin, unitmax, unitdiff),
                                      'environment')

        # Agent abilities and resources needed in the scope of one task could also be combined in order to be represented by one fuzzy input
        abil_res = ctrl.Antecedent(np.arange(unitmin, unitmax, unitdiff),
                                   'abil_res')
        abil_res['some'] = fuzz.trapmf(abil_res.universe, [0.0, 0.0, 0.4, 0.4])
        abil_res['all_&optional'] = fuzz.trapmf(abil_res.universe,
                                                [0.6, 0.6, 1.0, 1.0])
        # abil_res.view()
        # The agent's own progress wrt to tasks, or plans in general could also serve as a trigger to interact or not
        own_progress = ctrl.Antecedent(np.arange(unitmin, unitmax, unitdiff),
                                       'own_progress')

        # Fuzzy output, the willingness to ask for help
        willingness = ctrl.Consequent(np.arange(unitmin, unitmax, unitdiff),
                                      'willingness')

        # Auto membership function population
        health.automf(3)
        best_agent.automf(3)
        environment.automf(3)
        own_progress.automf(3)
        willingness.automf(3)

        # health.view()
        # willingness.view()

        # Define rules
        rules = []

        ## either poor health or only some of abilities and resources are enough to have high willingness to ask for help
        rules.append(
            ctrl.Rule(health['poor'] | abil_res['some'] | own_progress['poor'],
                      willingness['good']))
        rules.append(
            ctrl.Rule((health['good'] | health['average'])
                      & abil_res['all_&optional'] &
                      (own_progress['good'] | own_progress['average']),
                      willingness['poor']))
        # rules.append(ctrl.Rule(best_agent['good'] & health['average'] & abil_res['all_&optional'], willingness['average']))
        # rules.append(ctrl.Rule(best_agent['poor'] & health['average'] & abil_res['all_&optional'], willingness['poor']))

        ## View rules graphically
        # rule1.view()

        # inputs = [4400, 0.7, 0.3, 0.5]

        interact_ctrl = ctrl.ControlSystem(rules)
        interact = ctrl.ControlSystemSimulation(interact_ctrl)
        interact.input['health'] = inputs[0]
        # interact.input['best_agent'] = inputs[1]
        interact.input['abil_res'] = inputs[2]
        interact.input['own_progress'] = inputs[3]

        interact.compute()

        print interact.output['willingness']
        test = random.random()
        print test
        # The function will return depend either true or false, either ask or don't ask for help
        if test < interact.output['willingness']:
            return True
        else:
            return False
Example #23
0
# largura.view()
# especie.view()

# Definindo regras

#Comprimento Baixo e Largura Baixa => Espécie 1
regra1 = ctrl.Rule(comprimento['CB'] & (largura['LB']), especie['E1'])
#Comprimento Médio e Largura Média => Espécie 2
regra2 = ctrl.Rule(comprimento['CM'] & (largura['LM']), especie['E2'])
#Comprimento Alto e Largura Alta => Espécie 3
regra3 = ctrl.Rule(comprimento['CA'] & (largura['LA']), especie['E3'])

regras = [regra1, regra2, regra3]

# Inserindo as regras
fuzzyIris_ctrl = ctrl.ControlSystem(regras)
fuzzyIris = ctrl.ControlSystemSimulation(fuzzyIris_ctrl)

# Rotina para a verificar cada amostra
datatc = np.vstack((data1c, data2c, data3c))
resultados = []

for i in range(len(datatc[:, 1])):

    cteste = datatc[i, 2]
    lteste = datatc[i, 3]
    fuzzyIris.input['comprimento'] = cteste
    fuzzyIris.input['largura'] = lteste

    fuzzyIris.compute()
    resultados.insert(i, fuzzyIris.output['especie'])
Example #24
0
    def expert_system(self):

        df = self.df
        cp = self.cutpoints
        # Membership function for sex
        # F = 1, M = 0
        x = np.arange(df["sex"].min(), df["sex"].max() + 1, 1)
        sex = ctrl.Antecedent(x, "sex")
        sex["M"] = np.array([1, 0])
        sex["F"] = np.array([0, 1])

        # Membership function for mstatus
        x = np.arange(df["mstatus"].min(), df["mstatus"].max()+1, 1)
        mstatus = ctrl.Antecedent(x, "mstatus")
        mstatus["single"] = np.array([1, 0, 0, 0])
        mstatus["married"] = np.array([0, 1, 0, 0])
        mstatus["widowed"] = np.array([0, 0, 1, 0])
        mstatus["divorced"] = np.array([0, 0, 0, 1])

        # Membership function for age
        # x = np.arange(df["age"].min(), df["age"].max()+1, 0.01)
        # x = sorted(df["age"])
        x = df["age"].sort_values().unique()
        age = ctrl.Antecedent(x, "age")
        age["young"] = fuzz.membership.trapmf(age.universe, [0, 0, cp["age"][0], cp["age"][1]])
        age["middle"] = fuzz.membership.trimf(age.universe, [cp["age"][0], cp["age"][1], cp["age"][2]])
        age["old"] = fuzz.membership.trapmf(age.universe, [cp["age"][1], cp["age"][2], max(x), max(x)])

        # Membership function for children
        x = np.arange(df["children"].min(), df["children"].max()+1, 1)
        children = ctrl.Antecedent(x, "children")
        children["low"] = np.array([1, 1, 0.5, 0, 0])
        children["high"] = np.array([0, 0, 0.5, 0.7, 1])


        # Membership function for occupation
        x = np.arange(df["occupation"].min(), df["occupation"].max()+1, 1)
        occupation = ctrl.Antecedent(x, "occupation")
        occupation["legal"] = np.array([1, 0, 0, 0, 0, 0, 0, 0, 0])
        occupation["IT"] = np.array([0, 1, 0, 0, 0, 0, 0, 0, 0])
        occupation["government"] = np.array([0, 0, 1, 0, 0, 0, 0, 0, 0])
        occupation["manuf"] = np.array([0, 0, 0, 1, 0, 0, 0, 0, 0])
        occupation["retired"] = np.array([0, 0, 0, 0, 1, 0, 0, 0, 0])
        occupation["finance"] = np.array([0, 0, 0, 0, 0, 1, 0, 0, 0])
        occupation["construct"] = np.array([0, 0, 0, 0, 0, 0, 1, 0, 0])
        occupation["education"] = np.array([0, 0, 0, 0, 0, 0, 0, 1, 0])
        occupation["medicine"] = np.array([0, 0, 0, 0, 0, 0, 0, 0, 1])

        # Membership function for education
        x = np.arange(df["education"].min(), df["education"].max()+1, 1)
        education = ctrl.Antecedent(x, "education")
        education["low"] = np.array([1, 1, 0, 0])
        education["high"] = np.array([0, 0, 1, 1])

        # Membership function for income
        # x = np.arange(df["income"].min(), df["income"].max()+1, 0.01)
        # x = sorted(df["income"])
        x = df["income"].sort_values().unique()
        income = ctrl.Antecedent(x, "income")
        income["low"] = fuzz.membership.trapmf(income.universe, [0, 0, cp["income"][0], cp["income"][1]])
        income["medium"] = fuzz.membership.trimf(income.universe, [cp["income"][0], cp["income"][1], cp["income"][2]])
        income["high"] = fuzz.membership.trapmf(income.universe, [cp["income"][1], cp["income"][2], max(x), max(x)])

        # Membership function for avbal
        # x = np.arange(df["avbal"].min(), df["avbal"].max()+1, 0.01)
        # x = sorted(df["avbal"])
        x = df["avbal"].sort_values().unique()
        avbal = ctrl.Antecedent(x, "avbal")
        avbal["low"] = fuzz.membership.trapmf(avbal.universe, [0, 0, cp["avbal"][0], cp["avbal"][1]])
        avbal["medium"] = fuzz.membership.trimf(avbal.universe, [cp["avbal"][0], cp["avbal"][1], cp["avbal"][2]])
        avbal["high"] = fuzz.membership.trapmf(avbal.universe, [cp["avbal"][1], cp["avbal"][2], max(x), max(x)])

        # Membership function for avtrans
        # x = np.arange(df["avtrans"].min(), df["avtrans"].max()+1, 0.01)
        # x = sorted(df["avtrans"])
        x = df["avtrans"].sort_values().unique()
        avtrans = ctrl.Antecedent(x, "avtrans")
        avtrans["low"] = fuzz.membership.trapmf(avtrans.universe, [0, 0, cp["avtrans"][0], cp["avtrans"][1]])
        avtrans["medium"] = fuzz.membership.trimf(avtrans.universe, [cp["avtrans"][0], cp["avtrans"][1], cp["avtrans"][2]])
        avtrans["high"] = fuzz.membership.trapmf(avtrans.universe, [cp["avtrans"][1], cp["avtrans"][2], max(x), max(x)])

        # Membership function for cip
        # x = np.arange(0, 10 + 1, 0.01)
        x = np.arange(0, 10 + 1, 0.1)
        cip = ctrl.Consequent(x, "cip")
        cip["low"] = fuzz.membership.trapmf(cip.universe, [0, 0, cp["cip"][0], cp["cip"][1]])
        cip["medium"] = fuzz.membership.trimf(cip.universe, [cp["cip"][0], cp["cip"][1], cp["cip"][2]])
        cip["high"] = fuzz.membership.trapmf(cip.universe, [cp["cip"][1], cp["cip"][2], max(x), max(x)])

        rules = []
    
        # Rules for Account Activity
        rules.append(ctrl.Rule(avbal["high"] & avtrans["high"], cip["high"]))
        rules.append(ctrl.Rule(avbal["high"] & avtrans["medium"], cip["medium"]))
        rules.append(ctrl.Rule(avbal["medium"] & avtrans["high"], cip["medium"]))
        rules.append(ctrl.Rule(avbal["medium"] & avtrans["medium"], cip["medium"]))
        rules.append(ctrl.Rule(avbal["low"] | avtrans["low"], cip["low"]))

        # Rules for Personal Factors
        rules.append(ctrl.Rule(sex["M"], cip["high"]))
        rules.append(ctrl.Rule(sex["F"] & mstatus["single"], cip["high"]))
        rules.append(ctrl.Rule(income["high"], cip["high"]))
        rules.append(ctrl.Rule(age["middle"], cip["high"]))
        rules.append(ctrl.Rule(occupation["retired"], cip["low"]))
        rules.append(ctrl.Rule(occupation["legal"] | occupation["medicine"] | occupation["education"]
                    | occupation["finance"] | occupation["IT"], cip["high"]))
        rules.append(ctrl.Rule(education["high"], cip["high"]))
        rules.append(ctrl.Rule(education["high"] & age["middle"], cip["high"]))
        rules.append(ctrl.Rule(income["high"] & age["old"], cip["high"]))

        # Rule Control System
        rule_ctrl = ctrl.ControlSystem(rules)
        simulator = ctrl.ControlSystemSimulation(rule_ctrl)

        return simulator
import skfuzzy as fuzzy
from skfuzzy import control as ctrl
import matplotlib.pyplot as plt
import pandas as pd

wind_speed = ctrl.Antecedent(np.arange(1, 20), 'wind_speed')
wind_speed['poor'] = fuzzy.trimf(wind_speed.universe, [0, 0, 5])
wind_speed['average'] = fuzzy.trimf(wind_speed.universe, [0, 5, 15])
wind_speed['good'] = fuzzy.trimf(wind_speed.universe, [0, 15, 20])

# wind_direction

Power = ctrl.Consequent(np.arange(1, 4000, 1), 'Power')
Power.automf(3)
Power.view()
plt.show()

rule1 = ctrl.Rule(wind_speed['poor'], Power['poor'])
rule2 = ctrl.Rule(wind_speed['average'], Power['average'])
rule3 = ctrl.Rule(wind_speed['good'], Power['good'])

rule1.view()

power_ctrl = ctrl.ControlSystem([rule1, rule2, rule3])
power = ctrl.ControlSystemSimulation(power_ctrl)

power.input['wind_speed'] = 11
power.compute()

print(power.output['Power'])
Power.view(sim=power)
Example #26
0
def buildFuzzySystem(showDescription=False):
    """ 
    ===========================================================================
    Build Fuzzy Sistem for variable: cnxs: network connections  
    ===========================================================================   
    
    **Args**:
        showDescription: (boolean)
    **Returns**:
        None
    """
    #==========================================================================
    # Set labels of inputs and outputs
    #==========================================================================

    in1_max = 20000

    var_in1_label = 'cnxs'
    var_out_label = 'out'

    logger.info("buildFuzzySystem:" + var_in1_label)

    #==========================================================================
    # Set numerical range of inputs and outputs
    #==========================================================================

    var_in1_universe = np.arange(0, in1_max, in1_max / 1000)
    var_out_universe = np.arange(0, 1, 0.01)

    #==========================================================================
    # Set inputs(Antecedent) and outputs (Consequent)
    #==========================================================================

    var_in1 = ctrl.Antecedent(var_in1_universe, var_in1_label)
    var_out = ctrl.Consequent(var_out_universe, var_out_label)

    #==========================================================================
    # Set membership functions of fuzzy set
    #==========================================================================

    var_in1.automf(number=3, variable_type='quant')
    var_in1['low'] = fuzz.trimf(var_in1.universe, [0, 0, in1_max * 0.3])
    var_in1['average'] = fuzz.trapmf(
        var_in1.universe, [0, 0.3 * in1_max, 0.7 * in1_max, in1_max])
    var_in1['high'] = fuzz.trimf(var_in1.universe,
                                 [0.7 * in1_max, in1_max, in1_max])

    var_out.automf(number=3, variable_type='quant')

    #==========================================================================
    # Set fuzzy rules
    #==========================================================================

    rule1 = ctrl.Rule(var_in1['high'], var_out['high'])
    rule2 = ctrl.Rule(var_in1['average'], var_out['average'])
    rule3 = ctrl.Rule(var_in1['low'], var_out['low'])

    #==========================================================================
    # Build fuzzy control system and simulation
    #==========================================================================

    var_ctrl = ctrl.ControlSystem([rule1, rule2, rule3])
    var_fuzzysim = ctrl.ControlSystemSimulation(var_ctrl)

    #==========================================================================
    # Set fuzzy rules
    #==========================================================================

    if showDescription:
        fig = plt.figure(figsize=(12, 12))
        plt.subplot(3, 1, 1)
        plt.title('Input: ' + var_in1_label)
        plt.plot(var_in1_universe, var_in1['low'].mf, label='low')
        plt.plot(var_in1_universe, var_in1['average'].mf, label='average')
        plt.plot(var_in1_universe, var_in1['high'].mf, label='high')
        plt.legend()

        plt.subplot(3, 1, 2)
        plt.title('Output: ' + var_out_label)
        plt.plot(var_out_universe, var_out['low'].mf, label='low')
        plt.plot(var_out_universe, var_out['high'].mf, label='high')
        plt.legend()

        var_fuzzysim.input[var_in1_label] = var_in1_universe
        var_fuzzysim.compute()
        y = var_fuzzysim.output[var_out_label]
        plt.subplot(3, 1, 3)
        plt.plot(var_in1_universe,
                 y,
                 label='Fuzzy transform of ' + var_in1_label)

        #plt.show()
        plt.savefig('/tmp/fuzzy_' + var_in1_label + '.png')

    return var_fuzzysim
Example #27
0
theta_dot['to_left'] = fuzz.trimf(theta_dot.universe, [-500, -500, 0])
theta_dot['static'] = fuzz.trimf(theta_dot.universe, [-3, 0, 3])
theta_dot['to_right'] = fuzz.trimf(theta_dot.universe, [0, 500, 500])

force['to_left'] = fuzz.trimf(force.universe, [-env.force_mag, -env.force_mag, 0])
force['static'] = fuzz.trimf(force.universe, [-env.force_mag, 0, env.force_mag])
force['to_right'] = fuzz.trimf(force.universe, [0, env.force_mag, env.force_mag])

# Generate fuzzy rules
rule1 = ctrl.Rule(x['left'] & x_dot['to_left'], force['to_right'])
rule2 = ctrl.Rule(x['right'] & x_dot['to_right'], force['to_left'])
rule3 = ctrl.Rule(theta['left'] & theta_dot['to_left'], force['to_left'])
rule4 = ctrl.Rule(theta['right'] & theta_dot['to_right'], force['to_right'])


my_cartpole_ctrl = ctrl.ControlSystem([rule1, rule2, rule3, rule4])
my_cartpole_ctrl_sim = ctrl.ControlSystemSimulation(my_cartpole_ctrl)

MAX_EPISODES = 20
MAX_EPISODES_STEPS = 200
total_reward = 0

for i_episode in range(MAX_EPISODES):
    observation = env.reset()
    episode_reward = 0
    for timestep in range(MAX_EPISODES_STEPS):
        env.render()
        print(observation)
        my_cartpole_ctrl_sim.inputs({'x': observation[0],
                                     'x_dot': observation[1],
                                     'theta': observation[2],
Example #28
0
def main(in_network, pt_type, ex_type, scratch):

    arcpy.env.overwriteOutput = True

    network_fields = [f.name for f in arcpy.ListFields(in_network)]

    # fix any values outside of fis range
    if pt_type == "true":

        # delete oVC_PT field if exists
        if "oVC_PT" in network_fields:
            arcpy.DeleteField_management(in_network, "oVC_PT")

        cursor = arcpy.da.UpdateCursor(in_network, ["iVeg_100PT", "iVeg_30PT"])
        for row in cursor:
            if row[0] < 0:
                row[0] = 0
            elif row[0] > 4:
                row[0] = 3.9
            elif row[1] < 0:
                row[1] = 0
            elif row[1] > 4:
                row[1] = 3.9
            else:
                pass
            cursor.updateRow(row)
        del row
        del cursor

        # get arrays for fields of interest
        riparian_area_a = arcpy.da.FeatureClassToNumPyArray(
            in_network, "iVeg_100PT")
        streamside_a = arcpy.da.FeatureClassToNumPyArray(
            in_network, "iVeg_30PT")

        riparian_array = np.asarray(riparian_area_a, np.float64)
        streamside_array = np.asarray(streamside_a, np.float64)

        del riparian_area_a, streamside_a

        # set up input and output ranges
        riparian = ctrl.Antecedent(np.arange(0, 4, 0.04), 'input1')
        streamside = ctrl.Antecedent(np.arange(0, 4, 0.04), 'input2')
        density = ctrl.Consequent(np.arange(0, 45, 0.5), 'result')

        # membership functions
        riparian['unsuitable'] = fuzz.trapmf(riparian.universe, [0, 0, 0.1, 1])
        riparian['barely'] = fuzz.trimf(riparian.universe, [0.1, 1, 2])
        riparian['moderately'] = fuzz.trimf(riparian.universe, [1, 2, 3])
        riparian['suitable'] = fuzz.trimf(riparian.universe, [2, 3, 4])
        riparian['preferred'] = fuzz.trimf(riparian.universe, [3, 4, 4])

        streamside['unsuitable'] = fuzz.trapmf(streamside.universe,
                                               [0, 0, 0.1, 1])
        streamside['barely'] = fuzz.trimf(streamside.universe, [0.1, 1, 2])
        streamside['moderately'] = fuzz.trimf(streamside.universe, [1, 2, 3])
        streamside['suitable'] = fuzz.trimf(streamside.universe, [2, 3, 4])
        streamside['preferred'] = fuzz.trimf(streamside.universe, [3, 4, 4])

        density['none'] = fuzz.trimf(density.universe, [0, 0, 0.1])
        density['rare'] = fuzz.trapmf(density.universe, [0, 0.1, 0.5, 1.5])
        density['occasional'] = fuzz.trapmf(density.universe, [0.5, 1.5, 4, 8])
        density['frequent'] = fuzz.trapmf(density.universe, [4, 8, 12, 25])
        density['pervasive'] = fuzz.trapmf(density.universe, [12, 25, 45, 45])

        # rules
        rule1 = ctrl.Rule(riparian['unsuitable'] & streamside['unsuitable'],
                          density['none'])
        rule2 = ctrl.Rule(riparian['barely'] & streamside['unsuitable'],
                          density['rare'])
        rule3 = ctrl.Rule(riparian['moderately'] & streamside['unsuitable'],
                          density['occasional'])
        rule4 = ctrl.Rule(riparian['suitable'] & streamside['unsuitable'],
                          density['occasional'])
        rule5 = ctrl.Rule(riparian['preferred'] & streamside['unsuitable'],
                          density['occasional'])
        rule6 = ctrl.Rule(riparian['unsuitable'] & streamside['barely'],
                          density['rare'])
        rule7 = ctrl.Rule(riparian['barely'] & streamside['barely'],
                          density['rare'])
        rule8 = ctrl.Rule(riparian['moderately'] & streamside['barely'],
                          density['occasional'])
        rule9 = ctrl.Rule(riparian['suitable'] & streamside['barely'],
                          density['frequent'])
        rule10 = ctrl.Rule(riparian['preferred'] & streamside['barely'],
                           density['frequent'])
        rule11 = ctrl.Rule(riparian['unsuitable'] & streamside['moderately'],
                           density['rare'])
        rule12 = ctrl.Rule(riparian['barely'] & streamside['moderately'],
                           density['occasional'])
        rule13 = ctrl.Rule(riparian['moderately'] & streamside['moderately'],
                           density['occasional'])
        rule14 = ctrl.Rule(riparian['suitable'] & streamside['moderately'],
                           density['frequent'])
        rule15 = ctrl.Rule(riparian['preferred'] & streamside['moderately'],
                           density['pervasive'])
        rule16 = ctrl.Rule(riparian['unsuitable'] & streamside['suitable'],
                           density['rare'])
        rule17 = ctrl.Rule(riparian['barely'] & streamside['suitable'],
                           density['frequent'])
        rule18 = ctrl.Rule(riparian['moderately'] & streamside['suitable'],
                           density['frequent'])
        rule19 = ctrl.Rule(riparian['suitable'] & streamside['suitable'],
                           density['frequent'])
        rule20 = ctrl.Rule(riparian['preferred'] & streamside['suitable'],
                           density['pervasive'])
        rule21 = ctrl.Rule(riparian['unsuitable'] & streamside['preferred'],
                           density['occasional'])
        rule22 = ctrl.Rule(riparian['barely'] & streamside['preferred'],
                           density['frequent'])
        rule23 = ctrl.Rule(riparian['moderately'] & streamside['preferred'],
                           density['frequent'])
        rule24 = ctrl.Rule(riparian['suitable'] & streamside['preferred'],
                           density['pervasive'])
        rule25 = ctrl.Rule(riparian['preferred'] & streamside['preferred'],
                           density['pervasive'])

        # FIS
        veg_ctrl = ctrl.ControlSystem([
            rule1, rule2, rule3, rule4, rule5, rule6, rule7, rule8, rule9,
            rule10, rule11, rule12, rule13, rule14, rule15, rule16, rule17,
            rule18, rule19, rule20, rule21, rule22, rule23, rule24, rule25
        ])
        veg_fis = ctrl.ControlSystemSimulation(veg_ctrl)

        out = np.zeros(len(riparian_array))
        for i in range(len(out)):
            veg_fis.input['input1'] = riparian_array[i]
            veg_fis.input['input2'] = streamside_array[i]
            veg_fis.compute()
            out[i] = veg_fis.output['result']

        # save the output text file then merge to shapefile
        fid = np.arange(0, len(out), 1)
        columns = np.column_stack((fid, out))
        out_table = os.path.dirname(in_network) + "/oVC_PT_Table.txt"
        np.savetxt(out_table,
                   columns,
                   delimiter=",",
                   header="FID, oVC_PT",
                   comments="")

        ovc_table = scratch + "/ovc_pt_table"
        arcpy.CopyRows_management(out_table, ovc_table)
        arcpy.JoinField_management(in_network, "FID", ovc_table, "FID",
                                   "oVC_PT")
        arcpy.Delete_management(out_table)

        del out, fid, columns, out_table, ovc_table

    elif ex_type == "true":

        if "oVC_EX" in network_fields:
            arcpy.DeleteField_management(in_network, "oVC_EX")

        cursor = arcpy.da.UpdateCursor(in_network, ["iVeg_100EX", "iVeg_30EX"])
        for row in cursor:
            if row[0] < 0:
                row[0] = 0
            elif row[0] > 4:
                row[0] = 3.9
            elif row[1] < 0:
                row[1] = 0
            elif row[1] > 4:
                row[1] = 3.9
            else:
                pass
            cursor.updateRow(row)
        del row
        del cursor

        # get arrays for fields of interest
        riparian_area_a = arcpy.da.FeatureClassToNumPyArray(
            in_network, "iVeg_100EX")
        streamside_a = arcpy.da.FeatureClassToNumPyArray(
            in_network, "iVeg_30EX")

        riparian_array = np.asarray(riparian_area_a, np.float64)
        streamside_array = np.asarray(streamside_a, np.float64)

        del riparian_area_a, streamside_a

        # set up input and output ranges
        riparian = ctrl.Antecedent(np.arange(0, 4, 0.04), 'input1')
        streamside = ctrl.Antecedent(np.arange(0, 4, 0.04), 'input2')
        density = ctrl.Consequent(np.arange(0, 45, 0.5), 'result')

        # membership functions
        riparian['unsuitable'] = fuzz.trapmf(riparian.universe, [0, 0, 0.1, 1])
        riparian['barely'] = fuzz.trimf(riparian.universe, [0.1, 1, 2])
        riparian['moderately'] = fuzz.trimf(riparian.universe, [1, 2, 3])
        riparian['suitable'] = fuzz.trimf(riparian.universe, [2, 3, 4])
        riparian['preferred'] = fuzz.trimf(riparian.universe, [3, 4, 4])

        streamside['unsuitable'] = fuzz.trapmf(streamside.universe,
                                               [0, 0, 0.1, 1])
        streamside['barely'] = fuzz.trimf(streamside.universe, [0.1, 1, 2])
        streamside['moderately'] = fuzz.trimf(streamside.universe, [1, 2, 3])
        streamside['suitable'] = fuzz.trimf(streamside.universe, [2, 3, 4])
        streamside['preferred'] = fuzz.trimf(streamside.universe, [3, 4, 4])

        density['none'] = fuzz.trimf(density.universe, [0, 0, 0.1])
        density['rare'] = fuzz.trapmf(density.universe, [0, 0.1, 0.5, 1.5])
        density['occasional'] = fuzz.trapmf(density.universe, [0.5, 1.5, 4, 8])
        density['frequent'] = fuzz.trapmf(density.universe, [4, 8, 12, 25])
        density['pervasive'] = fuzz.trapmf(density.universe, [12, 25, 45, 45])

        # rules
        rule1 = ctrl.Rule(riparian['unsuitable'] & streamside['unsuitable'],
                          density['none'])
        rule2 = ctrl.Rule(riparian['barely'] & streamside['unsuitable'],
                          density['rare'])
        rule3 = ctrl.Rule(riparian['moderately'] & streamside['unsuitable'],
                          density['occasional'])
        rule4 = ctrl.Rule(riparian['suitable'] & streamside['unsuitable'],
                          density['occasional'])
        rule5 = ctrl.Rule(riparian['preferred'] & streamside['unsuitable'],
                          density['occasional'])
        rule6 = ctrl.Rule(riparian['unsuitable'] & streamside['barely'],
                          density['rare'])
        rule7 = ctrl.Rule(riparian['barely'] & streamside['barely'],
                          density['rare'])
        rule8 = ctrl.Rule(riparian['moderately'] & streamside['barely'],
                          density['occasional'])
        rule9 = ctrl.Rule(riparian['suitable'] & streamside['barely'],
                          density['frequent'])
        rule10 = ctrl.Rule(riparian['preferred'] & streamside['barely'],
                           density['frequent'])
        rule11 = ctrl.Rule(riparian['unsuitable'] & streamside['moderately'],
                           density['rare'])
        rule12 = ctrl.Rule(riparian['barely'] & streamside['moderately'],
                           density['occasional'])
        rule13 = ctrl.Rule(riparian['moderately'] & streamside['moderately'],
                           density['occasional'])
        rule14 = ctrl.Rule(riparian['suitable'] & streamside['moderately'],
                           density['frequent'])
        rule15 = ctrl.Rule(riparian['preferred'] & streamside['moderately'],
                           density['pervasive'])
        rule16 = ctrl.Rule(riparian['unsuitable'] & streamside['suitable'],
                           density['rare'])
        rule17 = ctrl.Rule(riparian['barely'] & streamside['suitable'],
                           density['frequent'])
        rule18 = ctrl.Rule(riparian['moderately'] & streamside['suitable'],
                           density['frequent'])
        rule19 = ctrl.Rule(riparian['suitable'] & streamside['suitable'],
                           density['frequent'])
        rule20 = ctrl.Rule(riparian['preferred'] & streamside['suitable'],
                           density['pervasive'])
        rule21 = ctrl.Rule(riparian['unsuitable'] & streamside['preferred'],
                           density['occasional'])
        rule22 = ctrl.Rule(riparian['barely'] & streamside['preferred'],
                           density['frequent'])
        rule23 = ctrl.Rule(riparian['moderately'] & streamside['preferred'],
                           density['frequent'])
        rule24 = ctrl.Rule(riparian['suitable'] & streamside['preferred'],
                           density['pervasive'])
        rule25 = ctrl.Rule(riparian['preferred'] & streamside['preferred'],
                           density['pervasive'])

        # FIS
        veg_ctrl = ctrl.ControlSystem([
            rule1, rule2, rule3, rule4, rule5, rule6, rule7, rule8, rule9,
            rule10, rule11, rule12, rule13, rule14, rule15, rule16, rule17,
            rule18, rule19, rule20, rule21, rule22, rule23, rule24, rule25
        ])
        veg_fis = ctrl.ControlSystemSimulation(veg_ctrl)

        out = np.zeros(len(riparian_array))
        for i in range(len(out)):
            veg_fis.input['input1'] = riparian_array[i]
            veg_fis.input['input2'] = streamside_array[i]
            veg_fis.compute()
            out[i] = veg_fis.output['result']

        # save the output text file then merge to shapefile
        fid = np.arange(0, len(out), 1)
        columns = np.column_stack((fid, out))
        out_table = os.path.dirname(in_network) + "/oVC_EX_Table.txt"
        np.savetxt(out_table,
                   columns,
                   delimiter=",",
                   header="FID, oVC_EX",
                   comments="")

        ovc_table = scratch + "/ovc_ex_table"
        arcpy.CopyRows_management(out_table, ovc_table)
        arcpy.JoinField_management(in_network, "FID", ovc_table, "FID",
                                   "oVC_EX")
        arcpy.Delete_management(out_table)

        del out, fid, columns, out_table, ovc_table

    else:
        raise Exception("either historic or existing must be selected")

    return
Example #29
0
 def build(self) -> NoReturn:
     ctrl_system = ctrl.ControlSystem(list(self.rules.values()))
     self.css = ctrl.ControlSystemSimulation(ctrl_system)
    clientID, 'KJunior_motorRight', vrep.simx_opmode_oneshot_wait)

# returnCode, BubbleRobHandle      = vrep.simxGetObjectHandle(clientID, 'bubbleRob',            vrep.simx_opmode_oneshot_wait)
# returnCode, BubbleRobLeftHandle  = vrep.simxGetObjectHandle(clientID, 'bubbleRob_leftMotor',  vrep.simx_opmode_oneshot_wait)
# returnCode, BubbleRobRightHandle = vrep.simxGetObjectHandle(clientID, 'bubbleRob_rightMotor', vrep.simx_opmode_oneshot_wait)

returnCode, LaptopHandle = vrep.simxGetObjectHandle(
    clientID, 'laptop', vrep.simx_opmode_oneshot_wait)

from fcl_parser import FCLParser

# Fuzzy FCL file reader
parser = FCLParser()  # Create the parser
parser.read_fcl_file('wheelRules.fcl')  # Parse a file

wheelControl = ctrl.ControlSystem(parser.rules)
wheelFuzzy = ctrl.ControlSystemSimulation(wheelControl)

KJuniorProxSensors = []
KJuniorProxSensorsVal = []

for i in [1, 2, 4, 5]:
    errorCode, proxSensor = vrep.simxGetObjectHandle(
        clientID, 'KJunior_proxSensor' + str(i), vrep.simx_opmode_oneshot_wait)
    KJuniorProxSensors.append(proxSensor)
    errorCode, detectionState, detectedPoint, detectedObjectHandle, detectedSurfaceNormalVector = vrep.simxReadProximitySensor(
        clientID, proxSensor, vrep.simx_opmode_streaming)
    distance = round(2000 - np.linalg.norm(detectedPoint) * 20000, 2)
    if distance <= 0 or distance == 2000:
        distance = 0
    KJuniorProxSensorsVal.append(distance)