Why do my fuzzy rules not fire? - rules

I have created a fuzzy rulebase for a project.I am currently testing to see if the rules work. I am trying to explicitly test Rule 7 from the below given rules (though the fuzzy controller has all the rules written in them).
RULE 7 : IF hotelClass IS aboveAverage AND travellerType IS familyMan AND room IS poor THEN trustWeight IS medium;
I am planning to keep the "hotelClass", "travllerType" constant while only changing the "room" values to check how the output behaves. The code for that is:
for (double room = 0.0; room <= 10; room += 0.1) {
fis.getVariable("room").setValue(room);
fis.getVariable("hotelClass").setValue(5);
fis.getVariable("travellerType").setValue(travellerType);
fis.evaluate();
// Print result & update plot
System.out.println(String.format("Room: %2.2f\t=> tweight: %2.2f ", room, fis.getVariable("trustWeight").getValue()));
}
But it seems that when I have all my rules in place, the rules dont get hit, leaving the output fuzzy set values to remain at 0. But I have no problem, when my fuzzy controller only has that one rule.
These are my rules from the original controller file:
RULE 1 : IF hotelClass IS aboveAverage AND travellerType IS businessMan AND room IS poor THEN trustWeight IS high;
RULE 2 : IF hotelClass IS aboveAverage AND travellerType IS businessMan AND service IS poor THEN trustWeight IS high;
RULE 3 : IF hotelClass IS aboveAverage AND travellerType IS businessMan AND room IS excellent THEN trustWeight IS less;
RULE 4 : IF hotelClass IS aboveAverage AND travellerType IS businessMan AND service IS excellent THEN trustWeight IS less;
RULE 5 : IF hotelClass IS aboveAverage AND travellerType IS businessMan AND room IS good THEN trustWeight IS medium;
RULE 6 : IF hotelClass IS aboveAverage AND travellerType IS businessMan AND service IS good THEN trustWeight IS medium;
RULE 7 : IF hotelClass IS aboveAverage AND travellerType IS familyMan AND room IS poor THEN trustWeight IS medium;
RULE 8 : IF hotelClass IS aboveAverage AND travellerType IS familyMan AND service IS poor THEN trustWeight IS medium;
RULE 9 : IF hotelClass IS aboveAverage AND travellerType IS familyMan AND room IS excellent THEN trustWeight IS medium;
RULE 10 : IF hotelClass IS aboveAverage AND travellerType IS familyMan AND service IS excellent THEN trustWeight IS medium;
RULE 11 : IF hotelClass IS aboveAverage AND travellerType IS familyMan AND room IS good THEN trustWeight IS high;
RULE 12 : IF hotelClass IS aboveAverage AND travellerType IS familyMan AND service IS good THEN trustWeight IS high;
Additional information :
I am making use of "Center Of Gravity" defuzzification method to
obtainvalues for the "trustweight"
My fuzzy variables and sets are given below as well
Can anyone tell me what or where I am going wrong? Any comments, pointers, explanations etc, will really help.

Have you tried making sure there are no contradictions in the rules? What would happen if the room was poor and the service was excellent?

Related

Size of Binary Tree: wrong result when submitting code to online judge

I was trying to solve GeeksForGeeks problem Size of Binary Tree:
Given a binary tree of size N, you have to count number of nodes in it. For example, count of nodes in below tree is 4.
1
/ \
10 39
/
5
Unfortunately for the test case below I'm getting "incorrect answer" on my recursive code. Can someone tell me where I'm going wrong?
Input:
2 // Number of test cases
1 2 3 // Test Case #1
10 5 9 N 1 3 6 // Test Case #2
My Output:
3
9
Expected Output:
3
6
My Code:
/* Tree node structure used in the program
struct Node
{
int data;
Node* left;
Node* right;
}; */
/* Computes the number of nodes in a tree. */
int nodes=0;
void dfs(Node* node) {
if (node==NULL) return;
++nodes;
// cout << node->data << " ";
dfs(node->left);
dfs(node->right);
}
int getSize(Node* node)
{
// Your code here
dfs(node);
return nodes;
}
The mistake is that your code has a global int nodes that is only initialised once. When getSize is called multiple times, then only at the first call you can be sure it really is zero. All other calls will just keep incrementing that counter without it having been reset.
So either reset that counter just before the call to dfs is made, or -- better -- redesign your code so that you don't need a global counter at all, for example by having dfs return a counter. And if you do that, you can even make getSize recursive itself, without any need of a separate dfs function.
NB: don't use NULL in C++, but nullptr.
Here is a spoiler solution:
int getSize(Node* node) {
if (node==nullptr) return 0;
return 1 + getSize(node->left) + getSize(node->right);
}

How to validate code that read/write to hardware memory mapped registers (mmio) with frama-c Eva plugin or WP-RTE?

The closest answer I found maybe related to -absolute-valid-range for the Eva plugin but is that it? Do I have to come up with read/write ACSL predicates to do dummy read/write?
Sample code:
#include <stdint.h>
#define BASE_ADDR 0x0e000000
#define BASE_LIMIT 0x0e001000
#define TEST_REG 0x10
/*# requires BASE_ADDR <= addr < BASE_LIMIT;
# assigns \nothing;
*/
static inline uint32_t mmio_read32(volatile uintptr_t addr)
{
volatile uint32_t *ptr = (volatile uint32_t *)addr;
return *ptr;
}
/*#
# requires 0 <= offset <= 0x1000;
# assigns \nothing;
*/
static inline uint32_t read32(uintptr_t offset)
{
return mmio_read32((uintptr_t)BASE_ADDR + offset);
}
void main(){
uint32_t test;
test = read32(TEST_REG);
return;
}
Frama-c command and output:
[frama -absolute-valid-range 0x0e000000-0x0e001000 -wp mmio2.c
[kernel] Parsing mmio2.c (with preprocessing)
[wp] Warning: Missing RTE guards
[wp] 6 goals scheduled
[wp] [Alt-Ergo] Goal typed_read32_call_mmio_read32_pre : Unknown (Qed:4ms) (51ms)
[wp] Proved goals: 5 / 6
Qed: 5
Alt-Ergo: 0 (unknown: 1)][1]
How to discharge goal "typed_read32_call_mmio_read32_pre" or is this expected?
The fact that the proof fails is related to two independent issues, but none of them is related to using absolute addresses.
First, as the argument of mmio_read32 is marked as volatile, WP consider that its value can be anything. In particular, none of the hypotheses that are made on offset are known to hold when evaluating addr. You can see that in the GUI by looking at the generated goal (go in the WP Goals tab at the bottom and double click in the Script colon and the line of the failed proof attempt):
Goal Instance of 'Pre-condition'
(call 'mmio_read32'):
Assume {
Type: is_uint32(offset_0).
(* Pre-condition *)
Have: (0 <= offset_0) /\ (offset_0 <= 4095).
}
Prove: (234881024 <= w) /\ (w_1 <= 234885119).
w and w_1 correspond to two read accesses to the volatile content of addr. I'm not sure if you really intended the addr parameter to be volatile (as opposed to a non-volatile pointer to a volatile location), as this would require a pretty weird execution environment.
Assuming that the volatile qualifier should not present in the declaration of addr, a remaining issue is that the constraint on offset in read32 is too weak: it should read offset < 0x1000 with a strict inequality (or the precondition of mmio_read32 be made non-strict, but again this would be quite uncommon).
Regarding the initial question about physical adressing and volatile, in ACSL (see section 2.12.1 of the manual), you have a specific volatile clause that allows you to specify (C, usually ghost) functions to represent read and write accesses to volatile locations. Unfortunately, support for these clauses is currently only accessible through a non-publicly distributed plug-in.
I'm afraid that if you want to use WP on code with physical adressing, you need indeed to use an encoding (e.g. with a ghost array of appropriate size), and/or model volatile accesses with appropriate functions.

Recursive Newton Square Root Function Only Terminates for Perfect Squares

I wrote a program that looks very similar to other recursive newton square root functions I have seen on the web. For some reason this one only works with perfect squares and I can't seem to find a reason why. I have tried passing 3 variables(epsilon), setting x=a, setting a = to the equation passed in line 9 then passing abs(a*a-x). I tried to describe it the best I could it's a slightly new topic for me and I am just not sure if this is only capable of finding perfect roots or if my code/equation is incorrect.
1 #include <cmath>
2 #include <iostream>
3 using namespace std;
4
5 double newtroot(double x, double a) {
6 if (fabs(a*a - x) <= DBL_EPSILON)
7 return a;
8 else
9 return newtroot(x, fabs(a*a + x)/(2*a));
10 }
11
12 int main() {
13 cout << newtroot(9, 1) << endl;
14 system("pause");
15 return 0;
16 }
EDIT: The function does not only work for perfect squares but it only returns correctly for perfect squares. If it is not a perfect square a ends up being the correct value (checked in the debugger) but the recursion never stops. I figured it must be something with the comparison in line 6 so I tried replacing DBL_EPSILON with a and the incorrect value is returned.
This error also shows on line 6 when a non-perfect square is entered:
Unhandled exception at 0x00007FFE8E9C06F0 (ucrtbased.dll) in RecursionProgrammingExcercisesMurphyT.exe: 0xC00000FD: Stack overflow (parameters: 0x0000000000000001, 0x00000013B2603FE8). occurred
Not detecting the base case is due to an overly optimistic interpretation:
DBL_EPSILON is not "a value suitable to terminate improving any approximation," but
Difference between 1 and the least value greater than 1 that is representable:
it needs to be scaled to limit relative error.
return (fabs(approx*approx - x) <= 2*x*DBL_EPSILON) ? approx
        : newtroot(x, fabs(approx*approx + x)/(2*approx));
When an approximation is fast enough to tolerate numerical errors, a promising approach to terminate it is to check that the new approximate value is neither the current nor the previous one.
/*! approximate the value of x**.5 */
double newtroot(double x, double approx, double previous) {
double next = fabs(approx*approx + x)/(2*approx);
return next == approx || next == previous
? approx : newtroot(x, next, approx);
}

Don't laugh, but what on earth am i missing?

OK, I probably have no business trying to learn an OOP and I'm having trouble with the simplest little first program. I am getting a message that my implementation is incomplete (I commented the line that is giving 4 errors below). What is wrong? It wants a type specifier among other things, but don't I give it one with NSString? I do notice that NSString doesn't change color to a green type color in XCODE in the implementation like it does in the interface.
ALSO, why do we need to declare the method in the interface and type the exact same thing in the implementation? that is, why the need to type the startDrinking: (NSString*) newBeverage in both?
#import <Foundation/Foundation.h>
#interface Drinks : NSObject {
NSString *beverage;
}
- (void) startDrinking: (NSString*) newBeverage; // setter
- (void) printDrink;
#end
#implementation Drinks
{
//THIS NEXT LINE IS WHERE I GET 4 ERRORS
- (void) startDrinking: (NSString *) newBeverage {
beverage = [[NSString alloc]initwithString:newBeverage]
}
-(void) printDrink {
NSLog(#"How is your", beverage);
}
}
#end
int main (int argc, const char * argv[]) {
Drinks *beverage = [[Drinks alloc] init];
[beverage startDrinking:#"Lemonade"];
return 0;
}
Your question is too chatty.
You missed a semi-colon in line beverage = [[NSString alloc]initwithString:newBeverage]
The line should be :
beverage = newBeverage;
and the NSLog line should be:
NSLog(#"How is your %#", beverage);
and for the declaration of method signature in header, it is followed by C and C++ . You can think of, the Compiler needs to know which functions are available first.
Your mistake is the { right below #implementation Drinks.
That's why the alignment is messed up too.
In general, if you can't find an error on the line it is reported on, just check any extraneous or missing parenthesis, brackets or braces.
The weird alignment is another clue to this.
Hope this helps. Also, like some other said, it helps if your subject is more meaningful. Not just for yourself, but also for any others that might be having a similar problem

FSM data structure design

I want to write an FSM which starts with an idle state and moves from one state to another based on some event. I am not familiar with coding of FSM and google didn't help.
Appreciate if someone could post the C data structure that could be used for the same.
Thanks,
syuga2012
We've implemented finite state machine for Telcos in the past and always used an array of structures, pre-populated like:
/* States */
#define ST_ANY 0
#define ST_START 1
: : : : :
/* Events */
#define EV_INIT 0
#define EV_ERROR 1
: : : : :
/* Rule functions */
int initialize(void) {
/* Initialize FSM here */
return ST_INIT_DONE
}
: : : : :
/* Structures for transition rules */
typedef struct {
int state;
int event;
(int)(*fn)();
} rule;
rule ruleset[] = {
{ST_START, EV_INIT, initialize},
: : : : :
{ST_ANY, EV_ERROR, error},
{ST_ANY, EV_ANY, fatal_fsm_error}
};
I may have the function pointer fn declared wrong since this is from memory. Basically the state machine searched the array for a relevant state and event and called the function which did what had to be done then returned the new state.
The specific states were put first and the ST_ANY entries last since priority of the rules depended on their position in the array. The first rule that was found was the one used.
In addition, I remember we had an array of indexes to the first rule for each state to speed up the searches (all rules with the same starting state were grouped).
Also keep in mind that this was pure C - there may well be a better way to do it with C++.
A finite state machine consists of a finite number discrete of states (I know pedantic, but still), which can generally be represented as integer values. In c or c++ using an enumeration is very common.
The machine responds to a finite number of inputs which can often be represented with another integer valued variable. In more complicated cases you can use a structure to represent the input state.
Each combination of internal state and external input will cause the machine to:
possibly transition to another state
possibly generate some output
A simple case in c might look like this
enum state_val {
IDLE_STATE,
SOME_STATE,
...
STOP_STATE
}
//...
state_val state = IDLE_STATE
while (state != STOP_STATE){
int input = GetInput();
switch (state) {
case IDLE_STATE:
switch (input) {
case 0:
case 3: // note the fall-though here to handle multiple states
write(input); // no change of state
break;
case 1:
state = SOME_STATE;
break
case 2:
// ...
};
break;
case SOME_STATE:
switch (input) {
case 7:
// ...
};
break;
//...
};
};
// handle final output, clean up, whatever
though this is hard to read and more easily split into multiple function by something like:
while (state != STOP_STATE){
int input = GetInput();
switch (state) {
case IDLE_STATE:
state = DoIdleState(input);
break;
// ..
};
};
with the complexities of each state held in it's own function.
As m3rLinEz says, you can hold transitions in an array for quick indexing. You can also hold function pointer in an array to efficiently handle the action phase. This is especially useful for automatic generation of large and complex state machines.
The answers here seem really complex (but accurate, nonetheless.) So here are my thoughts.
First, I like dmckee's (operational) definition of an FSM and how they apply to programming.
A finite state machine consists of a
finite number discrete of states (I
know pedantic, but still), which can
generally be represented as integer
values. In c or c++ using an
enumeration is very common.
The machine responds to a finite
number of inputs which can often be
represented with another integer
valued variable. In more complicated
cases you can use a structure to
represent the input state.
Each combination of internal state and
external input will cause the machine
to:
possibly transition to another state
possibly generate some output
So you have a program. It has states, and there is a finite number of them. ("the light bulb is bright" or "the light bulb is dim" or "the light bulb is off." 3 states. finite.) Your program can only be in one state at a time.
So, say you want your program to change states. Usually, you'll want something to happen to trigger a state change. In this example, how about we take user input to determine the state - say, a key press.
You might want logic like this. When the user presses a key:
If the bulb is "off" then make the bulb "dim".
If the bulb is "dim", make the bulb "bright".
If the bulb is "bright", make the bulb "off".
Obviously, instead of "changing a bulb", you might be "changing the text color" or whatever it is you program needs to do. Before you start, you'll want to define your states.
So looking at some pseudoish C code:
/* We have 3 states. We can use constants to represent those states */
#define BULB_OFF 0
#define BULB_DIM 1
#define BULB_BRIGHT 2
/* And now we set the default state */
int currentState = BULB_OFF;
/* now we want to wait for the user's input. While we're waiting, we are "idle" */
while(1) {
waitForUserKeystroke(); /* Waiting for something to happen... */
/* Okay, the user has pressed a key. Now for our state machine */
switch(currentState) {
case BULB_OFF:
currentState = BULB_DIM;
break;
case BULB_DIM:
currentState = BULB_BRIGHT;
doCoolBulbStuff();
break;
case BULB_BRIGHT:
currentState = BULB_OFF;
break;
}
}
And, voila. A simple program which changes the state.
This code executes only a small part of the switch statement - depending on the current state. Then it updates that state. That's how FSMs work.
Now here are some things you can do:
Obviously, this program just changes the currentState variable. You'll want your code to do something more interesting on a state change. The doCoolBulbStuff() function might, i dunno, actually put a picture of a lightbulb on a screen. Or something.
This code only looks for a keypress. But your FSM (and thus your switch statement) can choose state based on what the user inputted (eg, "O" means "go to off" rather than just going to whatever is next in the sequence.)
Part of your question asked for a data structure.
One person suggested using an enum to keep track of states. This is a good alternative to the #defines that I used in my example. People have also been suggesting arrays - and these arrays keep track of the transitions between states. This is also a fine structure to use.
Given the above, well, you could use any sort of structure (something tree-like, an array, anything) to keep track of the individual states and define what to do in each state (hence some of the suggestions to use "function pointers" - have a state map to a function pointer which indicates what to do at that state.)
Hope that helps!
See Wikipedia for the formal definition. You need to decide on your set of states S, your input alphabet Σ and your transition function δ. The simplest representation is to have S be the set of integers 0, 1, 2, ..., N-1, where N is the number of states, and for Σ be the set of integers 0, 1, 2, ..., M-1, where M is the number of inputs, and then δ is just a big N by M matrix. Finally, you can store the set of accepting states by storing an array of N bits, where the ith bit is 1 if the ith state is an accepting state, or 0 if it is not an accepting state.
For example, here is the FSM in Figure 3 of the Wikipedia article:
#define NSTATES 2
#define NINPUTS 2
const int transition_function[NSTATES][NINPUTS] = {{1, 0}, {0, 1}};
const int is_accepting_state[NSTATES] = {1, 0};
int main(void)
{
int current_state = 0; // initial state
while(has_more_input())
{
// advance to next state based on input
int input = get_next_input();
current_state = transition_function[current_state][input];
}
int accepted = is_accepting_state[current_state];
// do stuff
}
You can basically use "if" conditional and a variable to store the current state of FSM.
For example (just a concept):
int state = 0;
while((ch = getch()) != 'q'){
if(state == 0)
if(ch == '0')
state = 1;
else if(ch == '1')
state = 0;
else if(state == 1)
if(ch == '0')
state = 2;
else if(ch == '1')
state = 0;
else if(state == 2)
{
printf("detected two 0s\n");
break;
}
}
For more sophisticated implementation, you may consider store state transition in two dimension array:
int t[][] = {{1,0},{2,0},{2,2}};
int state = 0;
while((ch = getch()) != 'q'){
state = t[state][ch - '0'];
if(state == 2){
...
}
}
A few guys from AT&T, now at Google, wrote one of the best FSM libraries available for general use. Check it out here, it's called OpenFST.
It's fast, efficient, and they created a very clear set of operations you can perform on the FSMs to do things like minimize them or determinize them to make them even more useful for real world problems.
if by FSM you mean finite state machine,
and you like it simple, use enums to name your states
and switch betweem them.
Otherwise use functors. you can look the
fancy definition up in the stl or boost docs.
They are more or less objects, that have a
method e.g. called run(), that executes
everything that should be done in that state,
with the advantage that each state has it's own
scope.

Resources