packages feed

Emping (empty) → 0.1

raw patch · 16 files changed

+936/−0 lines, 16 filesdep +basedep +parsecbuild-type:Customsetup-changedbinary-added

Dependencies added: base, parsec

Files

+ Emping.cabal view
@@ -0,0 +1,28 @@+name:                Emping+version:             0.1+license:             GPL+license-file:        LICENSE+build-depends:       base, parsec+copyright:           Hans van Thiel 2006 - 2007+author:              Hans van Thiel+maintainer:          hthiel.char@zonnet.nl+stability:           experimental+homepage:            j-van-thiel.speedlinq.nl/+synopsis:            derives heuristic rules from nominal data+description:         utility that reads a table in a csv (comma+       separated) format that can be generated from +       Open Office Calc (spreadsheet), derives all shortest rules+       for a selected attribute, and writes them to a .csv file+                     that can be read by OO Calc.+category:            Data Mining+extra-source-files:  README+      +executable:        emping+hs-source-dirs:    src+main-is:           Main.hs+ghc-options:       -o+other-modules:     CSVParse+                   Codec+                   Aux+                   Reduce+                   CSVTable
+ LICENSE view
@@ -0,0 +1,339 @@+		    GNU GENERAL PUBLIC LICENSE+		       Version 2, June 1991++ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA+ Everyone is permitted to copy and distribute verbatim copies+ of this license document, but changing it is not allowed.++			    Preamble++  The licenses for most software are designed to take away your+freedom to share and change it.  By contrast, the GNU General Public+License is intended to guarantee your freedom to share and change free+software--to make sure the software is free for all its users.  This+General Public License applies to most of the Free Software+Foundation's software and to any other program whose authors commit to+using it.  (Some other Free Software Foundation software is covered by+the GNU Lesser General Public License instead.)  You can apply it to+your programs, too.++  When we speak of free software, we are referring to freedom, not+price.  Our General Public Licenses are designed to make sure that you+have the freedom to distribute copies of free software (and charge for+this service if you wish), that you receive source code or can get it+if you want it, that you can change the software or use pieces of it+in new free programs; and that you know you can do these things.++  To protect your rights, we need to make restrictions that forbid+anyone to deny you these rights or to ask you to surrender the rights.+These restrictions translate to certain responsibilities for you if you+distribute copies of the software, or if you modify it.++  For example, if you distribute copies of such a program, whether+gratis or for a fee, you must give the recipients all the rights that+you have.  You must make sure that they, too, receive or can get the+source code.  And you must show them these terms so they know their+rights.++  We protect your rights with two steps: (1) copyright the software, and+(2) offer you this license which gives you legal permission to copy,+distribute and/or modify the software.++  Also, for each author's protection and ours, we want to make certain+that everyone understands that there is no warranty for this free+software.  If the software is modified by someone else and passed on, we+want its recipients to know that what they have is not the original, so+that any problems introduced by others will not reflect on the original+authors' reputations.++  Finally, any free program is threatened constantly by software+patents.  We wish to avoid the danger that redistributors of a free+program will individually obtain patent licenses, in effect making the+program proprietary.  To prevent this, we have made it clear that any+patent must be licensed for everyone's free use or not licensed at all.++  The precise terms and conditions for copying, distribution and+modification follow.++		    GNU GENERAL PUBLIC LICENSE+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION++  0. This License applies to any program or other work which contains+a notice placed by the copyright holder saying it may be distributed+under the terms of this General Public License.  The "Program", below,+refers to any such program or work, and a "work based on the Program"+means either the Program or any derivative work under copyright law:+that is to say, a work containing the Program or a portion of it,+either verbatim or with modifications and/or translated into another+language.  (Hereinafter, translation is included without limitation in+the term "modification".)  Each licensee is addressed as "you".++Activities other than copying, distribution and modification are not+covered by this License; they are outside its scope.  The act of+running the Program is not restricted, and the output from the Program+is covered only if its contents constitute a work based on the+Program (independent of having been made by running the Program).+Whether that is true depends on what the Program does.++  1. You may copy and distribute verbatim copies of the Program's+source code as you receive it, in any medium, provided that you+conspicuously and appropriately publish on each copy an appropriate+copyright notice and disclaimer of warranty; keep intact all the+notices that refer to this License and to the absence of any warranty;+and give any other recipients of the Program a copy of this License+along with the Program.++You may charge a fee for the physical act of transferring a copy, and+you may at your option offer warranty protection in exchange for a fee.++  2. You may modify your copy or copies of the Program or any portion+of it, thus forming a work based on the Program, and copy and+distribute such modifications or work under the terms of Section 1+above, provided that you also meet all of these conditions:++    a) You must cause the modified files to carry prominent notices+    stating that you changed the files and the date of any change.++    b) You must cause any work that you distribute or publish, that in+    whole or in part contains or is derived from the Program or any+    part thereof, to be licensed as a whole at no charge to all third+    parties under the terms of this License.++    c) If the modified program normally reads commands interactively+    when run, you must cause it, when started running for such+    interactive use in the most ordinary way, to print or display an+    announcement including an appropriate copyright notice and a+    notice that there is no warranty (or else, saying that you provide+    a warranty) and that users may redistribute the program under+    these conditions, and telling the user how to view a copy of this+    License.  (Exception: if the Program itself is interactive but+    does not normally print such an announcement, your work based on+    the Program is not required to print an announcement.)++These requirements apply to the modified work as a whole.  If+identifiable sections of that work are not derived from the Program,+and can be reasonably considered independent and separate works in+themselves, then this License, and its terms, do not apply to those+sections when you distribute them as separate works.  But when you+distribute the same sections as part of a whole which is a work based+on the Program, the distribution of the whole must be on the terms of+this License, whose permissions for other licensees extend to the+entire whole, and thus to each and every part regardless of who wrote it.++Thus, it is not the intent of this section to claim rights or contest+your rights to work written entirely by you; rather, the intent is to+exercise the right to control the distribution of derivative or+collective works based on the Program.++In addition, mere aggregation of another work not based on the Program+with the Program (or with a work based on the Program) on a volume of+a storage or distribution medium does not bring the other work under+the scope of this License.++  3. You may copy and distribute the Program (or a work based on it,+under Section 2) in object code or executable form under the terms of+Sections 1 and 2 above provided that you also do one of the following:++    a) Accompany it with the complete corresponding machine-readable+    source code, which must be distributed under the terms of Sections+    1 and 2 above on a medium customarily used for software interchange; or,++    b) Accompany it with a written offer, valid for at least three+    years, to give any third party, for a charge no more than your+    cost of physically performing source distribution, a complete+    machine-readable copy of the corresponding source code, to be+    distributed under the terms of Sections 1 and 2 above on a medium+    customarily used for software interchange; or,++    c) Accompany it with the information you received as to the offer+    to distribute corresponding source code.  (This alternative is+    allowed only for noncommercial distribution and only if you+    received the program in object code or executable form with such+    an offer, in accord with Subsection b above.)++The source code for a work means the preferred form of the work for+making modifications to it.  For an executable work, complete source+code means all the source code for all modules it contains, plus any+associated interface definition files, plus the scripts used to+control compilation and installation of the executable.  However, as a+special exception, the source code distributed need not include+anything that is normally distributed (in either source or binary+form) with the major components (compiler, kernel, and so on) of the+operating system on which the executable runs, unless that component+itself accompanies the executable.++If distribution of executable or object code is made by offering+access to copy from a designated place, then offering equivalent+access to copy the source code from the same place counts as+distribution of the source code, even though third parties are not+compelled to copy the source along with the object code.++  4. You may not copy, modify, sublicense, or distribute the Program+except as expressly provided under this License.  Any attempt+otherwise to copy, modify, sublicense or distribute the Program is+void, and will automatically terminate your rights under this License.+However, parties who have received copies, or rights, from you under+this License will not have their licenses terminated so long as such+parties remain in full compliance.++  5. You are not required to accept this License, since you have not+signed it.  However, nothing else grants you permission to modify or+distribute the Program or its derivative works.  These actions are+prohibited by law if you do not accept this License.  Therefore, by+modifying or distributing the Program (or any work based on the+Program), you indicate your acceptance of this License to do so, and+all its terms and conditions for copying, distributing or modifying+the Program or works based on it.++  6. Each time you redistribute the Program (or any work based on the+Program), the recipient automatically receives a license from the+original licensor to copy, distribute or modify the Program subject to+these terms and conditions.  You may not impose any further+restrictions on the recipients' exercise of the rights granted herein.+You are not responsible for enforcing compliance by third parties to+this License.++  7. If, as a consequence of a court judgment or allegation of patent+infringement or for any other reason (not limited to patent issues),+conditions are imposed on you (whether by court order, agreement or+otherwise) that contradict the conditions of this License, they do not+excuse you from the conditions of this License.  If you cannot+distribute so as to satisfy simultaneously your obligations under this+License and any other pertinent obligations, then as a consequence you+may not distribute the Program at all.  For example, if a patent+license would not permit royalty-free redistribution of the Program by+all those who receive copies directly or indirectly through you, then+the only way you could satisfy both it and this License would be to+refrain entirely from distribution of the Program.++If any portion of this section is held invalid or unenforceable under+any particular circumstance, the balance of the section is intended to+apply and the section as a whole is intended to apply in other+circumstances.++It is not the purpose of this section to induce you to infringe any+patents or other property right claims or to contest validity of any+such claims; this section has the sole purpose of protecting the+integrity of the free software distribution system, which is+implemented by public license practices.  Many people have made+generous contributions to the wide range of software distributed+through that system in reliance on consistent application of that+system; it is up to the author/donor to decide if he or she is willing+to distribute software through any other system and a licensee cannot+impose that choice.++This section is intended to make thoroughly clear what is believed to+be a consequence of the rest of this License.++  8. If the distribution and/or use of the Program is restricted in+certain countries either by patents or by copyrighted interfaces, the+original copyright holder who places the Program under this License+may add an explicit geographical distribution limitation excluding+those countries, so that distribution is permitted only in or among+countries not thus excluded.  In such case, this License incorporates+the limitation as if written in the body of this License.++  9. The Free Software Foundation may publish revised and/or new versions+of the General Public License from time to time.  Such new versions will+be similar in spirit to the present version, but may differ in detail to+address new problems or concerns.++Each version is given a distinguishing version number.  If the Program+specifies a version number of this License which applies to it and "any+later version", you have the option of following the terms and conditions+either of that version or of any later version published by the Free+Software Foundation.  If the Program does not specify a version number of+this License, you may choose any version ever published by the Free Software+Foundation.++  10. If you wish to incorporate parts of the Program into other free+programs whose distribution conditions are different, write to the author+to ask for permission.  For software which is copyrighted by the Free+Software Foundation, write to the Free Software Foundation; we sometimes+make exceptions for this.  Our decision will be guided by the two goals+of preserving the free status of all derivatives of our free software and+of promoting the sharing and reuse of software generally.++			    NO WARRANTY++  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,+REPAIR OR CORRECTION.++  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE+POSSIBILITY OF SUCH DAMAGES.++		     END OF TERMS AND CONDITIONS++	    How to Apply These Terms to Your New Programs++  If you develop a new program, and you want it to be of the greatest+possible use to the public, the best way to achieve this is to make it+free software which everyone can redistribute and change under these terms.++  To do so, attach the following notices to the program.  It is safest+to attach them to the start of each source file to most effectively+convey the exclusion of warranty; and each file should have at least+the "copyright" line and a pointer to where the full notice is found.++    <one line to give the program's name and a brief idea of what it does.>+    Copyright (C) <year>  <name of author>++    This program is free software; you can redistribute it and/or modify+    it under the terms of the GNU General Public License as published by+    the Free Software Foundation; either version 2 of the License, or+    (at your option) any later version.++    This program is distributed in the hope that it will be useful,+    but WITHOUT ANY WARRANTY; without even the implied warranty of+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the+    GNU General Public License for more details.++    You should have received a copy of the GNU General Public License along+    with this program; if not, write to the Free Software Foundation, Inc.,+    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.++Also add information on how to contact you by electronic and paper mail.++If the program is interactive, make it output a short notice like this+when it starts in an interactive mode:++    Gnomovision version 69, Copyright (C) year name of author+    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.+    This is free software, and you are welcome to redistribute it+    under certain conditions; type `show c' for details.++The hypothetical commands `show w' and `show c' should show the appropriate+parts of the General Public License.  Of course, the commands you use may+be called something other than `show w' and `show c'; they could even be+mouse-clicks or menu items--whatever suits your program.++You should also get your employer (if you work as a programmer) or your+school, if any, to sign a "copyright disclaimer" for the program, if+necessary.  Here is a sample; alter the names:++  Yoyodyne, Inc., hereby disclaims all copyright interest in the program+  `Gnomovision' (which makes passes at compilers) written by James Hacker.++  <signature of Ty Coon>, 1 April 1989+  Ty Coon, President of Vice++This General Public License does not permit incorporating your program into+proprietary programs.  If your program is a subroutine library, you may+consider it more useful to permit linking proprietary applications with the+library.  If this is what you want to do, use the GNU Lesser General+Public License instead of this License.
+ README view
@@ -0,0 +1,23 @@+The preferred way to install emping is through Cabal, for example:++$ runhaskell Setup.lhs configure --prefix=$HOME+$ runhaskell Setup.lhs build+$ runhaskell Setup.lhs install++where the commands might need to follow:+     /usr/bin/env+depending on your settings.++You might want to look at: http://www.haskell.org/haskellwiki/How_to_write_a_Haskell_program ++and/or the cabal documentation at: http://www.haskell.org/ghc/docs/latest/html/Cabal/index.html++for more information.++-------------------------------------------++Or, put the the source files in a directory of your choice and compile them with:++ghc --make Main.hs -o emping++where ghc is the Haskell compiler and emping is the executable.
+ Setup.hs view
@@ -0,0 +1,2 @@+import Distribution.Simple+main = defaultMain
+ docs/Emp_UG.html view
@@ -0,0 +1,114 @@+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">+<HTML>+<HEAD>+<META NAME="generator" CONTENT="http://txt2tags.sf.net">+<TITLE>Emping User Guide</TITLE>+</HEAD><BODY BGCOLOR="white" TEXT="black">+<P ALIGN="center"><CENTER><H1>Emping User Guide</H1>+<FONT SIZE="4">+<I>Author: Hans van Thiel, April 2007</I><BR>+email: hthiel.char@zonnet.nl+</FONT></CENTER>++<H1>1. Overview</H1>+<H2>1.1. What</H2>+<P>+Emping is a utility that derives heuristic rules from nominal data. Nominal data are qualitative and unordered, as in:+</P>+<UL>+<LI>Color: red, green, blue, yellow, black+<LI>Proposition 1: True, False+<LI>Class: A,B,C,D+</UL>++<P>+Class is actually an ordinal attribute, but when the order is disregarded, it is nominal.+</P>+<P>+Heuristic rules consist of attribute values (predicates) that together imply another attribute value. For example:+</P>+<DL>+<DT>Color:green and Proposition 1:True  is Class:B</DT><DD>+</DL>++<P>+Heuristic rules are purely empirical, with no foundation in a theory or model. Emping automatically derives all such rules from a table of facts. This result is called a <B>reduced normal form</B>. Such a result can be analized and simplified further, but this first version of emping only performs the reduction.+</P>+<H2>1.2. How</H2>+<P>+Emping reads a file in a comma seperated format (.csv) as produced by the Open Office Calc spreadsheet, and returns the result as a .csv file that can be read by OO Calc.+</P>+<P>+You start the utility from a terminal and provide the file name as a command line parameter. For example:+</P>+<P>+<CODE>$ ./emping QuinLanFacts.csv</CODE>+</P>+<P>+Emping then asks you to supply the name of the attribute that is to be the consequent of the rules, and the result is saved as a file with that attribute as its name and the .csv extension.+</P>+<P>+This file can then be loaded into OO Calc.+</P>+<H2>1.3. More</H2>+<P>+More about the principles on which emping is based can be found in the white paper, <B>Deriving Heuristic Rules from Facts</B> , which is included in the distribution (pdf).+</P>+<H1>2. Example</H1>+<H2>2.1. Step 1</H2>+<P>+Enter the data in Open Office Calc as shown:+</P>+<P>+<IMG ALIGN="middle" SRC="./Quinlan.png" BORDER="0" ALT="">+</P>+<P>+As you can see, the table can have empty lines and does not have to start in the first column. But:+</P>+<UL>+<LI>The first row must list the attribute names, which must all be unique. The values must be unique only for the same attribute.+<LI>All rows must be aligned, and no fields may be empty+<LI>you can use whole numbers, like 0, 1, 3, 22 etc., but they will be treated as nominal values, just like A,B,C etc.+</UL>++<H2>2.2. Step 2</H2>+<P>+Save the table in Text CSV format. Choose double quotes as the text delimiter (default). Whole numbers will be stored without delimiters, and emping will use them after checking if they are all digits (no negatives, no fractions).+</P>+<H2>2.3. Step 3</H2>+<P>+Open the terminal and type <CODE>emping</CODE>, followed by the filename of the table (including the path). You may have to precede the command with the directory, which contains the emping executable. For example, if it is in your working directory:+</P>+<DL>+<DT>$ ./emping (followed by the file name)</DT><DD>+</DL>++<H2>2.4. Step 4</H2>+<P>+The program will now ask for the attribute which is to be predicted. This can be any one of the names in the table header.+If you type <CODE>?</CODE> you will see a list of the names.+</P>+<H2>2.5. Step 5</H2>+<P>+The program will have saved the result in a file with the attribute name and the <CODE>.csv</CODE> extension. This can then be loaded into OO Calc, as shown in the image.+</P>+<P>+<IMG ALIGN="middle" SRC="./Fishing.png" BORDER="0" ALT="">+</P>+<H1>3. Miscellaneous</H1>+<P>+The emping utility is written in Haskell, and has been developed and tested on the Fedora Core 6 Linux platform, using the Haskell tools which are available as FC6 packages.+</P>+<P>+(Potential) users will probably be somewhat wary, in particular if their data is critical. Keep in mind that emping derives the rules, which is the hard part. Checking the results for correctness is easy.+</P>+<P>+As stated above, this utility is by no means the end of the story (see the included wp). Work will continue, and I'm very interested in comments, ideas and crits from anyone. Thanks in advance.+</P>+<P>+<I>Emping</I> stands for <I>empirical reasoning</I> or the Indonesian snack with that name.+</P>++<!-- html code generated by txt2tags 2.3 (http://txt2tags.sf.net) -->+<!-- cmdline: txt2tags -\-target html EmpMan.t2t -->+</BODY></HTML>
+ docs/EmpingWP.pdf view

binary file changed (absent → 214968 bytes)

+ docs/Fishing.png view

binary file changed (absent → 58079 bytes)

+ docs/Quinlan.png view

binary file changed (absent → 63605 bytes)

+ src/Aux.hs view
@@ -0,0 +1,45 @@+module Aux (redAtt, selavN, gtAtec ) where++-- (c) 2007 Hans van Thiel+-- Version 0.1 License GPL++import Reduce ( redCons )+import Data.Array+import Data.List ( delete )++-- module: auxiliary functions for Main++-- reduction for a consequent attribute, coded by Codec++-- execute the reduction on all attribute-value pairs+-- the result matches each reduction with its consequent++redAtt :: [(Int,Int)] -> [[(Int,Int)]] -> [([[(Int,Int)]], (Int,Int))]+redAtt avls src = zip (map ((flip redCons) src) avls) avls+--------------------------------------------------------------+-- get the index of an attribute string++selAtt :: String -> Array Int [String] -> Int+selAtt att attvarr  = slAtt att (indices attvarr) attvarr where+                            slAtt at [] arr = error "Attribute not found..."+                            slAtt at (x:xs) arr | att == (head (arr ! x)) = x+                                                | otherwise = slAtt at xs arr++-- get the coded attribute-value pairs from the attribute index++selAV :: Int -> Array Int [String] -> [(Int,Int)]+selAV ai attvarr = let avstr = attvarr ! ai+                       vais = [1..(length avstr)-1]+                   in  [(ai, x) | x <- vais ]++-- get the coded attribute-value pairs from the attribute name++selavN :: String -> Array Int [String] -> [(Int,Int)]+selavN atn attvarr = selAV ai attvarr where ai = selAtt atn attvarr++-- get antecedent and consequent attribute indices from consequent index++gtAtec :: Int -> Array Int [String] -> ([Int],Int)+gtAtec cns attvarr = ((delete cns ils),cns) where+                                 ils = indices attvarr              +-----------------------------------------------------
+ src/CSVParse.hs view
@@ -0,0 +1,43 @@+module CSVParse ( getTable ) where++-- (c) 2007 Hans van Thiel+-- Version 0.1 License GPL++import Text.ParserCombinators.Parsec+{- module: parse a table in Open Office Calc csv-format+   empty lines are skipped+   empty fields at the beginning of a line are skipped+   a text field starts with " and ends with "+   a numerical field consists of digits only+-}+comma = char ','++txtField = do { char '\"' ; +                txt <- many (noneOf "\""); +                char '\"'; return txt }+               +numField = many1 digit++getField = do {many (char ' '); txtField <|> numField }++csvLine = do { many comma; +               fields <- (sepBy getField comma);+               many (char ' '); newline; +               return fields }++csvTable = many csvLine++getTable :: String -> IO [[String]]+getTable fname = do pares <- parseFromFile csvTable fname+                    let res = case pares of +                               Right res -> res+                               Left err -> error "CSVParse: Parse error in input file"+                    return (res)  ++-- test the table in csv format for parse errors++test = do putStrLn "Enter CSV file:"+          name <- getLine+          res <- parseFromFile csvTable name+          case res of Left err -> print err+                      Right xs -> print xs
+ src/CSVTable.hs view
@@ -0,0 +1,99 @@+module CSVTable ( red2Table ) where++-- (c) 2007 Hans van Thiel+-- Version 0.1 License GPL++-- module: convert reduction result to CSV +-- format that can be read by Open Office Calc++import Data.Char (isDigit )+import Data.List ( delete )+import Data.Array++---------- some auxiliary functions ----------------++-- check whether a string is a number or text++allDigit :: String -> Bool+allDigit [] = True+allDigit (x:xs) | isDigit x = allDigit xs+                | otherwise = False++-- convert string or number to OO Calc format++toCalc :: String -> String+toCalc x | allDigit x = x+         | otherwise = "\"" ++ x ++ "\""++-- get the value string of an attribute-value tuple++strVal :: Array Int [String] -> (Int,Int) ->  String+strVal attvarr x  =   +     toCalc $ (attvarr ! (fst x)) !! (snd x)++-- get the attribute string from an index +strAtt :: Array Int [String] -> Int -> String+strAtt attvarr ix = head (attvarr ! ix)++-- insert a separator s between two strings++inSep :: String -> String -> String -> String+inSep s x y = x ++ s ++ y+----------------------------------------------++-- show the value of the attribute index or a blank++indStr :: Array Int [String] -> [(Int,Int)] ->  Int-> String+indStr attvarr []  x = " "+indStr attvarr (y:ys) x | x == fst y = strVal  attvarr y+                        | otherwise = indStr attvarr ys x +++-- turn antecedent into CSV string ++ant2Str :: Array Int [String] -> [Int]-> [(Int,Int)]-> String+ant2Str attvarr indls redlin =  +           foldl1 (inSep ",") y where+                   y = map (indStr attvarr redlin ) indls+++-- get consequent value string and newline+cns2Str :: Array Int [String] -> (Int,Int) ->  String+cns2Str attvarr cons = +           ",\" is \"," ++ (strVal attvarr cons) ++ "\n"++-- get the table antecedent header+ahd2Str :: Array Int [String] -> [Int] ->  String+ahd2Str attvarr indls  = foldl1 (inSep ",") y where+                   y = [ strAtt attvarr z | z <- indls ]++-- get consequent attribute string and newline+chd2Str ::  Array Int [String] -> Int -> String+chd2Str attvarr ati = +     ", ," ++  (toCalc (head (attvarr ! ati))) ++ "\n"++-- show the table header in csv format+hd2csv :: Array Int [String] -> ([Int], Int) -> String+hd2csv attvarr hdp = +     (ahd2Str attvarr (fst hdp)) ++ (chd2Str attvarr (snd hdp))+---------------------------------------------------++-- show a reduction for a consequent value in csv++red2csv :: Array Int [String] -> [Int] -> ([[(Int,Int)]], (Int,Int)) -> [String]+red2csv attvarr indls rstp = +          map ( ++ cns2Str attvarr (snd rstp)) redstr where +                    redstr =  map (ant2Str attvarr indls) (fst rstp)++-- show the reduction results for an attribute in csv++all2csv :: Array Int [String] -> [Int] -> [([[(Int,Int)]], (Int,Int))] -> String+all2csv attvarr indls redres = concat $ concatMap (red2csv attvarr indls) redres++-- output a csv table from the array of attribute-value names,+-- the antecedent attributes and consequent, and the +-- zip of the reduction results and the consequent values++red2Table :: Array Int [String] -> ([Int],Int)-> [([[(Int,Int)]], (Int,Int))] -> String+red2Table attvarr indls redres = +  (hd2csv attvarr indls) ++ (all2csv attvarr (fst indls) redres)
+ src/Codec.hs view
@@ -0,0 +1,64 @@+module Codec ( avCod, avArr )where++-- (c) 2007 Hans van Thiel+-- Version 0.1 License GPL++-- Note: extended Haskell because of dependent parameters+ +{- module: code a table of strings into:+    attribute-value lists, with the attributes in the heads+    lists of tuples, fst indexing att, snd indexing val +        attribute indexes av-list of lists, start 0+        value indexes value in av-list, start 1+   string table has: attribute names in first line+                     attribute values in following lines+-}++import Data.List (transpose, elemIndex)+import Control.Monad.State+import Data.Array++-- get unique value-list and code strings as indices+-- Note: index incremented by 1, index 0 is the attribute++repl1 :: String -> [String] -> (Int, [String])+repl1 x tb  = case elemIndex x tb of+                 Nothing -> ((length tb) + 1, tb ++ [x] )+                 Just i -> (i + 1, tb)++toState :: String -> State [String] Int+toState x = State (repl1 x)++getVals :: [String] -> ([Int],[String])+getVals x = (runState (getState x)) [] where+                  getState = sequence . (map toState)++getInds :: [String] -> [Int]+getInds  =  fst . getVals++getTb :: [String] -> [String]+getTb = snd . getVals++-- get attribute-value lists from the table+-- Note: see comment at start for indexing scheme++avLs :: [[String]] -> [[String]]+avLs (x:xs) = zipWith (:)  x (values xs) where +        values  = (map getTb) . transpose ++-- replace table, except first line, with:+-- tuples representing attribute-value pair+-- Note: see comment at start for indexing scheme++avCod :: [[String]] -> [[(Int, Int)]]+avCod (x:xs) = map (zip [0..]) (values xs) +  where  values = transpose . (map getInds) . transpose++-- make an array of attribute-value lists from the +-- table, instead of a list of lists of Strings++avArr :: [[String]] -> Array Int [String]+avArr tb = listArray (0, (length attvals) -1) attvals where+      attvals = avLs tb++   
+ src/Main.hs view
@@ -0,0 +1,41 @@+module Main where++-- (c) 2007 Hans van Thiel+-- Version 0.1 License GPL++import System.Environment (getArgs )+import CSVParse (getTable )+import Codec (avArr, avCod )+import Aux (redAtt, selavN, gtAtec )+import CSVTable ( red2Table )+import Data.Array++main = do  [fname] <- getArgs+           tb <- getTable fname+           let  attvarr = avArr tb+           consN <- getConsAtt attvarr+           let  src = avCod tb+                cons = selavN consN attvarr+                redres = redAtt cons src+                indls = gtAtec (fst (head cons)) attvarr+                outTable = red2Table attvarr indls redres+           writeFile (consN ++ ".csv") outTable++-----------------------------------------+-- print the list of attribute names++shAtts :: Array Int [String] -> IO ()+shAtts attvar = print als where+               als = [ head x | x <- elems attvar ]   ++-- get the consequent attribute from the user++getConsAtt :: Array Int [String] -> IO String+getConsAtt attvarr = do { putStrLn "Select the consequent attribute /n ( ? to see all)" ;+                  answ <- getLine ;+                  if answ == "?" +                     then do { shAtts attvarr;+                                           getConsAtt attvarr }+                     else return answ +                         }+-------------------------------------------
+ src/Reduce.hs view
@@ -0,0 +1,107 @@+module Reduce ( redCons ) where++-- (c) 2007 Hans van Thiel+-- Version 0.1 License GPL++-- module: get the reduced normal form of a rule model+-- some general purpose functions++import Data.List (nub, (\\), nubBy, partition )++isSub, isSuper :: Eq a => [a] -> [a] -> Bool+isSub [] y = True+isSub (x:xs) y | not (x `elem` y) = False+               | otherwise = isSub xs y++isSuper = flip isSub++isEq :: Eq a => [a] -> [a] -> Bool+isEq x y = isSub x y && isSub y x++-- minLs needs to take second value because of foldr in extrMin++minLs :: Eq a => [a] -> [a] -> [a]+minLs x y | x `isSub` y = x+          | otherwise = y++-- A: formulate hypothesis from original rules (positive)++hypot :: Eq a => [[a]] -> [a]+hypot = nub . concat++-- B: falsify the hypothesis+--    1. match with all the rules (negative)++match :: Eq a => [a] -> [[a]] -> [[a]]+match h  = map (h \\) ++--    2. transform the orlist of andlists to andlist of orlists++-- test if an attribute is in the list and get it++attElem :: (Eq a, Eq b) => (a,b) -> [(a,b)] -> Maybe (a,b)+attElem x [] = Nothing+attElem x (y:ys) = if fst x == fst y then Just y+                                     else attElem x ys+{- and a predicate to an andlist+     attributes with different values contradict+     attributes with the same value are equal -}++andP :: (Eq a,Eq b) => (a,b) -> [(a,b)] -> [(a,b)]+andP x ans = case attElem x ans of +                   Nothing -> x:ans+                   Just y -> if snd x == snd y +                                    then ans+                                    else []            ++-- first: anding an orlist to an orlist of andlists+-- remove all the empty lists++repandPls :: (Eq a,Eq b) => [(a,b)] -> [[(a,b)]] -> [[(a,b)]]+repandPls ors als = +    filter (/= []) [ andP x y | x <- ors, y <- als ]++-- then: extract the smallest sublists from an orlist of andlists++extrMin :: Eq a => [[a]] -> [[a]]+extrMin ls =  nubBy isEq [ getMinin x ls | x <-ls ] +          where  getMinin x y = foldr minLs x y++-- B.2.1: anding an orlist to an orlist of andlists++andOrAnds :: (Eq a,Eq b) => [(a,b)] -> [[(a,b)]] -> [[(a,b)]]+andOrAnds x = extrMin . (repandPls x)++-- B.2.2: transform andlist of orlists to orlist of andlists in batch++trAndOr :: (Eq a,Eq b) => [[(a,b)]] -> [[(a,b)]]+trAndOr x = foldr andOrAnds (raise (last x)) (init x)+                 where raise ls = [ [y] | y <- ls]++-- C: Verify the falsification result with the original positive rules++verify :: Eq a => [[a]] -> [[a]] -> [[a]]+verify flsd orig = [x | x <- flsd , x `isIn` orig ] where+                    isIn y ls = or (map (isSub y) ls)++-- A, B and C: reduce a list of positive original rules ++redPos :: (Eq a,Eq b) => [[(a,b)]] -> [[(a,b)]] -> [[(a,b)]]+redPos p n = verify (trAndOr (match (hypot p) n)) p++-- reduce a list of attribute-value pairs by selecting the+-- consequent. The consequent attribute is removed from p and n++-- remove the consequent attributes++rmAtt :: (Eq a, Eq b) => a -> [[(a,b)]] -> [[(a,b)]]+rmAtt at rws =  map rm rws where +                    rm  ls = [y | y <- ls, at /= fst y ]++-- reduce the list of attribute- value pairs (no consequent)++redCons :: (Eq a, Eq b) => (a,b) -> [[(a,b)]] -> [[(a,b)]]+redCons x y = redPos p n where+                    z= partition (x `elem`) y +                    p = rmAtt (fst x) (fst z)+                    n = rmAtt (fst x) (snd z)
+ test_data/Fishing.csv view
@@ -0,0 +1,15 @@+Weather,Temperature,Humidity,Windy, ,"Fishing"+"sunny","hot", , ," is ","bad"+"sunny", ,"high", ," is ","bad"+ ,"hot", ,"yes"," is ","bad"+"sunny","mild", ,"no"," is ","bad"+"rain", , ,"yes"," is ","bad"+"cloudy", , , ," is ","good"+ ,"cool", ,"no"," is ","good"+ , ,"normal","no"," is ","good"+ ,"mild","normal", ," is ","good"+ ,"hot","normal", ," is ","good"+"rain", , ,"no"," is ","good"+"sunny", ,"normal", ," is ","good"+"sunny","mild", ,"yes"," is ","good"+"sunny","cool", , ," is ","good"
+ test_data/QuinFacts.csv view
@@ -0,0 +1,16 @@+,"Weather","Temperature","Humidity","Windy","Fishing"+,,,,,+,"sunny","hot","high","no","bad"+,"sunny","hot","high","yes","bad"+,"cloudy","hot","high","no","good"+,"rain","mild","high","no","good"+,"rain","cool","normal","no","good"+,"rain","cool","normal","yes","bad"+,"cloudy","cool","normal","yes","good"+,"sunny","mild","high","no","bad"+,"sunny","cool","normal","no","good"+,"rain","mild","normal","no","good"+,"sunny","mild","normal","yes","good"+,"cloudy","mild","high","yes","good"+,"cloudy","hot","normal","no","good"+,"rain","mild","high","yes","bad"