FuzzyCLIPS Version 6.02A User's Guide Knowledge Systems Laboratory Institute for Information Technology National Research Council Canada September 1994 Abstract FuzzyCLIPS is an extended version of the CLIPS rule-based shell for representing and manipulating fuzzy facts and rules. In addition to the CLIPS functionality, FuzzyCLIPS can deal with exact, fuzzy (or inexact), and combined reasoning, allowing fuzzy and normal terms to be freely mixed in the rules and facts of an expert system. The system uses two basic inexact concepts, fuzziness and uncertainty. 1.0 Introduction 1 2.0 Licence for NRC Software 2 2.1 Title and Conditions 2 2.2 Record of Use 2 2.3 Value of the Software 2 2.4 Warranty 2 3.0 Installation Information 3 3.1 Unix Version (Sun) 7 3.2 IBM PC version 9 3.3 Macintosh version 10 4.0 Fuzzy Expert Systems 12 4.1 Fuzziness 12 4.2 Uncertainty 16 4.3 Inference techniques 17 4.3.1 Simple rules 17 4.3.2 Complex rules 25 4.3.3 Global contribution 27 4.3.4 Threshold certainty factors 28 4.3.5 Certainty factors in assert statements 30 4.4 Defuzzification 32 4.4.1 Centre of gravity algorithm 32 4.4.2 Mean of maxima algorithm 33 5.0 Using the FuzzyCLIPS extensions 36 5.1 Defining Fuzzy Variables in Deftemplate Constructs 36 5.1.1 Primary terms 37 5.2 Standard Deftemplate Definitions with Fuzzy Slots (fields) 43 5.3 Modifiers (Hedges) and Linguistic Expressions 45 5.3.1 Predefined Modifiers 45 5.3.2 User Defined Modifiers 52 5.3.3 Linguistic Expressions 55 5.4 Using Fuzzy Variables in LHS Patterns 57 5.5 Using Fuzzy Variables in Deffacts Constructs 59 5.6 Using Fuzzy Variables in Assert Statements 60 5.7 Defuzzification 62 5.8 Certainty Factors of Rules 63 5.9 FuzzyCLIPS Commands and Functions 64 5.9.1 Accessing the universe of discourse (get-u, get-u-from, get-u-to, get-u-units) 64 5.9.2 Accessing the fuzzy set (get-fs, get-fs-x, get-fs-y, get-fs-length, get-fs-lv, get-fs-value) 67 5.9.3 Accessing the certainty factor (get-cf) 70 5.9.4 Accessing the threshold certainty factor (threshold, get-threshold) 70 5.9.5 Setting the Rule CF Evaluation Behaviour (set-CF-evaluation, set-CF-evaluation) 70 5.9.6 Controlling the Fuzzy Set Display Precision (set-fuzzy-display-precision, get-fuzzy-display-precision) 71 5.9.7 Controlling the Fuzzy Inference Method (set-fuzzy-inference-type, get-fuzzy-inference-type) 72 5.9.8 Setting the Fuzzy Pattern Matching Threshold (set-fuzzy-inference-type, get-fuzzy-inference-type) 72 5.9.9 Fuzzy Value Predicate Function (fuzzvaluep) 74 5.9.10 Creating and operating on FUZZY-VALUEs (create-fuzzy-value, fuzzy-union, fuzzy-intersection, fuzzy-modify) 75 5.9.11 Accessing a Fuzzy Slot in a Fact (get-fuzzy-slot) 79 5.9.12 Displaying a Fuzzy Value in a Format function 79 5.9.13 Plotting a Fuzzy Value (plot-fuzzy-value) 80 5.10 Simple example 84 6.0 Continuous Systems 85 7.0 CLIPS Functionality within FuzzyCLIPS 87 7.1 Modifying and Duplicating Facts 87 7.2 Load, Save, Bload, Bsave, Load-facts, Save-facts 87 7.3 Constructs-to-c 87 7.4 CreateFact, GetFactSlot, PutFactSlot 87 8.0 Changes from the CLIPS 6.02 Version of FuzzyCLIPS to 6.02A 88 8.1 Vertical lines in fuzzy sets 88 8.2 Expanded Syntax for Linguistic Expressions 89 8.3 Linguistic Expresions in Fuzzy Deftemplate Definitions 89 8.4 Fuzzy Modifiers (Hedges) are Handled in a New Way 90 8.5 Plotting of Fuzzy Values 90 8.6 Fuzzy Alpha Value to Set Threshold for Fuzzy Pattern Matches 90 8.7 Two New Functions for Accessing Fuzzy Value Information 90 8.8 New Functions for Creating and Manipulating Fuzzy Values (external to facts) 90 8.9 Ability to Set Inference Type to Max-min or Max-prod 91 8.10 Ability to Control Precision of Fuzzy Set Values When Displayed 91 8.11 Fuzzy Slots allowed in Standard Deftemplates 91 8.12 Accessing a Fuzzy Slot in a Fuzzy Deftemplate Fact or a Fuzzy Fact 91 8.13 Printing Fuzzy Values in a Format Function 91 9.0 Limitations and Future Work 92 10.0 References 95 Appendix A: Shower Example 97 1.0 Introduction This report describes changes made at the National Research Council to implement a fuzzy expert system shell on top of CLIPS ([\x111], [\x112]). This extended version of CLIPS is called FuzzyCLIPS. The modifications made to CLIPS contain the capability of handling fuzzy concepts and reasoning. It enables domain experts to express rules using their own fuzzy terms. It allows any mix of fuzzy and normal terms, numeric-comparison logic con- trols, and uncertainties in the rules and facts. Fuzzy sets and relations deal with fuzziness in approximate reasoning, while certainty factors for rules and facts manipulate the uncer- tainty. The use of the above modifications are optional and existing CLIPS programs still execute correctly. Section \x112.0 describes restrictions and conditions of use for Fuzzy- CLIPS. Section \x113.0 gives information on how to install FuzzyCLIPS at your site. Section \x114.0 describes the changes made to CLIPS to implement fuzzy expert systems, and gives some theoretical background on fuzzy logic. Section \x115.0 describes how to use the changes made at the NRC. Section \x116.0 discusses the further changes made to CLIPS to accommo- date the needs of continuously operating systems. Section \x118.0 describes changes between the current version of FuzzyCLIPS and version 6.02 of FuzzyCLIPS. Section \x119.0 briefly discusses some of the limitations of FuzzyCLIPS and what future work could be done. 2.0 Licence for NRC Software This software is provided by The National Research Council of Canada (called NRC) whose address for communications with respect to this software is: Knowledge Systems Laboratory Institute for Information Technology National Research Council Canada Ottawa, Ontario Canada K1A 0R6 Electronic mail: fzclips@ai.iit.nrc.ca 2.1 Title and Conditions NRC provides a fully paid up and non exclusive licence to the software package with the following conditions: 1. The software will be used for educational and research purposes only. 2. The licence does not include the right to sublicense the software, or to make it avail- able for independent use by third parties outside the recipient organization. 3. Copies of the software may be made for use within the recipient organization, how- ever, copyright remains with NRC. 4. All publications arising from the use of the software shall duly acknowledge such use in accordance with normal practices followed in scientific research publications. 5. The software is provided in its current state and NRC assumes no obligation to provide services, for example maintenance or updates. 6. All users are requested to provide their name, the name of their organization and a mailing or email address so that we may track the use of the software as well as pro- vide information to users as updates and enhancements are made. 2.2 Record of Use Users are requested to inform NRC of any corrections, changes or extensions to the soft- ware. NRC would also appreciate being informed of noteworthy uses. 2.3 Value of the Software This software is considered to have no market value. 2.4 Warranty NRC disclaims any warranties, expressed, implied, or statutory, of any kind or nature with respect to the software, including without limitation any warranty of fitness for a particu- lar purpose. NRC shall not be liable in any event for damages, whether direct or indirect, special or general, consequential or incidental, arising from the use of the software. 3.0 Installation Information FuzzyCLIPS has been successfully compiled and tested on the following machines: Sun Sparc workstations (using cc compiler) IBM PC DOS machines (using Borland C++ 4.0 [huge model ONLY]) Macintosh II (using the MPW C 3.3 compiler) FuzzyCLIPS is available via anonymous ftp from ai.iit.nrc.ca and via the World Wide Web (WWW) using URL designation http://ai.iit.nrc.ca/fuzzy/fuzzy.html. After connect- ing to the system with ftp do the following: 1. cd pub/fzclips 2. binary (binary transfers are required) 3. get fzclips.tar.Z (unix version - compiled for sun workstation - tar'd and compressed) or get fzclips.sea.hqx (Macintosh version - self extracting archive format created with Stuffit Deluxe then converted to binhex format) or get fzclips.exe (PC version - self extracting archive format created with PAK) \x11\x11\x11\x11\x11or get fzdocs.ps (FuzzyCLIPS documentation - postscript file) The documentation is only included with the unix version (fzclips.tar.Z - both postscript format and framemaker format). If the framemaker files are required by others then they can be made available on request. If using the WWW to access FuzzyCLIPS you will be prompted to provide your name and address of your organization and then will be able to access one or all of the documents. On a unix system the following commands are used to install FuzzyCLIPS. uncompress fzclips.tar.Z \x11\x11(only required if accessed from ftp; WWW will automatically \x11\x11uncompress the file) tar -xvf fzclips.tar On a Macintosh system use a Binhex program to extract the fzclips.sea file then double- click on the fzclips.sea file and it will automatically uncompress and install the system. Note that if you have a version of the Stuffit file compression program you could extract only the parts that you need instead of the entire system. On a PC system the program fzclips.exe when executed will uncompress and install the FuzzyCLIPS system. Execute the program with the following commands: mkdir \fzcl602A - create a directory for the files to be unpacked into; the \x11fzclips.exe file should be in this directory cd \fzcl602A fzclips /path - the /path is necessary to recreate the correct directory \x11structure; if omitted then all files will be placed in the \x11current directory without any sub-directories. If you have a version of the PAK archiving/compression program then you could extract only the parts that you need instead of the entire system. Other files of interest found on the ftp site in the directory pub/fzclips are: README - general information including much of the above README.BUGS - A discussion of bugs or other issues concerning the current version of FuzzyCLIPS. Normally there will be a discussion of what to do to fix the system. fixes.602A - the source files that have been modified to fix problems reported in the README.BUGS file. docs.MIF - the set of documentation files in `Maker Interchange Format' as produced by Framemaker wxfuzzy.tar.Z - FuzzyCLIPS combined with wxCLIPS (unix format) wxfuzzy.zip - FuzzyCLIPS combined with wxCLIPS (PC format) The following is a list of files included for all systems. Those marked with an exclamation mark (!) are new files that have been added to CLIPS to support FuzzyCLIPS. agenda.c analysis.c argacces.c bload.c bmathfun.c bsave.c (!)cfdef.c classcom.c classexm.c classfun.c classinf.c classini.c classpsr.c clsltpsr.c commline.c conscomp.c constrct.c constrnt.c crstrtgy.c cstrcbin.c cstrccom.c cstrcpsr.c cstrnbin.c cstrnchk.c cstrncmp.c cstrnops.c cstrnpsr.c cstrnutl.c default.c defins.c developr.c dffctbin.c dffctbsc.c dffctcmp.c dffctdef.c dffctpsr.c dffnxbin.c dffnxcmp.c dffnxexe.c dffnxfun.c dffnxpsr.c dfinsbin.c dfinscmp.c drive.c edbasic.c edmain.c edmisc.c edstruct.c edterm.c emathfun.c engine.c evaluatn.c expressn.c exprnbin.c exprnops.c exprnpsr.c extnfunc.c factbin.c factbld.c factcmp.c factcom.c factgen.c facthsh.c factlhs.c factmch.c factmngr.c factprt.c factrete.c factrhs.c filecom.c filertr.c generate.c genrcbin.c genrccmp.c genrccom.c genrcexe.c genrcfun.c genrcpsr.c globlbin.c globlbsc.c globlcmp.c globlcom.c globldef.c globlpsr.c immthpsr.c incrrset.c inherpsr.c inscom.c insfile.c insfun.c insmngr.c insmoddp.c insmult.c inspsr.c insquery.c insqypsr.c iofun.c lgcldpnd.c macmain.c main.c memory.c miscfun.c modulbin.c modulbsc.c modulcmp.c moduldef.c modulpsr.c modulutl.c msgcom.c msgfun.c msgpass.c msgpsr.c multifld.c multifun.c objbin.c objcmp.c objrtbin.c objrtbld.c objrtcmp.c objrtfnx.c objrtgen.c objrtmch.c pattern.c pprint.c prccode.c prcdrfun.c prcdrpsr.c prdctfun.c prntutil.c reorder.c reteutil.c retract.c router.c rulebin.c rulebld.c rulebsc.c rulecmp.c rulecom.c rulecstr.c ruledef.c ruledlt.c rulelhs.c rulepsr.c scanner.c strngfun.c strngrtr.c symblbin.c symblcmp.c symbol.c sysdep.c textpro.c tmpltbin.c tmpltbsc.c tmpltcmp.c tmpltcom.c tmpltdef.c tmpltfun.c tmpltlhs.c tmpltpsr.c tmpltrhs.c utility.c watch.c (!)fuzzycom.c (!)fuzzydef.c (!)fuzzylhs.c (!)fuzzymod.c (!)fuzzypsr.c (!)fuzzyrhs.c (!)fuzzyutl.c agenda.h analysis.h argacces.h bload.h bmathfun.h bsave.h (!)cfdef.h classcom.h classexm.h classfun.h classinf.h classini.h classpsr.h clips.h clipsmem.h clsltpsr.h commline.h conscomp.h constant.h constrct.h constrnt.h crstrtgy.h cstrcbin.h cstrccmp.h cstrccom.h cstrcpsr.h cstrnbin.h cstrnchk.h cstrncmp.h cstrnops.h cstrnpsr.h cstrnutl.h default.h defins.h developr.h dffctbin.h dffctbsc.h dffctcmp.h dffctdef.h dffctpsr.h dffnxbin.h dffnxcmp.h dffnxexe.h dffnxfun.h dffnxpsr.h dfinsbin.h dfinscmp.h drive.h ed.h engine.h evaluatn.h expressn.h exprnbin.h exprnops.h exprnpsr.h extnfunc.h extobj.h factbin.h factbld.h factcmp.h factcom.h factgen.h facthsh.h factlhs.h factmch.h factmngr.h factprt.h factrete.h factrhs.h filecom.h filertr.h generate.h genrcbin.h genrccmp.h genrccom.h genrcexe.h genrcfun.h genrcpsr.h globlbin.h globlbsc.h globlcmp.h globlcom.h globldef.h globlpsr.h immthpsr.h incrrset.h inherpsr.h inscom.h insfile.h insfun.h insmngr.h insmoddp.h insmult.h inspsr.h insquery.h insqypsr.h lgcldpnd.h match.h miscfun.h modulbin.h modulbsc.h modulcmp.h moduldef.h modulpsr.h modulutl.h msgcom.h msgfun.h msgpass.h msgpsr.h multifld.h multifun.h network.h objbin.h objcmp.h object.h objrtbin.h objrtbld.h objrtcmp.h objrtfnx.h objrtgen.h objrtmch.h pattern.h pprint.h prccode.h prcdrfun.h prcdrpsr.h prntutil.h reorder.h reteutil.h retract.h router.h rulebin.h rulebld.h rulebsc.h rulecmp.h rulecom.h rulecstr.h ruledef.h ruledlt.h rulelhs.h rulepsr.h scanner.h setup.h shrtlnkn.h strngfun.h strngrtr.h symblbin.h symblcmp.h symbol.h sysdep.h tmpltbin.h tmpltbsc.h tmpltcmp.h tmpltcom.h tmpltdef.h tmpltfun.h tmpltlhs.h tmpltpsr.h tmpltrhs.h utility.h watch.h cmptblty.h (!)fuzzycom.h (!)fuzzydef.h (!)fuzzylhs.h (!)fuzzylv.h (!)fuzzymod.h (!)fuzzypsr.h (!)fuzzyrhs.h (!)fuzzyutl.h (!)fuzzyval.h clips.hlp \x11\x11\x11- this file may appear in a different directory from those above All of the executable files distributed with FuzzyCLIPS have been created to include fuzzy facts and reasoning, certainty factors, and runtime extensions (see section 6.0). Any or all of these three components can be selectively removed from inclusion in the system by modifying the file setup.h and recompiling and linking FuzzyCLIPS. The following FLAGS in setup.h are set to 1 to include the feature and to 0 to exclude the feature: FUZZY_DEFTEMPLATES - for fuzzy facts and reasoning CERTAINTY_FACTORS - for certainty factors EXTENDED_RUN_OPTIONS - for extended runtime options The next 3 sections describe the file structures and contents of directories for each of the unix (Sun), Macintosh, and PC versions of FuzzyCLIPS. 3.1 Unix Version (Sun) The main directory FZ__CLIPS.6.02A has all of the files (*.c and *.h) listed above plus the following files and directories. makefile.x (File used to create FZ_XCLIPS_shower, FZ_XCLIPS, FZ_CLIPS or FZ_CLIPS_shower. Note that for X versions the flag WINDOW_INTERFACE in setup.h must be set to 1 and for non X versions it must be 0. Also note that the flag ShowerProblemUI in main.c or xmain.c must be set to 1 for versions with the graphical interface for the shower problem included and to 0 for those without it.) FZ_XCLIPS_shower (executable FuzzyCLIPS system with shower problem included) (includes the code for X development interface) FZ_CLIPS_shower (executable FuzzyCLIPS system with shower problem included) (generic - NO X development interface) (files that support the X windows development interface - % indicates some minor changes made at NRC to better support the Restart option when quitting clips [xmanin.c, xmenu_file.c] and to allow Control-C to halt execution of a CLIPS program [xclipstext.c]) xclips.c (%)xmain.c (%)xmenu_file.c xmenu_wind.c (%)xclipstext.c xmenu.c xmenu_opt.c xedit.c xmenu_exec.c xmenu_watch.c xclips.h xmain.h xmenu_wind.h xedit.h xmenu.h xsetup.h DOCS: (directory - framemaker documentation files + postscript output of documenta- tion) FuzzyCLIPS.doc FuzzyCLIPSTitle.doc FuzzyCLIPSTOC.doc FuzzyCLIPS.book FuzzyCLIPS.doc.ps snapshot.shower ShowerProblem: (directory - files to support shower problem - see Appendix A) EventNames.h Events.h Shower.G Shower.c Shower.po ShowerCallbacks.c ShowerGraph.par ShowerSimulate.c ShowerSimulate.h Shower_audio.c Simulate.c Simulate.h audio_device.h audio_errno.h audio_hdr.h flush.au formatData formatData.c libaudio.a libaudio.h showerUI25.clp showerUI8.clp src: (Directory) Shower.ps Shower_I.ps Shower_c.cps Shower_m.c Shower_p.h tmp: (Directory) Shower.PS Shower.h Shower_C.c Shower_C.cps Shower_C.h Shower_c.c Shower_c.h Shower_s.c fzexamples: (Directory - sample of examples in FuzzyCLIPS) lin1st.clp (control of linear 1st order system) lin1stdl.clp (control of linear 1st order system with delay) simplTst.clp (basic non-sensical example) fzCmplr.clp (fuzzy compiler example) fzCmpmod.clp (fuzzy compiler example using MODULES) shwrNOUI.clp (shower example with NO graphical user interface) lin1st.par (used with xvgr program to plot results of lin1st.clp or lin1stdl.clp) (there may also be some .dat files that are the outputs for these programs) The FZ_XCLIPS_shower executable file has been created to include the code required to support the Shower Problem simulation (graphics user interface version). To run the simulation you will need to be using Openwindows version 3.0 or later (Note it will NOT run under Solaris 2 since it uses the NeWS system which has been removed in that version of the operating system). The ShowerProblem directory contains all of the files needed to modify the simulation if required and the details are presented in Appendix A. A second version of the shower problem (shwrNOUI.clp) that is text-based is provided in the directory `fzexamples'. It requires no special features and is also described in Appendix A. FuzzyCLIPS has been compiled (using cc, a non-ANSI compiler) and tested on a Sun Sparc system running SunOS version 4.1.x. 3.2 IBM PC version The main directory FZCL602A\SOURCES has all of the files (*.c and *.h) listed above. The following files and directories are also contained in the directory FZCL602A (assum- ing that this is the name of the directory in which the distributed system was placed). clips.hlp (file used by the CLIPS help command) clips6.hlp (file used by the CLIPS help command) clipscmd.exe (FuzzyCLIPS command line version - runs under windows) clipswin.exe (FuzzyCLIPS windows version - development GUI included) (Note that the size of the runtime stack is set to 32K. See clipswin.def or clipscmd.def files for exact values. Also note that to recreate (i.e. recompile/relink) either of these versions it may be necessary to modify the setup.h file to reflect the features to be included. In partic- ular for clipswin versions the flag WINDOW_INTERFACE in setup.h must be set to 1 and for clipscmd versions it should be 0. Also note that the flag ShowerProblemUI in main.c (SOURCES directory) or main.c (PCINTFAC directory) must be set to 0 or there will be unresolved externals. This flag is only applicable on Sun workstations. Both versions have been created with stack checking ON. This may cause programs to run slower but the check was felt to be useful and perhaps even necessary. The project files were set to create and use precompiled header files. This will cause quite large .CSM files to be created but does speed up compilations. Finally note that these versions of FuzzyCLIPS have been created using the HUGE memory model and that no other models were tried. Therefore it is expected that some effort may needed to make the system work with any other memory model.) FZEXMPLE (Directory with FuzzyCLIPS example programs) lin1st.clp (control of linear 1st order system) lin1stdl.clp (control of linear 1st order system with delay) simpltst.clp (basic non-sensical example) fzcmplr.clp (fuzzy compiler example) fzcmpmod.clp (fuzzy compiler example using MODULES) shwrnoui.clp (shower example with NO graphical user interface) (there may also be some .dat files that are the outputs for these programs) PCINTFAC (Directory containing files used to create the GUI interface for developers) 1.cur 2.cur 3.cur 4.cur 5.cur 6.cur 7.cur 8.cur 9.cur wait.cur clipsdde.h dialog.h menucmds.c dialog1.c menucmds.h clipswin.def clipswin.ico dialog2.c query.cur clipswin.rc status.c clipswin.res ids.h status.h clipswin.rws joe.bmp main.c system.c main.h clipscmd.def diag_win.c clipsdde.c diag_win.h menu.c PCPROJ (Directory with project files for Borland C++ 4.0) clips6.hpj clipscmd.ide clipswin.dsw ide_clps.prj clips6.rtf clipscmd.prj clipswin.ide clipscmd.csm clipswin.prj clipscmd.dsw clipswin.csm clipswin.mak clipscmd.mak FuzzyCLIPS has been compiled (using Borland C++ 4.0, an ANSI compiler) and tested on a PC compatible system running DOS 6.2 and Windows 3.1. Note that the PC version caused more problems during development and testing (by far) than either the unix (sun) version or the Macintosh version. 3.3 Macintosh version The main directory `FZ__CLIPS 6.02A:FZ_CLIPS source' has all of the files (*.c and *.h) listed above. The following files and directories are also contained in the directory `FZ__CLIPS 6.02A'. MPW C Project Files (Directory - contains the makefiles for creating FuzzyCLIPS) FZ_CLIPS.6.02A.make (for making FuzzyCLIPS with Interfaces version) FZ_CLIPS.6.02AG.make (for making FuzzyCLIPS command line version) FZ_CLIPS.6.02A \x11 (executable version of FuzzyCLIPS with Interfaces) FZ_CLIPS.6.02A.r (FZ_CLIPS resource file) clips.hlp (help file used by the CLIPS help command) Note that to recreate (i.e. recompile/relink) either of these versions it may be necessary to modify the setup.h file to reflect the features to be included. In particular for the interface version the flag, WINDOW_INTERFACE, in setup.h must be set to 1 and for the non- interface version it should be 0. Also note that the flag, ShowerProblemUI, in main.c and macmain.c must be set to 0 or there will be unresolved externals. This flag is only applica- ble on Sun workstations. fzexamples (Directory - contains the example programs and associated files) lin1st.clp (control of linear 1st order system) lin1stdl.clp (control of linear 1st order system with delay) simplTst.clp (basic non-sensical example) fzCmplr.clp (fuzzy compiler example) fzCmpmod.clp (fuzzy compiler example using MODULES) shwrNOUI.clp (shower example with NO graphical user interface) Mac Interface Source (Directory - contains the Interface source files) ALPHA.C EDITW.C MACINIT.C RULEDLOG.C CLIPSMNU.C EXECDLOG.C MACMAIN.C SCRAP.C CLIPSSTW.C FACTDLOG.C MAINLOOP.C SEARCH.C COOLDLOG.C FILEMENU.C MENUCMDS.C STATUSW.C DISPLAYW.C FONTPICK.C MENUHNDL.C STNRDMAC.C DLOGMNGR.C GNRCDLOG.C PRCDDLOG.C UNDO.C EDITDLOG.C MACFUNCS.C PRINT.C WINDOW.C EDITMENU.C alpha.h editmenu.h interface.h print.h clipsmnu.h editw.h interface_scrap.h ruledlog.h clipsstw.h execdlog.h macinit.h search.h common.h factdlog.h mainloop.h statusw.h cooldlog.h filemenu.h menucmds.h stnrdmac.h displayw.h fontpick.h menuhndl.h undo.h dlogmngr.h gnrcdlog.h prcddlog.h window.h editdlog.h [Note that 4 files in the interface sources (WINDOW.C, EXECDLOG.C, EDITDLOG.C and MENUHNDL.C) must be compiled with the -d dangerousPattern switch set] FuzzyCLIPS has been compiled (using MPW 3.3, an ANSI compiler) and tested under Mac OS System 7.x. The distributed version is created with a minimum size set to 1.5K and a preferred size of 4.0K. These values can be changed although it is possible that some of your programs will not run with less memory. 4.0 Fuzzy Expert Systems In the real world there exists much fuzzy knowledge, i.e., knowledge which is vague, imprecise, uncertain, ambiguous, inexact or probabilistic in nature. Human thinking and reasoning frequently involve fuzzy information, possibly originating from inherently inex- act human concepts and matching of similar rather then identical experiences. In systems based upon classical set theory and two-valued logic, it is very difficult to answer some questions because they do not have completely true answers. Humans, however, can give satisfactory answers, which are probably true. Expert systems should not only give such answers but also describe their reality level. This level should be calculated using impreci- sion and the uncertainty of facts and rules which were applied. Expert systems should also be able to cope with unreliable and incomplete information and with different expert opin- ions. Many of today's commercial expert system building tools or shells use different approaches such as certainty factors [\x113], Bayesian [\x114] and Dempster-Shafer's [\x115] models to handle uncertainty in the knowledge or data, but they cannot cope with fuzzy data which constitute a very significant part of a natural language. Several systems such as Cadiag-2 [\x116], Fault [\x117], FLOPS [\x118], FRIL [\x119], SYSTEMZ-II [\x1110] and FLISP [\x1111] sup- port some fuzzy reasoning but they are purposely built from high-level languages for a specific domain of application. Following the main idea of CLIPS, which is to develop an expert system tool written in and fully integrated with the C language for high portability, low cost and easy integration with external systems, this work was undertaken to extend CLIPS for representing and manipulating fuzzy facts and rules. Fuzziness and uncertainty are the two distinct inexact concepts employed in the system. The following sections will discuss the general theory of both fuzziness and uncertainty, their implications on rule evaluation in FuzzyCLIPS, and algorithms implemented for extracting exact values from fuzzy facts. 4.1 Fuzziness Fuzziness occurs when the boundary of a piece of information is not clear-cut. For exam- ple, concepts such as young, tall, good or high are fuzzy. There is no single quantitative value which defines the term young. For some people, age 25 is young, and for others, age 35 is young. In fact the concept young has no clean boundary. Age 1 is definitely young and age 100 is definitely not young, however, age 35 has some possibility of being young and usually depends on the context in which it is being considered. The representation of this kind of information in FuzzyCLIPS is based on the concept of fuzzy set theory [\x1112]. Unlike classical set theory where one deals with objects whose membership to a set can be clearly described, in fuzzy set theory membership of an element to a set can be partial, i.e., an element belongs to a set with a certain grade (possibility) of membership. More for- mally a fuzzy set A in a universe of discourse U is characterized by a membership func- tion mA : U Æ [0,1] (1) which associates with each element x of U a number mA(x) in the interval [0,1] which rep- resents the grade of membership of x in the fuzzy set A. For example, the fuzzy term young might be defined by the fuzzy set in Table 1. Table 1: Fuzzy Term young Age Grade of Membership 25 1.0 30 0.8 35 0.6 40 0.4 45 0.2 50 0.0 Regarding (1), one can write myoung(25)=1, myoung(30)=0.8, ... , myoung(50)=0 Grade of membership values constitute a possibility distribution of the term young. The table can also be shown graphically (see \x11Figure 1 ). Figure 1: Possibility distribution of young The possibility distribution of a fuzzy concept like somewhat young or very young can be obtained by applying arithmetic operations to the fuzzy set of the basic fuzzy term young, where the modifiers somewhat and very are associated with specific mathematical func- tions. For instance, the possibility values of each age in the fuzzy set representing the fuzzy concept somewhat young might be calculated by taking the square root of the corre- sponding possibility values in the fuzzy set of young (see \x11Figure 2 ). These modifiers are often referred to as hedges. A more complete description of the hedges supplied with FuzzyCLIPS and how to add user defined hedges are described in section 5.1.2. Figure 2: Possibility distribution of somewhat young Fuzzy facts may be defined, matched as a pattern in a rule, and asserted in a manner simi- lar to the ordinary crisp facts employed in standard CLIPS. Example 1 (deftemplate age ;definition of fuzzy variable `age' \x11\x11\x110 120 years \x11\x11( (young (25 1) (50 0)) \x11\x11\x11\x11(old \x11\x11(50 0) (65 1)) \x11\x11) ) (deffacts fuzzy-fact (age young) ; a fuzzy fact ) (defrule one ; a rule that matches and asserts fuzzy facts (Speed_error big) \x11=> (assert (Throttle_change small)) ) where young, big and small are fuzzy terms, and age, Speed_error and Throttle_change are linguistic (fuzzy) variables. Each linguistic (fuzzy) variable has an associated fuzzy term set (called "primary terms" in FuzzyCLIPS) which is the set of values that the fuzzy variable may take. For example, the fuzzy variable water_temperature might have the primary term set {cold, warm, hot}, where each primary term represents a specific fuzzy set. \x11Figure 3 illustrates the primary term values of the fuzzy variable water_temperature. Figure 3: Primary terms of a linguistic variable The syntax for defining fuzzy variables and fuzzy terms is discussed in detail in 5.1. 4.2 Uncertainty Uncertainty occurs when one is not absolutely certain about a piece of information. The degree of certainty is usually represented by a crisp numerical value on a scale from 0 to 1, where a certainty factor of 1 indicates that the expert system is very certain that a fact is true, and a certainty factor of 0 indicates that it is very uncertain that a fact is true. In FuzzyCLIPS, a fact is composed of two parts: the fact in the sense of standard CLIPS and its certainty factor. In general a FuzzyCLIPS fact takes the following form: (fact) [CF certainty factor] The CF acts as the delimiter between the fact and the certainty factor and [ ] indicates an optional part. For example, (prediction sunny) CF 0.8 is a fact which indicates that the weather will be sunny with a certainty of 80%. How- ever, if the certainty factor is omitted, as in a normal CLIPS fact, (prediction sunny) then FuzzyCLIPS assumes that the weather will be sunny with a certainty of 100%. Certainty factors may also be associated with entire rules as illustrated by Example 2. Example 2 (defrule flight-rule (declare (CF 0.95)) ;declares certainty factor of the rule (animal type bird) \x11=> (assert (animal can fly)) ) represents the hypothesis that, 95% of the time, if an animal is a bird, then it can fly. Similar to facts, if the certainty factor of a rule is not declared, it is assumed to be equal to the value 1.0. Uncertainty and fuzziness can occur simultaneously (see Example 3). Example 3 (deffacts FuzzyAndUncertainFact (Speed_error more_or_less zero) CF 0.9 ) (defrule Uncertain_rule (declare (CF 0.8) ) (Johns_age young) \x11=> (assert (John goes to school)) ) where Speed_error and Johns_age are fuzzy variables, zero and young are fuzzy terms, more_or_less is a fuzzy term modifier and 0.9 and 0.8 are certainty factors associated with a fact and a rule respectively. 4.3 Inference techniques Rule evaluation depends on a number of different factors, such as whether or not fuzzy variables are found in the antecedent or consequent part of a rule, whether a rule contains multiple antecedents or consequents, whether a fuzzy fact being asserted has the same fuzzy variable as an already existing fuzzy fact (global contribution) and so on. In this sec- tion, the algorithms for evaluating the certainty factors and fuzzy objects of rules will be discussed. 4.3.1 Simple rules Consider the simple rule of form if A then C CFr A¢ CFf ------------------------ C¢ CFc where: A is the antecedent of the rule A¢ is the matching fact in the fact database C is the consequent of the rule C¢ is the actual consequent calculated CFr is the certainty factor of the rule CFf is the certainty factor of the fact CFc is the certainty factor of the conclusion Three types of simple rules are defined: CRISP_, FUZZY_CRISP and FUZZY_FUZZY. If the antecedent of the rule does not contain a fuzzy object, then the type of rule is CRISP_ regardless of whether or not a consequent contains a fuzzy fact. If only the ante- cedent contains a fuzzy fact, then the type of rule is FUZZY_CRISP. If both antecedent and consequent contain fuzzy facts, then the type of rule is FUZZY_FUZZY. 4.3.1.1 CRISP_ Simple Rule If the type of rule is CRISP_, then A¢ must be equal to A in order for this rule to fire. This is a `normal' CLIPS rule (actually A would be a pattern and A¢ would match the pattern specification but for simplicity we will not deal with patterns). In that case the conclusion C¢ is equal to C, and CFc = CFr * CFf (2) Example 4 Given a rule: (defrule crisp-simple-rule (declare (CF 0.7)) ;crisp rule certainty factor of 0.7 (light_switch off) ;crisp antecedent \x11=> (assert (illumination_level dark)) ; fuzzy consequent ) ; end of rule definition and given that the fact: (light_switch off) CF 0.8 has been asserted. Then the following fact will be asserted into the fact database due to the firing of the crisp-simple-rule: (illumination_level dark) CF 0.56 where the certainty factor of the conclusion has been calculated as follows CFc = 0.7 * 0.8 4.3.1.2 FUZZY_CRISP Simple Rule If the type of rule is FUZZY_CRISP, then A¢ must be a fuzzy fact with the same fuzzy variable as specified in A in order for a match to occur and the rule to be placed on the agenda. In addition, while values of the fuzzy variables A and A¢ represented by the fuzzy sets Fa and F¢a do not have to be equal, they must overlap. For example, the fuzzy facts (temperature high) and (pressure high) do not match because the fuzzy variables temperature and pressure are not the same. However, given the fuzzy facts (pressure low), (pressure medium) and (pressure high), as illustrated in \x11Figure 4, clearly (pressure low) and (pressure medium) overlap and thus match, while (pressure low) and (pressure high) do not match. . Figure 4: Matching of fuzzy facts For a FUZZY_CRISP rule, the conclusion C¢ is equal to C, and CFc = CFr * CFf * S where S is a measure of similarity between the fuzzy sets Fa (determined by the fuzzy pattern A) and F¢a (of the matching fact A¢). The measure of similarity is based upon the measure of possibility P and the measure of necessity N. It is calculated according to the following formula [\x1117] S = P(Fa\x11|\x11F¢a)\x11\x11\x11\x11 if N(Fa\x11|\x11F¢a) > 0.5 S = (N(Fa\x11|\x11F¢a) + 0.5) * P(Fa\x11|\x11F¢a) otherwise where: and Fa is the complement of Fa described by the following membership function Therefore if the similarity between the fuzzy sets associated with the fuzzy pattern (A) and the matching fact (A¢) is high the certainty factor of the conclusion is very close to CFr * CFf since S will be close to 1. If the fuzzy sets are identical then S will be 1 and the certainty factor of the conclusion will equal CFr * CFf. If the match is poor then this is reflected in a lower certainty factor for the conclusion. Note also that if the fuzzy sets do not overlap then the similarity measure would be zero and the certainty factor of the conclusion would be zero as well. In this case the conclusion should not be asserted and the match would be considered to have failed and the rule would not be placed on the agenda. Example 5 (defrule simple-fuzzy-crisp-rule (declare (CF 0.7)) ;rule has a certainty factor of 0.7 (fuzzy-fact fact2) ;fuzzy antecedent \x11=> (assert (crisp-fact fact3)) ;crisp consequent ) where (fuzzy-fact fact1) CF 0.8 is the matching fact in the fact database, and the fuzzy sets are illustrated in \x11Figure 5: Figure 5: Fact and antecedent fuzzy sets First, the necessity is calculated as in \x11Figure 6. Figure 6: N(Fa|F'a) Since the necessity is less than 0.5, S = (N(Fa\x11|\x11F¢a) + 0.5) * P(Fa\x11|\x11F¢a) (see \x11Figure 7 ). Figure 7: S=(N(Fa|F´a)+0.5)*P(Fa|F´a) And thus CFc = (0.7) * (0.8) * (0.6667) = 0.3733. 4.3.1.3 FUZZY_FUZZY Simple Rule If the type of rule is FUZZY_FUZZY, and the fuzzy fact and antecedent fuzzy pattern match in the same manner as discussed for a FUZZY_CRISP rule, then it is shown in [\x1113] that the antecedent and consequent of such a rule are connected by the fuzzy rela- tion R = Fa * Fc where: Fa is a fuzzy set denoting the value of the fuzzy antecedent pattern Fc is a fuzzy set denoting the value of the fuzzy consequent In the current version of the system the membership function of the relation R is calcu- lated according to the formula Other algorithms for forming this relation can be found in [\x1118]. The calculation of the conclusion is based upon the compositional rule of inference [\x1113], which can be described as follows: F¢c = F¢a R where F¢c is a fuzzy set denoting the value of the fuzzy object of the consequent. The membership function of F¢c is calculated as follows [\x1119] which may be simplified to: where The certainty factor of the conclusion is calculated according to (2) CFc = CFr * CFf. Example 6 (defrule fuzzy-fuzzy-rule \x11;both antecedent and consequent are fuzzy objects (temperature hot) => (assert (temp_change little)) ) (temperature warm) ; a fact in the fact database A graphical illustration of the matching of the fuzzy fact with the fuzzy pattern and the generation of the fuzzy conclusion is shown below in \x11Figure 8. Note that this type of inference method is commonly referred to as max-min rule of inference. The conclusion set is simply clipped off at the z value. Figure 9 shows the same results using a max- prod rule of inference. In this case the conclusion has all of its membership values scaled by the z value. The FuzzyCLIPS function set-inference-type allows the control of which method is used. Figure 8: Compositional Rule of Inference (Max-min) Figure 9: Compositional Rule of Inference (Max-prod) 4.3.2 Complex rules 4.3.2.1 Multiple consequents In CLIPS, the consequent part of the rule can only contain multiple patterns (C1, C2 ,..., Cn) with the implicit and conjunction between them. They are treated as multiple rules with a single consequent. So the following rule: if Antecedents then C1 and C2 and ... and Cn is equivalent to the following rules: if Antecedents then C1 if Antecedents then C2 ... if Antecedents then Cn 4.3.2.2 Multiple antecedents From the above, clearly, only the problem of multiple patterns in the antecedent with a single assertion in the consequent needs to be considered. If the consequent assertion is not a fuzzy fact, no special treatment is needed since the conclusion will be the crisp (non-fuzzy) fact. However, if the consequent assertion is a fuzzy fact, the fuzzy value is calculated using the following basic algorithm [\x1120]. If logical and is used, one has if A1 and A2 then C CFr A¢1 CFf1 A¢2 CFf2 ---------------------------------------- C¢ CFc where A¢1 and A¢2 are facts (crisp or fuzzy) which match the antecedents A1 and A2 respectively. In this case the fuzzy set describing the value of the fuzzy assertion in the conclusion is calculated according to the formula F¢c = F¢c1 « F¢c2 where: « denotes the intersection of two fuzzy sets F¢c1 is the result of fuzzy inference for the fact A¢1 and the simple rule if A1 then C F¢c2 is the result of fuzzy inference for the fact A¢2 and the simple rule if A2 then C In \x11Figure 9 we see the results of a rule in which both A1 and A2 are fuzzy patterns. Note that if both A1 and A2 were crisp (non-fuzzy) facts then the conclusion would just be the fuzzy fact C since we would be dealing with two CRISP_FUZZY simple rules. If one of the patterns is crisp (say A1) and the other is fuzzy then the conclusion is F¢c2 since the CRISP_FUZZY simple rule would conclude C and the FUZZY_FUZZY sim- ple rule would conclude F¢c2. The intersection of these two would just be F¢c2. Figure 10: Compositional rule for multiple antecedents The certainty factor of the conclusion is calculated according to MYCIN's model CFc = min(CF¢f1 ,CF¢f2 ) * CFr where min denotes the minimum of the two numbers and CF¢f1 is the CF of the simple rule if A1 then C given the matching fact A¢1 CF¢f2 is the CF of the simple rule if A2 then C given the matching fact A¢2 The above algorithm can be applied repeatedly to handle any combination of anteced- ent patterns. i.e. F¢c = F¢c1 « F¢c2 ... « F¢cn CFc = min(CF¢f1 ,CF¢f2, ... ,CF¢fn) * CFr 4.3.3 Global contribution In standard CLIPS a fact is asserted with specific values for its fields. If the fact already exists then the behaviour is as if the fact was not asserted (unless fact duplication is allowed). In such a crisp system there is never any need to re-assess the facts in the sys- tem - once they exist, they exist (unless certainty factors are being used as discussed below; then the certainty factors are modified to account for the new evidence). But in a fuzzy system, refinement of a fuzzy fact may be possible. Thus, in the case where a fuzzy fact is asserted, this fact is treated as giving contributing evidence towards the conclu- sion about the fuzzy variable (it contributes globally). If information about that fuzzy variable has already been asserted then this new evidence (or information) about the fuzzy variable is combined with the existing information in the fuzzy fact. The concept of fact duplication for fuzzy facts, therefore, does not apply. There are many readily identifiable methods of combining evidence. In the current version of the system, the new value of the fuzzy fact is calculated in accordance with the formula Fg = Ff\x11 »\x11 F¢c where: Fg is the new value of the fuzzy fact Ff is the existing value of the fuzzy fact F¢c is the value of the fuzzy fact to be asserted » denotes the union of two fuzzy sets Figure 11: union of fuzzy sets - global contribution The uncertainties are also aggregated to form an overall uncertainty. Basically, two uncertainties are combined, using the following formula CFg = maximum(CFf , CFc ) where: CFg is the combined uncertainty CFf is the uncertainty of the existing fact CFc is the uncertainty of the asserted fact As an example of the importance of the global contribution to a fuzzy fact, consider the implementation of a fuzzy logic controller. In this case the user has to ensure the firing of all rules which contribute to the control action to be performed, before any other rule (usually defuzzification) fires. This can be done by attaching a suitable salience to the rules or by separating the rules that all contribute to the same control action into a sepa- rate MODULE. As an example see Appendix A and also see the example FuzzyCLIPS programs fzCmplr.clp and fzCmpmod.clp which use salience and MODULES respec- tively to ensure all fuzzy rules that are related fire together. 4.3.4 Threshold certainty factors In FuzzyCLIPS it is possible to set a threshold certainty factor value such that no rule will be fired unless the rule has a calculated certainty factor value greater than or equal to the threshold value (see also [\x1120]). This feature may be useful in preventing a chain of rules with very low certainty and little logical contribution from firing, and thus speed up the run time. The default is to have no threshold certainty factor set (i.e. a threshold of 0.0), and for rules to be fired as usual (see also section \x115.7.4). The calculated certainty factor for a rule is: CFrule * min(CF1, ... ,CFn) where CFrule is the certainty factor for the rule and CFi are the certainty factors for the facts that matched the n patterns on the lefthand side of the rule. Example 7 (defrule below-threshold-rule (declare (CF 0.5)) ;rule certainty factor of 0.5 (fuzzy-fact antecedent-fact) ;fuzzy antecedent \x11=> (assert (crisp-fact c1)) ;crisp consequent (assert (another-fuzzy-fact c2)) ;fuzzy consequent ) Suppose the following fact has been asserted (fuzzy-fact fact-list-fact) CF 0.6 The calculated certainty factor for the rule is CF = 0.5 * 0.6 = 0.3 The rule will fire only if the threshold certainty factor is less than or equal to 0.3 at the time the rule is selected to fire. The certainty factor for (another-fuzzy-fact c2), the fuzzy conse- quent in the previous rule, is CF = 0.5 * 0.6 = 0.3 from equation (2), as for a simple FUZZY_FUZZY rule. However, the certainty factor for (crisp-fact c1) is CF = 0.5 * 0.6 * S, where S is the measure of similarity, as for a simple FUZZY_CRISP rule. Suppose that S=0.8. Then the following conclusions are reached on the RHS: ... => (assert (crisp-fact c1)) ; calculated CF = 0.24 (assert (another-fuzzy-fact c2)) ; calculated CF = 0.3 Combining rule certainty factors, fact certainty factors, multiple patterns on the lefthand side of a rule and multiple assertions on the righthand side of a rule can lead to a compli- cated determination of threshold and certainty factors for the asserted facts. Example 8 (defrule complex (declare (CF 0.9)) (crisp1) (fuzzy1 very few) \x11\x11=> (assert (crisp2) \x11\x11\x11(fuzzy2 hot)) ) with asserted facts (crisp1) CF 0.8 (fuzzy1 few) CF 0.7 The calculated certainty factor for the rule is 0.9 * min(0.8, 0.7) = 0.63 Therefore the rule will fire if the threshold value is less than or equal to 0.63 and the certainty factors of the two asserted facts will be (assuming the similarity between (fuzzy1 very few) and (fuzzy1 few) is 0.6) CF of (crisp2) = 0.9 * min(0.8, 0.7*0.6) = 0.378 CF of (fuzzy1 few) = 0.9 * min(0.8, 0.7) = 0.63 Note that the calculated certainty factor for a rule is evaluated when the rule is selected to fire and NOT when it is added to the agenda. This is because the certainty factors for the facts that match the patterns of the rule can change due to global contribution while the rule is on the agenda. 4.3.5 Certainty factors in assert statements When a fact is asserted in FuzzyCLIPS, its certainty factor may be specified (see 5.4.3 for details). It is thus possible to assert a fact on the RHS of a rule with a specific cer- tainty factor. Example 9 (assert (some-consequent) CF 0.8) ;asserting fact with CF = 0.8 Note that a certainty factor will also be calculated according to the nature of the rule (having multiple antecedents, FUZZY_FUZZY, CRISP_, or FUZZY_CRISP) and any global contribution. This calculated certainty factor will then be multiplied by the cer- tainty factor given in the assert statement. This could be useful as a method of assigning weighted certainty factors for a rule with multiple consequents. Note that if the fact is not asserted during a rule execution (e.g. from the CLIPS command level) then only global contribution will apply in determining the certainty factor for the asserted fact (i.e. if the fact does not exist already then the certainty will be as specified in the assert and if it does exist the certainty will be modified to be the maximum of the existing certainty and the certainty specified in the assert). Example 10 (defrule assert-cf-rule (declare (CF 0.8)) ; rule CF is 0.8 (fact 1) => (assert (c1)) (assert (c2) CF 0.7) ; assert c2 with CF 0.7 (assert (c3)) (assert (c4)) ) where: (fact 1) CF 0.9 ; matching fact has CF 0.9 the conclusions reached on the RHS would be: (assert (c1)) ; CF = 0.8*0.9 = 0.72 (assert (c2) CF 0.7) ; CF = 0.8*0.9*0.7 = 0.504 (assert (c3)) ; CF = 0.8*0.9 = 0.72 (assert (c4)) ; CF = 0.8*0.9 = 0.72 The above rule attaches a lower CF to conclusion c2 than to the other conclusions. 4.4 Defuzzification The outcome of the fuzzy inference process is a fuzzy set, specifying a fuzzy distribution of a conclusion. However, in some cases, such as control applications, only a single dis- crete action may be applied, so a single point that reflects the best value of the set needs to be selected. This process of reducing a fuzzy set to a single point is known as defuzzifica- tion. There are several possible methods, each one of which has advantages and disadvantages. A method which has been widely adopted is to take the center of gravity (COG or moment) of the whole set. This has the advantage of producing smoothly varying control- ler output, but it is sometimes criticized as giving insufficient weight to rule consequents which agree and ought to reinforce each other. Another method concentrates on the values where the possibility distribution reaches a maximum, called the mean of maxima method. The mean of maxima (MOM) algorithm is criticized as producing less smooth controller output, but has the advantage of greater speed due to fewer floating point calculations. In FuzzyCLIPS, the user has the option of choosing either the COG or MOM algorithm when defuzzifying a fuzzy set (For details on the functions that perform defuzzification in FuzzyCLIPS see section \x115.5. 4.4.1 Centre of gravity algorithm The centre of gravity method may be written formally as where x¢ is the recommended, defuzzified value, and the universe of discourse is U. In FuzzyCLIPS, a fuzzy set is defined by a set of points which are considered to be con- nected by straight line segments. The integral then reduces to a simple summation: where x'i is the local centre of gravity and Ai is the local area of the shape underneath line segment (pi-1, pi), and n is the total number of points. Example 11 Figure 12: Example of COG defuzzification For each shaded subsection above, the area and centre of gravity is calculated according to the shape identified (i.e. triangle, rect- angle or trapezoid). The centre of gravity of the whole set is then determined: 4.4.2 Mean of maxima algorithm The MOM algorithm returns the x-coordinate (x) of the point at which the maximum membership (y) value of the set is reached. Example 12 Given the fuzzy set illustrated in \x11Figure 11, the MOM result would be 3.0. If the maximum y value is reached at more than one point, then the average of all the x is taken. More formally: where xj are the x-coordinates of all the maxima, and J is the total number of maxima. Example 13 Figure 13: Example of MOM defuzzification Note that an ambiguity occurs when the maximum value occurs along a plateau rather than just a series of individual peaks (see \x11Figure 13 ). In this case there are an infinite number of maximum points between x1 and x2 and using the average of the 3 points x1, x2 and x3 results in what may be an incorrect or perhaps an unexpected value. It is not entirely clear what the answer should be (see [\x119.0] for a discussion of this problem and see [\x115.5] to see how to perform defuzzification in FuzzyCLIPS using the moment- defuzzify and maximum-defuzzify functions). Figure 14: MOM example - Ambiguity 5.0 Using the FuzzyCLIPS extensions The following sections present the syntax for defining fuzzy variables, using fuzzy vari- ables in LHS patterns and in facts, declaring certainty factors, changes made to the assert statement, defuzzification functions and commands for accessing fuzzy parameters and for accessing certainty factor information. 5.1 Defining Fuzzy Variables in Deftemplate Constructs All fuzzy variables must be predefined before use with the deftemplate statement. This is an extension of the standard deftemplate construct in CLIPS. The extended syntax of this construct is as follows: (deftemplate [""] [] ; universe of discourse ( t1 . . ; list of primary terms . tn ) ) is the identifier used for the fuzzy variable. The description of the universe of dis- course consists of three elements. The and should be floating point numbers. They represent the begin and end of the interval which describes the domain of the fuzzy variable (the universe of discourse). The value of must be less than the value for . The is a word which represents the unit of measurement (optional). The ti are specifications for the fuzzy terms (such as hot, cold, warm) used to describe the fuzzy variable. These specifications describe the shape of the fuzzy set associated with the terms. \x11Example 14 below shows an incomplete fuzzy deftemplate with only the universe of discourse specified. Example 14 (deftemplate water_flow 0 100 liters/sec . . . \x11\x11\x11\x11\x11\x11 ) 5.1.1 Primary terms A primary term ti (i=1,...,n) has the form ( ) where represents the name of a primary term used to describe a fuzzy concept, and defines a membership function of the given primary term. The membership function can be described using either a singleton representation, a standard function representation or a linguistic expression that uses terms defined previ- ously in the fuzzy deftemplate definition. ::= | | 5.1.1.1 Singleton representation The grade of membership mA(x) of x in fuzzy set A is a positive number and the pair (mA(x), x) will be called a singleton (often these pairs are represented by mA(x)/x or m(x)/x for short). A fuzzy set A in a universe of discourse U can be described as fol- lows: where the integration symbol denotes the union of singletons. If a universe of discourse U is a finite set, then A is expressed as follows In FuzzyCLIPS we consider the universe of discourse to be a range of the real number line and do not deal with finite sets for U. A singleton will be represented here as a pair (xi\x11 m(xi )) . A fuzzy set A will be represented as a list of singletons ::= (x1\x11 m1) (x2\x11 m2) . . . (xn\x11 mn) where: xi £ xi+1\x11 for i = 1, 2, ... , n-1 xi is an element from U mi is a number denoting the grade of membership of x in the fuzzy set A As mentioned in section 4.4.1, a fuzzy set is represented by an ordered set of points joined by straight line segments. The grade of membership of an x value not listed in a list of singletons will be calculated on the basis of interpolation according to the fol- lowing formula (for points that do not have multiple membership values; in these cases the membership value is defined to be the maximum of all values at that same x value): Example 15 Let U = {x | 0 £ \x11x £ 9} We may then define a fuzzy set "few" as follows m(0) = 0,\x11\x11 m(1) = 0,\x11\x11 m(2) = 0.3,\x11\x11 m(3) = 0.9, m(4) = 1,\x11\x11 m(5) = 0.8,\x11\x11 m(6) = 0.5,\x11\x11 m(7) = 0, m(8) = 0,\x11\x11 m(9) = 0 One can represent this fuzzy set by the following list of single- tons (1 0) (2 0.3) (3 0.9) (4 1) (5 0.8) (6 0.5) (7 0) One can also show this set graphically as in Figure 15. Figure 15: Fuzzy set of group few In FuzzyCLIPS one can define a linguistic variable group which has a universe of discourse from 0 to 9 (units unspecified) and the primary term few as follows: (deftemplate group ; a linguistic variable declaration 0 9 ; universe of discourse limits (no units) ( ; start of primary term declarations \x11\x11; a primary term few described in singleton notation (few (1 0) (2 0.3) (3 0.9) (4 1) (5 0.8) (6 0.5) (7 0)) ) ; end of primary term declarations ) ; end of fuzzy deftemplate Note that it is possible for consecutive x values to be the same. This describes a crisp boundary in the fuzzy set (vertical line). If more than 3 points have the same value then only 3 will be kept (the 4th will always replace the 3rd). If 2 points have exactly the same x and y values then one of them will be discarded. Consider the following 2 examples of fuzzy sets with crisp boundaries. Example 16 The singleton set described as (three (3 0) (3 1) (3 0)) might represent the crisp concept 3 as a fuzzy set. It is shown graphically as Example 17 Another more complex (and probably unrealistic set might be defined with the following set of singleton values (weird (1 0) (1 1) (1 0) (3 0) (4 .25) (4 1) (4 .4) (4 .5) (6 1) (8 0) ) The graph is shown below. Note that in this case the point (4 .4) is discarded. 5.1.1.2 Standard function representation Frequently, it is useful to describe a membership function using one of a set of standard functions S, P, or Z. Parameters of these functions can be chosen, depending on appli- cations. These functions are defined as follows and are shown graphically in \x11Figure 15. Note that the names are suggestive of the shape of the functions. Figure 16: Standard fuzzy set functions A standard representation of a membership function has the following format: \x11\x11\x11\x11 ::= (S a c)\x11|\x11(s a c)\x11|\x11(Z a c)\x11|\x11(z a c)\x11|\x11 (PI d b) | (pi d b) where : a, b, c, d are numbers which represent the parameters of the respective func- tions. Example 18 (deftemplate Tx \x11\x11"output water temperature" \x11\x11\x11\x11\x115 65 Celsius \x11\x11\x11\x11\x11( (cold (z 10 26)) ;standard set representation \x11\x11\x11\x11\x11\x11 (OK (PI 2 36)) \x11\x11\x11\x11\x11 (hot (s 37 60)) \x11\x11\x11\x11\x11) \x11) FuzzyCLIPS converts all standard notation to singleton representation. Nine points, equally spaced along the x axis are selected to represent the functions (see \x11Figure 16 ). The number of points (9) can be changed by modifiying the value of ArraySIZE which is defined in the file fuzzypsr.h and then recompiling FuzzyCLIPS. Note however, that increasing this size will increase the computational load during fuzzy inferencing. Also note that in many instances a simple 2 or 3 point singleton set that approximates these functions will be acceptable and will result in less computation during inferencing. Figure 17: Approximation of standard functions As a special note, consider the case where the parameter a is equal to c for the S or Z functions. In this case 2 points will be used to represent the function. Example 19 (S 10 10) will be represented (10 0) (10 1) (Z 10 10) will be represented (10 1) (10 0) For the PI function, if parameter d is zero then the function will be represented by 3 points. Example 20 (PI 0 10) will be represented (10 0) (10 1) (10 0) 5.1.1.3 Linguistic Expression representation Linguistic expressions are defined in section 5.2 in detail, but a simple example will illustrate the usage. Example 21 (deftemplate temperature \x11\x11\x110 100 C \x11\x11\x11\x11\x11( (cold (z 10 26)) ;standard set representation \x11\x11\x11\x11\x11 (hot (s 37 60)) ;standard set representation (warm not [ hot or cold ]) ; linguistic expression \x11\x11\x11\x11\x11) \x11) Note that the term warm is described as being not hot or cold. It uses the terms hot and cold previously defined in this deftemplate to describe the warm concept. Only terms described in this deftemplate (before the term definition being defined) can be used (along with any available modifiers and the and and or operations. 5.2 Standard Deftemplate Definitions with Fuzzy Slots (fields) A fuzzy deftemplate describes a fuzzy variable. One may use these deftemplates to describe fuzzy facts in patterns and assert commands. For example, (defrule high-temp \x11\x11\x11\x11\x11(temperature hot) => \x11\x11\x11\x11(assert (move-throttle negative-big) \x11\x11\x11\x11\x11(printout t "The temperature is hot") ) contains a fuzzy pattern based on the fuzzy deftemplate temperature. It also contains an assertion of a fuzzy fact based on the fuzzy deftemplate for move-throttle. Facts that have as their relation name, the name of a fuzzy deftemplate will be referred to as fuzzy deftemplate facts. These facts in essence have a single slot that holds the fuzzy value described by the linguistic expression (or fuzzy set description). It is also possible to sup- plement standard CLIPS deftemplate facts by having one or more of the slots be a fuzzy value slot. In these cases the slot is associated with a fuzzy deftemplate description so that the appropriate universe of discourse and terms are known. These facts with fuzzy slots are known as fuzzy facts. A fuzzy slot has the form: (fuzzy-slot> ::= (slot (type FUZZY-VALUE ) where is the name of the slot and is the name of a previously defined fuzzy deftemplate. Note that no other options are allowed in the slot specification. For example the slot cannot have multiple possible types like INTEGER and FUZZY-VALUE and the options that determine other constraints such default values or cardinality are not allowed. Fuzzy slots can only hold fuzzy values and must have a value. Example 22 ;; assume that the fuzzy deftemplates fz-height and ;; fz-weight have already been defined (deftemplate person (slot name (type SYMBOL)) (slot height (type FUZZY-VALUE fz-height)) (slot weight (type FUZZY-VALUE fz-weight)) ) (defrule big-person (person (name ?n) (weight heavy) (height tall)) \x11\x11=> (printout t ?n " is a big person" crlf) ) The use of fuzzy slots has a big payoff in many situations. Given the last example and only fuzzy deftemplate facts it would be necessary to define a fuzzy deftemplate for each per- son's weight and each person's height as well as rules for each person. In effect a fuzzy deftemplate acts somewhat like a type definition for the language in which a fuzzy vari- able type is defined. 5.3 Modifiers (Hedges) and Linguistic Expressions 5.3.1 Predefined Modifiers As mentioned in section 4.1, a modifier may be used to further enhance the ability to describe our fuzzy concepts. Modifiers (very, slightly, etc.) used in phrases such as very hot or slightly cold change (modify) the shape of a fuzzy set in a way which suits the meaning of the word used. These modifiers are commonly referred to as hedges. FuzzyCLIPS has a set of pre- defined modifiers that can be used at any time to describe fuzzy concepts when fuzzy terms are described in fuzzy deftemplates, fuzzy rule patterns are written or fuzzy facts or fuzzy slots are asserted. Modifier Name Modifier Description not 1-y very y**2 somewhat y**0.333 more-or-less y**0.5 extremely y**3 above (see description is Earl Cox's book) below (see description is Earl Cox's book) intensify 2(y**2) if y in [0, 0.5] 1 - 2(1-y)**2 if y in (0.5, 1] plus y**1.25 norm normalizes the fuzzy set so that the maximum value of the set is scaled to be 1.0 ( y = y*1.0/max-value ) slightly intensify ( norm (plus A AND not very A)) These modifiers change the shape of a fuzzy set using mathematical operations on each point of the set. In the above table the variable y represents each membership value in the fuzzy set and A represents the entire fuzzy set (i.e. y**2 squares each membership value and very A applies the very modifier to the entire set). Note that when a modifier is used it can be used in upper or lower case (NOT or not) or even a mix of cases (NoT). The following diagrams show the effect of each of the modifiers on a base fuzzy set. The diagrams have been produced using the plot-fuzzy-value function described later in the manual. Fuzzy Value: base-fv Linguistic Value: base (*) 1.00 * 0.95 0.90 * * 0.85 * * 0.80 0.75 * * 0.70 * * 0.65 0.60 * * 0.55 0.50 * * 0.45 * * 0.40 0.35 * * 0.30 * * 0.25 0.20 * * 0.15 0.10 * * 0.05 * * 0.00************* ************* |----|----|----|----|----|----|----|----|----|----| 0.00 20.00 40.00 60.00 80.00 100.00 Universe of Discourse: From 0.00 to 100.00 Fuzzy Value: base-fv Linguistic Value: not base (*) 1.00************* ************* 0.95 * * 0.90 * * 0.85 0.80 * * 0.75 0.70 * * 0.65 * * 0.60 0.55 * * 0.50 * * 0.45 0.40 * * 0.35 0.30 * * 0.25 * * 0.20 0.15 * * 0.10 * * 0.05 0.00 * |----|----|----|----|----|----|----|----|----|----| 0.00 20.00 40.00 60.00 80.00 100.00 Fuzzy Value: base-fv Linguistic Value: very base (*) 1.00 * 0.95 0.90 0.85 * * 0.80 0.75 0.70 * * 0.65 0.60 * * 0.55 0.50 0.45 * * 0.40 0.35 * * 0.30 0.25 * * 0.20 * * 0.15 * * 0.10 * * 0.05 * * 0.00*************** *************** |----|----|----|----|----|----|----|----|----|----| 0.00 20.00 40.00 60.00 80.00 100.00 Fuzzy Value: base-fv Linguistic Value: more-or-less base (*) 1.00 * 0.95 * * 0.90 * * 0.85 * * 0.80 * * 0.75 * * 0.70 * * 0.65 * * 0.60 * * 0.55 * * 0.50 0.45 * * 0.40 0.35 * * 0.30 0.25 0.20 0.15 * * 0.10 0.05 0.00************* ************* |----|----|----|----|----|----|----|----|----|----| 0.00 20.00 40.00 60.00 80.00 100.00 Fuzzy Value: base-fv Linguistic Value: somewhat base (*) 1.00 * 0.95 ** ** 0.90 ** ** 0.85 * * 0.80 * * 0.75 * * 0.70 * * 0.65 * * 0.60 * * 0.55 0.50 * * 0.45 0.40 0.35 0.30 0.25 0.20 * * 0.15 0.10 0.05 0.00************* ************* |----|----|----|----|----|----|----|----|----|----| 0.00 20.00 40.00 60.00 80.00 100.00 Fuzzy Value: base-fv Linguistic Value: slightly base (*) 1.00 ** ** 0.95 0.90 * * 0.85 * * 0.80 0.75 0.70 * * 0.65 0.60 0.55 0.50 * * 0.45 * * 0.40 0.35 0.30 0.25 * * 0.20 0.15 * * 0.10 * * 0.05 * * 0.00************** * ************** |----|----|----|----|----|----|----|----|----|----| 0.00 20.00 40.00 60.00 80.00 100.00 Fuzzy Value: base-fv Linguistic Value: above base (*) 1.00 ************* 0.95 * 0.90 * 0.85 0.80 * 0.75 0.70 * 0.65 * 0.60 0.55 * 0.50 * 0.45 0.40 * 0.35 0.30 * 0.25 * 0.20 0.15 * 0.10 * 0.05 0.00************************** |----|----|----|----|----|----|----|----|----|----| 0.00 20.00 40.00 60.00 80.00 100.00 Fuzzy Value: base-fv Linguistic Value: below base (*) 1.00************* 0.95 * 0.90 * 0.85 0.80 * 0.75 0.70 * 0.65 * 0.60 0.55 * 0.50 * 0.45 0.40 * 0.35 0.30 * 0.25 * 0.20 0.15 * 0.10 * 0.05 0.00 ************************** |----|----|----|----|----|----|----|----|----|----| 0.00 20.00 40.00 60.00 80.00 100.00 Fuzzy Value: base-fv Linguistic Value: intensify base (*) 1.00 *** 0.95 * * 0.90 * * 0.85 0.80 * * 0.75 0.70 * * 0.65 0.60 0.55 * * 0.50 0.45 0.40 * * 0.35 0.30 0.25 * * 0.20 0.15 * * 0.10 * * 0.05 * * 0.00************** ************** |----|----|----|----|----|----|----|----|----|----| 0.00 20.00 40.00 60.00 80.00 100.00 Fuzzy Value: base-fv Linguistic Value: extremely base (*) 1.00 * 0.95 0.90 0.85 0.80 * * 0.75 0.70 0.65 0.60 * * 0.55 0.50 0.45 * * 0.40 0.35 0.30 * * 0.25 0.20 * * 0.15 * * 0.10 * * 0.05 * * 0.00***************** ***************** |----|----|----|----|----|----|----|----|----|----| 0.00 20.00 40.00 60.00 80.00 100.00 Fuzzy Value: base-fv2 Linguistic Value: base (+), norm base (*) 1.00 * 0.95 0.90 * * 0.85 * * 0.80 0.75 * * 0.70 * + * 0.65 + + 0.60 * + + * 0.55 + + 0.50 * + + * 0.45 * * 0.40 + + 0.35 * + + * 0.30 * + + * 0.25 + + 0.20 *+ +* 0.15 + + 0.10 * * 0.05 * * 0.00************* ************* |----|----|----|----|----|----|----|----|----|----| 0.00 20.00 40.00 60.00 80.00 100.00 These predefined modifiers are available for use at all times in fuzzy deftemplate defini- tions, fuzzy patterns specifications, fuzzy slot assert specifications and in the fuzzy-mod- ify function. Some examples below illustrate the use of the modifiers. Example 23 (deftemplate temp \x11\x110 100 C \x11\x11( (cold (Z 20 40)) \x11\x11\x11\x11(hot \x11(S 60 80)) \x11\x11\x11\x11(freezing extremely cold) \x11\x11) ) (defrule temp-rule \x11\x11(temp not hot and not cold) => \x11\x11(printout t "It's such a pleasant day" crlf) ) 5.3.2 User Defined Modifiers The FuzzyCLIPS user may also define modifiers that can be used in exactly the same manner as the predefined ones. This can be done at the FuzzyCLIPS code level or for more complicated definitions or for efficiency at the `C' code level. Adding a new modifier at the FuzzyCLIPS level is done with the function (add-fuzzy-modifier modname modfunction) where: modname id the name (symbol) to be used for the modifier modfunction is the name of a CLIPS function or a user defined deffunction which takes a floating point number and returns a floating point number (the function should return a number between 0 and 1 and if it does not then it will be set to 0 if it is less than 0 or to 1 if it is greater than 1; the function will be passed numbers between 0 and 1) Example 24 (add-fuzzy-modifier my-somewhat sqrt) (deffunction most-extremely-fcn (?x) (** ?x 5) ) (add-fuzzy-modifier most-extremely most-extremely-fcn) (deftemplate temp 0 100 C ( (low (10 1) (50 0)) (high (50 0) (90 1)) (sort-of-high my-somewhat high) (incredibly-low most-extremely low) ) ) In the above example sqrt is a system defined function that returns the square root of a number. With this definition the modifier my-somewhat will act exactly like the some- what modifier supplied with the system. The function most-extremely-fcn is a user defined deffunction which will handle the work of the modifier most-extremely. With this definition it will behave similar to the system supplied modifier extremely. The function- ality of the modifiers defined this way are somewhat limited (for example it would not be possible to define the above or below modifiers this way or the slightly modifier). It is also possible to remove any modifiers added this way with the function (remove-fuzzy-modifier modname) Note that only modifiers added with the add-fuzzy-modifier function can be removed. The second method of adding modifiers requires that the source code for FuzzyCLIPS be modified and the system be recreated with these new modifiers being available as system defined modifiers. This will allow for more complex modifiers to be added and for sim- ple one's to be added with better performance. The only source file that should need to be changed is fuzzymod.c. Most modifiers can be added by simply following the code for system supplied modifiers that are in this file. In general it is just necessary to do the fol- lowing things. 1. Modify the function initFuzzyModifierList to identify the name of the modifier and it's 'C' code function (example for the very modifier is given below). \x11\x11AddFuzzyModifier("very", veryModFunction, NULL #if DEFFUNCTION_CONSTRUCT \x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11 , NULL #endif \x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11); 2. Then the function definition is added (example for the very modifier is given below). /*************************************************************/ /* veryModFunction: */ /* */ /* implements the 'very' hedge */ /* */ /* each element is squared (y**2) \x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11*/ /* */ /*************************************************************/ static VOID veryModFunction(fv) struct fuzzy_value *fv; { concentrate_dilute(fv, 2.0); } The concentrate-dilute function handles all of the similar types of modifiers that involve an exponentiation operation on the membership values. In this function there is a call to another function called Yexpand. This code determines if any straight line segments need to be expanded into further points so that the exponentiation operation will have the desired effect. For example, if the line segment was from (10 0) to (20 1) the squaring operation of the very modifier would just return these same two points since 0**2 = 0 and 1**2 = 1. This would not reflect the shape properly. In essence we try to keep a compact representation of the fuzzy set when we can but expand to more points when necessary. The figure below demonstrates the effect of the Yexpand operation on a straight line segment. Figure 18: Modifier interpolation method (Yexpand) If further assistance is required please contact NRC by email. 5.3.3 Linguistic Expressions The use of fuzzy primary terms and modifiers together with the binary operators and and or allow us to express the problem solutions in a more natural way. These expressions are called linguistic expressions. Expressions such as temperature very hot or very cold height below tall and above short are examples of expressions that could be used to describe fuzzy variable. The BNF that describes formally the syntax of such expressions is shown below. ::= \x11| \x11 OR ::= \x11| \x11 AND ::= MODIFIER \x11 | \x11 ::= PRIMARY-TERM\x11 | \x11[ ] where MODIFIER is a valid modifier (not, very, etc.) PRIMARY-TERM is a term defined in a fuzzy deftemplate Note that this gives AND higher precedence than OR and that modifiers are basically unary operators with the highest precedence. One can control the order of the expression evaluation through the use os brackets [ and ]. These brackets must be separated from other items by a space due to the nature of the CLIPS token parser. Therefore, A or B and C or D is the same as A or [ B and C ] or D The following graph shows an example of the fuzzy sets temp hot, temp cold and temp not [ hot or cold ]. Fuzzy Value: temp Linguistic Value: hot (.), cold (+), not [ hot OR cold ] (*) 1.00+++++++ ************* ....... 0.95 + * * . 0.90 + * * . 0.85 + * * . 0.80 0.75 + * * . 0.70 + * * . 0.65 0.60 0.55 +* *. 0.50 0.45 *+ .* 0.40 0.35 * + . * 0.30 0.25 * + . * 0.20 0.15 * + . * 0.10 * + . * 0.05 * + . * 0.00*******............+++++++++++++++++++++++++******* |----|----|----|----|----|----|----|----|----|----| 0.00 20.00 40.00 60.00 80.00 100.00 5.4 Using Fuzzy Variables in LHS Patterns A fuzzy LHS pattern is of the form: ( fuzzy-variable-name ) or ( fuzzy-variable-name ?) or ( fuzzy-variable-name ?) or ( fuzzy-variable-name ? & ) or (template-name +) where + indicates that there are one or more of the entries; at least one of these is a ; and a is ( fuzzy-slot-name ) or ( fuzzy-slot-name ?) or ( fuzzy-slot-name ?) or ( fuzzy-slot-name ? & ) The is a fuzzy set specified by a combination of primary terms, modifi- ers, and the logical operators NOT and OR as described in Section 5.3.3. A fuzzy-vari- able-name is the name of any fuzzy deftemplate. A template-name is the name of any non fuzzy deftemplate. A fuzzy-slot-name is the name of a slot declared to have type FUZZY- VALUE (as described in Section 5.2). The examples below show some of the ways in which fuzzy patterns might appear on the left hand side of rules. Example 25 (deftemplate group ;declaration of fuzzy variable group \x11\x110 20 members ((few (3 1) (6 0)) ;primary term few \x11(many (4 0) (6 1)) ;primary term many ) ) (defrule simple-LHS (group few) ;a simple fuzzy LHS pattern \x11\x11... ) Example 26 (defrule more-complex-lhs \x11\x11?f <- (group very few or very many) \x11=> \x11\x11(printout t "We are at the extreme limits of the number of" \x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11(get-u-units ?f) " in our club" crlf) ) Example 27 (deftemplate height \x11\x110 8 feet \x11((short (Z 3 4.5)) \x11\x11(medium (pi 0.8 5)) \x11\x11(tall (S 5.5 6)) \x11) ) (deftemplate person \x11\x11(slot name) \x11\x11(slot ht (type FUZZY-VALUE height)) ) (defrule quite-complex-lhs \x11\x11(person (name ?n) (ht ?h & very tall)) \x11=> \x11\x11(printout t ?n " is very tall, with a height of about " \x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11(maximum-defuzzify ?h) " " \x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11(get-u-units ?h) crlf ) ) In the last example ?h will become the fuzzy value which matches the very tall specifica- tion. It can then be used as an argument to various functions that can process fuzzy values, such as maximum-deffuzzify or get-u-units. 5.5 Using Fuzzy Variables in Deffacts Constructs The syntax of the deffacts construct has been extended to allow fuzzy facts to be declared. Both fuzzy and non-fuzzy (crisp) facts can be declared in the same deffacts construct. Also certainty factors for crisp or fuzzy facts may be specified. Fuzzy fact specifications in a deffacts construct have the following form: (deffacts [] * ) where has been extended as follows ::= | | := ( +) [CF | ] ::= (deftemplate-name> *) [CF | ] := ( [CF | ] where The certainty factor (CF) is optional (if not specified a CF of 1.0 is assumed) The is a or a (section 5.1.1.2) fuzzy set specification or a (section 5.1.1.1) fuzzy set description. The ability to use global variables and function calls is as per standard deffacts statements. Also note that a RHS-slot may be a slot of type FUZZY-VALUE. Example 28 (deffacts groupA "some fuzzy facts" (my_group (1 0) (5 1) (7 0)) ;singleton description (your_group (z 4 8)) ;standard descriptio n (their_group (s (+ 1 1) 4)) \x11\x11\x11\x11(person (name ralph) (ht tall)) ) (deffacts groupB "some fuzzy facts with certainty factors" (this_group (1 0) (5 1) (7 0)) CF 0.35 (that_group (pi 2 (+ 3 4))) CF (+ .2 .3) ) 5.6 Using Fuzzy Variables in Assert Statements The syntax of the assert construct has been expanded to allow fuzzy facts as arguments, and for the certainty factor of a crisp or fuzzy fact to be specified. The assert command (with a single fact asserted in an assert function call) is of the form: (assert ( | fuzzy-variable-name | \x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11(template-name +) [CF | ] ) where + indicates that there are one or more of the entries; at least one of these is a ; and a is ( fuzzy-slot-name ) and is \x11| \x11\x11\x11|\x11\x11 and the certainty factor is optional (if not specified a CF of 1.0 is assumed). Some examples will illustrate the forms allowed for asserting fuzzy facts and fuzzy deftemplate facts. Example 29 (assert (group few)) (assert (group (1 0) (5 1) (7 0)) ) (assert (group NOT [ very few OR many ] )) (assert (group (z 4 8)) ) (assert (person (name john) (ht extremely tall))) (assert (person (name dan) (ht (pi 0 5.6))) (assert (temp (24 0) (25 1) (26 0))) Example 30 (defrule assert-rule-1 (zmin ?minval) ;variable ?minval must be numeric (zmax ?maxval) ;variable ?maxval must be numeric \x11\x11=> (assert (group (z ?minval ?maxval)) ) ;fuzzy set description with variables ) (defrule assert-rule-2 ;asserts standard set with functions (zmin ?minval) (zmax ?maxval) \x11\x11=> (assert (group (z ?minval (+ ?maxval 2)))) ) (defrule assert-rule-3 ; asserts singleton set with functions (x1 ?x1val) (x2 ?x2val) \x11\x11=> (assert (group (?x1val 0) (?x2val 1) ((+ ?x2val 1) 0.6) ((sqr ?x2val) 0)) ) ) The assert-string function of CLIPS may also be used to assert fuzzy facts. The rules for constructing the strings is as described in the CLIPS reference manual. Example 31 (assert-string "(group (z 4 8))") (assert-string "(group (s 4 (+ 5 3)))") (assert-string "(person (name bob) (ht medium))") The is a constant numeric value between 0.0 and 1.0. Example 32 (assert (somefact) CF 0.8) ;with CF of 0.8 (assert (group few) CF (+ 0.2 0.4) ) ;with CF of 0.6 Note that the certainty factor will be calculated as described in section 4.3.5. A has the same syntax as a , except that the constant numeric value may be replaced by a variable or function which returns a numeric value between 0.0 and 1.0. Example 33 ( defrule assert-rule-4 ;illustrates various CF assertions (certainty-factor ?cf) ;where ?cf is between 0 and 1 ?f <- (somefact) \x11\x11=> (assert (fact1) CF ?cf) (assert (fact3) CF (* 0.8 ?cf)) (assert (fact5) CF (get-cf ?f)) ;get-cf is a function discussed in section \x115.7 ) 5.7 Defuzzification A crisp value may be extracted from a fuzzy set using either the centre of gravity or mean of maxima techniques developed in section \x114.4. The syntax is as follows: (moment-defuzzify ? | integer | )\x11\x11\x11 ; COG algorithm (maximum-defuzzify ? | integer | ) ; MOM algorithm The argument may be fact variable (?) which normally is bound on the LHS of a rule as described in the CLIPS Reference Manual. It may be the integer value of a fact number (i.e. the index of the fact on the fact list). It may also be a which can be obtained (among other ways) by matching in the pattern of a fuzzy deftemplate fact or a FUZZY-VALUE slot. These functions return a floating point number which is the result of performing the defuzzification. Example 34 Suppose that fact-1 (a fuzzy deftemplate fact) on the fact list is (temperature warm) and that the COG method returns a value of 28, while the MOM method returns a value of 32.5. When the following defuzzification command is issued at the CLIPS prompt level it will return the value 28.0 and display this value at the CLIPS prompt level (moment-defuzzify 1) When either of the following rules are executed they will print `Temperature is 32.5'. (defrule defuzzification-1 ?f <- (temperature ?) ;? used to assure match of the \x11\x11 ;temperature fuzzy fact => (bind ?t (maximum-defuzzify ?f)) ;get the value (printout t "Temperature is " ?t crlf) ;print 32.5 ) (defrule defuzzification-2 (temperature ?fv) ;?fv used to hold the fuzzy value \x11\x11 ;of the matching fuzzy fact => (printout t "Temperature is " (maximum-defuzzify ?fv) crlf) ) 5.8 Certainty Factors of Rules This section will discuss the syntax for declaring the certainty factor of rules. The certainty factor of a rule may be declared in a manner similar to declaring the rule salience: (defrule some-rule (declare (CF )) ...... \x11\x11=> ...... ) The is a number between and including 0 and 1. Example 35 (deffacts initial-facts (fact1) CF 0.8 ;fact with crisp CF of 0.8 ) (defrule some-other-rule (declare (CF 0.7)) ;a rule with CF of 0.7 (fact1) \x11\x11=> (printout t "Hello!") ) 5.9 FuzzyCLIPS Commands and Functions A number of commands supplied with CLIPS can be used to look at fuzzy facts and tem- plates just as one looks at standard facts (see commands facts, ppdeftemplate, list-deftem- plates, undeftemplate, ppdeffacts, list-deffacts, undeffacts). The following commands or functions add capability to access components of fuzzy facts, control thresholds for rule firings, set precision for fuzzy set display, set the fuzzy inference type, set a threshold for fuzzy pattern matching, create and manipulate fuzzy values, etc. 5.9.1 Accessing the universe of discourse (get-u, get-u-from, get-u-to, get-u-units) Command: get-u Syntax: (get-u ?)\x11\x11 or\x11\x11\x11 (get-u ) \x11or (get-u ) \x11or (get-u ) where ? is a fact variable, normally bound on the LHS of a rule; is the number of a fact on the fact list (constant or expression); is a symbol that represents the name of a fuzzy deftemplate; is an element of type FUZZY-VALUE Purpose: Returns a string of the form: " - ", the limits of the uni- verse of discourse and the units (if specified). If no units have been declared in the deftemplate statement, then the function just returns " - ". Example 36 (get-u ?t)\x11\x11\x11\x11\x11\x11\x11;; ?t is bound to the temp fuzzy fact (get-u 2) \x11\x11\x11\x11\x11\x11\x11;; 2 is a fact index (get-u temp)\x11\x11\x11\x11\x11;; temp is the name of the fuzzy deftemplate (defrule test \x11\x11(temp ?fv) ;; ?fv is a fuzzy value \x11=> \x11\x11(printout t (get-u ?fv)) ) Command: get-u-from Syntax: (get-u-from ?)\x11\x11or (get-u-from ) \x11or (get-u-from ) \x11or (get-u-from ) Purpose: Returns the lower limit of the universe of discourse in floating point format. Command: get-u-to Syntax: (get-u-to ?)\x11\x11or (get-u-to ) \x11or (get-u-to ) \x11or (get-u-to ) Purpose: Returns the upper limit of the universe of discourse in floating point format. Example 37 ;; Deffunction fuzzify ;; ;; Inputs: ?fztemplate - name of a fuzzy deftemplate ;; \x11\x11\x11\x11\x11\x11\x11\x11\x11\x11?value \x11\x11\x11\x11\x11\x11- float value to be fuzzified ;; \x11\x11\x11\x11\x11\x11\x11\x11\x11\x11?delta \x11\x11\x11\x11\x11\x11- precision of the value ;; ;; Asserts a fuzzy fact for the fuzzy deftemplate. The fuzzy set is ;; a triangular shape centered on the value provided with zero ;; possibility at value+delta and value-delta. Note that it ;; checks bounds of the universe of discourse to generate a fuzzy ;; set that does not have values outside of the universe range. (deffunction fuzzify (?fztemplate ?value ?delta) \x11\x11(bind ?low (get-u-from ?fztemplate)) \x11\x11(bind ?hi (get-u-to ?fztemplate)) \x11\x11(if (<= ?value ?low) \x11\x11\x11\x11then \x11\x11\x11\x11\x11\x11(assert-string \x11\x11\x11\x11\x11\x11\x11\x11\x11(format nil "(%s (%g 1.0) (%g 0.0))" \x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11?fztemplate ?low ?delta)) \x11\x11\x11\x11else \x11\x11\x11\x11\x11\x11(if (>= ?value ?hi) \x11\x11\x11\x11\x11\x11\x11\x11then \x11\x11\x11\x11\x11\x11\x11\x11\x11\x11(assert-string \x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11(format nil "(%s (%g 0.0) (%g 1.0))" \x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11?fztemplate (- ?hi ?delta) ?hi)) \x11\x11\x11\x11\x11\x11\x11\x11else \x11\x11\x11\x11\x11\x11\x11\x11\x11\x11(assert-string \x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11(format nil "(%s (%g 0.0) (%g 1.0) (%g 0.0))" \x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11?fztemplate (max ?low (- ?value ?delta)) \x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11?value (min ?hi (+ ?value ?delta)) )) \x11\x11\x11\x11\x11\x11\x11) \x11\x11\x11\x11) ) As an example the following uses the fuzzify function: (deftemplate temp \x11\x11\x110 100 Degrees-F \x11\x11\x11( (warm (30 0) (60 1) (90 0)) \x11\x11\x11) ) (defrule test \x11\x11\x11(temp warm) \x11=> \x11\x11\x11(bind ?x (assert (dummy))) \x11\x11\x11(printout t "Certainty Factor = " (get-cf ?x) crlf) \x11\x11\x11(retract ?x) ) Asserting a fuzzified fact with (fuzzify temp 50 0.001) and firing the rule `test' will result in the output: \x11\x11\x11Certainty Factor = 0.66667 Command: get-u-units Syntax: (get-u-units ?)\x11\x11or (get-u-units ) \x11or (get-u-units ) \x11or (get-u-units ) Purpose: Returns the units of the universe of discourse in string format. If no units have been specified, then the empty string, " ", is returned. 5.9.2 Accessing the fuzzy set (get-fs, get-fs-x, get-fs-y, get-fs-length, get-fs-lv, get-fs- value) Command: get-fs Syntax: (get-fs ?)\x11\x11or (get-fs ) \x11or (get-fs ) Purpose: Returns the entire fuzzy set in singleton representation, in string format. Command: get-fs-length Syntax: (get-fs-length ?)\x11\x11or (get-fs-length ) \x11or (get-fs-length ) Purpose: Returns the number of pairs in a fuzzy set description as an integer. Command: get-fs-x Syntax: (get-fs-x ? ) \x11or (get-fs-x ) \x11or (get-fs-x ) where is an integer, variable, or function expression. Purpose: Returns the x-coordinate of the ith pair in the fuzzy set, where the pairs are numbered left to right from 0 to (n-1), and n is the total number of pairs in the set. If the expression evaluates to a non-integer value, then it is truncated to the nearest integer. The x-coordinate is returned as a floating point value. Command: get-fs-y Syntax: (get-fs-y ? )\x11\x11or (get-fs-y ) \x11or (get-fs-y ) Purpose: Returns the y-coordinate of the ith pair in the fuzzy set as a floating point value. Example 38 Suppose the fuzzy fact (temperature ???) was fact-2 on the fact list (the ??? indicates that the fuzzy set is not expressible using terms and modifiers for that fuzzy variable; it may have been defined using a singleton description or modified by the compositional rule of inference). Suppose also that it has a fuzzy set consisting of the following 3 singletons ((0 0) (25 1) (40 0)). Then (get-fs-x 2 1) at the command line would return 25. In a rule one could do the following: (defrule print-last-coordinate ?f <- (temperature ?) => (bind ?n (get-fs-length ?f)) (bind ?x (get-fs-x ?f (- ?n 1))) (bind ?y (get-fs-y ?f (- ?n 1))) (printout t "The last point in the set is:" ?x "," ?y crlf) ) \x11\x11\x11\x11OR (defrule print-last-coordinate (temperature ?fv) => (bind ?n (get-fs-length ?fv)) (bind ?x (get-fs-x ?fv (- ?n 1))) (bind ?y (get-fs-y ?fv (- ?n 1))) (printout t "The last point in the set is:" ?x "," ?y crlf) ) Command: get-fs-lv Syntax: (get-fs-lv ?)\x11\x11or (get-fs-lv ) \x11or (get-fs-lv ) Purpose: Returns the returns the linguistic value associated with the fuzzy set. Example 39 if (temp very hot) is asserted and the variable ?fuzzyfact is assigned to this fact then the function call (get-fs-lv ?fuzzyfact) would return the string "very hot" Command: get-fs-value Syntax: (get-fs-value ? )\x11\x11or (get-fs-value ) \x11or (get-fs-value ) Purpose: Returns the returns the value of the fuzzy set at the specified x value (). The is a value that must lie between the lower and upper lim- its of the universe of discourse for the fuzzy set. Example 40 Suppose we have defined the following (deftemplate temp \x11\x110 100 C \x11\x11( \x11\x11\x11\x11\x11... \x11\x11\x11\x11(OK (30 0) (60 1) (90 0)) \x11\x11\x11\x11\x11... \x11\x11) ) and we assert the fact (temp OK). Then if we bind that fact to a variable ?fact we could call (get-fs-value ?fact 50.0) and it would return 0.6666667 5.9.3 Accessing the certainty factor (get-cf) Command: get-cf Syntax: (get-cf ?) (get-cf ) \x11or Purpose: Returns the certainty factor of a fact as a floating point number. Example 41 Suppose a fact on the fact list is (temperature cold) CF 0.7. (defrule print-cf-rule \x11\x11\x11?f <- (temperature ?) \x11=> \x11\x11\x11(printout t "The certainty of the temperature measurement is: " (get-cf ?f)) ) Then the above rule will print "The certainty of the temperature measurement is: 0.7". 5.9.4 Accessing the threshold certainty factor (threshold, get-threshold) Command: threshold Syntax: (threshold ) Purpose: Sets threshold certainty factor to the value of . must evaluate to a floating value between 0.0 and 1.0. By default the threshold value is 0.0. Command: get-threshold Syntax: (get-threshold) Purpose: Returns the floating point value of the threshold certainty factor if threshold capability is ON. If it is OFF, then a value of 0.0 is returned. 5.9.5 Setting the Rule CF Evaluation Behaviour (set-CF-evaluation, set-CF-evalua- tion) Command: set-CF-evaluation Syntax: (set-CF-evaluation ) Purpose: Sets the behavior for evaluating the CF of rules to . Value must be one of when-defined (default) or when-activated. This is simi- lar to the set-salience-evaluation function of CLIPS. The value when-defined forces the rule's certainty factor to be evaluated at time of rule definition (com- pilation). The value when-activated forces the rule's certainty factor to be defined at the time of rule definition and when the rule is activated (added to the agenda). Command: get-CF-evaluation Syntax: (get-CF-evaluation) Purpose: Returns the current setting of the behavior for evaluating the CF of rules. Return value is either when-defined or when-activated. This is similar to the get-salience-evaluation function of CLIPS. 5.9.6 Controlling the Fuzzy Set Display Precision (set-fuzzy-display-precision, get- fuzzy-display-precision) Command: set-fuzzy-display-precision Syntax: (set-fuzzy-display-precision ) Purpose: When fuzzy facts are displayed the fuzzy set values are displayed in floating point format. This function allows the number of significant digits displayed after the decimal point to be set. The argument is an integer value between 2 and 16. If it is less than 2 it is set to 2 and if it is greater than 16 it is set to 16. The default value is 4. Note that clear will not reset this value to 4. Example 42 (set-fuzzy-display-precision 16) (facts) f-0 (speed_error more_or_less large_positive) CF 1.00 ( (0.0 0.0) (0.1 0.3162277660168379) (0.2 0.4472135954999579) (0.3 0.5477225575051661) (0.35 0.5916079783099616) (0.4 0.6324555320336759) (0.5 0.7071067811865476) (0.6 0.7745966692414834) (0.7 0.8366600265340756) (0.8 0.8944271909999159) (0.9 0.9486832980505138) (1.0 1.0) ) (set-fuzzy-display-precision 2) (facts) f-0 (speed_error more_or_less large_positive) CF 1.00 ( (0.0 0.0) (0.1 0.32) (0.2 0.45) (0.3 0.55) (0.35 0.59) (0.4 0.63) (0.5 0.71) (0.6 0.77) (0.7 0.84) (0.8 0.89) (0.9 0.95) (1.0 1.0) ) Command: get-fuzzy-display-precision Syntax: (get-fuzzy-display-precision) Purpose: Returns an integer value that is the current display precision. 5.9.7 Controlling the Fuzzy Inference Method (set-fuzzy-inference-type, get-fuzzy- inference-type) Command: set-fuzzy-inference-type Syntax: (set-fuzzy-inference-type ) Purpose: Sets the current inference type to one of max-min or max-prod. The default is max-min. The effect of this is described in more detail in section 4.3.1.3. Note that clear will not reset this value to max-min. Command: get-fuzzy-inference-type Syntax: (get-fuzzy-inference-type) Purpose: Returns a symbol that is one of max-min or max-prod indicating the current inference type. 5.9.8 Setting the Fuzzy Pattern Matching Threshold (set-fuzzy-inference-type, get- fuzzy-inference-type) Command: set-alpha-value Syntax: (set-alpha-value ) Purpose: When fuzzy slots are matched to fuzzy patterns on the LHS of rules, the match is considered to be successful if there is any overlap (intersection) between the two fuzzy sets involved in the matching. This function allows the match to suc- ceed only if the maximum of intersection set has a membership value greater than this threshold. The default alpha-value is 0.0. There will be a performance penalty if the value is other than 0.0, since currently it is very simple to test for non-intersection (no overlap) but when a threshold other than 0.0 is used the intersection of the sets must be performed. Note that a clear does not reset the alpha-value to 0.0. Example 43 (deftemplate temp 0 100 C ( (low (10 1) (50 0)) (ok (20 0) (50 1) (80 0)) (high (50 0) (90 1)) ) ) (defrule test-alpha (temp low) => (printout t "Rule fired ****" crlf) ) (set-alpha-value 0.0) (assert (temp (pi 0 30))) (run) ; rule should fire with alpha 0.0 Rule fired **** (retract *) (set-alpha-value 0.5) (assert (temp (pi 0 30))) (run) ; rule should fire with alpha 0.5 Rule fired **** (retract *) (set-alpha-value 0.55) (run) ; rule should NOT fire with alpha 0.55 ;; no output here -- match was not successful Command: get-alpha-value Syntax: (get-alpha-value) Purpose: Returns a floating point value which is the current alpha-value. 5.9.9 Fuzzy Value Predicate Function (fuzzvaluep) Command: fuzzyvaluep Syntax: (fuzzyvaluep\x11 ) Purpose: This function returns TRUE if the argument is of type FUZZY-VALUE, other- wise it will return FALSE. Example 44 (fuzzyvaluep 45.6) FALSE (fuzzyvaluep "string") FALSE (fuzzyvaluep (create-fuzzy-value temp cold)) TRUE (defrule check-fuzzyvaluep \x11\x11(temp ?fv & cold) \x11=> \x11\x11(fuzzyvaluep ?fv) ) (assert (temp cold)) (run) TRUE 5.9.10 Creating and operating on FUZZY-VALUEs (create-fuzzy-value, fuzzy-union, fuzzy-intersection, fuzzy-modify) Command: create-fuzzy-value Syntax: (create-fuzzy-value ) Purpose: This function allows a fuzzy value to be created. A fuzzy value is a fuzzy set which is associated with a particular fuzzy deftemplate. The fuzzy deftemplate determines the universe of discourse for the fuzzy set and the terms that can be used to describe the fuzzy set. The first argument, , is the name of a fuzzy deftemplate. The remaining parts describe the fuzzy set as is done for a fuzzy slot when a fuzzy fact is asserted. This can be a linguistic expression, a singleton specification or a standard function expression (see sec- tion 5.1.1). Example 45 (create-fuzzy-value temp cold) (create-fuzzy-value temp very hot or very cold) (create-fuzzy-value temp (pi 10 20)) (create-fuzzy-value temp (s ?x (+ ?x 10))) (create-fuzzy-value temp (10 1) (20 0)) (defrule test \x11\x11=> \x11\x11\x11\x11(bind ?fv (create-fuzzy-value temp cold)) \x11\x11\x11\x11(assert (temp ?fv)) ; NOTE use of variable here! ) Command: fuzzy-union Syntax: (fuzzy-union ) Purpose: Returns a new fuzzy value that is the union of two other fuzzy values. Both arguments must be of type FUZZY-VALUE. Example 46 (deftemplate temp \x11\x11\x110 100 C \x11\x11((cold (z 20 70)) \x11\x11(hot (s 30 80)) \x11\x11) ) (fuzzy-union (create-fuzzy-value temp cold) \x11\x11\x11\x11\x11(create-fuzzy-value temp hot)) cold or hot (plot-fuzzy-value t ".+*" nil nil \x11\x11\x11\x11\x11\x11(create-fuzzy-value temp cold) \x11\x11\x11\x11\x11\x11(create-fuzzy-value temp hot) \x11\x11\x11\x11\x11\x11(fuzzy-union (create-fuzzy-value temp cold) \x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11(create-fuzzy-value temp hot)) ) Fuzzy Value: temp Linguistic Value: cold (.), hot (+), [ cold ] OR [ hot ] (*) 1.00************* ************* 0.95 ** ** 0.90 ** ** 0.85 * * 0.80 * * 0.75 * * 0.70 * * 0.65 0.60 * * 0.55 * * 0.50 0.45 * * 0.40 * * 0.35 + 0.30 * 0.25 + . 0.20 + . 0.15 + . 0.10 ++ .. 0.05 ++ .. 0.00++++++++++++++++++ .................. |----|----|----|----|----|----|----|----|----|----| 0.00 20.00 40.00 60.00 80.00 100.00 Command: fuzzy-intersection Syntax: (fuzzy-intersection ) Purpose: Returns a new fuzzy value that is the intersection of two other fuzzy values. Both arguments must be of type FUZZY-VALUE. Example 47 (fuzzy-intersection (create-fuzzy-value temp cold) \x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11(create-fuzzy-value temp hot)) cold and hot (plot-fuzzy-value t ".+*" nil nil \x11\x11\x11\x11\x11\x11(create-fuzzy-value temp cold) \x11\x11\x11\x11\x11\x11(create-fuzzy-value temp hot) \x11\x11\x11\x11\x11\x11(fuzzy-intersection (create-fuzzy-value temp cold) \x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11(create-fuzzy-value temp hot)) ) Fuzzy Value: temp Linguistic Value: cold (.), hot (+), [ cold ] AND [ hot ] (*) 1.00............. +++++++++++++ 0.95 .. ++ 0.90 .. ++ 0.85 . + 0.80 . + 0.75 . + 0.70 . + 0.65 0.60 . + 0.55 . + 0.50 0.45 . + 0.40 . + 0.35 + 0.30 * 0.25 * * 0.20 * * 0.15 * * 0.10 ** ** 0.05 ** ** 0.00****************** ****************** |----|----|----|----|----|----|----|----|----|----| 0.00 20.00 40.00 60.00 80.00 100.00 Command: fuzzy-modify Syntax: (fuzzy-modify ) Purpose: Returns a new fuzzy value that is a modification of the fuzzy value argument. The modification performed is specified by the modifier argument. This modi- fier can be any active modifier (very, slightly, etc.). Example 48 (plot-fuzzy-value t "+*" nil nil (create-fuzzy-value temp hot) (fuzzy-modify (create-fuzzy-value temp hot) extremely)) Fuzzy Value: temp Linguistic Value: hot (+), extremely hot (*) 1.00 ++*********** 0.95 ++** 0.90 ++ * 0.85 + * 0.80 + 0.75 + * 0.70 + * 0.65 0.60 + * 0.55 + 0.50 * 0.45 + 0.40 + * 0.35 + 0.30 * 0.25 + 0.20 + * 0.15 + * 0.10 ++ * 0.05 ++ ** 0.00************************* |----|----|----|----|----|----|----|----|----|----| 0.00 20.00 40.00 60.00 80.00 100.00 5.9.11 Accessing a Fuzzy Slot in a Fact (get-fuzzy-slot) Command: get-fuzzy-slot Syntax: (get-fuzzy-slot ? [ ]) (get-fuzzy-slot [ ]) Purpose: This function will retrieve the fuzzy value associated with a fuzzy slot in a fact. The first argument can be a variable that is associated with a fact address or an integer that is the fact number for a fact. If the fact is a fuzzy deftemplate fact (one whose relation name is a fuzzy deftemplate name) then the second argu- ment is not needed since the only slot for the fact is the fuzzy value. If the fact is a standard deftemplate fact with fuzzy slots, then the second argument is a symbol that identifies the slot to access. (Note that the slot of fuzzy deftemplate facts is always name `GenericFuzzySlot' and it could be accessed using that name.) Example 49 (defrule test1-get-fuzzy-slot \x11\x11?f <- (temp hot) \x11=> \x11\x11(plot-fuzzy-value t * nil nil (get-fuzzy-slot ?f)) ) (defrule test2-get-fuzzy-slot \x11\x11?f <- (system (name sysA) (t-outflow hot)) \x11=> \x11\x11(plot-fuzzy-value t * nil nil (get-fuzzy-slot ?f t-outflow)) ) 5.9.12 Displaying a Fuzzy Value in a Format function This is not a function or comand but is an addition to CLIPS to allow the formatting of fuzzy values in a format function. The specifier %F is used. Example 50 (deftemplate temp \x11\x11\x110 100 C \x11((cold (z 20 50))) ) (assert (temp cold)) (format t "Value is '%F'%n" (get-fuzzy-slot 0)) Value is 'cold' 5.9.13 Plotting a Fuzzy Value (plot-fuzzy-value) Command: plot-fuzzy-value Syntax: (plot-fuzzy-value \x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11+) Purpose: This function is used to plot fuzzy sets. The arguments are: is any open router to direct the output to (e.g. t for the standard output) specifies the characters to be used in plotting (e.g. * or "*+.") - for each fuzzyvalue specified a corresponding character from the string or symbol is used as the plotting symbol -- if more fuzzyvalues than symbols are specified then the last symbol is used for the remain- ing plots is a numeric value that specifies the lowest x value to be displayed in the plot OR if it is not a numeric value then it will default to the low limit of the universe of discourse is a numeric value that specifies the highest x value to be dis- played in the plot OR if it is not a numeric value then it will default to the high limit of the universe of discourse is one of 3 things - an integer that identifies a fuzzy deftemplate fact (in this case the fuzzy value from the fact is extracted and used) - a variable with a fuzzy deftemplate fact address (in this case the fuzzy value from the fact is extracted and used) - a variable with a fuzzy value The + identifies that 1 or more arguments may be present. The fuzzy deftemplate associated with ALL fuzzy values to be plotted on the same plot must be the same one. This is required since the x axis must have the same meaning. The and values allow a window of the universe of discourse to be displayed and provides for scaling the graph in the x axis. Example 51 (deftemplate temp \x11\x11\x110 100 C \x11\x11((cold (z 20 70)) \x11\x11(hot (s 30 80)) \x11\x11) ) (plot-fuzzy-value t * nil nil (create-fuzzy-value temp hot)) Fuzzy Value: temp Linguistic Value: hot (*) 1.00 ************* 0.95 ** 0.90 ** 0.85 * 0.80 * 0.75 * 0.70 * 0.65 0.60 * 0.55 * 0.50 0.45 * 0.40 * 0.35 * 0.30 0.25 * 0.20 * 0.15 * 0.10 ** 0.05 ** 0.00****************** |----|----|----|----|----|----|----|----|----|----| 0.00 20.00 40.00 60.00 80.00 100.00 Universe of Discourse: From 0.00 to 100.00 (plot-fuzzy-value t * 20 70 (create-fuzzy-value temp hot)) Fuzzy Value: temp Linguistic Value: hot (*) 1.00 0.95 0.90 *** 0.85 ** 0.80 ** 0.75 ** 0.70 ** 0.65 * 0.60 * 0.55 ** 0.50 * 0.45 ** 0.40 * 0.35 ** 0.30 * 0.25 ** 0.20 ** 0.15 ** 0.10 *** 0.05 ***** 0.00*************** |----|----|----|----|----|----|----|----|----|----| 20.00 30.00 40.00 50.00 60.00 70.00 Universe of Discourse: From 0.00 to 100.00 Example 52 (deftemplate system (slot name) \x11\x11\x11 (slot t-outflow (type FUZZY-VALUE temp)) ) (assert (system (name sysA) (t-outflow not hot))) (plot-fuzzy-value t "+*" nil nil (create-fuzzy-value temp hot) (get-fuzzy-slot 1 t-outflow) ) Fuzzy Value: temp Linguistic Value: hot (+), not hot (*) 1.00****************** +++++++++++++ 0.95 ** ++ 0.90 ** ++ 0.85 * + 0.80 * + 0.75 * + 0.70 * + 0.65 0.60 * + 0.55 *+ 0.50 0.45 +* 0.40 + * 0.35 + * 0.30 0.25 + * 0.20 + * 0.15 + * 0.10 ++ ** 0.05 ++ ** 0.00++++++++++++++++++ ************* |----|----|----|----|----|----|----|----|----|----| 0.00 20.00 40.00 60.00 80.00 100.00 Universe of Discourse: From 0.00 to 100.00 5.10 Simple example This section describes the output of watching facts and rules fire for the example found in the file simplTst.clp (Please note that this was not intended to be a real example of the use of FuzzyCLIPS. For that see the other examples included in the distribution). CLIPS> (load "simplTst.clp") Defining deftemplate: speed_error Defining deftemplate: speed_change Defining deffacts: my_facts Defining defrule: speed-too-fast +j Defining defrule: speed-ok +j Defining defrule: get-crisp-value-and-print-result +j TRUE CLIPS> (reset) ==> f-0 (initial-fact) CF 1.00 ==> f-1 (speed_error zero) CF 0.90 [ linguistic description of fuzzy set ] (\x11 (0.0 1.0) \x11(0.11 0.0) ) [ singletons describe fuzzy set in detail ] ==> Activation 0 speed-ok: f-1 ==> Activation 0 speed-too-fast: f-1 CLIPS> (run) FIRE 1 speed-too-fast: f-1 ==> f-2 (speed_change ???)\x11 CF 0.63 [ CF = 0.9 * 0.7 for fuzzy-fuzzy rule ] (\x11 (0.1 0.0) \x11(0.1495 0.0991) ) ==> Activation -1 get-crisp-value-and-print-result: f-2 FIRE 2 speed-ok: f-1 ~~~ f-2 (speed_change ???) \x11CF 0.63 ( \x11(0.0 1.0)\x11\x11 (0.1 0.1) \x11(0.1333 0.06667)\x11\x11(0.1495 0.0991)\x11 ) [ ~~~ means fuzzy set being modified ] FIRE 3 get-crisp-value-and-print-result: f-2 Change speed by a factor of: 0.3553202565269306 <== Focus MAIN 3 rules fired Run time is 0.08600000000024011 seconds. 34.88372093013516 rules per second. 3 mean number of facts (3 maximum). 1 mean number of instances (1 maximum). 1 mean number of activations (2 maximum). CLIPS> 6.0 Continuous Systems This section describes further extensions made to CLIPS to take care of the needs of con- tinuously operating systems. a. The Run Command Normally, CLIPS terminates when the agenda is empty. For real-time systems (or any con- tinuously operating system) there is need for a mechanism that allows the inference engine to idle, waiting for events to occur. In FuzzyCLIPS the run command is extended to receive any of the following parameters: \x11n (a positive integer) \x11\x11FuzzyCLIPS will run until n rules have executed or until the agenda is empty, whichever comes first. e.g. (run 10) -1 FuzzyCLIPS runs until the agenda is empty. \x11\x11e.g. (run -1) -2 FuzzyCLIPS runs forever. Control-C interrupts the execution. e.g. (run -2) -n (a negative integer less than -2).\x11\x11 FuzzyCLIPS runs until n rules have executed. e.g. (run -10) The halt function can be called at any time to terminate the run. b. Runstart and Runstop Functions CLIPS allows users to call external functions that are executed at the end of each cycle of the inference engine (i.e. after each rule firing). This is done by calling the AddRunFunc- tion routine of CLIPS to include the function in the list of exec functions. In certain cases, however, it is useful to be able to execute special routines on entry or exit from the run command. The runstart and runstop functions of FuzzyCLIPS allow this. This could be useful in situations where a simulated clock is used to keep track of time. When the sys- tem is stopped (with (run -n) or control-C), one would want the simulated clock to stop too. When the system is resumed, one would want the clock to resume from where it left off when the system was stopped (i.e. without advancing during the stopped interval). A function is added to the list of functions called when the run command is executed by calling the AddRunStartFunction. It can be removed from this list by calling the Remov- eRunStartFunction. Similarly, a function is added to the list of functions called when the run command is terminated by calling the AddRunStopFunction. It can be removed from this list by calling the RemoveRunStopFunction. (Note: these external functions must have been previously defined as user functions.) The following are examples of calls to these four functions. AddRunStopFunction("haltTimer",haltTimer,1); AddRunStartFunction("continueTimer",continueTimer,1); RemoveRunStopFunction("haltTimer"); RemoveRunStartFunction("continueTimer"); The AddRunStopFunction and AddRunStartFunction functions have 3 arguments: a string name of the function to be added; a pointer to a function to be executed; and a priority for the function. 7.0 CLIPS Functionality within FuzzyCLIPS 7.1 Modifying and Duplicating Facts The CLIPS functions modify and duplicate are not relevant for fuzzy facts. These func- tions will always return FALSE when used with fuzzy facts. 7.2 Load, Save, Bload, Bsave, Load-facts, Save-facts The CLIPS functions load, save, bload, bsave, load-facts and save-facts should all work correctly with FuzzyCLIPS programs that include fuzzy facts, fuzzy deftemplates, and certainty factors. 7.3 Constructs-to-c Creating a runtime version of a FuzzyCLIPS program can be done as for a normal CLIPS program using the constructs-to-c function and following the instructions in the CLIPS manuals. 7.4 CreateFact, GetFactSlot, PutFactSlot Functions defined in the advanced user's guide like CreateFact, GetFactSlot and Put- FactSlot will be usable with FuzzyCLIPS however the exact details for creating and accessing Fuzzy Values will require some further detailed knowledge of the internal struc- tures of FuzzyCLIPS. Contact NRC if these are needed. Other functions to support embedded applications and user extensions to FuzzyCLIPS may be needed and suggestions will be entertained. Contact NRC with details. 8.0 Changes from the CLIPS 6.02 Version of FuzzyCLIPS to 6.02A 8.1 Vertical lines in fuzzy sets The previous version of FuzzyCLIPS did not allow vertical lines to be used in the descrip- tion of a fuzzy set. We now allow vertical lines in the fuzzy sets. For example, ___________ | | | | | | | | -------- -------- This means 2 consecutive x values can be the same (with different y values). Also 3 con- secutive values can be used to define a fuzzy representation of a crisp number. Consider, | | | | | ----------------- This could be define as (5 0) (5 1) (5 0) OR (pi 0 5). If there are 4 consecutive points with the same x values then only 3 of them will be kept. For example, (5 0) (5 1) (5 .3) (5 .7) will be changed to (5 0) (5 1) (5 .7) We can even have the following: \x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11| | | | | | | | | |---- | | | \ ----------------- \------ or any such shape with vertical bars. The caution is to note that when 'moment' defuzzifying a set with these types of shapes, there is no area under these peaks and therefore no 'moment' and they will not contribute to the calculation of the defuzzified value. 'maximum' defuzzification will be as expected. 8.2 Expanded Syntax for Linguistic Expressions Previously the syntax for linguistic expressions: (NOT [ very cold OR hot ] ) was somewhat restrictive. It does not allow expressions that use the AND (intersection) operator. It does not allow NOT to appear more than once in an expression. Therefore one cannot say: (NOT hot AND NOT cold) This syntax has been extended to give a more normal set of expressions with AND allowed as well as OR. Brackets [ and ] still are used to group sub expressions as in: [ hot AND cold ] OR OK Modifiers (hedges) have the highest precedence followed by AND and then by OR. They will be evaluated left to right. Note that 'not' is not a special artifact anymore -- it is just another modifier Therefore, A OR B AND C OR D is the same as A OR [ B AND C ] OR D The BNF for these expressions is as follows: ::= | OR ::= | AND ::= MODIFIER | ::= PRIMARY-TERM | [ ] 8.3 Linguistic Expresions in Fuzzy Deftemplate Definitions In a fuzzy deftemplate definition one can now use previously defined terms and any active modifiers to define terms. (deftemplate temp 0 100 C \x11\x11\x11\x11\x11\x11( (cold (Z 5 20)) (hot (S 80 95)) (ok NOT [ cold OR hot ] )\x11\x11\x11\x11<- this is new \x11\x11\x11\x11\x11\x11) ) 8.4 Fuzzy Modifiers (Hedges) are Handled in a New Way The previous version of FuzzyCLIPS had no predefined modifiers. Also the modifiers were defined in fuzzy deftemplate constructs. The new version changes this significantly. This is the only change that will affect existing programs. a number of modifiers are predefined and available for use in any linguistic expression. These are very, extremely, more-or-less, somewhat, norm, slightly, intensify, plus, above, and below. User defined modifiers can be added from the CLIPS code level (see add-fuzzy-modifier and remove- fuzzy-modifier) and from the `C' code level. See sections 5.3.1 and 5.3.2. 8.5 Plotting of Fuzzy Values A new function, plot-fuzzy-value, has been added to create ASCII plots of fuzzy sets. See section 5.9.12. 8.6 Fuzzy Alpha Value to Set Threshold for Fuzzy Pattern Matches Two functions, set-alpha.value and get-alpha-value have been added to control the sensi- tivity of matches between fuzzy patterns and fuzzy values in facts. See section 5.9.8 for details. 8.7 Two New Functions for Accessing Fuzzy Value Information The functions get-fs-lv and get-fs-value have been added. For details see section 5.9.2. 8.8 New Functions for Creating and Manipulating Fuzzy Values (exter- nal to facts) The functions fuzzyvaluep, create-fuzzy-value, fuzzy-union, fuzzy-intersection and fuzzy- modify have been added. See sections 5.9.9 and 5.9.10. But do note that these fuzzy val- ues created and manipulated can be used in various places including asserts of fuzzy deftemplate facts or fuzzy slots. \x11\x11\x11\x11\x11(defrule test \x11\x11\x11\x11\x11\x11\x11\x11\x11=> \x11\x11\x11\x11\x11\x11\x11\x11\x11(bind ?fv (create-fuzzy-value temp low)) \x11\x11\x11\x11\x11\x11\x11\x11(assert (temp ?fv)) \x11\x11\x11\x11\x11\x11) Note also a current restriction. The above cannot be written as: \x11\x11\x11\x11\x11(defrule test \x11\x11\x11\x11\x11\x11\x11\x11\x11=> \x11\x11\x11\x11\x11\x11\x11\x11(assert (temp (create-fuzzy-value temp low))) \x11\x11\x11\x11\x11\x11) 8.9 Ability to Set Inference Type to Max-min or Max-prod The two functions set-fuzzy-inference-type and get-fuzzy-inference-type are used to con- trol the method used to modify fuzzy conclusions in rules. For details see section 5.9.7. 8.10 Ability to Control Precision of Fuzzy Set Values When Displayed Two functions allow one to control the number of significant digits in the display of fuzzy set values. See section 5.9.6. 8.11 Fuzzy Slots allowed in Standard Deftemplates This is the most significant change to version 6.02A of FuzzyCLIPS. By defining a new type FUZZY-VALUE for deftemplate slots, one can now work with more complex deftemplates that include fuzzy sets. See section 5.2. 8.12 Accessing a Fuzzy Slot in a Fuzzy Deftemplate Fact or a Fuzzy Fact A function, get-fuzzy-slot, has been added to allow one to extract fuzzy values from slots in facts. See section 5.9.11. 8.13 Printing Fuzzy Values in a Format Function The specification %F can now be used in a format function to control the output of fuzzy values. At this time ONLY the linguistic values is displayed (e.g. very cold). 9.0 Limitations and Future Work The current version of FuzzyCLIPS has been tested with some diligence but there may be omissions or errors that are discovered. Future extensions/modifications to FuzzyCLIPS will depend on user feedback. As experience is gained using FuzzyCLIPS, it may be that users will find things that work in unexpected or undesirable ways. Please feel free to comment on such things in the interest of promoting a useful tool. One example of an area that might provoke some discussion is the maximum-defuzzify function which is used to defuzzify fuzzy facts. As pointed out in [\x114.4.2] this is a situation that is difficult to decide how best to handle. One solution is to perform the average of all discrete maximum values (as we have done in this implementation). Perhaps a better method would be to consider points that define a continuous range of x values all at the maximum value to be represented by the mid-point of that range plus a weight equal to the difference between the upper and lower x values of that range. A single point maximum would be represented by the x value plus a weight of zero. Then the defuzzified value would be calculated as a) if weights are all zero b) if not all weights are zero Consider the following two examples: Another possible source of discussion is the calculation of certainty factors. This can be quite difficult to understand, especially when complex rules are used. Could this be sim- plified and still retain the intensions as described in this document? A third possible problem area is the handling of truth maintenance via the logical con- struct in rules. Consider the following 2 rules: where temp is a fuzzy deftemplate (fuzzy variable). If both of these rules are fired then the temp fact will exist as (temp low OR medium) due to global contribution. If both facts (x) and (y) are retracted then the logical support for the temp fact will be lost and the fact will be retracted as expected. However, when one of the logically supporting facts is retracted the other still supports the fact and it remains asserted as (temp low OR medium). The effect of global contribution is not undone. For example, should the fact (x) be retracted then perhaps the effect of the assertion (temp low) should be undone leaving the fact as (temp medium). This is difficult to do without retaining a lot of extra information to assist in removing the effect of that assertion. How- ever, it would be possible to do this in another way. Instead of applying the effects of glo- bal contribution as fuzzy facts are asserted it could be delayed until required. That is when the two rules fire two facts are asserted: (temp low) with logical dependence on fact (x) (temp medium) with logical dependence on fact (y) This is similar to standard clips facts being asserted with the same template name but dif- ferent content in the slots. If the fact (x) is retracted then the fuzzy fact (temp low) is retracted but the fact (temp medium) would still remain. A function such as: (combine-evidence temp) could then be executed to create a single fact from all of the facts with the template temp. It would replace all of these facts with a single one and would need to deal with the depen- dencies of these facts in some way. Or, rather than having such a function and actually doing any combination of the facts into a single fact it could be that the defuzzification function(s) do this combining of evidence internally and produce a result that reflects this. We could in this case provide 2 types of functions for defuzzification: one that operates on individual fuzzy facts (no combining of evidence) and one that operates on fuzzy tem- plates (combining evidence of all facts for the template before doing the defuzzification). There may be other suggestions and possibilities. A third area that needs investigation is the idea of making FUZZY-VALUES a standard type in CLIPS (like integers, symbols, etc.). The current implementation has proceeded towards this goal and this may be a next logical step. This would allow FUZZY-VALUES to be stored in objects as well as in facts. Considerable effort is still needed to go this extra step and assistance from NASA or others would be appreciated. Bug reports and any suggestions for modifications and further extensions are welcome. Many, perhaps most of the enhancements from 6.02 to 6.02A were a result of feedback from users. Let's keep the communication going. 10.0 References 1 Artificial Intelligence Section, CLIPS Reference Guide Volume I Basic Programming Guide, CLIPS Version 6.0, Lyndon B. Johnson Space Center, June 2nd 1993. 2 Artificial Intelligence Section, CLIPS Reference Guide Volume II Advanced Program- ming Guide, CLIPS Version 6.0, Lyndon B. Johnson Space Center, June 2nd 1993. 3 E.H. Shortliffe, Computer-based medical consultation: MYCIN, New York, American Elsevier, 1976. 4 B.G. Buchanan, E.H. Shortliffe, Rule-Based Expert Systems, Addison-Wesley, Read- ing, Mass., 1984. 5 G. Shafer, A Mathematical Theory of Evidence, Princeton University Press, Princeton, N.J., 1976. 6 K.P. Adlassing, G. Kolarz, Representation and Semiautomatic Acquisition of Medical Knowledge in Cadiag-1 and Cadiag-2, Computers and Biomedical Research, vol.19, 1988, p.63-79. 7 T. Whalen, B. Schott, and F. Ganoe, Fault Diagnosis in Fuzzy Network, Proc. 1982 Int. Conf. Cybernetics and Society, IEEE Press, New York, 1982. 8 J. Buckley and W. Siler, Fuzzy Operators for Possibility Interval Sets, Fuzzy Sets and Systems, vol.22, 1987, p.215-27. 9 J.F. Baldwin, Evidential Support Logic Programming, Fuzzy Sets and Systems, vol.24, 1987, p.1-26. 10 K.S. Leung, W.S.F. Wong, and W. Lam, Application of a Novel Fuzzy Expert System Shell, Expert Systems, 1989, vol.6, no.1, p.2-10. 11 Z.A. Sosnowski, FLISP - A Language for Processing Fuzzy Data, Fuzzy Sets and Sys- tems, vol.37, 1990, p.23-32. 12 L.A. Zadeh, Fuzzy Sets, Information and Control, 8, 1965, 338-383. 13 L.A. Zadeh, The Concept of a Linguistic Variable and its Application to Approximate Reasoning, New York, 1973. 14 Z.A. Sosnowski, A Linguistic Variable in FLISP Programming Language, The Second Joint IFSA-EC and EURO-WG Workshop "Progress in Fuzzy Sets in Europe", April 6-8, 1988,Vienna, p.71-4. 15 A. Kaufman, M.M. Gupta, Introduction to Fuzzy Arithmetic. Theory and Applica- tions, Van Nostrand Reinhold, 1985. 16 K.S. Leung and W.Lam, Fuzzy Concepts in Expert Systems, IEEE, September 1988, 43-56. 17 M. Cayrol, H. Farency and H. Prade, Fuzzy Pattern Matching, Kybernetes, 11, 1982, pp.103-6. 18 M. Mizumoto, S. Fukami, and K. Tanaka, Some Methods of Fuzzy Reasoning, in Advances in Fuzzy Set Theory and Applications, M.M. Gupta, R.K. Ragade, and R.R. Yager, eds., North-Holland, Amsterdam, 1979, p.117-136. 19 Tzi-cker Chiueh, Optimization of Fuzzy Logic Inference Architecture, Computer, May 1992, 67-71. 20 T. Whalen, B. Schott, Issues in fuzzy production systems, Int. J. Man-Machine Stud- ies, 19, 1983, 57-7. 21 A. Kaufmann and M.M. Gupta, Fuzzy Mathematical Models in Engineering and Man- agement Science, North-Holland, 1988. 22 Giarratano and Riley, Expert Systems: Principles and Programming, PWS-KENT Publishing Company, 1989, p.270. 23 Earl Cox, The Fuzzy Systems Handbook, AP Professional, 1995. Appendix A: Shower Example The purpose of the shower example is to simulate the flow and temperature of water leav- ing a shower head as a function of time and to build a fuzzy controller to keep the flow and temperature within some required ranges. Shower model 1. The volumes of the pipes are zero. 2. Water mixes perfectly at point X (see Figure B1). 3. The water pipe is a perfect thermal insulator. 4. There is no heat transfer in the water as it travels from point X to the shower head. As a consequence of the above model, the flow out of the shower head (Fx) at any time t is exactly equal to the flow of cold water (Fc) at time t plus the flow of hot water (Fh) at time t. Any change to a valve position (vc, vh) or to the water pressure (Ph, Pc) is immediately reflected in the flow from the shower head. The temperature of the water leaving the shower head (Tx) at time t is equal to the temperature of water at point X. See equations below. Shower model equations Tc ¿ [0, 35] C Th > Tc Th ¿ [0, 100] C Tx = (FcTc + FhTh)/Fx Fx = Fc + Fh Px = 30 kPa \x11\x11\x11(atmospheric pressure) Fc = vc(Pc - Px) Fh = vh(Ph - Px) vc ¿ [0,1] - cold water valve position vh ¿ [0,1] - hot water valve position Pc = f(neighbor watering lawn,clothes washing machine, etc.) Ph = f(dish washing machine water consumption,etc.) Changes of Pc and Ph are simulated. Figure. B1. Shower control objectives 1. The temperature of the water leaving the shower head must "never" exceed 45 C. This is generally impossible. 2. The water temperature should rarely be less than 15 C. 3. The water temperature should have a mean value of 36 C and have a small variance. 4. The water flow should have a mean value of 12 liters/minute and have a small vari- ance. 5. The hot and cold water valve actuators should be moved infrequently. (The control computer wants to spend more time washing than adjusting the taps). Fuzzy control loop Text based version (No graphical interface - shwrNOUI.clp) Steps to follow to run fuzzy shower example (Unix version) 1. Start a version of FZ_CLIPS. 2. Load shower example (load "shwrNOUI.clp" from fuzzy examples directory) 3. Run an example ((reset) and (run)) The program will ask for the values of parameters for temperature, pressure and valve positions. It stops when it reaches a flow between 11 and 13 liters/minute, and water temperature between 34 - 38 C.). The values of certain parameters will be printed after each set of fuzzy rules and defuzzification has taken place. 4. You will be prompted to enter further values or to quit. Graphical Interface Version of Shower Problem The graphical interface version of the shower controller will run only on a Sun Sparc machine with Openwin version 3.0 or later (with NeWS/X11). This is because we used the GUIDE (Devguide) software with GNT (NeWS Toolkit Code Generator). Devguide is used to interactively create most of the user interface. GNT translates the output from Devguide (Shower.G) into `C', cps, and postscript files that form the code for the interface (Shower.c, tmp/Shower.h, srcShower.ps, and tmp/Shower_c.cps, tmp/Shower_m.c, etc.). In Shower.c and Shower_m.c a number of changes are made: 1. The main routine is renamed to UI_init so that it can be embedded into CLIPS. 2. The `while' loop at the end of the main routine (just before the `return 0' statement is commented out (control of events is taken care of by other code found in the simula- tion part of the extensions). 3. In the routine runShower the statement `setShowerPipingCanvasPaint()' is added before `Allocate_Shower_Tags()' to draw a graphic in the interface window. 4. In the various locations commented with /* Custom code goes here */ calls to appro- priate Callback routines have been added as needed. The code for these Callbacks is found in ShowerCallbacks.c. src/Shower_c.cps is custom code to add special `cdef' routines needed to complete the interface functionality. The files Shower_audio.c, audio_device.h, audio_errno.h, audio_hdr.h, libaudio.a, libau- dio.h, and flush.au support a very limited sound capability in the program. Simulate.h and Simulate.c provide a simple event based simulation capability. This is cus- tomized by adding code specific to the simulation being developed. Files Events.h, Event- Names.h, ShowerSimulate.c and ShowerSimulate.h provide the specific code for the shower simulation. If logging is turned on during the simulation (described later) a file is created (extension of .log) with data that records system state when changes take place (time, temperature of hot water, temperature of cold water, pressure of hot water, pressure of cold water, position of cold water valve, position of hot water valve, flow of output, and temperature of output). A second file (extension is .stat) is created to show some statistics of the run, such as the number of moves of the hot and cold valves required to get the temperature and the flow back into the comfortable range. An example file is shown below: StartTime Temp Flow ElapsedTime Moves \x110 10.730 0.000 0.000 0.660 10 \x111 17.290 38.333 10.968 0.100 1 \x112 21.580 42.228 9.820 0.340 5 \x113 25.660 46.106 8.890 0.400 3 \x114 29.990 27.039 16.582 0.520 7 \x115 32.260 32.212 14.945 0.220 3 \x116 36.580 30.394 14.573 0.270 2 Avg. Time to Recover: 0.358571 Avg. Number Moves: 4.428571 In order to use a plotting program called `xvgr' (available via anonymous ftp from ese3.ese.ogi.edu [129.95.20.62] in pub/grtool) we supply the program formatData (for- matData.c) to convert the time information into a suitable form (julian) and to split the data into separate sets. The formatData program takes the name of the log file (without the extension (.log assumed) and creates a file with the extension .dat. The data can be plotted with: xvgr -p ShowerGraph.par xxxx.dat where xxxx.dat is the converted file and ShowerGraph.par is a parameter file used by xvgr to format the plotting window correctly. The Graphical Interface The diagram in Figure 2 shows the GUI interface for this problem. The Shower tempera- ture and flow rate are shown in gauges along the top. The hot water and cold water valve positions are shown on opposite sides in sliders. These sliders can be moved only when in manual mode. The temperature of the hot and cold supplies are shown on opposite sides as well in sliders. These can be adjusted at any time (manual or auto mode). The pressures of the hot and cold supplies are shown in gauges along the bottom. The mode selection allows one to operate in auto or manual mode (by default the system will start in manual mode). In manual mode the temperature and flow of the output will respond to your changes in the sliders and selections under the `change pressure' menu. In auto mode the fuzzy logic controller is in control of the hot and cold water valves and tries to maintain the correct operating ranges for the system. The RealTime Scale menu is not operable. The Data Logging menu allows you to start recording data in a file (extension .log is added) and to stop the logging. The Change Pressure menu provides a number of selections that make events occur which have an effect on the water pressure. E.g. flush toilets (hence the audio stuff!), turn on/off the garden hose, etc. The shower temp gauge will show green when the temp is in range, red when too high and blue when too cold. Similar reactions hold for the shower flow gauge. How to Run the Shower Example with the User Interface 1. Start FZ_XCLIPS_shower (a version supplied with the Sun distribution) or use a ver- sion compiled with the flag ShowerProblemUI in xmain.c or main.c set to 1. 2. Load the example clips code -- (load "showerUI25.clp") a. showerUI25.clp is a 25 rule controller, showerUI8.clp is an 8 rule controller -- use either one. b. the file flush.au should be in your current directory 3. Enter -- (reset) 4. Enter -- (run -2) \x11\x11\x11; keeps CLIPS looping even when no rules 5. Interact with the window that contains the user interface (normally will turn on auto mode and try various things). 6. A control-C (from within the clips window) will stop the clips loop and allow you to exit clips. Acknowledgment The shower example was suggested by Robert Spring of the Noranda Technology Centre. Figure B2