1
0
mirror of https://github.com/vcmi/vcmi.git synced 2025-03-27 21:49:10 +02:00

Replaced embedded copy of fuzzylite with fuzzylite 5.0

- retrieved from
   https://github.com/fuzzylite/fuzzylite/archive/v5.0.tar.gz
 - only modification to tarball content was the removal of the examples
   directory
 - fuzzylite release 5.0 tags fuzzylite git commit c11556f
This commit is contained in:
josch 2014-09-09 07:19:15 +02:00
parent fab31642d9
commit 101ac04c13
278 changed files with 23390 additions and 7145 deletions

21
AI/FuzzyLite/.gitignore vendored Normal file
View File

@ -0,0 +1,21 @@
# Compiled Object files
*.slo
*.lo
*.o
*.obj
# Compiled Dynamic libraries
*.so
*.dylib
*.dll
# Compiled Static libraries
*.lai
*.la
*.a
*.lib
# Executables
*.exe
*.out
*.app

3
AI/FuzzyLite/AUTHOR Normal file
View File

@ -0,0 +1,3 @@
Juan Rada-Vilela, Ph.D.
jcrada@fuzzylite.com
http://www.fuzzylite.com/jcrada

View File

@ -1,165 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "AreaCentroidAlgorithm.h"
#include "FuzzyOperation.h"
#include "LinguisticTerm.h"
namespace fl {
std::string TriangulationAlgorithm::name() const {
return "Triangulation";
}
flScalar TriangulationAlgorithm::area(const LinguisticTerm* term,
int samples) const {
flScalar x, y;
return areaAndCentroid(term, x, y, samples);
}
void TriangulationAlgorithm::centroid(const LinguisticTerm* term,
flScalar& x, flScalar& y, int samples) const {
areaAndCentroid(term, x, y, samples);
}
flScalar TriangulationAlgorithm::areaAndCentroid(
const LinguisticTerm* term, flScalar& centroid_x,
flScalar& centroid_y, int samples) const {
centroid_x = flScalar(0);
centroid_y = flScalar(0);
flScalar sum_area = flScalar(0.0);
flScalar sum_a_x = flScalar(0.0);
flScalar sum_a_y = flScalar(0.0);
flScalar tmp_area = flScalar(0.0);
flScalar range = term->maximum() - term->minimum();
flScalar step_size = range / samples;
int pi = 0;
flScalar x[3];
flScalar y[3];
/*******
* first triangle should include (minimum, 0)
* fix requires y_is_0 to start false & pi to start at 1
* updated by rctaylor 02/08/11
********/
bool y_is_0 = false;
x[0] = term->minimum();
y[0] = term->membership(x[0]);
x[1] = term->minimum();
y[1] = 0;
pi = 1;
// end update 02/08/11
int i = 1;
//Triangulation:
// rctaylor 02/08/11 - updated to <= because that is the only way x will ever equal
// term->maximum (ie. term->maximum = term->minimum + samples * step_size)
while (pi <= samples) {
++i;
if (y_is_0) {
x[i % 3] = x[(i - 1) % 3];
y[i % 3] = 0;
++pi; // rctaylor 02/08/11 - since y_is_0 starts false, this moves here
} else {
x[i % 3] = term->minimum() + pi * step_size;
y[i % 3] = term->membership(x[i % 3]);
}
y_is_0 = !y_is_0;
//Area of triangle:
// |Ax(By - Cy) + Bx(Cy - Ay) + Cx(Ay - By)| / 2
// |x0(y1 - y2) + x1(y2 - y0) + x2(y0 - y1)| / 2
tmp_area = FuzzyOperation::Absolute(x[0] * (y[1] - y[2]) + x[1]
* (y[2] - y[0]) + x[2] * (y[0] - y[1])) / 2;
//Centroid of a triangle:
// x = (x0 + x1 + x2)/3; y = (y0 + y1 + y2)/3;
sum_a_x += tmp_area * (x[0] + x[1] + x[2]) / 3;
sum_a_y += tmp_area * (y[0] + y[1] + y[2]) / 3;
sum_area += tmp_area;
}
centroid_x = sum_a_x / sum_area;
centroid_y = sum_a_y / sum_area;
return sum_area;
}
std::string TrapezoidalAlgorithm::name() const {
return "Trapezoidal";
}
flScalar TrapezoidalAlgorithm::area(const LinguisticTerm* term, int samples) const {
flScalar sum_area = 0.0;
flScalar step_size = (term->maximum() - term->minimum()) / samples;
flScalar step = term->minimum();
flScalar mu, prev_mu = term->membership(step);
for (int i = 0; i < samples; ++i) {
step += step_size;
mu = term->membership(step);
sum_area += step_size * (mu + prev_mu);
prev_mu = mu;
}
sum_area *= 0.5;
return sum_area;
}
void TrapezoidalAlgorithm::centroid(const LinguisticTerm* term,
flScalar& centroid_x, flScalar& centroid_y, int samples) const {
areaAndCentroid(term, centroid_x, centroid_y, samples);
}
flScalar TrapezoidalAlgorithm::areaAndCentroid(const LinguisticTerm* term,
flScalar& centroid_x, flScalar& centroid_y, int samples) const {
flScalar sum_area = 0.0;
flScalar step_size = (term->maximum() - term->minimum()) / samples;
flScalar step = term->minimum();
flScalar mu, prev_mu = term->membership(step);
flScalar area, x, y;
centroid_x = 0.0;
centroid_y = 0.0;
/*
* centroid_x = a (h_1 + 2h_2)/3(h_1+h_2) ; h_1 = prev_mu; h_2 = mu
* centroid_y = (h_1^2/(h_1+h_2) + h_2) * 1/3
*/
for (int i = 0; i <= samples ; ++i) {
step += step_size;
mu = term->membership(step);
area = 0.5 * step_size * (prev_mu + mu);
sum_area += area;
x = ((step_size * (prev_mu + 2 * mu)) / (3.0 * (prev_mu + mu)))
+ (step - step_size);
y = ((prev_mu * prev_mu) / (prev_mu + mu) + mu) / 3.0;
centroid_x += area * x;
centroid_y += area * y;
prev_mu = mu;
}
centroid_x /= sum_area;
centroid_y /= sum_area;
return sum_area;
}
}

View File

@ -1,75 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* File: AreaCentroidAlgorithm.h
* Author: jcrada
*
* Created on April 6, 2010, 5:33 PM
*/
#ifndef FL_AREACENTROIDALGORITHM_H
#define FL_AREACENTROIDALGORITHM_H
#include "flScalar.h"
#include <string>
namespace fl {
class LinguisticTerm;
class AreaCentroidAlgorithm {
public:
virtual ~AreaCentroidAlgorithm(){}
virtual std::string name() const = 0;
virtual flScalar area(const LinguisticTerm* term, int samples) const = 0;
virtual void centroid(const LinguisticTerm* term, flScalar& centroid_x, flScalar& centroid_y,
int samples) const = 0;
virtual flScalar areaAndCentroid(const LinguisticTerm* term, flScalar& centroid_x,
flScalar& centroid_y, int samples) const = 0;
};
class TriangulationAlgorithm : public AreaCentroidAlgorithm {
public:
virtual std::string name() const;
virtual flScalar area(const LinguisticTerm* term, int samples) const;
virtual void centroid(const LinguisticTerm* term, flScalar& centroid_x, flScalar& centroid_y,
int samples) const;
virtual flScalar areaAndCentroid(const LinguisticTerm* term, flScalar& centroid_x,
flScalar& centroid_y, int samples) const;
};
class TrapezoidalAlgorithm : public AreaCentroidAlgorithm {
//Feature suggested by William Roeder
public:
virtual std::string name() const;
virtual flScalar area(const LinguisticTerm* term, int samples) const;
virtual void centroid(const LinguisticTerm* term, flScalar& centroid_x, flScalar& centroid_y,
int samples) const;
virtual flScalar areaAndCentroid(const LinguisticTerm* term, flScalar& centroid_x,
flScalar& centroid_y, int samples) const;
};
}
#endif /* FL_AREACENTROIDALGORITHM_H */

View File

@ -1,55 +0,0 @@
project(FuzzyLite_lib)
cmake_minimum_required(VERSION 2.6)
include_directories(${CMAKE_HOME_DIRECTORY} ${CMAKE_CURRENT_SOURCE_DIR})
set(FuzzyLite_lib_SRCS
AreaCentroidAlgorithm.cpp
FuzzyOperation.cpp
OutputLVar.cpp
CompoundTerm.cpp
FuzzyOperator.cpp
RectangularTerm.cpp
DescriptiveAntecedent.cpp
FuzzyOr.cpp
RuleBlock.cpp
DiscreteTerm.cpp
FuzzyRule.cpp
ShoulderTerm.cpp
FunctionTerm.cpp
Hedge.cpp
SingletonTerm.cpp
FuzzyAnd.cpp
HedgeSet.cpp
StrOp.cpp
FuzzyAntecedent.cpp
InfixToPostfix.cpp
TakagiSugenoConsequent.cpp
FuzzyConsequent.cpp
InputLVar.cpp
TakagiSugenoRule.cpp
FuzzyDefuzzifier.cpp
LinguisticTerm.cpp
TakagiSugenoTerm.cpp
FuzzyEngine.cpp
LinguisticVariable.cpp
test.cpp
FuzzyException.cpp
main.cpp
TrapezoidalTerm.cpp
FuzzyExceptions.cpp
MamdaniConsequent.cpp
TriangularTerm.cpp
FuzzyModulation.cpp
MamdaniRule.cpp
)
add_library(FuzzyLite_lib STATIC ${FuzzyLite_lib_SRCS})
# This is more like a workaround. Gcc when linking VCAI fill keep
# all symobls from FuzzyLite exposed to public. This triggers errors
# when library is checked by analizers for issues
# Correct solution is either make FuzzyLite symbols hidden or turn lib into dynamic
if(NOT WIN32)
SET_TARGET_PROPERTIES(FuzzyLite_lib PROPERTIES COMPILE_FLAGS "-fPIC")
endif()

674
AI/FuzzyLite/COPYING Normal file
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. 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
them 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 prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. 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.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey 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;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If 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 convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU 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 that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
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.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
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.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
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
state 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 3 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, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program 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, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU 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. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

165
AI/FuzzyLite/COPYING.LESSER Normal file
View File

@ -0,0 +1,165 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser 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
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

214
AI/FuzzyLite/ChangeLog Normal file
View File

@ -0,0 +1,214 @@
Version 5.0
* Modified Function::Unary and Binary to take scalar instead of double
* Fixed building using -DFL_USE_FLOAT=ON
* Added deductive type of Engine with Engine::type()
* Fixed minor memory leak at RuleBlock (conjunction, disjunction, activation)
* Fixed minor memory leak at Accumulated (accumulation, thresholded terms)
* Fixed minor memory leak at OutputVariable (defuzzifier)
* Fixed minor memory leak at Function::Node
* Fixed minor memory leak at FactoryManager
* Improved handling of Exceptions
* Modified FclExporter and FisExporter to provide backward compatibility with FCL and FIS formats
* Updated the FIS and FCL examples for backward compatibility
* Included the original example files
* Updated FLD examples produced from the engines of the original examples
* Fixed some original examples of takagi-sugeno to use AlgebraicProduct activation
* FldExporter no longer restarts the engine
* Fixed rethrowing of exceptions to provide proper information about errors!
* Catching std::exceptions where possible to avoid unexpected exceptions
* FldExporter exports from a custom input dataset
* Console includes option to read custom input dataset from file
* Console provides more information about its usage
* Renamed methods FldExporter::toWriter() to FldExporter::write()
* Removed variable and methods for property FldExporter::maximum
* Accuracy improvements importing fis files with large number of decimals
* Updated FLD examples to reflect accuracy
* Changed operation for multiple hedges to operate from last to first
* Fixed OutputVariable to store last valid output value regardless of locks
* Renamed Op::isNan to Op::isNaN
* New OutputVariable::(get|set)OutputValue to store value from defuzzification
* Changed OutputVariable::defuzzify to store its output value
* Changed return type of scalar OutputVariable::defuzzify to void OutputVariable::defuzzify
* Renamed OutputVariable::(get|set)LastValidOutput to OutputVariable::(get|set)LastValidOutputValue
* Removed OutputVariable::defuzzifyNoLocks
* Removed const from Term* Accumulated::(get|set)Accumulation
* Added InputVariable::fuzzyInputValue and OutputVariable::fuzzyOutputValue
* Removed defaults in Engine::configure
* Added Engine::configure without conjuntion and disjuntion
* Added parameter string to Engine::type
* Changed Engine::isReady
* Correct handling of integral defuzzification with min|max=NaN|Inf
* Added method Rule::isLoaded to determine whether a rule is to be activated
* Added method Rule::unload to allow existence of invalid rules
* Added methods Engine::set((Input|Output)Variables), Engine::setRuleBlocks
* Added method RuleBlock::setRules
* Changed visibility of Rule::setText to public
* Added method Rule::load(const Engine*)
* Renamed term Thresholded to Activated
* Renamed Thresholded::(set|get)Threshold to Activated::(set|get)Degree
* Removed variable Rule::FL_ASSIGNS="=" and method Rule::assignsKeyword()
* Modified original takagi-sugeno examples to reflect proper activation and accumulation
* Moved Engine::_hedges (and methods) to Rule::_hedges
* Renamed Antecedent::(get|set)Root to Antecedent::(get|set)Expression
* Added (Antecedent|Consequent)::(get|set)Text
* Added (Antecedent|Consequent)::load|unload
* Renamed typedef Factory::Creator to Factory::Constructor
* Added an M-file to compare output values of fuzzylite engines with Matlab
* Removed const from Norms in RuleBlock::(get|set)(Activation|Conjunction|Disjunction)
* Deleted method Op::repeat
* Added built-in functions gt,lt,ge,le,eq and operator !
* Renamed Term::copy to Term::clone in every Term
* Added copy constructors and assignment operators to (Input|Output)Variable
* Added copy constructors and assignment operators to Accumulated
* Merged Function::Operator and Function::BuiltInFunction into Function::Element
* Created FunctionFactory for Function::Elements
* IMPORTANT: Changed starting precedence of Function::Element::Operators to 10 (refer to FunctionFactory)
* Setters of FactoryManager no longer delete previous factories
* Renamed Factory<T>::(register|deregister)Class to Factory<T>::(register|deregister)Constructor
* Renamed Factory<T> to ConstructionFactory<T>
* Created CloningFactory<T>
* Moved functions and operators of term Function to a FunctionFactory
* Added clone methods to Defuzzifiers, Hedges, Norms, and Terms
* Changed Exception::btCallStack(const int) to Exception::btCallStack(void)
* Using std::auto_ptr to (T|S)Norms in RuleBlock, SNorm in Accumulated, and Defuzzifier in OutputVariable
* Added methods Engine::set((Input|Output)Variable) and Engine::setRuleBlock()
* Added method RuleBlock::reloadRules()
* Changed Linear pointers to input variables for a pointer to Engine
* Added support to compare infinity values with fl::Op::isEq and therefore other comparison operators
* Parameters of all terms are set to fl::nan by default
* Added methods Engine::(input|output)Variables() and ::ruleBlocks() to return mutable references
* Added method Variable::terms() to return mutable reference
* Added method RuleBlock::rules() to return mutable reference
* Added methods Ramp::direction() and Sigmoid::direction() to represent direction of slope
* Added method fl::Op::isFinite(x) to check x is not (nan or inf)
* Changed fl::Op::isEq(a,b) to return true if a = b = NaN
* Added method Accumulated::terms() to return mutable reference
* Changed visibility of Linear::coefficients to protected
* Added methods Linear::coefficients(), Linear::setCoefficients()
* Removed public variables Discrete::x,y
* Added in Discrete a typedef to std::pair<scalar, scalar> Pair, and changed signatures of methods and types of their parameters
* Changed representation of Discrete::(x,y) from std::vector<scalar> to std::vector<Pair>
* Added methods Discrete::setXY(), Discrete::xy(), ::xy(int) to set and get new representation
* Added methods Discrete::toPairs(std::vector<scalar>) and Discrete::toVector(std::vector<Pair>)
* Added method Discrete::formatXY() to get pairs (x,y) nicely formatted
* Linear term no longer throws exception when inputVariables != |coefficients|
* Changed visibility of Function::root to protected and renamed it to Function::_root
* Added method Function::root() to return pointer to Function::_root
* Added option to prefix the namespace in CppExporter, by default it does not prefix
* Added method OutputVariable::clear() to restart the output variable
* Renamed variable OutputVariable::_lastValidOutputValue to ::_previousOutputValue
* Renamed method OutputVariable::(get|set)LastValidOutputValue to ::(get|set)PreviousOutputValue
* Renamed variable OutputVariable::_lockOutputRange to ::_lockOutputValueInRange
* Renamed method OutputVariable::setLockOutputRange() to ::setLockOutputValueInRange
* Renamed method OutputVariable::isLockingOutputRange() to ::isLockedOutputValueInRange
* Renamed variable OutputVariable::_lockValidOutput to ::_lockPreviousOutputValue
* Renamed method OutputVariable::setLockValidOutput() to ::setLockPreviousOutputValue
* Renamed method OutputVariable::isLockingValidOutput() to ::isLockedPreviousOutputValue
* Renamed FLL property 'lock-valid' to 'lock-previous'
* Renamed FIS property 'LockValid' to 'LockPrevious'
* Renamed FCL property 'LOCK: VALID' to 'LOCK: PREVIOUS'
* Added method Engine::variables() to retrieve both Input and OutputVariables
* Added method Term::updateReference(Term*, Engine*) to ensure Linear and Function terms to update references of engines
* Added method Engine::updateReferences() to update references to the engine in its terms.
* Added in Discrete a typedef to std::pair<scalar, scalar> Pair, and changed signatures of methods and types of their parameters
* Added terms: Concave, Cosine and Spike
* Renamed methods Triangle::(set|get)(A|B|C) to (set|get)(Vertex(A|B|C))
* Renamed methods Trapezoid::(set|get)(A|B|C|D) to (set|get)(Vertex(A|B|C|D))
* Removed method fuzzylite::configuration()
* Renamed MACRO FL_DEBUG to FL_DBG
* Renamed MACRO (FL_BEGIN_DEBUG_BLOCK and FL_END_DEBUG_BLOCK) to (FL_DEBUG_BEGIN and FL_DEBUG_END)
* Renamed methods in (Fis|Fcl)Importers::extract? to ::parse?
* Made defaultResolution a static property of IntegralDefuzzifiers
* Added method Engine::type(name, reason) to show type and reason why type
* Added method Engine::clone()
* Added support for Tsukamoto with Concave terms
* Changed Accumulated to take Activated* terms instead of const Terms*
* Deleted class Tsukamoto
* Created class WeightedDefuzzifier from which Weighted(Average|Sum) derive with options: Automatic|TakagiSugeno|Tsukamoto
* Added methods WeightedDefuzzifier::tsukamoto() and ::inferType()
* Added benchmarks for fuzzylite in Linux
* Created the FuzzyLite Interactive Console
* Added basic rule chaining such that Output Variables can be utilized as antecedents
* Added two examples for rule chaining: mamdani/Laundry.fll and mamdani/SimpleDimmerInverse.fll
* Added Term::(get|set)Height and changed all terms accordingly
* Renamed method Op::makeValidId to Op::validName, which now returns "unnamed" for empty strings.
* Converted examples/original/*.fis to examples/original/*.fll
* Removed Exception Specification from methods in Discrete, Linear and Function terms
* Changed name of debug libraries to fuzzylited.dll and fuzzylite-staticd.lib
* Removed method Operation::toScalar(std::string, bool, scalar)
* Added method Operation::toScalar(std::string) [throws Exception], and ::toScalar(std::string, scalar alternative) throw()
* Added method ImEx::(from|to)File to import and export engines using files
* WeightedAverage and WeightedSum without Activation operators have default behaviour, i.e., AlgebraicProduct
* FactoryManager utilizes smart pointers.
* Rule utilizes smart pointers for Antecedent and Consequent
* Exceptions are thrown when Conjunction, Disjunction, Activation and Accumulation operators are NULL when they are required
* Exception is thrown when Defuzzifier is required and not set.
* Added support for C++11 utilizing smart pointers, identifiers (override, noexcept), and delete identifiers to DISABLE_COPY(Class)
* Macros for identifiers are FL_IOVERRIDE, FL_IFINAL, FL_IDEFAULT, FL_IDELETE, and FL_INOEXCEPT (fl/fuzzylite.h)
* Added macro FL_unique_ptr to refer to std::auto_ptr (C++98) or std::unique_ptr (C++11), and its respective FL_move_ptr(x) to move a smart pointer.
* Added constant fl::null to refer to 0L (C++98) or nullptr (C++11)
* Added macros FL_DEFAULT_COPY(Class), FL_DEFAULT_MOVE(Class), and FL_DEFAULT_COPY_AND_MOVE(Class) for default copy and move constructors and operators
* Added build.sh to build fuzzylite
* Changed default to fuzzylite::_macheps = 1e-6;
* Renamed macro FL_EXPORTS to FL_API
* Added macro FL_SHARED_LIBRARY and FL_STATIC_LIBRARY to be defined when building shared and static libraries
Version 4.0
* FuzzyRule merged with Rule, and FuzzyRule deleted.
* FuzzyAntecedent merged with Antecedent, and FuzzyAntecedent deleted
* FuzzyConsequent merged with Consequent, and FuzzyConsequent deleted
* FuzzyExpression renamed Expression
* Renamed Rule::get/setUnparsedRule to get/setText
* Renamed RuleBlock::get/set(Tnorm|Snorm) to get/set(Conjunction|Disjunction)
* Renamed RuleBlock::fireRules to activate
* Renamed Rule::fireStrength to activationDegree, fire to activate
* Renamed Consequent::fire to modify
* Created IntegralDefuzzifier to extract divisions from Defuzzifier
* Renamed divisions from IntegralDefuzzifier to resolution, FL_DIVISIONS to FL_RESOLUTION
* Deleted MaximumDefuzzifier
* Centroid, Bisector, and Largest/Smallest/Mean Defuzzifiers inherit from IntegralDefuzzifier
* Changed names of arithmetic operations in fl::Operation
* Renamed Function::get/set(Infix) to get/set(Formula)
* Renamed InputVariable::get/set(Input) to get/set(InputValue)
* Renamed Antecedent::firingStrength to activationDegree
* Renamed Antecedent::toString/(Prefix,Infix,Postfix) to to/(Prefix,Infix,Postfix)
* Renamed Rule::FL_ASSIGN to Rule::FL_EQUALS
* New method restart in Engine
* New methods Engine::setInputValue(name, value), scalar Engine::getOutputValue(name)
* Renamed Op::str(vector/varargs) to Op::join(vector/varargs)
* Refactored associtativity, unary and binary properties in Element within Function
* Removed unnecessary Hedges creation upon importing engines, now is automatic via Factories
* Created the JavaExporter
* Renamed methods within Fis/Fcl/CppExporter to toString(*);
* Extracted TNorms and SNorms from TNorm.h/cpp and SNorm.h/cpp
* Created proper Factories with registration of classes and constructors
* Renamed method Factory::create to Factory::createInstance
* Added static constructor method to every Defuzzifier, Hedge, TNorm, and SNorm
* Removed FL_PRECISION, FL_DECIMALS as Macros, and created static variables in fuzzylite.h
* Renamed FL_PRECISION to macheps, i.e., machine epsilon to differentiate real numbers
* Removed FL_DEBUG and created a static variable in fuzzylite.h
* Removed FL_NO_LOG as it is now controlled with fuzzylite::logging(), previously named logEnabled()
* Libraries and Console application are both built in folder bin/ (previously libraries were at lib/)
* Removed Engine::toStringFis/Fcl/Cpp to encourage use of Fcl/Fis/CppExporters instead
* Renamed Op::logical_and to Op::logicalAnd, Op::logical_or to Op::logicalOr
* Added support to Fis/FclImporters to treat comments (%,#,//,/*) in fis and fcl files
* Created the Console application instead of previous demo
* Added Variable::range() to return (maximum - minimum)
* Removed Variable::isEmpty, use Variable::terms().empty()
* Removed RuleBlock::isEmpty, use RuleBlock::rules().empty()
* Created method Op::makeValidId to ensure names are valid
* Engine, Variable and Term::toString return FllExport::toString
* Created Term::parameters to return list of parameter values as string separated by spaces
* Created Term::configure to configure from Term::parameters
* FclImEx import and export terms using Term::parameters
* Created the FuzzyLite Language in FllImporter and FllExporter
* Created the FuzzyLite Dataset FldExporter
* Added property Enable to Engine, Variable and RuleBlock
* Extended FCL and FIS to consider Enabled properties
* Changed Engine::defuzzify() to consider enabled variables
* Changed Engine::process() to consider enabled rule blocks
* Changed OutputVariable::output() to OutputVariable::fuzzyOutput()
* Renamed Rectangle::minimum/maximum to Rectangle::start/end
* Renamed fuzzylite::shortVersion to fuzzylite::version
* Improved accuracy of Triangle and Trapezoid

View File

@ -1,112 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* CompoundTerm.cpp
*
* Created on: Dec 13, 2009
* Author: jcrada
*/
#include "CompoundTerm.h"
namespace fl {
CompoundTerm::CompoundTerm() :
LinguisticTerm() {
}
CompoundTerm::CompoundTerm(const std::string& name, flScalar minimum,
flScalar maximum) :
LinguisticTerm(name, minimum, maximum) {
}
CompoundTerm::CompoundTerm(const FuzzyOperator& fuzzy_op, const std::string& name,
flScalar minimum, flScalar maximum) :
LinguisticTerm(fuzzy_op, name, minimum, maximum) {
}
CompoundTerm::~CompoundTerm() {
clear();
}
void CompoundTerm::addTerm(const LinguisticTerm& term) {
_terms.push_back(term.clone());
if (term.minimum() < minimum() || isinf(minimum())) {
setMinimum(term.minimum());
}
if (term.maximum() > maximum() || isinf(maximum())) {
setMaximum(term.maximum());
}
}
const LinguisticTerm& CompoundTerm::term(int index) const {
return *this->_terms[index];
}
void CompoundTerm::removeTerm(int index){
LinguisticTerm* t = this->_terms[index];
this->_terms.erase(this->_terms.begin() + index);
delete t;
}
int CompoundTerm::numberOfTerms() const{
return this->_terms.size();
}
void CompoundTerm::clear() {
for (size_t i = 0; i < _terms.size(); ++i) {
delete _terms[i];
}
_terms.clear();
setMinimum(-INFINITY);
setMaximum(INFINITY);
}
CompoundTerm* CompoundTerm::clone() const {
CompoundTerm* result = new CompoundTerm;
for (int i = 0 ; i < numberOfTerms(); ++i){
result->addTerm(term(i));
}
return result;
}
flScalar CompoundTerm::membership(flScalar crisp) const {
flScalar max = flScalar(0);
for (size_t i = 0; i < _terms.size(); ++i) {
max = fuzzyOperator().aggregation().execute(max, _terms[i]->membership(crisp));
}
return fuzzyOperator().modulation().execute(modulation(), max);
}
LinguisticTerm::eMembershipFunction CompoundTerm::type() const {
return MF_COMPOUND;
}
std::string CompoundTerm::toString() const {
std::stringstream ss;
ss << LinguisticTerm::toString();
ss << "Compound (";
for (size_t i = 0; i < _terms.size(); ++i) {
ss << _terms[i]->toString();
if (i < _terms.size() -1 ) ss << " + ";
}
ss << ")";
return ss.str();
}
} // namespace fuzzy_lite

View File

@ -1,59 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* CompoundTerm.h
*
* Created on: Dec 13, 2009
* Author: jcrada
*/
#ifndef FL_COMPOUNDTERM_H_
#define FL_COMPOUNDTERM_H_
#include "LinguisticTerm.h"
#include <vector>
namespace fl {
class CompoundTerm : public LinguisticTerm {
private:
std::vector<LinguisticTerm*> _terms;
public:
CompoundTerm();
CompoundTerm(const std::string& name, flScalar minimum = -INFINITY,
flScalar maximum = INFINITY);
CompoundTerm(const FuzzyOperator& fuzzy_op, const std::string& name,
flScalar minimum = -INFINITY, flScalar maximum = INFINITY);
virtual ~CompoundTerm();
virtual void addTerm(const LinguisticTerm& term);
virtual const LinguisticTerm& term(int index) const;
virtual void removeTerm(int index);
virtual int numberOfTerms() const;
virtual void clear();
virtual CompoundTerm* clone() const;
virtual flScalar membership(flScalar crisp) const;
virtual eMembershipFunction type() const;
virtual std::string toString() const;
};
} // namespace fuzzy_lite
#endif /* FL_COMPOUNDTERM_H_ */

View File

@ -1,296 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "DescriptiveAntecedent.h"
#include "StrOp.h"
#include <stack>
#include "FuzzyRule.h"
namespace fl {
DescriptiveAntecedent::DescriptiveAntecedent() : FuzzyAntecedent(),
_left(NULL), _right(NULL), _operation(O_NONE), _term(NULL) {
}
DescriptiveAntecedent::DescriptiveAntecedent(const FuzzyOperator& fuzzy_op) :
FuzzyAntecedent(fuzzy_op), _left(NULL), _right(NULL), _operation(O_NONE),
_term(NULL) {
}
DescriptiveAntecedent::~DescriptiveAntecedent() {
if (_left) {
delete _left;
}
if (_right) {
delete _right;
}
}
void DescriptiveAntecedent::setLeft(DescriptiveAntecedent* l_antecedent) {
this->_left = l_antecedent;
}
DescriptiveAntecedent* DescriptiveAntecedent::left() const {
return this->_left;
}
void DescriptiveAntecedent::setRight(DescriptiveAntecedent* r_antecedent) {
this->_right = r_antecedent;
}
DescriptiveAntecedent* DescriptiveAntecedent::right() const {
return this->_right;
}
void DescriptiveAntecedent::setOperation(OPERATION operation) {
this->_operation = operation;
}
DescriptiveAntecedent::OPERATION DescriptiveAntecedent::operation() const {
return this->_operation;
}
void DescriptiveAntecedent::addHedge(Hedge* hedge) {
this->_hedges.push_back(hedge);
}
int DescriptiveAntecedent::numberOfHedges() const {
return this->_hedges.size();
}
Hedge* DescriptiveAntecedent::hedge(int index) const {
return this->_hedges[index];
}
void DescriptiveAntecedent::setTerm(const LinguisticTerm* term) {
this->_term = term;
}
const LinguisticTerm* DescriptiveAntecedent::term() const {
return this->_term;
}
bool DescriptiveAntecedent::isTerminal() const {
return operation() == O_NONE;
}
flScalar DescriptiveAntecedent::degreeOfTruth() const {
if (!isTerminal()) {
if (left() == NULL || right() == NULL) {
throw NullPointerException(FL_AT, toString());
}
switch (operation()) {
case O_AND:
return fuzzyOperator().tnorm().execute(left()->degreeOfTruth(),
right()->degreeOfTruth());
case O_OR:
return fuzzyOperator().snorm().execute(left()->degreeOfTruth(),
right()->degreeOfTruth());
default:
throw InvalidArgumentException(FL_AT, "Operation " + StrOp::IntToString(operation()) + " not available");
}
}
flScalar result = term()->membership(inputLVar()->input());
for (int i = 0; i < numberOfHedges(); ++i) {
result = hedge(i)->hedge(result);
}
return result;
}
std::string DescriptiveAntecedent::toString() const {
std::stringstream ss;
if (isTerminal()) {
ss << inputLVar()->name() + " " + FuzzyRule::FR_IS + " ";
for (int i = 0; i < numberOfHedges(); ++i) {
ss << hedge(i)->name() << " ";
}
ss << term()->name();
} else {
ss << " ( " + (left() ? left()->toString() : "NULL");
ss << " " + (operation() == O_AND ? FuzzyRule::FR_AND : FuzzyRule::FR_OR);
ss << " " + (right() ? right()->toString() : "NULL") + " ) ";
}
return ss.str();
}
void DescriptiveAntecedent::parse(const std::string& antecedent,
const FuzzyEngine& engine) throw (ParsingException) {
enum e_state {
//e.g. Posfix antecedent: Energy is LOW Distance is FAR_AWAY and
S_LVAR = 1, S_IS, S_HEDGE, S_TERM, S_OPERATOR
};
e_state current_state = S_LVAR;
std::string postfix_antecedent = InfixToPostfix(antecedent);
std::stringstream ss(postfix_antecedent);
std::string token;
InputLVar* input = NULL;
std::vector<Hedge*> hedges;
Hedge* hedge = NULL;
LinguisticTerm* term = NULL;
std::stack<DescriptiveAntecedent*> f_antecedents;
DescriptiveAntecedent* tmp_antecedent = NULL;
// <editor-fold desc="State Machine">
while (ss >> token) {
switch (current_state) {
//e.g.Postfix: Energy is LOW Distance is FAR_AWAY and. After term follows Operator or LVar
case S_LVAR:
case S_OPERATOR:
input = engine.inputLVar(token);
if (input) {
current_state = S_IS;
break;
}
if (token != FuzzyRule::FR_AND && token != FuzzyRule::FR_OR) {
//if it is not and InputLVar and not an Operator then exception
throw ParsingException(FL_AT, "Input variable <" +
token + "> not registered in fuzzy engine");
// throw RuleParsingException(FL_AT,
// "Operator expected but found <" + token +
// ">. Antecedent: " + antecedent);
}
//A is a B is b and
if (isTerminal()) {
setLeft(f_antecedents.top());
f_antecedents.pop();
setRight(f_antecedents.top());
f_antecedents.pop();
setOperation(token == FuzzyRule::FR_AND ? DescriptiveAntecedent::O_AND :
DescriptiveAntecedent::O_OR); //I am not terminal anymore
} else {
setLeft(new DescriptiveAntecedent(*this));
setRight(f_antecedents.top());
f_antecedents.pop();
setOperation(token == FuzzyRule::FR_AND ? DescriptiveAntecedent::O_AND :
DescriptiveAntecedent::O_OR); //I am not terminal anymore
}
break;
case S_IS:
if (token == FuzzyRule::FR_IS) {
current_state = S_HEDGE;
} else {
throw ParsingException(FL_AT, "<is> expected but found <" +
token + ">");
}
break;
case S_HEDGE:
hedge = engine.hedgeSet().get(token);
if (hedge) {
hedges.push_back(hedge); //And check for more hedges
break;
}
//intentional fall-through in case there are no hedges
case S_TERM:
term = input->term(token);
if (!term) {
throw ParsingException(FL_AT, "Term <" + token +
"> not found in input variable <" + input->name() +
">");
}
current_state = S_OPERATOR;
tmp_antecedent = new DescriptiveAntecedent(engine.fuzzyOperator());
tmp_antecedent->setInputLVar(input);
tmp_antecedent->setTerm(term);
for (size_t i = 0; i < hedges.size(); ++i) {
tmp_antecedent->addHedge(hedges[i]);
}
f_antecedents.push(tmp_antecedent);
tmp_antecedent = NULL;
hedges.clear();
break;
}
}
//</editor-fold>
if (!f_antecedents.empty()) { //e.g. Rule: if A is a then X is x (one antecedent only)
FL_ASSERT(f_antecedents.size() == 1);
DescriptiveAntecedent* me = f_antecedents.top();
setInputLVar(me->inputLVar());
for (int i = 0; i < me->numberOfHedges(); ++i) {
addHedge(me->hedge(i));
}
setTerm(me->term());
delete me;
}
}
std::string DescriptiveAntecedent::Preprocess(const std::string& infix) {
std::string result;
for (size_t i = 0; i < infix.size(); ++i) {
if (infix[i] == '(') {
result += " ( ";
} else if (infix[i] == ')') {
result += " ) ";
} else {
result += infix[i];
}
}
return result;
}
std::string DescriptiveAntecedent::InfixToPostfix(const std::string& infix) {
std::string p_infix = Preprocess(infix);
std::stringstream ss(p_infix);
std::string token;
std::string tmp;
std::string result;
std::stack<std::string> stack;
while (ss >> token) {
if (token == "(") {
stack.push(token);
} else if (token == ")") {
FL_ASSERT(!stack.empty());
tmp = stack.top();
stack.pop();
while (tmp != "(") {
result += tmp + " ";
FL_ASSERT(!stack.empty());
tmp = stack.top();
stack.pop();
}
} else if (token == FuzzyRule::FR_AND || token == FuzzyRule::FR_OR) {
if (stack.empty()) {
stack.push(token);
} else {
FL_ASSERT(!stack.empty())
tmp = stack.top();
stack.pop();
while (tmp != FuzzyRule::FR_AND && tmp != FuzzyRule::FR_OR && tmp != "(") {
result += tmp + " ";
FL_ASSERT(!stack.empty())
tmp = stack.top();
stack.pop();
}
stack.push(tmp);
stack.push(token);
}
} else {
result += token + " ";
}
}
while (!stack.empty()) {
FL_ASSERT(!stack.empty())
token = stack.top();
stack.pop();
result += token + " ";
}
return result;
}
}

View File

@ -1,88 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* File: DescriptiveAntecedent.h
* Author: jcrada
*
* Created on March 3, 2010, 12:32 AM
*/
#ifndef FL_DESCRIPTIVEANTECEDENT_H
#define FL_DESCRIPTIVEANTECEDENT_H
#include "FuzzyAntecedent.h"
#include "FuzzyOperator.h"
#include "InputLVar.h"
#include "Hedge.h"
#include "LinguisticTerm.h"
#include <vector>
#include <string>
#include "FuzzyEngine.h"
#include "FuzzyExceptions.h"
namespace fl {
class DescriptiveAntecedent : public FuzzyAntecedent {
public:
enum OPERATION {
O_NONE = ' ', O_AND = '&', O_OR = '*',
};
private:
DescriptiveAntecedent* _left;
DescriptiveAntecedent* _right;
OPERATION _operation;
std::vector<Hedge*> _hedges; //very
const LinguisticTerm* _term; //high
public:
DescriptiveAntecedent();
DescriptiveAntecedent(const FuzzyOperator& fuzzy_op);
virtual ~DescriptiveAntecedent();
virtual flScalar degreeOfTruth() const;
virtual std::string toString() const;
virtual void parse(const std::string& antecedent,
const FuzzyEngine& engine) throw (ParsingException);
virtual void setLeft(DescriptiveAntecedent* l_antecedent);
virtual DescriptiveAntecedent* left() const;
virtual void setRight(DescriptiveAntecedent* r_antecedent);
virtual DescriptiveAntecedent* right() const;
virtual void setOperation(OPERATION operation);
virtual OPERATION operation() const;
virtual void addHedge(Hedge* hedge);
virtual int numberOfHedges() const;
virtual Hedge* hedge(int index) const;
virtual void setTerm(const LinguisticTerm* term);
virtual const LinguisticTerm* term() const;
virtual bool isTerminal() const;
// static bool IsValid(const std::string& rule, const FuzzyEngine& engine);
std::string Preprocess(const std::string& infix);
std::string InfixToPostfix(const std::string& infix);
};
}
#endif /* FL_DESCRIPTIVEANTECEDENT_H */

View File

@ -1,120 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "DiscreteTerm.h"
namespace fl {
DiscreteTerm::DiscreteTerm() : LinguisticTerm() {
}
DiscreteTerm::DiscreteTerm(const std::string& name, const std::vector<flScalar>& x,
const std::vector<flScalar>& y)
: LinguisticTerm(name) {
setXY(x, y);
}
DiscreteTerm::DiscreteTerm(const FuzzyOperator& fuzzy_op, const std::string& name,
const std::vector<flScalar>& x, const std::vector<flScalar>& y)
: LinguisticTerm(fuzzy_op, name) {
setXY(x, y);
}
DiscreteTerm::~DiscreteTerm() {
}
void DiscreteTerm::setXY(const std::vector<flScalar>& x, const std::vector<flScalar>& y) {
this->_x = x;
this->_y = y;
}
void DiscreteTerm::setXY(int index, flScalar x, flScalar y) {
this->_x.insert(this->_x.begin() + index, x);
this->_y.insert(this->_y.begin() + index, y);
}
void DiscreteTerm::addXY(flScalar x, flScalar y) {
this->_x.push_back(x);
this->_y.push_back(y);
}
void DiscreteTerm::remove(int index) {
this->_x.erase(this->_x.begin() + index);
this->_y.erase(this->_y.begin() + index);
}
void DiscreteTerm::clear() {
this->_x.clear();
this->_y.clear();
}
int DiscreteTerm::numberOfCoords() const {
return (int) this->_x.size();
}
flScalar DiscreteTerm::minimum() const {
flScalar result = INFINITY;
for (int i = 0; i < numberOfCoords(); ++i) {
if (_x[i] < result) {
result = _x[i];
}
}
return isinf(result) ? NAN : result;
}
flScalar DiscreteTerm::maximum() const {
flScalar result = -INFINITY;
for (int i = 0; i < numberOfCoords(); ++i) {
if (_x[i] > result) {
result = _x[i];
}
}
return isinf(result) ? NAN : result;
}
DiscreteTerm* DiscreteTerm::clone() const {
return new DiscreteTerm(*this);
}
flScalar DiscreteTerm::membership(flScalar crisp) const {
flScalar closer = INFINITY;
flScalar result = NAN;
for (int i = 0; i < numberOfCoords(); ++i) {
if (fabs(crisp - _x[i]) < closer) {
closer = fabs(crisp - _x[i]);
result = _y[i];
}
}
return result;
}
LinguisticTerm::eMembershipFunction DiscreteTerm::type() const {
return LinguisticTerm::MF_DISCRETE;
}
std::string DiscreteTerm::toString() const {
std::stringstream ss;
ss << LinguisticTerm::toString();
ss << "Discrete (";
for (int i = 0; i < numberOfCoords(); ++i) {
ss << "{" << _x[i] << "," << _y[i] << "}";
if (i < numberOfCoords() - 1) {
ss << " ";
}
}
ss << ")";
return ss.str();
}
}

View File

@ -1,50 +0,0 @@
/*
* File: DiscreteTerm.h
* Author: jcrada
*
* Created on May 9, 2010, 8:17 PM
*/
#ifndef FL_DISCRETETERM_H
#define FL_DISCRETETERM_H
#include "LinguisticTerm.h"
namespace fl {
class DiscreteTerm : public LinguisticTerm {
private:
std::vector<flScalar> _x;
std::vector<flScalar> _y;
public:
DiscreteTerm();
DiscreteTerm(const std::string& name, const std::vector<flScalar>& x = std::vector<flScalar>(),
const std::vector<flScalar>& y = std::vector<flScalar>());
DiscreteTerm(const FuzzyOperator& fuzzy_op, const std::string& name,
const std::vector<flScalar>& x = std::vector<flScalar>(),
const std::vector<flScalar>& y = std::vector<flScalar>());
virtual ~DiscreteTerm();
virtual void setXY(int index, flScalar x, flScalar y);
virtual void setXY(const std::vector<flScalar>&x, const std::vector<flScalar>&y);
virtual void addXY(flScalar x, flScalar y);
virtual void remove(int index);
virtual void clear();
virtual int numberOfCoords() const;
virtual flScalar minimum() const;
virtual flScalar maximum() const;
virtual DiscreteTerm* clone() const;
virtual flScalar membership(flScalar crisp) const;
virtual eMembershipFunction type() const;
virtual std::string toString() const;
};
}
#endif /* FL_DISCRETETERM_H */

View File

@ -1,94 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "FunctionTerm.h"
namespace fl {
FunctionTerm::FunctionTerm() : LinguisticTerm() {
_ip.loadMathOperators();
}
FunctionTerm::FunctionTerm(const std::string& name, const std::string& f_infix,
flScalar minimum, flScalar maximum)
: LinguisticTerm(name, minimum, maximum) {
_ip.loadMathOperators();
setInfixFunction(f_infix);
}
FunctionTerm::FunctionTerm(const FuzzyOperator& fuzzy_op, const std::string& name,
const std::string& f_infix, flScalar minimum, flScalar maximum)
: LinguisticTerm(fuzzy_op, name, minimum, maximum) {
_ip.loadMathOperators();
setInfixFunction(f_infix);
}
FunctionTerm::~FunctionTerm() {
}
void FunctionTerm::setInfixFunction(const std::string& infix) {
this->_infix_function = infix;
setPostfixFunction(_ip.transform(infix));
}
std::string FunctionTerm::infixFunction() const {
return this->_infix_function;
}
void FunctionTerm::setPostfixFunction(const std::string& postfix) {
this->_postfix_function = postfix;
}
std::string FunctionTerm::postfixFunction() const {
return this->_postfix_function;
}
bool FunctionTerm::isValid() const {
std::map<std::string, flScalar> x;
x["x"] = 0;
x["min"] = minimum();
x["max"] = maximum();
try {
_ip.evaluate(postfixFunction(), &x);
return true;
} catch (std::exception ex) {
return false;
}
}
flScalar FunctionTerm::membership(flScalar crisp) const {
std::map<std::string, flScalar> m;
m["x"] = crisp;
m["min"] = minimum();
m["max"] = maximum();
return _ip.evaluate(postfixFunction(), &m);
}
FunctionTerm* FunctionTerm::clone() const {
return new FunctionTerm(*this);
}
LinguisticTerm::eMembershipFunction FunctionTerm::type() const {
return MF_FUNCTION;
}
std::string FunctionTerm::toString() const {
std::stringstream ss;
ss << LinguisticTerm::toString();
ss << "Function f = " << postfixFunction() << " | x=[" << minimum() << " " << maximum() << "]";
return ss.str();
}
}

View File

@ -1,60 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* File: FunctionTerm.h
* Author: jcrada
*
* Created on March 10, 2010, 6:16 PM
*/
#ifndef FL_FUNCTIONTERM_H
#define FL_FUNCTIONTERM_H
#include "LinguisticTerm.h"
#include "InfixToPostfix.h"
namespace fl {
class FunctionTerm : public LinguisticTerm {
private:
InfixToPostfix _ip;
std::string _postfix_function;
std::string _infix_function;
public:
FunctionTerm();
FunctionTerm(const std::string& name, const std::string& f_infix, flScalar minimum = -INFINITY,
flScalar maximum = INFINITY);
FunctionTerm(const FuzzyOperator& fuzzy_op, const std::string& name,
const std::string& f_infix, flScalar minimum = -INFINITY,
flScalar maximum = INFINITY);
virtual ~FunctionTerm();
virtual void setInfixFunction(const std::string& infix);
virtual std::string infixFunction() const;
virtual void setPostfixFunction(const std::string& postfix);
virtual std::string postfixFunction() const;
virtual bool isValid() const;
virtual FunctionTerm* clone() const;
virtual flScalar membership(flScalar crisp) const;
virtual eMembershipFunction type() const;
virtual std::string toString() const;
};
}
#endif /* FL_FUNCTIONTERM_H */

View File

@ -1,44 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "FuzzyAnd.h"
namespace fl {
std::string FuzzyAndMin::name() const {
return "Min";
}
flScalar FuzzyAndMin::execute(flScalar mu1, flScalar mu2) const {
return FuzzyOperation::Min(mu1, mu2);
}
std::string FuzzyAndProd::name() const {
return "Prod";
}
flScalar FuzzyAndProd::execute(flScalar mu1, flScalar mu2) const {
return FuzzyOperation::AlgebraicProduct(mu1, mu2);
}
std::string FuzzyAndBDiff::name() const {
return "BDiff";
}
flScalar FuzzyAndBDiff::execute(flScalar mu1, flScalar mu2) const {
return FuzzyOperation::BoundedDiff(mu1, mu2);
}
}

View File

@ -1,49 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* File: FuzzyAnd.h
* Author: jcrada
*
* Created on April 6, 2010, 5:11 PM
*/
#ifndef FL_FUZZYAND_H
#define FL_FUZZYAND_H
#include "FuzzyOperation.h"
namespace fl {
class FuzzyAndMin : public FuzzyOperation {
public:
virtual std::string name() const;
virtual flScalar execute(flScalar mu1, flScalar mu2) const;
};
class FuzzyAndProd : public FuzzyOperation {
public:
virtual std::string name() const;
virtual flScalar execute(flScalar mu1, flScalar mu2) const;
};
class FuzzyAndBDiff : public FuzzyOperation {
public:
virtual std::string name() const;
virtual flScalar execute(flScalar mu1, flScalar mu2) const;
};
}
#endif /* FL_FUZZYAND_H */

View File

@ -1,52 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "FuzzyAntecedent.h"
namespace fl {
FuzzyAntecedent::FuzzyAntecedent() : _input_lvar(NULL) {
setFuzzyOperator(FuzzyOperator::DefaultFuzzyOperator());
}
FuzzyAntecedent::FuzzyAntecedent(const FuzzyOperator& fuzzy_op)
: _fuzzy_operator(&fuzzy_op), _input_lvar(NULL) {
}
FuzzyAntecedent::~FuzzyAntecedent() {
}
void FuzzyAntecedent::setFuzzyOperator(const FuzzyOperator& fuzzy_op) {
this->_fuzzy_operator = &fuzzy_op;
}
const FuzzyOperator& FuzzyAntecedent::fuzzyOperator() const {
return *this->_fuzzy_operator;
}
void FuzzyAntecedent::setInputLVar(const InputLVar* input_lvar) {
this->_input_lvar = input_lvar;
}
const InputLVar* FuzzyAntecedent::inputLVar() const {
return this->_input_lvar;
}
}

View File

@ -1,57 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* File: FuzzyAntecedent.h
* Author: jcrada
*
* Created on March 3, 2010, 12:28 AM
*/
#ifndef FL_FUZZYANTECEDENT_H
#define FL_FUZZYANTECEDENT_H
#include "flScalar.h"
#include <string>
#include "FuzzyExceptions.h"
#include "FuzzyOperator.h"
#include "InputLVar.h"
#include "FuzzyEngine.h"
namespace fl {
class FuzzyAntecedent {
private:
const FuzzyOperator* _fuzzy_operator;
const InputLVar* _input_lvar; //e.g. power
public:
FuzzyAntecedent();
FuzzyAntecedent(const FuzzyOperator& fuzzy_op);
virtual ~FuzzyAntecedent();
virtual void setFuzzyOperator(const FuzzyOperator& fuzzy_op);
virtual const FuzzyOperator& fuzzyOperator() const;
virtual void setInputLVar(const InputLVar* input_lvar);
virtual const InputLVar* inputLVar() const;
virtual flScalar degreeOfTruth() const = 0;
virtual std::string toString() const = 0;
virtual void parse(const std::string& antecedent,
const FuzzyEngine& engine) throw (ParsingException) = 0;
};
}
#endif /* FL_FUZZYANTECEDENT_H */

View File

@ -1,46 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "FuzzyConsequent.h"
namespace fl {
FuzzyConsequent::FuzzyConsequent() : _output_lvar(NULL), _weight(1.0) {
}
FuzzyConsequent::~FuzzyConsequent() {
}
void FuzzyConsequent::setOutputLVar(OutputLVar* output_lvar) {
this->_output_lvar = output_lvar;
}
OutputLVar* FuzzyConsequent::outputLVar() const {
return this->_output_lvar;
}
void FuzzyConsequent::setWeight(flScalar weight) {
this->_weight = weight;
}
flScalar FuzzyConsequent::weight() const {
return this->_weight;
}
}

View File

@ -1,60 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* File: FuzzyConsequent.h
* Author: jcrada
*
* Created on March 2, 2010, 7:05 PM
*/
#ifndef FL_FUZZYCONSEQUENT_H
#define FL_FUZZYCONSEQUENT_H
#include "OutputLVar.h"
#include <string>
#include "FuzzyExceptions.h"
#include "FuzzyEngine.h"
namespace fl {
class FuzzyConsequent {
private:
OutputLVar* _output_lvar;
flScalar _weight;
public:
FuzzyConsequent();
virtual ~FuzzyConsequent();
virtual void setOutputLVar(OutputLVar* output_lvar);
virtual OutputLVar* outputLVar() const;
virtual void setWeight(flScalar weight);
virtual flScalar weight() const;
virtual void parse(const std::string& consequent,
const FuzzyEngine& engine) throw (ParsingException) = 0;
virtual void execute(flScalar degree) = 0;
virtual std::string toString() const = 0;
static void main(int argc, char** argv);
};
}
#endif /* FL_FUZZYCONSEQUENT_H */

View File

@ -1,62 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "FuzzyDefuzzifier.h"
#include "CompoundTerm.h"
#include "TakagiSugenoTerm.h"
namespace fl {
FuzzyDefuzzifier::~FuzzyDefuzzifier() {
}
std::string CoGDefuzzifier::name() const {
return "CoG";
}
flScalar CoGDefuzzifier::defuzzify(const LinguisticTerm* term, int number_of_samples,
const AreaCentroidAlgorithm* algorithm) const {
flScalar x, y;
algorithm->centroid(term, x, y, number_of_samples);
return x;
}
std::string TakagiSugenoDefuzzifier::name() const {
return "TSK";
}
flScalar TakagiSugenoDefuzzifier::defuzzify(const LinguisticTerm* term, int number_of_samples,
const AreaCentroidAlgorithm* algorithm) const {
const CompoundTerm* out = dynamic_cast<const CompoundTerm*> (term);
if (!out) {
FL_LOG("<CompoundTerm> expected, but <" << term->toString() << "> found." <<
"Takagi-Sugeno defuzzification works only on the output of Takagi-Sugeno Rules." );
return -1;
}
flScalar result = 0;
flScalar sum_wi = 0;
for (int i = 0; i < out->numberOfTerms(); ++i) {
const TakagiSugenoTerm* t = dynamic_cast<const TakagiSugenoTerm*> (&out->term(i));
if (!t) {
FL_LOG("<TakagiSugenoTerm> expected, but <" << out->term(i).toString() << "> found." <<
"Takagi-Sugeno defuzzification works only on the output of Takagi-Sugeno Rules");
return -1;
}
result += t->value() * t->weight();
sum_wi += t->weight();
}
return result / sum_wi;
}
}

View File

@ -1,57 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* File: FuzzyDefuzzifier.h
* Author: jcrada
*
* Created on April 6, 2010, 5:16 PM
*/
#ifndef FL_FUZZYDEFUZZIFIER_H
#define FL_FUZZYDEFUZZIFIER_H
#include "flScalar.h"
#include "AreaCentroidAlgorithm.h"
#include <string>
namespace fl {
class LinguisticTerm;
class FuzzyDefuzzifier {
public:
virtual ~FuzzyDefuzzifier();
virtual std::string name() const = 0;
virtual flScalar defuzzify(const LinguisticTerm* term, int number_of_samples,
const AreaCentroidAlgorithm* algorithm) const = 0;
};
class CoGDefuzzifier : public FuzzyDefuzzifier {
public:
virtual std::string name() const;
virtual flScalar defuzzify(const LinguisticTerm* term, int number_of_samples,
const AreaCentroidAlgorithm* algorithm) const;
};
class TakagiSugenoDefuzzifier : public FuzzyDefuzzifier {
public:
virtual std::string name() const;
virtual flScalar defuzzify(const LinguisticTerm* term, int number_of_samples,
const AreaCentroidAlgorithm* algorithm) const;
};
}
#endif /* FL_FUZZYDEFUZZIFIER_H */

View File

@ -1,332 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "FuzzyEngine.h"
#include "MamdaniRule.h"
#include "FuzzyExceptions.h"
#include "defs.h"
#include "StrOp.h"
#include "TriangularTerm.h"
#include "ShoulderTerm.h"
#include <iosfwd>
#include "FuzzyException.h"
namespace fl {
FuzzyEngine::FuzzyEngine() : _name(""),
_fuzzy_op(&FuzzyOperator::DefaultFuzzyOperator()),
_hedge_set(new HedgeSet) {
}
FuzzyEngine::FuzzyEngine(const std::string& name) : _name(name),
_fuzzy_op(&FuzzyOperator::DefaultFuzzyOperator()),
_hedge_set(new HedgeSet) {
}
FuzzyEngine::FuzzyEngine(const std::string& name, FuzzyOperator& fuzzy_operator) : _name(name),
_fuzzy_op(&fuzzy_operator),
_hedge_set(new HedgeSet) {
}
FuzzyEngine::~FuzzyEngine() {
reset();
delete _hedge_set;
}
void FuzzyEngine::setName(const std::string& name) {
this->_name = name;
}
std::string FuzzyEngine::name() const {
return this->_name;
}
void FuzzyEngine::process(bool clear) {
if (clear) {
for (int i = 0; i < numberOfOutputLVars(); ++i) {
outputLVar(i)->output().clear();
}
}
for (int i = 0; i < numberOfRuleBlocks(); ++i) {
ruleBlock(i)->fireRules();
}
}
void FuzzyEngine::process(int ruleblock, bool clear) {
if (clear) {
for (int i = 0; i < numberOfOutputLVars(); ++i) {
outputLVar(i)->output().clear();
}
}
ruleBlock(ruleblock)->fireRules();
}
void FuzzyEngine::reset() {
for (int i = numberOfRuleBlocks() - 1; i >= 0; --i) {
delete removeRuleBlock(i);
}
for (int i = numberOfInputLVars() - 1; i >= 0; --i) {
delete removeInputLVar(i);
}
for (int i = numberOfOutputLVars() - 1; i >= 0; --i) {
delete removeOutputLVar(i);
}
for (int i = hedgeSet().numberOfHedges() - 1; i >= 0; --i) {
delete hedgeSet().remove(i);
}
}
void FuzzyEngine::addInputLVar(InputLVar* lvar) {
_input_lvars.push_back(lvar);
}
InputLVar* FuzzyEngine::inputLVar(int index) const {
return _input_lvars[index];
}
InputLVar* FuzzyEngine::inputLVar(const std::string& name) const {
for (int i = 0; i < numberOfInputLVars(); ++i) {
if (inputLVar(i)->name() == name) {
return inputLVar(i);
}
}
return NULL;
}
InputLVar* FuzzyEngine::removeInputLVar(int index) {
InputLVar* result = inputLVar(index);
_input_lvars.erase(_input_lvars.begin() + index);
return result;
}
InputLVar* FuzzyEngine::removeInputLVar(const std::string& name) {
int index = indexOfInputLVar(name);
return index == -1 ? NULL : removeInputLVar(index);
}
int FuzzyEngine::indexOfInputLVar(const std::string& name) const {
for (int i = 0; i < numberOfInputLVars(); ++i) {
if (inputLVar(i)->name() == name) {
return i;
}
}
return -1;
}
int FuzzyEngine::numberOfInputLVars() const {
return _input_lvars.size();
}
void FuzzyEngine::addOutputLVar(OutputLVar* lvar) {
_output_lvars.push_back(lvar);
}
OutputLVar* FuzzyEngine::outputLVar(int index) const {
return _output_lvars[index];
}
OutputLVar* FuzzyEngine::outputLVar(const std::string& name) const {
for (int i = 0; i < numberOfOutputLVars(); ++i) {
if (outputLVar(i)->name() == name) {
return outputLVar(i);
}
}
return NULL;
}
OutputLVar* FuzzyEngine::removeOutputLVar(int index) {
OutputLVar* result = outputLVar(index);
_output_lvars.erase(_output_lvars.begin() + index);
return result;
}
OutputLVar* FuzzyEngine::removeOutputLVar(const std::string& name) {
int index = indexOfOutputLVar(name);
return index == -1 ? NULL : removeOutputLVar(index);
}
int FuzzyEngine::indexOfOutputLVar(const std::string& name) const {
for (int i = 0; i < numberOfOutputLVars(); ++i) {
if (outputLVar(i)->name() == name) {
return i;
}
}
return -1;
}
int FuzzyEngine::numberOfOutputLVars() const {
return _output_lvars.size();
}
HedgeSet& FuzzyEngine::hedgeSet() const {
return *this->_hedge_set;
}
void FuzzyEngine::setFuzzyOperator(FuzzyOperator& fuzzy_operator) {
this->_fuzzy_op = &fuzzy_operator;
}
FL_INLINE FuzzyOperator& FuzzyEngine::fuzzyOperator() const {
return *this->_fuzzy_op;
}
//RULES
void FuzzyEngine::addRuleBlock(RuleBlock* ruleblock) {
this->_rule_blocks.push_back(ruleblock);
}
RuleBlock* FuzzyEngine::removeRuleBlock(int index) {
RuleBlock* result = ruleBlock(index);
this->_rule_blocks.erase(this->_rule_blocks.begin() + index);
return result;
}
RuleBlock* FuzzyEngine::ruleBlock(int index) const {
return this->_rule_blocks[index];
}
RuleBlock* FuzzyEngine::ruleBlock(const std::string& name) const {
for (int i = 0; i < numberOfRuleBlocks(); ++i) {
if (ruleBlock(i)->name() == name) {
return ruleBlock(i);
}
}
return NULL;
}
int FuzzyEngine::numberOfRuleBlocks() const {
return this->_rule_blocks.size();
}
FL_INLINE void FuzzyEngine::setInput(const std::string& input_lvar, flScalar value) {
InputLVar* input = inputLVar(input_lvar);
if (!input) {
throw InvalidArgumentException(FL_AT, "Input variable <" + input_lvar + "> not registered in fuzzy engine");
}
input->setInput(value);
}
FL_INLINE flScalar FuzzyEngine::output(const std::string& output_lvar) const {
OutputLVar* output = outputLVar(output_lvar);
if (!output) {
throw InvalidArgumentException(FL_AT, "Output variable <" + output_lvar + "> not registered in fuzzy engine");
}
return output->output().defuzzify();
}
std::string FuzzyEngine::fuzzyOutput(const std::string& output_lvar) const {
flScalar defuzzified = output(output_lvar);
OutputLVar* output = outputLVar(output_lvar);
if (!output) {
throw InvalidArgumentException(FL_AT, "Output variable <" + output_lvar + "> not registered in fuzzy engine");
}
return output->fuzzify(defuzzified);
}
// void FuzzyEngine::fromString(const std::string& fcl) {
//
// enum eState {
// WAITING = 0, VAR_INPUT, FUZZIFY, DEFUZZIFY, RULE_BLOCK,
// };
// eState state = WAITING;
// std::string line;
// std::string token;
// std::istringstream is(fcl);
// std::string current_name;
// while (!is.eof()) {
// std::getline(is, line);
// StrOp::FindReplace(line, "(", " ( ");
// StrOp::FindReplace(line, ")", " ) ");
// while (StrOp::FindReplace(line, " ", " ") > 0) {
// //do nothing;
// }
// std::vector<std::string> tokens = StrOp::Tokenize(line, " ");
// if (tokens.size() == 0) continue;
// InputLVar* input = NULL;
// OutputLVar* output = NULL;
// switch (state) {
// case WAITING:
// current_name = tokens.size() > 0 ? tokens[1] : "";
// if (tokens[0] == "FUNCTION_BLOCK") setName(current_name);
// else if (tokens[0] == "VAR_INPUT") state = VAR_INPUT;
// else if (tokens[0] == "FUZZIFY") state = FUZZIFY;
// else if (tokens[0] == "DEFUZZIFY") state = DEFUZZIFY;
// else if (tokens[0] == "RULEBLOCK") state = RULE_BLOCK;
// break;
// case VAR_INPUT:
// if (tokens[0] == "END_VAR") state = WAITING;
// else addInputLVar(new InputLVar(tokens[0]));
// break;
// case FUZZIFY:
// if (tokens[0] == "TERM") {
// input = inputLVar(current_name);
// ParsingException::Assert(FL_AT, input, "Input <" << current_name << "> not registered");
//
// } else if (tokens[0] == "END_FUZZIFY") state = WAITING;
// break;
// case DEFUZZIFY:
// case RULE_BLOCK:
// }
// }
// }
std::string FuzzyEngine::toString() const {
std::stringstream ss;
ss << "FUNCTION_BLOCK " << name() << "\n\n";
ss << "VAR_INPUT\n";
for (int i = 0; i < numberOfInputLVars(); ++i) {
ss << inputLVar(i)->name() << ": REAL;\n";
}
ss << "END_VAR\n\n";
for (int i = 0; i < numberOfInputLVars(); ++i) {
ss << "FUZZIFY " << inputLVar(i)->name() << "\n";
for (int j = 0; j < inputLVar(i)->numberOfTerms(); ++j) {
ss << inputLVar(i)->term(j)->toString() << ";\n";
}
ss << "END_FUZZIFY\n\n";
}
ss << "VAR_OUTPUT\n";
for (int i = 0; i < numberOfOutputLVars(); ++i) {
ss << outputLVar(i)->name() << ": REAL\n";
}
ss << "END_VAR\n\n";
for (int i = 0; i < numberOfOutputLVars(); ++i) {
ss << "DEFUZZIFY " << outputLVar(i)->name() << "\n";
for (int j = 0; j < outputLVar(i)->numberOfTerms(); ++j) {
ss << outputLVar(i)->term(j)->toString() << ";\n";
}
ss << "END_DEFUZZIFY\n\n";
}
for (int i = 0; i < numberOfRuleBlocks(); ++i) {
ss << "Block " << i << " " << ruleBlock(i)->toString() << "\n\n";
}
ss << "END_FUNCTION_BLOCK";
return ss.str();
}
}

View File

@ -1,96 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* File: FuzzyEngine.h
* Author: jcrada
*
* Created on November 1, 2009, 4:51 PM
*/
#ifndef FL_FUZZYENGINE_H
#define FL_FUZZYENGINE_H
#include "FuzzyOperator.h"
#include "InputLVar.h"
#include "OutputLVar.h"
#include "Hedge.h"
#include "RuleBlock.h"
#include "HedgeSet.h"
namespace fl {
class FuzzyEngine {
private:
std::string _name;
FuzzyOperator* _fuzzy_op;
HedgeSet* _hedge_set;
std::vector<InputLVar*> _input_lvars;
std::vector<OutputLVar*> _output_lvars;
std::vector<RuleBlock*> _rule_blocks;
public:
FuzzyEngine();
FuzzyEngine(const std::string& name);
FuzzyEngine(const std::string& name, FuzzyOperator& fuzzy_operator);
virtual ~FuzzyEngine();
virtual void setName(const std::string& name);
virtual std::string name() const;
virtual void process(bool clear = true);
virtual void process(int ruleblock, bool clear = true);
virtual void reset();
virtual void addInputLVar(InputLVar* lvar);
virtual InputLVar* inputLVar(int index) const ;
virtual InputLVar* inputLVar(const std::string& name) const;
virtual InputLVar* removeInputLVar(int index) ;
virtual InputLVar* removeInputLVar(const std::string& name);
virtual int indexOfInputLVar(const std::string& name) const;
virtual int numberOfInputLVars() const;
virtual void addOutputLVar(OutputLVar* lvar);
virtual OutputLVar* outputLVar(int index) const ;
virtual OutputLVar* outputLVar(const std::string& name) const;
virtual OutputLVar* removeOutputLVar(int index) ;
virtual OutputLVar* removeOutputLVar(const std::string& name);
virtual int indexOfOutputLVar(const std::string& name) const;
virtual int numberOfOutputLVars() const;
virtual HedgeSet& hedgeSet() const;
virtual void addRuleBlock(RuleBlock* ruleblock);
virtual RuleBlock* removeRuleBlock(int index);
virtual RuleBlock* ruleBlock(int index) const;
virtual RuleBlock* ruleBlock(const std::string& name) const;
virtual int numberOfRuleBlocks() const;
virtual void setFuzzyOperator(FuzzyOperator& fuzzy_operator);
virtual FuzzyOperator& fuzzyOperator() const;
virtual void setInput(const std::string& input_lvar, flScalar value);
virtual flScalar output(const std::string& output_lvar) const;
virtual std::string fuzzyOutput(const std::string& output_lvar) const;
virtual std::string toString() const;
};
}
#endif /* FL_FUZZYENGINE_H */

View File

@ -1,100 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <sstream>
#include "FuzzyException.h"
#include "defs.h"
namespace fl {
FuzzyException::FuzzyException(const std::string& file, int line,
const std::string& function) :
exception(), _message(""), _previous_exception(NULL) {
setLocation(file, line, function);
}
FuzzyException::FuzzyException(const std::string& file, int line,
const std::string& function, const std::string& message) :
exception(), _message(message), _previous_exception(NULL) {
setLocation(file, line, function);
}
FuzzyException::FuzzyException(const std::string& file, int line,
const std::string& function, const std::string& message,
const FuzzyException& previous_exception) :
exception(), _message(message), _previous_exception(&previous_exception) {
setLocation(file, line, function);
}
FuzzyException::~FuzzyException() throw () {
}
std::string FuzzyException::name() const throw () {
return "General Error";
}
std::string FuzzyException::message() const throw () {
return this->_message;
}
void FuzzyException::setMessage(const std::string& message) throw () {
this->_message = message;
}
std::string FuzzyException::location() const throw () {
return this->_location;
}
void FuzzyException::setLocation(const std::string& file, int line,
const std::string& function) throw () {
std::stringstream ss;
ss << file + "[" << line << "]::" + function + "()";
this->_location = ss.str();
}
const FuzzyException* FuzzyException::previousException() const throw () {
return this->_previous_exception;
}
void FuzzyException::setPreviousException(const FuzzyException& exception) throw () {
this->_previous_exception = &exception;
}
const char* FuzzyException::what() const throw () {
return toString().c_str();
}
std::string FuzzyException::toString() const throw () {
return name() + ": " + message() + "\n\tIN " + location();
}
std::string FuzzyException::stackTrace() const throw () {
std::string result;
const FuzzyException* stack = this;
do {
result += stack->toString() + "\n";
stack = stack->previousException();
} while (stack);
return result;
}
void FuzzyException::Assert(const std::string& file, int line,
const std::string& function, bool assert, const std::string message) {
if (!assert) {
throw FuzzyException(file, line, function, message);
}
}
}

View File

@ -1,66 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* File: FuzzyException.h
* Author: jcrada
*
* Created on November 11, 2009, 7:15 AM
*/
#ifndef FL_FUZZYEXCEPTION_H
#define FL_FUZZYEXCEPTION_H
#include <string>
#include <exception>
namespace fl {
class FuzzyException : public std::exception {
private:
std::string _message;
std::string _location;
const FuzzyException* _previous_exception;
public:
FuzzyException(const std::string& file, int line, const std::string& function);
FuzzyException(const std::string& file, int line, const std::string& function,
const std::string& message);
FuzzyException(const std::string& file, int line, const std::string& function,
const std::string& message, const FuzzyException& previous_exception);
virtual ~FuzzyException() throw ();
virtual std::string name() const throw ();
virtual void setMessage(const std::string& message) throw ();
virtual std::string message() const throw ();
virtual void setLocation(const std::string& file, int line,
const std::string& function) throw ();
virtual std::string location() const throw ();
virtual void setPreviousException(const FuzzyException& exception) throw ();
virtual const FuzzyException* previousException() const throw ();
virtual const char* what() const throw ();
virtual std::string toString() const throw ();
virtual std::string stackTrace() const throw ();
static void Assert(const std::string& file, int line,
const std::string& function, bool assert, const std::string message = "");
};
}
#endif /* FL_FUZZYEXCEPTION_H */

View File

@ -1,124 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "FuzzyExceptions.h"
namespace fl {
OutOfRangeException::OutOfRangeException(const std::string& file, int line,
const std::string& function, const std::string& message)
: FuzzyException(file, line, function, message) {
}
OutOfRangeException::OutOfRangeException(const std::string& file, int line,
const std::string& function, const std::string& message,
const FuzzyException& previous_exception)
: FuzzyException(file, line, function, message, previous_exception) {
}
OutOfRangeException::~OutOfRangeException() throw () {
}
std::string OutOfRangeException::name() const throw () {
return "Out Of Range";
}
void OutOfRangeException::CheckArray(const std::string& file, int line, const std::string& function,
int index, int max) {
if (index < 0 || index >= max) {
std::stringstream ss;
ss << "index=" << index << " and maximum value is " << max - 1;
throw OutOfRangeException(file, line, function, ss.str());
}
}
}
namespace fl {
InvalidArgumentException::InvalidArgumentException(const std::string& file,
int line, const std::string& function, const std::string& message)
: FuzzyException(file, line, function, message) {
}
InvalidArgumentException::InvalidArgumentException(const std::string& file,
int line, const std::string& function, const std::string& message,
const FuzzyException& previous_exception)
: FuzzyException(file, line, function, message, previous_exception) {
}
InvalidArgumentException::~InvalidArgumentException() throw () {
}
std::string InvalidArgumentException::name() const throw () {
return "Invalid Argument";
}
}
namespace fl {
NullPointerException::NullPointerException(const std::string& file, int line,
const std::string& function, const std::string& message)
: FuzzyException(file, line, function, message) {
}
NullPointerException::NullPointerException(const std::string& file, int line,
const std::string& function, const std::string& message,
const FuzzyException& previous_exception)
: FuzzyException(file, line, function, message, previous_exception) {
}
NullPointerException::~NullPointerException() throw () {
}
std::string NullPointerException::name() const throw () {
return "Null Pointer";
}
}
namespace fl {
ParsingException::ParsingException(const std::string& file, int line,
const std::string& function, const std::string& message)
: FuzzyException(file, line, function, message) {
}
ParsingException::ParsingException(const std::string& file, int line,
const std::string& function, const std::string& message,
const FuzzyException& previous_exception)
: FuzzyException(file, line, function, message, previous_exception) {
}
ParsingException::~ParsingException() throw () {
}
std::string ParsingException::name() const throw () {
return "Rule Error";
}
}

View File

@ -1,79 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* File: FuzzyExceptions.h
* Author: jcrada
*
* Created on November 13, 2009, 3:34 PM
*/
#ifndef FL_FUZZYEXCEPTIONS_H
#define FL_FUZZYEXCEPTIONS_H
#include "FuzzyException.h"
#include <sstream>
namespace fl {
class OutOfRangeException : public FuzzyException {
public:
OutOfRangeException(const std::string& file, int line, const std::string& function,
const std::string& message);
OutOfRangeException(const std::string& file, int line, const std::string& function,
const std::string& message, const FuzzyException& previous_exception);
virtual ~OutOfRangeException() throw ();
virtual std::string name() const throw ();
static void CheckArray(const std::string& file, int line, const std::string& function,
int index, int max);
};
class InvalidArgumentException : public FuzzyException {
public:
InvalidArgumentException(const std::string& file, int line, const std::string& function,
const std::string& message);
InvalidArgumentException(const std::string& file, int line, const std::string& function,
const std::string& message, const FuzzyException& previous_exception);
virtual ~InvalidArgumentException() throw ();
virtual std::string name() const throw ();
};
class NullPointerException : public FuzzyException {
public:
NullPointerException(const std::string& file, int line, const std::string& function,
const std::string& message);
NullPointerException(const std::string& file, int line, const std::string& function,
const std::string& message, const FuzzyException& previous_exception);
virtual ~NullPointerException() throw ();
virtual std::string name() const throw ();
};
class ParsingException : public FuzzyException {
public:
ParsingException(const std::string& file, int line, const std::string& function,
const std::string& message);
ParsingException(const std::string& file, int line, const std::string& function,
const std::string& message, const FuzzyException& previous_exception);
virtual ~ParsingException() throw ();
virtual std::string name() const throw ();
};
}
#endif /* FL_FUZZYEXCEPTIONS_H */

View File

@ -1,160 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<CodeBlocks_project_file>
<FileVersion major="1" minor="6" />
<Project>
<Option title="FuzzyLite" />
<Option pch_mode="2" />
<Option compiler="gcc" />
<Build>
<Target title="Debug-win32-SDL2">
<Option platforms="Windows;" />
<Option output="bin/Debug/FuzzyLite" prefix_auto="1" extension_auto="1" />
<Option working_dir="" />
<Option object_output="obj/Debug/" />
<Option type="2" />
<Option compiler="gcc" />
<Option createDefFile="1" />
<Compiler>
<Add option="-g" />
</Compiler>
</Target>
<Target title="Release-win32-SDL2">
<Option platforms="Windows;" />
<Option output="bin/Release/FuzzyLite" prefix_auto="1" extension_auto="1" />
<Option working_dir="" />
<Option object_output="obj/Release/" />
<Option type="2" />
<Option compiler="gcc" />
<Option createDefFile="1" />
<Compiler>
<Add option="-fomit-frame-pointer" />
<Add option="-O2" />
</Compiler>
<Linker>
<Add option="-s" />
</Linker>
</Target>
<Target title="Debug-win32-SDL1">
<Option platforms="Windows;" />
<Option output="bin/Debug/FuzzyLite" prefix_auto="1" extension_auto="1" />
<Option working_dir="" />
<Option object_output="obj/Debug/" />
<Option type="2" />
<Option compiler="gcc" />
<Option createDefFile="1" />
<Compiler>
<Add option="-g" />
</Compiler>
</Target>
<Target title="Release-win32-SDL1">
<Option platforms="Windows;" />
<Option output="bin/Release/FuzzyLite" prefix_auto="1" extension_auto="1" />
<Option working_dir="" />
<Option object_output="obj/Release/" />
<Option type="2" />
<Option compiler="gcc" />
<Option createDefFile="1" />
<Compiler>
<Add option="-fomit-frame-pointer" />
<Add option="-O2" />
</Compiler>
<Linker>
<Add option="-s" />
</Linker>
</Target>
</Build>
<Compiler>
<Add option="-Wextra" />
<Add option="-Wall" />
<Add option="-fexceptions" />
<Add option="-Wpointer-arith" />
<Add option="-Wno-switch" />
<Add option="-Wno-sign-compare" />
<Add option="-Wno-unused-parameter" />
<Add option="-Wno-overloaded-virtual" />
</Compiler>
<Unit filename="AreaCentroidAlgorithm.cpp" />
<Unit filename="AreaCentroidAlgorithm.h" />
<Unit filename="CompoundTerm.cpp" />
<Unit filename="CompoundTerm.h" />
<Unit filename="DescriptiveAntecedent.cpp" />
<Unit filename="DescriptiveAntecedent.h" />
<Unit filename="DiscreteTerm.cpp" />
<Unit filename="DiscreteTerm.h" />
<Unit filename="FunctionTerm.cpp" />
<Unit filename="FunctionTerm.h" />
<Unit filename="FuzzyAnd.cpp" />
<Unit filename="FuzzyAnd.h" />
<Unit filename="FuzzyAntecedent.cpp" />
<Unit filename="FuzzyAntecedent.h" />
<Unit filename="FuzzyConsequent.cpp" />
<Unit filename="FuzzyConsequent.h" />
<Unit filename="FuzzyDefuzzifier.cpp" />
<Unit filename="FuzzyDefuzzifier.h" />
<Unit filename="FuzzyEngine.cpp" />
<Unit filename="FuzzyEngine.h" />
<Unit filename="FuzzyException.cpp" />
<Unit filename="FuzzyException.h" />
<Unit filename="FuzzyExceptions.cpp" />
<Unit filename="FuzzyExceptions.h" />
<Unit filename="FuzzyLite.h" />
<Unit filename="FuzzyModulation.cpp" />
<Unit filename="FuzzyModulation.h" />
<Unit filename="FuzzyOperation.cpp" />
<Unit filename="FuzzyOperation.h" />
<Unit filename="FuzzyOperator.cpp" />
<Unit filename="FuzzyOperator.h" />
<Unit filename="FuzzyOr.cpp" />
<Unit filename="FuzzyOr.h" />
<Unit filename="FuzzyRule.cpp" />
<Unit filename="FuzzyRule.h" />
<Unit filename="Hedge.cpp" />
<Unit filename="Hedge.h" />
<Unit filename="HedgeSet.cpp" />
<Unit filename="HedgeSet.h" />
<Unit filename="InfixToPostfix.cpp" />
<Unit filename="InfixToPostfix.h" />
<Unit filename="InputLVar.cpp" />
<Unit filename="InputLVar.h" />
<Unit filename="LinguisticTerm.cpp" />
<Unit filename="LinguisticTerm.h" />
<Unit filename="LinguisticVariable.cpp" />
<Unit filename="LinguisticVariable.h" />
<Unit filename="MamdaniConsequent.cpp" />
<Unit filename="MamdaniConsequent.h" />
<Unit filename="MamdaniRule.cpp" />
<Unit filename="MamdaniRule.h" />
<Unit filename="OutputLVar.cpp" />
<Unit filename="OutputLVar.h" />
<Unit filename="RectangularTerm.cpp" />
<Unit filename="RectangularTerm.h" />
<Unit filename="RuleBlock.cpp" />
<Unit filename="RuleBlock.h" />
<Unit filename="ShoulderTerm.cpp" />
<Unit filename="ShoulderTerm.h" />
<Unit filename="SingletonTerm.cpp" />
<Unit filename="SingletonTerm.h" />
<Unit filename="StrOp.cpp" />
<Unit filename="StrOp.h" />
<Unit filename="TakagiSugenoConsequent.cpp" />
<Unit filename="TakagiSugenoConsequent.h" />
<Unit filename="TakagiSugenoRule.cpp" />
<Unit filename="TakagiSugenoRule.h" />
<Unit filename="TakagiSugenoTerm.cpp" />
<Unit filename="TakagiSugenoTerm.h" />
<Unit filename="TrapezoidalTerm.cpp" />
<Unit filename="TrapezoidalTerm.h" />
<Unit filename="TriangularTerm.cpp" />
<Unit filename="TriangularTerm.h" />
<Unit filename="defs.h" />
<Unit filename="flScalar.h" />
<Unit filename="main.cpp" />
<Unit filename="test.h" />
<Extensions>
<code_completion />
<envvars />
<debugger />
<lib_finder disable_auto="1" />
</Extensions>
</Project>
</CodeBlocks_project_file>

View File

@ -1,65 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* File: FuzzyLite.h
* Author: jcrada
*
* Created on December 5, 2009, 9:54 PM
*/
#ifndef FL_FUZZYLITE_H
#define FL_FUZZYLITE_H
#include "AreaCentroidAlgorithm.h"
#include "CompoundTerm.h"
#include "DescriptiveAntecedent.h"
#include "DiscreteTerm.h"
#include "FunctionTerm.h"
#include "FuzzyAnd.h"
#include "FuzzyAntecedent.h"
#include "FuzzyConsequent.h"
#include "FuzzyDefuzzifier.h"
#include "FuzzyEngine.h"
#include "FuzzyException.h"
#include "FuzzyExceptions.h"
#include "FuzzyModulation.h"
#include "FuzzyOperation.h"
#include "FuzzyOperator.h"
#include "FuzzyOr.h"
#include "FuzzyRule.h"
#include "Hedge.h"
#include "HedgeSet.h"
#include "InfixToPostfix.h"
#include "InputLVar.h"
#include "LinguisticTerm.h"
#include "LinguisticVariable.h"
#include "MamdaniConsequent.h"
#include "MamdaniRule.h"
#include "OutputLVar.h"
#include "RectangularTerm.h"
#include "RuleBlock.h"
#include "ShoulderTerm.h"
#include "SingletonTerm.h"
#include "StrOp.h"
#include "TakagiSugenoConsequent.h"
#include "TakagiSugenoRule.h"
#include "TakagiSugenoTerm.h"
#include "TrapezoidalTerm.h"
#include "TriangularTerm.h"
#include "defs.h"
#include "flScalar.h"
#endif /* FL_FUZZYLITE_H */

View File

@ -1,179 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="RD|Win32">
<Configuration>RD</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="RD|x64">
<Configuration>RD</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<ItemGroup>
<ClCompile Include="AreaCentroidAlgorithm.cpp" />
<ClCompile Include="CompoundTerm.cpp" />
<ClCompile Include="DescriptiveAntecedent.cpp" />
<ClCompile Include="DiscreteTerm.cpp" />
<ClCompile Include="FunctionTerm.cpp" />
<ClCompile Include="FuzzyAnd.cpp" />
<ClCompile Include="FuzzyAntecedent.cpp" />
<ClCompile Include="FuzzyConsequent.cpp" />
<ClCompile Include="FuzzyDefuzzifier.cpp" />
<ClCompile Include="FuzzyEngine.cpp" />
<ClCompile Include="FuzzyException.cpp" />
<ClCompile Include="FuzzyExceptions.cpp" />
<ClCompile Include="FuzzyModulation.cpp" />
<ClCompile Include="FuzzyOperation.cpp" />
<ClCompile Include="FuzzyOperator.cpp" />
<ClCompile Include="FuzzyOr.cpp" />
<ClCompile Include="FuzzyRule.cpp" />
<ClCompile Include="Hedge.cpp" />
<ClCompile Include="HedgeSet.cpp" />
<ClCompile Include="InfixToPostfix.cpp" />
<ClCompile Include="InputLVar.cpp" />
<ClCompile Include="LinguisticTerm.cpp" />
<ClCompile Include="LinguisticVariable.cpp" />
<ClCompile Include="main.cpp" />
<ClCompile Include="MamdaniConsequent.cpp" />
<ClCompile Include="MamdaniRule.cpp" />
<ClCompile Include="OutputLVar.cpp" />
<ClCompile Include="RectangularTerm.cpp" />
<ClCompile Include="RuleBlock.cpp" />
<ClCompile Include="ShoulderTerm.cpp" />
<ClCompile Include="SingletonTerm.cpp" />
<ClCompile Include="StrOp.cpp" />
<ClCompile Include="TakagiSugenoConsequent.cpp" />
<ClCompile Include="TakagiSugenoRule.cpp" />
<ClCompile Include="TakagiSugenoTerm.cpp" />
<ClCompile Include="test.cpp" />
<ClCompile Include="TrapezoidalTerm.cpp" />
<ClCompile Include="TriangularTerm.cpp" />
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{D15B34EC-A32C-4968-9B0B-66998B579364}</ProjectGuid>
<RootNamespace>FuzzyLite</RootNamespace>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v120_xp</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v120_xp</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='RD|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v120_xp</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='RD|x64'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v120_xp</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="..\..\VCMI_global_debug.props" />
<Import Project="..\..\VCMI_global.props" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="..\..\VCMI_global_debug.props" />
<Import Project="..\..\VCMI_global.props" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='RD|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="..\..\VCMI_global_release.props" />
<Import Project="..\..\VCMI_global.props" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='RD|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="..\..\VCMI_global_release.props" />
<Import Project="..\..\VCMI_global.props" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<OutDir>$(VCMI_Out)\AI\</OutDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<OutDir>$(VCMI_Out)\AI\</OutDir>
<IncludePath>$(IncludePath)</IncludePath>
<LibraryPath>$(LibraryPath)</LibraryPath>
<IntDir>$(Configuration)\</IntDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='RD|Win32'">
<OutDir>..</OutDir>
<IncludePath>$(IncludePath)</IncludePath>
<LibraryPath>$(LibraryPath)</LibraryPath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='RD|x64'">
<OutDir>$(VCMI_Out)\AI\</OutDir>
<IncludePath>$(IncludePath)</IncludePath>
<LibraryPath>$(LibraryPath)</LibraryPath>
<IntDir>$(Configuration)\</IntDir>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile />
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>$(OutDir)..;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<OutputFile>$(OutDir)FuzzyLite.dll</OutputFile>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile />
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>$(OutDir)..;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<OutputFile>$(OutDir)FuzzyLite.dll</OutputFile>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='RD|Win32'">
<ClCompile />
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>$(OutDir)..;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<OutputFile>$(OutDir)FuzzyLite.dll</OutputFile>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='RD|x64'">
<ClCompile />
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>$(OutDir)..;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<OutputFile>$(OutDir)FuzzyLite.dll</OutputFile>
</Link>
</ItemDefinitionGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -1,35 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "FuzzyModulation.h"
namespace fl {
std::string FuzzyModClip::name() const {
return "Clip";
}
flScalar FuzzyModClip::execute(flScalar mu1, flScalar mu2) const {
return FuzzyOperation::Min(mu1, mu2);
}
std::string FuzzyModScale::name() const {
return "Scale";
}
flScalar FuzzyModScale::execute(flScalar mu1, flScalar mu2) const {
return FuzzyOperation::AlgebraicProduct(mu1, mu2);
}
}

View File

@ -1,44 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* File: FuzzyModulation.h
* Author: jcrada
*
* Created on April 6, 2010, 6:53 PM
*/
#ifndef FL_FUZZYMODULATION_H
#define FL_FUZZYMODULATION_H
#include "FuzzyOperation.h"
namespace fl {
class FuzzyModClip : public FuzzyOperation {
public:
virtual std::string name() const;
virtual flScalar execute(flScalar mu1, flScalar mu2) const;
};
class FuzzyModScale : public FuzzyOperation {
public:
virtual std::string name() const;
virtual flScalar execute(flScalar mu1, flScalar mu2) const;
};
}
#endif /* FL_FUZZYMODULATION_H */

View File

@ -1,78 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "FuzzyOperation.h"
#include <math.h>
namespace fl {
FuzzyOperation::~FuzzyOperation() {
}
//TNORMS
flScalar FuzzyOperation::Min(flScalar mu1, flScalar mu2) {
return mu1 < mu2 ? mu1 : mu2;
}
flScalar FuzzyOperation::AlgebraicProduct(flScalar mu1, flScalar mu2) {
return mu1 * mu2;
}
flScalar FuzzyOperation::BoundedDiff(flScalar mu1, flScalar mu2) {
return Max(0, mu1 + mu2 -1);
}
//SNORMS
flScalar FuzzyOperation::Max(flScalar mu1, flScalar mu2) {
return mu1 > mu2 ? mu1 : mu2;
}
flScalar FuzzyOperation::AlgebraicSum(flScalar mu1, flScalar mu2) {
return mu1 + mu2 - (mu1 * mu2);
}
flScalar FuzzyOperation::BoundedSum(flScalar mu1, flScalar mu2) {
return Min(1, mu1 + mu2);
}
//Other operators
flScalar FuzzyOperation::Absolute(flScalar value) {
return value < flScalar(0.0) ? value * flScalar(-1.0) : value;
}
bool FuzzyOperation::IsEq(flScalar x1, flScalar x2, flScalar epsilon) {
//http://stackoverflow.com/questions/17333/most-effective-way-for-float-and-double-comparison
// return fabs(x1 - x2) < std::numeric_limits<flScalar>::epsilon() ;
return fabs(x1 - x2) < epsilon;
}
bool FuzzyOperation::IsLEq(flScalar x1, flScalar x2, flScalar epsilon) {
return IsEq(x1, x2, epsilon) ? true : x1 < x2;
}
bool FuzzyOperation::IsGEq(flScalar x1, flScalar x2, flScalar epsilon) {
return IsEq(x1, x2,epsilon) ? true : x1 > x2;
}
flScalar FuzzyOperation::Scale(flScalar src_min, flScalar src_max, flScalar value,
flScalar target_min, flScalar target_max) {
//Courtesy of Rubén Parma :)
return (target_max - target_min) / (src_max - src_min) * (value - src_min)
+ target_min;
}
}

View File

@ -1,58 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* File: FuzzyOperation.h
* Author: jcrada
*
* Created on April 6, 2010, 6:42 PM
*/
#ifndef FL_FUZZYOPERATION_H
#define FL_FUZZYOPERATION_H
#include "flScalar.h"
#include <string>
namespace fl {
class FuzzyOperation {
public:
virtual ~FuzzyOperation();
virtual std::string name() const = 0;
virtual flScalar execute(flScalar mu1, flScalar mu2) const = 0;
//TNORMS
static flScalar Min(flScalar mu1, flScalar mu2);
static flScalar AlgebraicProduct(flScalar mu1, flScalar mu2);
static flScalar BoundedDiff(flScalar mu1, flScalar mu2);
//SNORMS
static flScalar Max(flScalar mu1, flScalar mu2);
static flScalar AlgebraicSum(flScalar mu1, flScalar mu2);
static flScalar BoundedSum(flScalar mu1, flScalar mu2);
//Other operators
static flScalar Absolute(flScalar value);
static bool IsEq(flScalar x1, flScalar x2, flScalar epsilon = FL_EPSILON);
static bool IsLEq(flScalar x1, flScalar x2, flScalar epsilon = FL_EPSILON);
static bool IsGEq(flScalar x1, flScalar x2, flScalar epsilon = FL_EPSILON);
static flScalar Scale(flScalar src_min, flScalar src_max, flScalar value,
flScalar target_min, flScalar target_max);
};
}
#endif /* FL_FUZZYOPERATION_H */

View File

@ -1,125 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "FuzzyOperator.h"
#include "StrOp.h"
#include <limits>
#include <math.h>
#include "CompoundTerm.h"
#include "TakagiSugenoTerm.h"
#include "MamdaniRule.h"
namespace fl {
FuzzyOperator::FuzzyOperator(const FuzzyOperation* tnorm,
const FuzzyOperation* snorm,
const FuzzyOperation* cmod,
const FuzzyOperation* aggregation,
const FuzzyDefuzzifier* defuzzifier,
const AreaCentroidAlgorithm* algorithm,
int number_of_samples)
: _tnorm(tnorm), _snorm(snorm), _cmodulation(cmod), _aggregation(aggregation),
_defuzzifier(defuzzifier), _acalgorithm(algorithm),
_number_of_samples(number_of_samples) {
}
FuzzyOperator::~FuzzyOperator() {
}
void FuzzyOperator::setTnorm(const FuzzyOperation* tnorm) {
delete this->_tnorm;
this->_tnorm = tnorm;
}
void FuzzyOperator::setSnorm(const FuzzyOperation* snorm) {
delete this->_snorm;
this->_snorm = snorm;
}
void FuzzyOperator::setModulation(const FuzzyOperation* modulation) {
delete this->_cmodulation;
this->_cmodulation = modulation;
}
void FuzzyOperator::setAggregation(const FuzzyOperation* aggregation) {
delete this->_aggregation;
this->_aggregation = aggregation;
}
void FuzzyOperator::setDefuzzifier(const FuzzyDefuzzifier* defuzzifier) {
delete this->_defuzzifier;
this->_defuzzifier = defuzzifier;
}
void FuzzyOperator::setAreaCentroidAlgorithm(const AreaCentroidAlgorithm* algorithm) {
delete this->_acalgorithm;
this->_acalgorithm = algorithm;
}
void FuzzyOperator::setNumberOfSamples(int samples) {
this->_number_of_samples = samples;
}
const FuzzyOperation& FuzzyOperator::tnorm() const {
return *this->_tnorm;
}
const FuzzyOperation& FuzzyOperator::snorm() const {
return *this->_snorm;
}
const FuzzyOperation& FuzzyOperator::modulation() const {
return *this->_cmodulation;
}
const FuzzyOperation& FuzzyOperator::aggregation() const {
return *this->_aggregation;
}
const FuzzyDefuzzifier& FuzzyOperator::defuzzifier() const {
return *this->_defuzzifier;
}
const AreaCentroidAlgorithm& FuzzyOperator::acAlgorithm() const {
return *this->_acalgorithm;
}
int FuzzyOperator::numberOfSamples() const {
return this->_number_of_samples;
}
flScalar FuzzyOperator::defuzzify(const LinguisticTerm* term) const {
return defuzzifier().defuzzify(term, numberOfSamples(), &acAlgorithm());
}
flScalar FuzzyOperator::area(const LinguisticTerm* term) const {
return acAlgorithm().area(term, numberOfSamples());
}
void FuzzyOperator::centroid(const LinguisticTerm* term, flScalar& x, flScalar& y) const {
acAlgorithm().centroid(term, x, y, numberOfSamples());
}
flScalar FuzzyOperator::areaAndCentroid(const LinguisticTerm* term, flScalar& x, flScalar& y) const {
return acAlgorithm().areaAndCentroid(term, x, y, numberOfSamples());
}
FuzzyOperator& FuzzyOperator::DefaultFuzzyOperator() {
static FuzzyOperator* FUZZY_OP = new fl::FuzzyOperator;
return *FUZZY_OP;
}
}

View File

@ -1,84 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* File: FuzzyOperator.h
* Author: jcrada
*
* Created on November 1, 2009, 3:05 PM
*/
#ifndef FL_FUZZYOPERATOR_H
#define FL_FUZZYOPERATOR_H
#include "defs.h"
#include "flScalar.h"
#include "FuzzyOperation.h"
#include "FuzzyAnd.h"
#include "FuzzyOr.h"
#include "FuzzyModulation.h"
#include "AreaCentroidAlgorithm.h"
#include "FuzzyDefuzzifier.h"
namespace fl {
class LinguisticTerm;
class FuzzyOperator {
private:
const FuzzyOperation* _tnorm;
const FuzzyOperation* _snorm;
const FuzzyOperation* _cmodulation;
const FuzzyOperation* _aggregation;
const FuzzyDefuzzifier* _defuzzifier;
const AreaCentroidAlgorithm* _acalgorithm;
int _number_of_samples;
public:
FuzzyOperator(const FuzzyOperation* tnorm = new FuzzyAndMin,
const FuzzyOperation* snorm = new FuzzyOrMax,
const FuzzyOperation* cmod = new FuzzyModClip,
const FuzzyOperation* aggregation = new FuzzyOrMax,
const FuzzyDefuzzifier* defuzzifier = new CoGDefuzzifier,
const AreaCentroidAlgorithm* algorithm = new TriangulationAlgorithm, //bugfix
int number_of_samples = FL_SAMPLE_SIZE);
virtual ~FuzzyOperator();
virtual void setTnorm(const FuzzyOperation* tnorm);
virtual void setSnorm(const FuzzyOperation* snorm);
virtual void setModulation(const FuzzyOperation* modulation);
virtual void setAggregation(const FuzzyOperation* aggregation);
virtual void setDefuzzifier(const FuzzyDefuzzifier* defuzzifier);
virtual void setAreaCentroidAlgorithm(const AreaCentroidAlgorithm* algorithm);
virtual void setNumberOfSamples(int samples);
virtual const FuzzyOperation& tnorm() const;
virtual const FuzzyOperation& snorm() const;
virtual const FuzzyOperation& modulation() const;
virtual const FuzzyOperation& aggregation() const;
virtual const FuzzyDefuzzifier& defuzzifier() const;
virtual const AreaCentroidAlgorithm& acAlgorithm() const;
virtual int numberOfSamples() const;
virtual flScalar defuzzify(const LinguisticTerm* term) const;
virtual flScalar area(const LinguisticTerm* term) const;
virtual void centroid(const LinguisticTerm* term, flScalar& x, flScalar& y) const;
virtual flScalar areaAndCentroid(const LinguisticTerm* term, flScalar& x, flScalar& y) const;
static FuzzyOperator& DefaultFuzzyOperator();
};
}
#endif /* FL_FUZZYOPERATOR_H */

View File

@ -1,44 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "FuzzyOr.h"
namespace fl {
std::string FuzzyOrMax::name() const{
return "Max";
}
flScalar FuzzyOrMax::execute(flScalar mu1, flScalar mu2) const{
return FuzzyOperation::Max(mu1,mu2);
}
std::string FuzzyOrSum::name() const{
return "Sum";
}
flScalar FuzzyOrSum::execute(flScalar mu1, flScalar mu2) const{
return FuzzyOperation::AlgebraicSum(mu1,mu2);
}
std::string FuzzyOrBSum::name() const{
return "BSum";
}
flScalar FuzzyOrBSum::execute(flScalar mu1, flScalar mu2) const{
return FuzzyOperation::BoundedSum(mu1,mu2);
}
}

View File

@ -1,49 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* File: FuzzyOr.h
* Author: jcrada
*
* Created on April 6, 2010, 5:13 PM
*/
#ifndef FL_FUZZYOR_H
#define FL_FUZZYOR_H
#include "FuzzyOperation.h"
namespace fl {
class FuzzyOrMax : public FuzzyOperation {
public:
virtual std::string name() const;
virtual flScalar execute(flScalar mu1, flScalar mu2) const;
};
class FuzzyOrSum : public FuzzyOperation {
public:
virtual std::string name() const;
virtual flScalar execute(flScalar mu1, flScalar mu2) const;
};
class FuzzyOrBSum : public FuzzyOperation {
public:
virtual std::string name() const;
virtual flScalar execute(flScalar mu1, flScalar mu2) const;
};
}
#endif /* FL_FUZZYOR_H */

View File

@ -1,135 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* FuzzyRule.cpp
*
* Created on: Dec 13, 2009
* Author: jcrada
*/
#include "FuzzyRule.h"
#include <stack>
#include <iosfwd>
#include "StrOp.h"
namespace fl {
const std::string FuzzyRule::FR_IF = "if";
const std::string FuzzyRule::FR_IS = "is";
const std::string FuzzyRule::FR_THEN = "then";
const std::string FuzzyRule::FR_AND = "and";
const std::string FuzzyRule::FR_OR = "or";
const std::string FuzzyRule::FR_WITH = "with";
FuzzyRule::FuzzyRule() : _antecedent(NULL) {
setFuzzyOperator(fuzzyOperator().DefaultFuzzyOperator());
}
FuzzyRule::FuzzyRule(const FuzzyOperator& fuzzy_op)
: _fuzzy_operator(&fuzzy_op), _antecedent(NULL) {
}
FuzzyRule::~FuzzyRule() {
if (_antecedent) {
delete _antecedent;
}
FuzzyConsequent* fconsequent = NULL;
for (int i = numberOfConsequents() - 1; i >= 0; --i) {
fconsequent = consequent(i);
_consequents.pop_back();
delete fconsequent;
}
}
void FuzzyRule::setFuzzyOperator(const FuzzyOperator& fuzzy_op){
this->_fuzzy_operator = &fuzzy_op;
if (antecedent()){
antecedent()->setFuzzyOperator(fuzzy_op);
}
//Todo: check if consequents must have a fuzzyoperator
for (int i =0 ; i < numberOfConsequents() ;++i){
}
}
const FuzzyOperator& FuzzyRule::fuzzyOperator() const{
return *this->_fuzzy_operator;
}
void FuzzyRule::setAntecedent(FuzzyAntecedent* antecedent) {
this->_antecedent = antecedent;
}
FuzzyAntecedent* FuzzyRule::antecedent() const {
return this->_antecedent;
}
FuzzyConsequent* FuzzyRule::consequent(int index) const {
return this->_consequents[index];
}
void FuzzyRule::addConsequent(FuzzyConsequent* consequent) {
this->_consequents.push_back(consequent);
}
int FuzzyRule::numberOfConsequents() const {
return this->_consequents.size();
}
bool FuzzyRule::isValid() const {
return this->_antecedent && this->_consequents.size() > 0;
}
flScalar FuzzyRule::firingStrength() const {
if (antecedent()) {
return antecedent()->degreeOfTruth();
}
throw InvalidArgumentException(FL_AT,"Antecedent was not parsed correctly");
}
void FuzzyRule::fire(flScalar strength) {
if (!FuzzyOperation::IsEq(strength, flScalar(0.0))) {
// FL_LOG("DoT: " << strength << " - Fired: " << toString());
for (int i = 0; i < numberOfConsequents(); ++i) {
consequent(i)->execute(strength);
}
}
}
std::string FuzzyRule::toString() const {
std::stringstream ss;
ss << FR_IF << " " << _antecedent->toString() << " " << FR_THEN;
for (int i = 0; i < numberOfConsequents(); ++i) {
ss << " " + consequent(i)->toString() + (i < numberOfConsequents() - 1 ? FR_AND : "");
}
return ss.str();
}
void FuzzyRule::ExtractFromRule(const std::string& rule, std::string& antecedent, std::string& consequent) {
std::vector<std::string> parse = StrOp::SplitByWord(rule, FR_IF);
if (parse.size() != 1) {
antecedent = "invalid";
consequent = "invalid";
return;
}
parse = StrOp::SplitByWord(parse[0], FR_THEN);
if (parse.size() != 2){
antecedent = "invalid";
consequent = "invalid";
return;
}
antecedent = parse[0];
consequent = parse[1];
}
}// namespace fuzzy_lite

View File

@ -1,79 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* File: FuzzyRule.h
* Author: jcrada
*
* Created on November 5, 2009, 11:11 AM
*/
#ifndef FL_FUZZYRULE_H
#define FL_FUZZYRULE_H
#include "FuzzyOperator.h"
#include "FuzzyAntecedent.h"
#include "FuzzyConsequent.h"
#include <string>
#include <vector>
#include "flScalar.h"
#include "FuzzyExceptions.h"
namespace fl {
class FuzzyRule {
public:
static const std::string FR_IF;
static const std::string FR_IS;
static const std::string FR_THEN;
static const std::string FR_AND;
static const std::string FR_OR;
static const std::string FR_WITH;
private:
const FuzzyOperator* _fuzzy_operator;
FuzzyAntecedent* _antecedent;
std::vector<FuzzyConsequent*> _consequents;
public:
FuzzyRule();
FuzzyRule(const FuzzyOperator& fuzzy_op);
virtual ~FuzzyRule();
virtual void setFuzzyOperator(const FuzzyOperator& fuzzy_op);
virtual const FuzzyOperator& fuzzyOperator() const;
virtual FuzzyAntecedent* antecedent() const;
virtual void setAntecedent(FuzzyAntecedent* antecedent);
virtual FuzzyConsequent* consequent(int index) const;
virtual void addConsequent(FuzzyConsequent* consequent);
virtual int numberOfConsequents() const;
virtual bool isValid() const;
virtual flScalar firingStrength() const;
virtual void fire(flScalar strength);
virtual std::string toString() const;
virtual void parse(const std::string& rule, const FuzzyEngine& engine) = 0;
static void ExtractFromRule(const std::string& rule, std::string& antecedent, std::string& consequent);
};
}
#endif /* _FUZZYRULE_H */

View File

@ -1,59 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* Hedge.cpp
*
* Created on: Dec 13, 2009
* Author: jcrada
*/
#include "Hedge.h"
namespace fl {
Hedge::~Hedge() {
}
std::string HedgeNot::name() const {
return "not";
}
flScalar HedgeNot::hedge(flScalar mu) const {
return 1 - mu;
}
std::string HedgeSomewhat::name() const {
return "somewhat";
}
flScalar HedgeSomewhat::hedge(flScalar mu) const {
return sqrt(mu);
}
std::string HedgeVery::name() const {
return "very";
}
flScalar HedgeVery::hedge(flScalar mu) const {
return mu * mu;
}
std::string HedgeAny::name() const {
return "any";
}
flScalar HedgeAny::hedge(flScalar mu) const {
return 1.0;
}
}

View File

@ -1,66 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* File: Hedge.h
* Author: jcrada
*
* Created on November 1, 2009, 2:55 PM
*/
#ifndef FL_HEDGE_H
#define FL_HEDGE_H
#include <string>
#include <math.h>
#include "flScalar.h"
#include "defs.h"
namespace fl {
class Hedge {
public:
virtual ~Hedge();
virtual std::string name() const = 0;
virtual flScalar hedge(flScalar mu) const = 0;
};
class HedgeNot : public Hedge {
public:
std::string name() const;
flScalar hedge(flScalar mu) const;
};
class HedgeSomewhat : public Hedge {
public:
std::string name() const;
flScalar hedge(flScalar mu) const;
};
class HedgeVery : public Hedge {
public:
std::string name() const;
flScalar hedge(flScalar mu) const;
};
class HedgeAny : public Hedge {
public:
std::string name() const;
flScalar hedge(flScalar mu) const;
};
}
#endif /* FL_HEDGE_H */

View File

@ -1,58 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "HedgeSet.h"
namespace fl {
HedgeSet::HedgeSet() {
}
HedgeSet::~HedgeSet() {
}
void HedgeSet::add(Hedge* hedge) {
this->_hedges.push_back(hedge);
}
Hedge* HedgeSet::remove(int index) {
Hedge* result = this->_hedges[index];
this->_hedges.erase(this->_hedges.begin() + index);
return result;
}
Hedge* HedgeSet::get(const std::string hedge) const {
int index = indexOf(hedge);
return index == -1 ? NULL : this->_hedges[index];
}
Hedge* HedgeSet::get(int index) const {
return this->_hedges[index];
}
int HedgeSet::indexOf(const std::string& hedge) const {
for (int i = 0; i < numberOfHedges(); ++i) {
if (get(i)->name() == hedge) {
return i;
}
}
return -1;
}
int HedgeSet::numberOfHedges() const {
return this->_hedges.size();
}
}

View File

@ -1,46 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* File: HedgeSet.h
* Author: jcrada
*
* Created on March 5, 2010, 1:09 AM
*/
#ifndef FL_HEDGESET_H
#define FL_HEDGESET_H
#include <vector>
#include "Hedge.h"
namespace fl{
class HedgeSet{
private:
std::vector<Hedge*> _hedges;
public:
HedgeSet();
virtual ~HedgeSet();
virtual void add(Hedge* hedge);
virtual Hedge* remove(int index);
virtual Hedge* get(const std::string hedge) const;
virtual Hedge* get(int index) const;
virtual int indexOf(const std::string& hedge) const;
virtual int numberOfHedges() const;
};
}
#endif /* FL_HEDGESET_H */

32
AI/FuzzyLite/INSTALL Normal file
View File

@ -0,0 +1,32 @@
INSTALL
=======
(1) Make sure you uninstall previous versions of fuzzylite from your computer.
(2) The following building script is available in folder `fuzzylite/fuzzylite/`:
```
#In Windows,
> build.bat help
Usage: build.bat [options]
where [options] can be any of the following:
all builds fuzzylite in debug and release mode (default)
debug builds fuzzylite in debug mode
release builds fuzzylite in release mode
clean erases previous builds
help shows this information
#In Unix, from fuzzylite/fuzzylite
$ ./build.sh help
Usage: [bash] ./build.sh [options]
where [options] can be any of the following:
all builds fuzzylite in debug and release mode (default)
debug builds fuzzylite in debug mode
release builds fuzzylite in release mode
clean erases previous builds
help shows this information
```
(3) After executing the script, the binaries will be built and stored in sub-folders `release/bin` and `debug/bin`
For more advanced building options, please check the contents of `fuzzylite/fuzzylite/build.[bat|sh]` and the contents of `fuzzylite/fuzzylite/CMakeLists.txt`.

View File

@ -1,250 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "InfixToPostfix.h"
#include <stack>
#include "defs.h"
#include <sstream>
#include "StrOp.h"
#include <math.h>
#include <stdlib.h>
namespace fl {
InfixToPostfix::InfixToPostfix() {
}
InfixToPostfix::~InfixToPostfix() {
}
void InfixToPostfix::addOperator(const std::string& op, int precedence) {
this->_operators.insert(this->_operators.begin() + precedence, op);
}
std::string InfixToPostfix::removeOperator(int index) {
std::string result = getOperator(index);
this->_operators.erase(this->_operators.begin() + index);
return result;
}
std::string InfixToPostfix::getOperator(int index) const {
return this->_operators.at(index);
}
int InfixToPostfix::operatorPrecedence(const std::string& op) const {
for (int i = 0; i < numberOfOperators(); ++i) {
std::stringstream ss(getOperator(i));
std::string token;
while (ss >> token) {
if (token == op) {
return i;
}
}
}
return -1;
}
int InfixToPostfix::numberOfOperators() const {
return this->_operators.size();
}
bool InfixToPostfix::isOperator(const std::string& op) const {
return operatorPrecedence(op) != -1;
}
bool InfixToPostfix::isUnaryOperator(const std::string op) const {
return op == "!" || op == "sin" || op == "cos" || op == "tan" ||
op == "sinh" || op == "cosh" || op == "tanh";
}
void InfixToPostfix::loadLogicalOperators() {
addOperator("!");
addOperator("or");
addOperator("and");
}
void InfixToPostfix::loadMathOperators() {
addOperator("^");
addOperator("/ * %");
addOperator("sin cos tan sinh cosh tanh");
addOperator("+ -");
}
bool InfixToPostfix::isOperand(const std::string& op) const {
return !isOperator(op) ;
}
bool InfixToPostfix::isNumeric(const std::string& x) const {
return (int) x.find_first_not_of("0123456789.-+") == -1;
}
std::string InfixToPostfix::preprocess(const std::string& infix) const {
std::string result = infix;
StrOp::FindReplace(result,"(", " ( ");
StrOp::FindReplace(result, ")", " ) ");
return result;
}
//TODO: Be Careful: sin(x) / x => x x / sin. The expected is obtained: (sin x) / x => x sin x /
std::string InfixToPostfix::transform(const std::string& infix) const {
std::string p_infix = preprocess(infix);
std::string postfix;
std::stack<std::string> stack;
std::stringstream ss(p_infix);
std::string token;
while (ss >> token) {
if (token == "(") {
stack.push(token);
} else if (token == ")") {
while (!stack.empty()) {
if (stack.top() == "(") {
stack.pop();
break;
}
postfix += stack.top() + " ";
stack.pop();
}
} else if (isOperand(token)) {
postfix += token + " ";
} else if (isOperator(token)) {
while (!stack.empty() &&
operatorPrecedence(token) <= operatorPrecedence(stack.top())) {
postfix += stack.top() + " ";
stack.pop();
}
stack.push(token);
}
}
while (!stack.empty()) {
postfix += stack.top() + " ";
stack.pop();
}
return postfix;
}
flScalar InfixToPostfix::evaluate(const std::string postfix,
const std::map<std::string, flScalar>* variables) const {
std::stack<flScalar> stack;
std::stringstream ss(postfix);
std::string token;
while (ss >> token) {
if (isOperand(token)) {
if (isNumeric(token)) {
stack.push(atof(token.c_str()));
} else {
if (!variables) {
throw FuzzyException(FL_AT, "Impossible to compute operand <" + token + "> because no map was supplied");
}
std::map<std::string, flScalar>::const_iterator it = variables->find(token);
if (it == variables->end()) {
throw FuzzyException(FL_AT, "Operand <" + token + "> not found in map");
}
stack.push(it->second);
}
} else if (isOperator(token)) {
if (isUnaryOperator(token)) {
if (stack.empty()) {
throw FuzzyException(FL_AT, "Error evaluating postfix expression <" + postfix + ">");
}
flScalar a = stack.top();
stack.pop();
stack.push(compute(token, a, 0));
} else {
if (stack.size() < 2) {
throw FuzzyException(FL_AT, "Error evaluating postfix expression <" + postfix + ">");
}
flScalar b = stack.top();
stack.pop();
flScalar a = stack.top();
stack.pop();
stack.push(compute(token, a, b));
}
}
}
if (stack.size() == 1){
return stack.top();
}
throw FuzzyException(FL_AT, "Error evaluating postfix expression <" + postfix + ">");
}
flScalar InfixToPostfix::compute(const std::string& op, flScalar a, flScalar b) const {
if (op == "!") {
return !(bool)a;
}
if (op == "and") {
return (bool)a && (bool)b;
}
if (op == "or") {
return (bool)a || (bool)b;
}
if (op == "+") {
return a + b;
}
if (op == "-") {
return a - b;
}
if (op == "*") {
return a * b;
}
if (op == "/") {
return a / b;
}
if (op == "%") {
return (long) a % (long) b;
}
if (op == "^") {
return pow(a, b);
}
if (op == "sin") {
return sin(a);
}
if (op == "cos") {
return cos(a);
}
if (op == "tan") {
return tan(a);
}
if (op == "sinh") {
return sinh(a);
}
if (op == "cosh") {
return cosh(a);
}
if (op == "tanh") {
return tanh(a);
}
throw FuzzyException(FL_AT, "Operator <" + op + "> not defined");
}
void InfixToPostfix::main(int args, char** argv) {
std::map<std::string, flScalar> m;
m["x"] = 4;
m["y"] = 2;
m["z"] = -4;
std::string x = "(sin x) / x";
FL_LOG(x);
InfixToPostfix ip;
ip.loadMathOperators();
std::string postfix = ip.transform(x);
FL_LOG(postfix);
for (flScalar x = 0.0 ; x < 10.5 ; x+=0.5){
m["x"] = x;
FL_LOG(ip.evaluate(postfix, &m));
}
}
}

View File

@ -1,67 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* File: InfixToPostfix.h
* Author: jcrada
*
* Created on March 6, 2010, 1:14 AM
*/
#ifndef _INFIXTOPOSTFIX_H
#define _INFIXTOPOSTFIX_H
#include <vector>
#include <string>
#include <map>
#include "flScalar.h"
namespace fl {
class InfixToPostfix {
private:
std::vector<std::string> _operators;
protected:
virtual std::string preprocess(const std::string& infix) const;
public:
InfixToPostfix();
virtual ~InfixToPostfix();
virtual void addOperator(const std::string& op, int precedence = 0);
virtual std::string removeOperator(int index);
virtual std::string getOperator(int index) const;
virtual int operatorPrecedence(const std::string& op) const;
virtual int numberOfOperators() const;
virtual bool isOperator(const std::string& op) const;
virtual bool isUnaryOperator(const std::string op) const;
virtual bool isOperand(const std::string& op) const;
virtual bool isNumeric(const std::string& op) const;
virtual void loadLogicalOperators();
virtual void loadMathOperators();
virtual std::string transform(const std::string& infix) const;
virtual flScalar evaluate(const std::string postfix,
const std::map<std::string, flScalar>* variables = NULL) const;
virtual flScalar compute(const std::string& op, flScalar a, flScalar b) const;
static void main(int args, char** argv);
};
}
#endif /* _INFIXTOPOSTFIX_H */

View File

@ -1,39 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "InputLVar.h"
namespace fl {
InputLVar::InputLVar() : LinguisticVariable(), _input(flScalar(0.0)) {
}
InputLVar::InputLVar(const std::string& name) : LinguisticVariable(name),
_input(flScalar(0.0)) {
}
InputLVar::~InputLVar() {
}
void InputLVar::setInput(flScalar input) {
this->_input = input;
}
flScalar InputLVar::input() const {
return this->_input;
}
}

View File

@ -1,44 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* File: InputLVar.h
* Author: jcrada
*
* Created on November 1, 2009, 2:25 PM
*/
#ifndef FL_INPUTLVAR_H
#define FL_INPUTLVAR_H
#include "LinguisticVariable.h"
namespace fl {
class InputLVar : public LinguisticVariable {
private:
flScalar _input;
public:
InputLVar();
InputLVar(const std::string& name);
virtual ~InputLVar();
virtual void setInput(flScalar input);
virtual flScalar input() const;
};
}
#endif /* FL_INPUTLVAR_H */

165
AI/FuzzyLite/LICENSE Normal file
View File

@ -0,0 +1,165 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser 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
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

View File

@ -1,118 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "LinguisticTerm.h"
#include "TriangularTerm.h"
#include "TrapezoidalTerm.h"
#include "ShoulderTerm.h"
#include "FuzzyException.h"
namespace fl {
LinguisticTerm::LinguisticTerm() :
_fuzzy_operator(NULL), _name(""), _minimum(-INFINITY), _maximum(INFINITY),
_modulation(flScalar(1.0)) {
setFuzzyOperator(FuzzyOperator::DefaultFuzzyOperator());
}
LinguisticTerm::LinguisticTerm(const std::string& name, flScalar minimum,
flScalar maximum) :
_fuzzy_operator(NULL), _name(name), _minimum(minimum), _maximum(maximum),
_modulation(flScalar(1.0)) {
setFuzzyOperator(FuzzyOperator::DefaultFuzzyOperator());
}
LinguisticTerm::LinguisticTerm(const FuzzyOperator& fuzzy_op,
const std::string& name, flScalar minimum, flScalar maximum) :
_fuzzy_operator(&fuzzy_op), _name(name), _minimum(minimum), _maximum(maximum),
_modulation(flScalar(1.0)) {
}
LinguisticTerm::~LinguisticTerm() {
}
void LinguisticTerm::setFuzzyOperator(const FuzzyOperator& fuzzy_operator) {
this->_fuzzy_operator = &fuzzy_operator;
}
const FuzzyOperator& LinguisticTerm::fuzzyOperator() const {
return *this->_fuzzy_operator;
}
void LinguisticTerm::setName(const std::string& name) {
this->_name = name;
}
std::string LinguisticTerm::name() const {
return this->_name;
}
void LinguisticTerm::setMinimum(flScalar min) {
this->_minimum = min;
}
flScalar LinguisticTerm::minimum() const {
return _minimum;
}
void LinguisticTerm::setMaximum(flScalar max) {
this->_maximum = max;
}
flScalar LinguisticTerm::maximum() const {
return _maximum;
}
void LinguisticTerm::setModulation(flScalar degree) {
this->_modulation = degree;
}
flScalar LinguisticTerm::modulation() const {
return this->_modulation;
}
flScalar LinguisticTerm::defuzzify() const {
return fuzzyOperator().defuzzify(this);
}
flScalar LinguisticTerm::area() const {
return fuzzyOperator().area(this);
}
void LinguisticTerm::centroid(flScalar& x, flScalar& y) const {
fuzzyOperator().centroid(this, x, y);
}
flScalar LinguisticTerm::areaAndCentroid(flScalar& x, flScalar& y) const {
return fuzzyOperator().areaAndCentroid(this, x, y);
}
void LinguisticTerm::samples(std::vector<flScalar>& x, std::vector<flScalar>& y,
int samples, int out_of_range) const {
flScalar step_size = (maximum() - minimum()) / samples;
flScalar step = minimum() - (out_of_range * step_size);
for (int i = 0 - out_of_range; i < samples + out_of_range + 1; ++i, step
+= step_size) {
x.push_back(step);
y.push_back(membership(step));
}
}
std::string LinguisticTerm::toString() const {
return "TERM " + name() + " := ";
}
}

View File

@ -1,96 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* File: Term.h
* Author: jcrada
*
* Created on December 9, 2009, 12:27 AM
*/
#ifndef FL_TERM_H
#define FL_TERM_H
#include "flScalar.h"
#include <vector>
#include <math.h>
#include <string>
#include "defs.h"
#include "FuzzyOperation.h"
#include "FuzzyOperator.h"
namespace fl {
class FuzzyOperator; //forward-declaration
class LinguisticTerm {
public:
enum eMembershipFunction {
MF_TRIANGULAR = 0, MF_TRAPEZOIDAL, MF_RECTANGULAR, MF_SHOULDER, MF_SINGLETON,
MF_COMPOUND, MF_FUNCTION, MF_TAKAGI_SUGENO, MF_DISCRETE,
//to implement
MF_SIGMOIDAL, MF_COSINE, MF_GAUSSIAN,
};
private:
const FuzzyOperator* _fuzzy_operator;
std::string _name;
flScalar _minimum;
flScalar _maximum;
flScalar _modulation;
public:
LinguisticTerm();
LinguisticTerm(const std::string& name, flScalar minimum = -INFINITY,
flScalar maximum = INFINITY);
LinguisticTerm(const FuzzyOperator& fuzzy_op, const std::string& name,
flScalar minimum = -INFINITY, flScalar maximum = INFINITY);
virtual ~LinguisticTerm();
virtual void setFuzzyOperator(const FuzzyOperator& fuzzy_op);
virtual const FuzzyOperator& fuzzyOperator() const;
virtual void setName(const std::string& name);
virtual std::string name() const;
virtual void setMinimum(flScalar min);
virtual flScalar minimum() const;
virtual void setMaximum(flScalar max);
virtual flScalar maximum() const;
virtual void setModulation(flScalar degree);
virtual flScalar modulation() const;
virtual flScalar defuzzify() const;
virtual std::string toString() const;
virtual LinguisticTerm* clone() const = 0;
virtual flScalar membership(flScalar crisp) const = 0;
virtual eMembershipFunction type() const = 0;
virtual void samples(std::vector<flScalar>& x, std::vector<flScalar>& y,
int samples = FL_SAMPLE_SIZE, int out_of_range = 0) const;
virtual flScalar area() const;
virtual void centroid(flScalar&x, flScalar& y) const;
virtual flScalar areaAndCentroid(flScalar& x, flScalar& y) const;
};
}
#endif /* FL_TERM_H */

View File

@ -1,238 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "LinguisticVariable.h"
#include "FuzzyExceptions.h"
#include "StrOp.h"
#include <algorithm>
#include <math.h>
#include "ShoulderTerm.h"
#include "TriangularTerm.h"
#include "TrapezoidalTerm.h"
namespace fl {
LinguisticVariable::LinguisticVariable() :
_fuzzy_operator(NULL) {
setFuzzyOperator(FuzzyOperator::DefaultFuzzyOperator());
}
LinguisticVariable::LinguisticVariable(const std::string& name) :
_fuzzy_operator(NULL), _name(name) {
setFuzzyOperator(FuzzyOperator::DefaultFuzzyOperator());
}
LinguisticVariable::LinguisticVariable(const FuzzyOperator& fuzzy_op,
const std::string& name) :
_fuzzy_operator(&fuzzy_op), _name(name) {
}
LinguisticVariable::~LinguisticVariable() {
for (int i = numberOfTerms() - 1; i >= 0; --i) {
delete removeTerm(i);
}
}
std::string LinguisticVariable::name() const {
return this->_name;
}
void LinguisticVariable::setName(const std::string& name) {
this->_name = name;
}
void LinguisticVariable::setFuzzyOperator(const FuzzyOperator& fuzzy_operator) {
this->_fuzzy_operator = &fuzzy_operator;
}
const FuzzyOperator& LinguisticVariable::fuzzyOperator() const {
return *this->_fuzzy_operator;
}
int LinguisticVariable::positionFor(const LinguisticTerm* lterm) {
for (int i = 0; i < numberOfTerms(); ++i) {
if (FuzzyOperation::IsLEq(lterm->minimum(), term(i)->minimum())) {
if (FuzzyOperation::IsEq(lterm->minimum(), term(i)->minimum())) {
return lterm->membership(lterm->minimum()) > term(i)->membership(lterm->minimum())
? i : i + 1;
}
return i;
}
}
return numberOfTerms();
}
void LinguisticVariable::addTerm(LinguisticTerm* term) {
int pos = positionFor(term);
_terms.insert(_terms.begin() + pos, term);
}
LinguisticTerm* LinguisticVariable::term(int index) const {
return _terms[index];
}
LinguisticTerm* LinguisticVariable::term(const std::string& name) const {
int index = indexOf(name);
return index == -1 ? NULL : term(index);
}
int LinguisticVariable::indexOf(const std::string& name) const {
for (int i = 0; i < numberOfTerms(); ++i) {
if (term(i)->name() == name) {
return i;
}
}
return -1;
}
LinguisticTerm* LinguisticVariable::removeTerm(int index) {
LinguisticTerm* result = _terms[index];
_terms.erase(_terms.begin() + index);
return result;
}
LinguisticTerm* LinguisticVariable::removeTerm(const std::string& name) {
int index = indexOf(name);
return index == -1 ? NULL : removeTerm(index);
}
LinguisticTerm* LinguisticVariable::firstTerm() const {
return numberOfTerms() > 0 ? term(0) : NULL;
}
LinguisticTerm* LinguisticVariable::lastTerm() const {
return numberOfTerms() > 0 ? term(numberOfTerms() - 1) : NULL;
}
bool LinguisticVariable::isEmpty() const {
return numberOfTerms() == 0;
}
int LinguisticVariable::numberOfTerms() const {
return _terms.size();
}
flScalar LinguisticVariable::minimum() const {
return numberOfTerms() == 0 ? NAN : firstTerm()->minimum();
}
flScalar LinguisticVariable::maximum() const {
return numberOfTerms() == 0 ? NAN : lastTerm()->maximum();
}
CompoundTerm LinguisticVariable::compound() const {
CompoundTerm result("Accumulated " + name(), minimum(), maximum());
for (int i = 0; i < numberOfTerms(); ++i) {
result.addTerm(*term(i));
}
return result;
}
std::string LinguisticVariable::fuzzify(flScalar crisp) const {
std::vector<std::string> fuzzyness;
for (int i = 0; i < numberOfTerms(); ++i) {
flScalar degree = term(i)->membership(crisp);
fuzzyness.push_back(StrOp::ScalarToString(degree) + "/"
+ term(i)->name());
}
// StringOperator::sort(fuzzyness, false);
std::string result;
for (size_t i = 0; i < fuzzyness.size(); ++i) {
result += fuzzyness[i] + (i < fuzzyness.size() - 1 ? " + " : "");
}
return result;
}
LinguisticTerm* LinguisticVariable::bestFuzzyApproximation(flScalar crisp) {
LinguisticTerm* result = NULL;
flScalar highest_degree = -1.0;
for (int i = 0; i < numberOfTerms(); ++i) {
flScalar degree = term(i)->membership(crisp);
if (degree > highest_degree) {
result = term(i);
highest_degree = degree;
}
}
return result;
}
void LinguisticVariable::createTerms(int number_of_terms,
LinguisticTerm::eMembershipFunction mf, flScalar min, flScalar max,
const std::vector<std::string>& labels) {
std::vector<std::string> final_labels;
for (int i = 0; i < number_of_terms; ++i) {
if ((int) labels.size() <= i) {
final_labels.push_back(name() + "-" + StrOp::IntToString(i + 1));
} else {
final_labels.push_back(labels[i]);
}
}
fl::flScalar intersection = NAN; //Proportion of intersection between terms
if (mf == LinguisticTerm::MF_TRAPEZOIDAL) {
intersection = 4.0 / 5.0;
} else {
intersection = 0.5;
}
//TODO: What is the intersection in other terms?
fl::flScalar term_range = (max - min) / (number_of_terms - number_of_terms / 2);
fl::flScalar current_step = min + (1 - intersection) * term_range;
for (int i = 0; i < number_of_terms; ++i) {
fl::LinguisticTerm* term = NULL;
switch (mf) {
case LinguisticTerm::MF_TRIANGULAR:
term = new fl::TriangularTerm(final_labels.at(i),
current_step - (1 - intersection) * term_range,
current_step + intersection * term_range);
break;
case LinguisticTerm::MF_SHOULDER:
if (i == 0 || i == number_of_terms - 1) {
term = new fl::ShoulderTerm(final_labels[i],
current_step - (1 - intersection) * term_range,
current_step + intersection * term_range, i == 0);
} else {
term = new fl::TriangularTerm(final_labels.at(i),
current_step - (1 - intersection) * term_range,
current_step + intersection * term_range);
}
break;
case LinguisticTerm::MF_TRAPEZOIDAL:
term = new fl::TrapezoidalTerm(final_labels.at(i),
current_step - (1 - intersection) * term_range,
current_step + intersection * term_range);
// term = new fl::TriangularTerm(final_labels.at(i), current_step
// - (1 - intersection) * term_range, current_step + intersection
// * term_range);
break;
default:
throw fl::InvalidArgumentException(FL_AT, "Invalid option for membership function");
}
current_step += intersection * term_range;
addTerm(term);
}
}
std::string LinguisticVariable::toString() const {
std::string result(name());
result += "={ ";
for (int i = 0; i < numberOfTerms(); ++i) {
result += term(i)->name() + " ";
}
result += "}";
return result;
}
}

View File

@ -1,83 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* File: LinguisticVariable.h
* Author: jcrada
*
* Created on November 1, 2009, 1:56 PM
*/
#ifndef FL_LINGUISTICVARIABLE_H
#define FL_LINGUISTICVARIABLE_H
#include <string>
#include <vector>
#include "LinguisticTerm.h"
#include "FuzzyExceptions.h"
#include "defs.h"
#include "CompoundTerm.h"
namespace fl {
class LinguisticVariable {
private:
const FuzzyOperator* _fuzzy_operator;
std::string _name;
std::vector<LinguisticTerm*> _terms;
protected:
virtual int positionFor(const LinguisticTerm* term);
public:
LinguisticVariable();
LinguisticVariable(const std::string& name);
LinguisticVariable(const FuzzyOperator& fuzzy_op, const std::string& name);
virtual ~LinguisticVariable();
virtual std::string name() const;
virtual void setName(const std::string& name);
virtual void setFuzzyOperator(const FuzzyOperator& fuzzy_op);
virtual const FuzzyOperator& fuzzyOperator() const;
virtual void addTerm(LinguisticTerm* term);
virtual LinguisticTerm* term(int index) const;
virtual LinguisticTerm* term(const std::string& name) const;
virtual int indexOf(const std::string& name) const;
virtual LinguisticTerm* removeTerm(int index);
virtual LinguisticTerm* removeTerm(const std::string& name);
virtual LinguisticTerm* firstTerm() const;
virtual LinguisticTerm* lastTerm() const;
virtual bool isEmpty() const;
virtual int numberOfTerms() const;
virtual void createTerms(int number_of_terms, LinguisticTerm::eMembershipFunction mf,
flScalar min, flScalar max,
const std::vector<std::string>& labels = std::vector<std::string>());
virtual flScalar minimum() const;
virtual flScalar maximum() const;
virtual CompoundTerm compound() const;
virtual std::string fuzzify(flScalar crisp) const;
virtual LinguisticTerm* bestFuzzyApproximation(flScalar crisp);
virtual std::string toString() const;
};
}
#endif /* FL_LINGUISTICVARIABLE_H */

View File

@ -1,152 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "MamdaniConsequent.h"
#include "FuzzyRule.h"
#include <stdlib.h>
#include "StrOp.h"
namespace fl {
MamdaniConsequent::MamdaniConsequent() : _term(NULL) {
}
MamdaniConsequent::~MamdaniConsequent() {
}
void MamdaniConsequent::setTerm(const LinguisticTerm* term) {
this->_term = term;
}
const LinguisticTerm* MamdaniConsequent::term() const {
return this->_term;
}
void MamdaniConsequent::addHedge(Hedge* hedge) {
this->_hedges.push_back(hedge);
}
Hedge* MamdaniConsequent::hedge(int index) const {
return _hedges[index];
}
int MamdaniConsequent::numberOfHedges() const {
return _hedges.size();
}
void MamdaniConsequent::execute(flScalar degree) {
LinguisticTerm* rule_output = term()->clone();
flScalar modulation = degree * weight();
for (int i = 0; i < numberOfHedges(); ++i) {
modulation = hedge(i)->hedge(modulation);
}
rule_output->setModulation(modulation);
outputLVar()->output().addTerm(*rule_output);
delete rule_output;
}
std::string MamdaniConsequent::toString() const {
std::stringstream ss;
ss << outputLVar()->name() << " " << FuzzyRule::FR_IS;
for (int i = 0; i < numberOfHedges(); ++i) {
ss << " " << hedge(i)->name();
}
ss << " " << term()->name();
if (weight() < flScalar(1.0)) {
ss << " " + FuzzyRule::FR_WITH + " " << weight();
}
return ss.str();
}
void MamdaniConsequent::parse(const std::string& consequent,
const FuzzyEngine& engine) throw (ParsingException) {
std::stringstream ss(consequent);
std::string token;
enum e_state {
S_LVAR = 1, S_IS, S_HEDGE, S_TERM, S_WITH, S_WEIGHT, S_END
};
e_state current_state = S_LVAR;
OutputLVar* output = NULL;
LinguisticTerm* term = NULL;
std::vector<Hedge*> hedges;
Hedge* hedge = NULL;
while (ss >> token) {
switch (current_state) {
case S_LVAR:
output = engine.outputLVar(token);
if (!output) {
throw ParsingException(FL_AT, "Output variable <" +
token + "> not registered in fuzzy engine");
}
current_state = S_IS;
break;
case S_IS:
if (token == FuzzyRule::FR_IS) {
current_state = S_HEDGE;
} else {
throw ParsingException(FL_AT, "<" + FuzzyRule::FR_IS + "> expected but found <" +
token + ">");
}
break;
case S_HEDGE:
hedge = engine.hedgeSet().get(token);
if (hedge) {
hedges.push_back(hedge); //And check for more hedges
break;
}
//intentional fall-through if a term follows
case S_TERM:
term = output->term(token);
if (!term) {
throw ParsingException(FL_AT, "Term <" + token +
"> not found in output variable <" + output->name() + ">");
}
setOutputLVar(output);
setTerm(term);
for (size_t i = 0; i < hedges.size(); ++i) {
addHedge(hedges[i]);
}
setWeight(1.0);
current_state = S_WITH;
break;
case S_WITH:
if (token != FuzzyRule::FR_WITH) {
throw ParsingException(FL_AT, "<" + FuzzyRule::FR_WITH + "> expected but found <"
+ token + ">");
}
current_state = S_WEIGHT;
break;
case S_WEIGHT:
setWeight(atof(token.c_str()));
if (weight() > 1.0){
throw ParsingException(FL_AT, "Weight [0.0, 1.0] expected but found <" +
StrOp::ScalarToString(weight()) + ">");
}
current_state = S_END;
break;
case S_END:
throw ParsingException(FL_AT, "End of line expected but found <" + token + ">");
}
}
if (current_state == S_WEIGHT){
throw ParsingException(FL_AT, "Weight [0.0, 1.0] expected after <" + FuzzyRule::FR_WITH +
"> but found nothing");
}
}
}

View File

@ -1,60 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* File: MamdaniConsequent.h
* Author: jcrada
*
* Created on March 3, 2010, 12:17 AM
*/
#ifndef FL_MAMDANICONSEQUENT_H
#define FL_MAMDANICONSEQUENT_H
#include "FuzzyConsequent.h"
#include "LinguisticTerm.h"
#include "Hedge.h"
#include <vector>
#include "FuzzyExceptions.h"
#include "FuzzyEngine.h"
namespace fl {
class MamdaniConsequent : public FuzzyConsequent {
private:
const LinguisticTerm* _term;
std::vector<Hedge*> _hedges;
public:
MamdaniConsequent();
virtual ~MamdaniConsequent();
virtual void setTerm(const LinguisticTerm* term);
virtual const LinguisticTerm* term() const;
virtual void addHedge(Hedge* hedge);
virtual Hedge* hedge(int index) const ;
virtual int numberOfHedges() const;
//Override
virtual void execute(flScalar degree);
virtual std::string toString() const;
virtual void parse(const std::string& consequent,
const FuzzyEngine& engine) throw (ParsingException) ;
};
}
#endif /* FL_MAMDANICONSEQUENT_H */

View File

@ -1,67 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "MamdaniRule.h"
#include "defs.h"
#include "StrOp.h"
#include "FuzzyOperator.h"
#include <sstream>
#include <stack>
#include "DescriptiveAntecedent.h"
#include "MamdaniConsequent.h"
namespace fl {
MamdaniRule::MamdaniRule()
: FuzzyRule() {
}
MamdaniRule::MamdaniRule(const std::string& rule, const FuzzyEngine& engine)
: FuzzyRule() {
try{
parse(rule,engine);
}catch(ParsingException& e){
FL_LOG(e.toString());
}
}
MamdaniRule::~MamdaniRule() {
}
void MamdaniRule::parse(const std::string& rule, const FuzzyEngine& engine) throw (ParsingException) {
std::string str_antecedent, str_consequent;
ExtractFromRule(rule, str_antecedent, str_consequent);
DescriptiveAntecedent* obj_antecedent = new DescriptiveAntecedent;
obj_antecedent->parse(str_antecedent, engine);
setAntecedent(obj_antecedent);
std::vector<std::string> consequents = StrOp::SplitByWord(str_consequent, FuzzyRule::FR_AND);
MamdaniConsequent* obj_consequent = NULL;
for (size_t i = 0; i < consequents.size(); ++i) {
obj_consequent = new MamdaniConsequent;
try {
obj_consequent->parse(consequents[i], engine);
} catch (ParsingException& e) {
delete obj_consequent;
throw e;
}
addConsequent(obj_consequent);
}
}
}

View File

@ -1,42 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* File: MamdaniRule.h
* Author: jcrada
*
* Created on November 5, 2009, 11:15 AM
*/
#ifndef FL_MAMDANIRULE_H
#define FL_MAMDANIRULE_H
#include "FuzzyRule.h"
namespace fl {
class MamdaniRule : public FuzzyRule {
public:
MamdaniRule();
MamdaniRule(const std::string& rule, const FuzzyEngine& engine);
virtual ~MamdaniRule();
virtual void parse(const std::string& rule, const FuzzyEngine& engine) throw (ParsingException);
};
}
#endif /* FL_MAMDANIRULE_H */

317
AI/FuzzyLite/NEWS Normal file
View File

@ -0,0 +1,317 @@
Extracted from [README.md](/README.md)
================================================
### <a name="features">Features</a>
**Controllers** *Types* (5) Mamdani, Takagi-Sugeno, Larsen, Tsukamoto, Inverse Tsukamoto
**Linguistic terms** *Basic* (4) triangle, trapezoid, rectangle, discrete. *Extended* (9) bell, cosine, gaussian, gaussian product, pi-shape, sigmoid difference, sigmoid product, spike. *Edges* (4) concave, ramp, sigmoid, s-shape, z-shape. *Functions* (3) constant, linear, function.
**Conjunction and Activation** *T-Norm* (7) minimum, algebraic product, bounded difference, drastic product, einstein product, hamacher product, nilpotent minimum.
**Disjunction and Accumulation** *S-Norm* (8) maximum, algebraic sum, bounded sum, normalized sum, drastic sum, einstein sum, hamacher sum, nilpotent maximum.
**Defuzzifiers** *Integral* (5) centroid, bisector, smallest of maximum, largest of maximum, mean of maximum, *Weighted* (2) weighted average, weighted sum.
**Hedges** *Types* (6) any, not, extremely, seldom, somewhat, very.
**Import** *Types* (3) FuzzyLite Language `fll`, Fuzzy Inference System `fis`, Fuzzy Control Language `fcl`.
**Export** *Types* (6) `C++`, `Java`, FuzzyLite Language `fll`, FuzzyLite Dataset `fld`, Fuzzy Inference System `fis`, Fuzzy Control Language `fcl`.
**Examples** (30+) of Mamdani, Takagi-Sugeno and Tsukamoto controllers from `fuzzylite`, Octave and Matlab, each included in the following formats: `C++`, `Java`, `fll`, `fld`, `fis`, and `fcl`.
***
### <a name="example">Example</a>
```cpp
#include "fl/Headers.h"
int main(int argc, char* argv[]){
using namespace fl;
Engine* engine = new Engine("simple-dimmer");
InputVariable* ambient = new InputVariable;
ambient->setName("Ambient");
ambient->setRange(0.000, 1.000);
ambient->addTerm(new Triangle("DARK", 0.000, 0.500));
ambient->addTerm(new Triangle("MEDIUM", 0.250, 0.750));
ambient->addTerm(new Triangle("BRIGHT", 0.500, 1.000));
engine->addInputVariable(ambient);
OutputVariable* power = new OutputVariable;
power->setName("Power");
power->setRange(0.000, 2.000);
power->setDefaultValue(fl::nan);
power->addTerm(new Triangle("LOW", 0.000, 1.000));
power->addTerm(new Triangle("MEDIUM", 0.500, 1.500));
power->addTerm(new Triangle("HIGH", 1.000, 2.000));
engine->addOutputVariable(power);
RuleBlock* ruleblock = new RuleBlock;
ruleblock->addRule(Rule::parse("if Ambient is DARK then Power is HIGH", engine));
ruleblock->addRule(Rule::parse("if Ambient is MEDIUM then Power is MEDIUM", engine));
ruleblock->addRule(Rule::parse("if Ambient is BRIGHT then Power is LOW", engine));
engine->addRuleBlock(ruleblock);
engine->configure("", "", "Minimum", "Maximum", "Centroid");
std::string status;
if (not engine->isReady(&status))
throw Exception("Engine not ready. "
"The following errors were encountered:\n" + status, FL_AT);
for (int i = 0; i < 50; ++i){
scalar light = ambient->getMinimum() + i * (ambient->range() / 50);
ambient->setInputValue(light);
engine->process();
FL_LOG("Ambient.input = " << Op::str(light) << " -> " <<
"Power.output = " << Op::str(power->getOutputValue()));
}
}
```
***
### <a name="whatsnew">What's New?</a>
The entire `fuzzylite` library has been thoroughly revised, refactored, validated, and significantly improved. The following sections detail the changes and enhancements of version 5.0. Users of previous versions are **strongly** encouraged to carefully read the list before migrating to version 5.0. Important changes and enhancements are marked as **(important)**, **(VERY important)** and **(EXTREMELY important)**.
#### <a name="new-general">General</a>
+ **(important)** `fuzzylite v5.0` is dual-licensed under the [GNU LGPL v3.0](https://www.gnu.org/licenses/lgpl.html) and a paid commercial license.
+ Support for both `C++98` and `C++11` using the latest features.
+ Support for multiple compilers `g++`, `Clang`, `MSVC`.
+ Refactoring of many classes to improve design and performance.
+ **(important)** Performance improvements of Takagi-Sugeno controllers by over 55% with respect to v4.0 (estimate based on the average performance on the examples included).
+ Smart pointers in many classes take care of automatically deleting objects when setting new pointers (`Accumulated`, `FactoryManager`, `Function`, `OutputVariable`, `Rule`, and `RuleBlock`).
* **(important)** Exceptions are thrown when any of the following `RuleBlock::[conjunction|disjunction|activation]`, `Accumulated::accumulation`, and `OutputVariable::defuzzifier` are required but set to `fl::null`, thereby replacing the operations that would lead to `[signal 11] Segmentation fault` to operations that throw a `fl::Exception` instead.
+ Automatic build script to build `fuzzylite` in `debug` and `release` mode.
+ Binaries of debug libraries are renamed to append the letter `d` (e.g.,`fuzzylited.dll`, `libfuzzylited.so`).
+ **(important)** New file [`fuzzylite/src/m/compare.m`](/fuzzylite/src/m/compare.m) <!---check link--> to compare the output values of your `fuzzylite` engines with the evaluation of the same engine in Octave/Matlab.
+ **(important)** There is practically no difference between the output values obtained with `fuzzylite` and those obtained with Octave/Matlab. Based on the examples, the average mean square error (MSE) between the output values is less than `7.3e-12` (or `0.0000000000073`) due to negligible differences in floating-point arithmetic. The results and comparison can be found in [`examples/examples.mat`](/examples/examples.mat) <!---check link-->.
+ **(important)** Source code of applications based on version 4.0 will most likely not compile with version 5.0.
+ Minor bugs and memory leaks fixed.
####<a name="new-macros">Macros</a>
* **(important)** Added support for `C++11` with smart pointers, method identifiers, move constructors and move operators as follows. For precise information, refer to file [`fuzzylite/fl/fuzzylite.h`](/fuzzylite/fl/fuzzylite.h). <!---check link-->
* **(important)** Macros for identifiers are defined as `FL_IOVERRIDE override`, `FL_IFINAL final`, `FL_IDEFAULT = default`, `FL_IDELETE = delete`, `FL_INOEXCEPT noexcept`, `FL_DEFAULT_COPY(Class)`, `FL_DEFAULT_MOVE(Class)`, and `FL_DEFAULT_COPY_AND_MOVE(Class)`.
* **(important)** Added macro `FL_unique_ptr` to refer to `std::auto_ptr` (`C++98`) or `std::unique_ptr` (`C++11`), and its respective `FL_move_ptr(x)` to move a smart pointer, albeit `FL_move_ptr(x)` is not used within the library as it is not needed.
* **(important)** Added global variables `const long fl::null = 0L` to refer to the null pointer in `C++98` and `const std::nullptr_t null = nullptr` to refer to the null pointer in `C++11`.
* **(important)** Renamed macro `FL_DEBUG` to `FL_DBG`.
* **(important)** Renamed macros `FL_BEGIN_DEBUG_BLOCK` and `FL_END_DEBUG_BLOCK` to `FL_DEBUG_BEGIN` and `FL_DEBUG_END`, respectively.
* **(important)** Renamed macro `FL_EXPORT` to `FL_API`
* **(EXTREMELY important)** Added macro definitions `FL_EXPORT_LIBRARY` and `FL_IMPORT_LIBRARY`. If you are building `fuzzylite` as a **shared library**, you need to define `FL_EXPORT_LIBRARY`. If you are building `fuzzylite` **executable** *and* it utilizes the `fuzzylite` **shared library**, you need to define `FL_IMPORT_LIBRARY`. If you are building `fuzzylite` as a **static library** and/or building `fuzzylite` **executable** using the `fuzzylite` **static library**, then you do not need to define either `FL_[IMPORT|EXPORT]_LIBRARY`. Note that the same conditions apply for your application. This is particularly important in Windows platforms, as `FL_IMPORT_LIBRARY` and `FL_EXPORT_LIBRARY` define `FL_API` to `__declspec(dllimport)` and `__declspec(dllexport)`, respectively. If in doubt, please check [`fuzzylite/CMakeLists.txt`](/fuzzylite/CMakeLists.txt)<!---check link-->
#### <a name="new-operation">Operation</a>
* **(important)** Added method `Operation::toScalar(std::string x, scalar alternative) FL_INOEXCEPT` which returns `alternative` if `x` is not a valid `scalar`, and never throws an exception.
* **(important)** Added method `Operation::toScalar(std::string x)` that returns the scalar value of `x` or throws a `fl::Exception` if `x` is not a valid `scalar`.
* **(VERY important)** Marked method (from v4.0) `Operation::toScalar(std::string, bool, scalar) FL_IDELETE;` and removed its implementation such that its usage is prevented at compile time in `C++11` and at linker time in `C++98`. Please, use the appropriate `Op::toScalar` methods mentioned above.
+ Renamed method `Op::isNan` to `Op::isNaN`.
* Added method `fl::Op::isFinite(x)` which returns `not (isNaN(x) or isInf(x))`.
* Changed `fl::Op::isEq(a,b)` to return `true` if `a == b == NaN`.
* Changed `fl::Op::isEq(a,b)` to return `true` if `a == b == Inf`.
* Changes to `fl::Op::isEq` affect other comparison methods `fl::Op::is[Lt|LEq|GEq|Gt]`.
* Added shortcuts of comparisons `fl::Op::[gt,lt,ge,le,eq,neq](scalar a, scalar b)`, mostly to provide binary versions (without `macheps`) for term `Function`.
* Deleted method `Op::repeat`.
* Removed method `fuzzylite::configuration()`.
* Changed default `fuzzylite::_macheps = 1e-6;`.
* Renamed method `Op::makeValidId` to `Op::validName`, which now returns `"unnamed"` for empty strings.
####<a name="new-engine">Engine</a>
* **(VERY important)** Moved `Engine::hedges` (and relevant methods) to `Rule::hedges`.
* Added enumeration for the type of engine: `enum Engine::Type{Mamdani, Larsen, TakagiSugeno, Tsukamoto, InverseTsukamoto, Hybrid, Unknown}`.
* Added method `Type Engine::type(std::string* name, std::string* reason)` to infer the type of the engine based on its configuration, additionally provides the name of the type and the inference reasons for its type.
* **(important)** Changed method `Engine::isReady(std::string)` to satisfy the default operation of controllers. The method `Engine::isReady(std::string)` was initially conceived to provide information before a potential `[signal 11] Segmentation fault` happened due to improper configuration. However, given the improved handling of signals and exceptions mentioned in Section [General](#new-general), using method `Engine::isReady(std::string)` is not necessary except for providing suggestions of what could potentially cause an error.
* Added methods `Engine::set[Input|Output]Variables(std::vector)` and `Engine::setRuleBlocks(std::vector)`.
* Added methods `Engine::[input|output]Variables()` and `Engine::ruleBlocks()` to return mutable references.
* Added method `Engine::variables()` to retrieve a vector (copy) containing the `InputVariables` followed by the `OutputVariables`.
* Added method `Engine::updateReferences()` to update the references to the engine in all the necessary linguistic terms (i.e., `Linear` and `Function`).
* Added method `Engine::clone()`.
* Added copy constructors, assignment operators, and default move constructor to `Engine`.
####<a name="new-inoutvars">Input Variables and Output Variables</a>
* **(important)** Added methods `OutputVariable::[get|set]OutputValue()` to [retrieve|store] value from defuzzification
* **(important)** Changed return type of `scalar OutputVariable::defuzzify()` to `void OutputVariable::defuzzify()` because now it automatically stores the defuzzified output value, and also stores the previous *valid* output value regardless of locks. Like in version 4.0, if `OutputVariable::lockPreviousOutputValue=true`, and the defuzzified output value is not valid (i.e., `[NaN|Inf]`) or no rules were activated, then the defuzzified output value is replaced for the previous valid output value.
* Removed method `OutputVariable::defuzzifyNoLocks()`.
* Renamed variable `OutputVariable::lastValidOutputValue` to `OutputVariable::previousOutputValue`.
* **(important)** Renamed method `OutputVariable::[get|set]LastValidOutput()` to `OutputVariable::[get|set]PreviousOutputValue()`.
* Renamed variable `OutputVariable::lockValidOutput` to `OutputVariable::lockPreviousOutputValue`.
* **(important)** Renamed method `OutputVariable::setLockValidOutput()` to `OutputVariable::setLockPreviousOutputValue()`.
* **(important)** Renamed method `OutputVariable::isLockingValidOutput()` to `OutputVariable::isLockedPreviousOutputValue()`.
* Renamed variable `OutputVariable::lockOutputRange` to `OutputVariable::lockOutputValueInRange`.
* **(important)** Renamed method `OutputVariable::setLockOutputRange()` to `OutputVariable::setLockOutputValueInRange()`.
* **(important)** Renamed method `OutputVariable::isLockingOutputRange()` to `OutputVariable::isLockedOutputValueInRange()`.
* Added methods `std::string InputVariable::fuzzyInputValue()` and `std::string OutputVariable::fuzzyOutputValue()`.
* Added method `OutputVariable::clear()` to clear the fuzzy output, and set `OutputVariable::previousOutputValue = fl::nan` and set `OutputVariable::outputValue = fl::nan`.
* Added copy constructors, assignment operators, move constructors and move operators to [Input|Output]Variable.
* Added method `Variable::terms()` to return mutable reference.
* **(important)** Changed `OutputVariable::[defuzzifier|fuzzyOutput]` to smart pointers (`FL_unique_ptr`).
#### <a name="new-terms">Linguistic Terms</a>
* **(VERY important)** Added Term::[get|set]Height to define the height of *integral* terms, and multiply their respective membership functions accordingly.
* Added copy constructors, assignment operators, move constructors and move operators to every `Term`.
* **(VERY important)** Parameters of all terms are set by default to `fl::nan`.
* **(important)** Renamed method `Term::copy()` to `Term::clone()` in every `Term`.
* Added method `Term::updateReference(Term*, Engine*)` to ensure `Linear` and `Function` terms have updated pointers to the `Engine` (useful when cloning and copy-constructing).
+ **(important)** Added linguistic terms `Concave`, `Cosine` and `Spike`.
* **(important)** Changed `Accumulated` to take `Activated*` terms instead of `const Terms*`.
* Removed `const` from return type of method `SNorm* Accumulated::[get|set]Accumulation()`.
* Changed `Accumulated::accumulation` to a smart pointer (`FL_unique_ptr`).
* Added method `Accumulated::terms()` to return mutable reference.
* **(important)** Renamed methods `Triangle::[set|get][A|B|C]` to `::[set|get]Vertex[A|B|C]`.
* **(important)** Renamed methods `Trapezoid::[set|get][A|B|C|D]` to `::[set|get]Vertex[A|B|C|D]`.
* **(important)** Renamed term `Thresholded` to `Activated`.
* **(important)** Renamed methods `Thresholded::[set|get]Threshold()` to `Activated::[set|get]Degree()`.
* Added enumeration `[Ramp|Sigmoid]::Direction{ NEGATIVE, ZERO, POSITIVE }` to refer to the slope.
* Added methods `Ramp::direction()` and `Sigmoid::direction()` to retrieve direction of slope.
* Removed Exception Specification from methods in `Discrete`, `Linear` and `Function` terms.
#### <a name="new-linear-discrete">Linear and Discrete Terms</a>
* **(important)** Changed `Linear` from having pointers to the input variables to having a pointer to the `Engine`.
* Changed visibility of `Linear::coefficients` to `protected`.
* **(important)** Added methods `Linear::coefficients()`, `Linear::setCoefficients()`.
* `Linear` term no longer throws exception when `inputVariables != |coefficients|`.
* **(important)** Removed public vector of variables `Discrete::[x|y]`.
* **(important)** Added a `typedef std::pair<scalar, scalar> Discrete::Pair`.
* **(important)** Changed representation of `Discrete::[x|y]` from `std::vector<scalar>` to `std::vector<Discrete::Pair>`.
* Added methods `Discrete::setXY()` and `Discrete::xy()` to set and get the new representation of pairs.
* Added methods `Discrete::xy(int index)` to retrieve `Discrete::Pair` at `index`.
* **(important)** Added methods `Discrete::toPairs(std::vector<scalar>)` which throws an exception if the vector is missing a value (i.e., `std::vector<scalar>.size() % 2 != 0`), and `Discrete::toPairs(std::vector<scalar>, scalar missingValue)` which adds `missingValue` in case `std::vector<scalar>.size() %2 == 1`, hence never throwing an exception.
* Added method `Discrete::toVector(std::vector<Discrete::Pair>)` to convert `std::vector<Discrete::Pair>` to a `std::vector<scalar>`.
* Added method `Discrete::formatXY()` to get pairs `(x,y)` nicely formatted.
####<a name="new-function">Function Term</a>
* **(important)** Merged structs `Function::Operator` and `Function::BuiltInFunction` into a single `struct Function::Element`.
* **(EXTREMELY important)** Changed the precedence of all built-in instances of `Function::Element` of type `Operator` starting from `100` and decreasing by `10`. The precedence of built-in operators is the following: `(100)` Logical not `[!]` and Negation `[~]`; `(90)` Power `[^]`; `(80)` Multiplication `[*]`, Division `[/]` and Modulo `[%]`; `(70)` Addition `[+]` and Subtraction `[-]`; `(60)` Logical AND `[and]` and Logical OR `[or]`. If you have registered your own operators, please adjust their precedence as required.
* Added to `Function` built-in comparison functions `gt,lt,ge,le,eq` and operator logical not `!`.
* Modified typedefs `Function::Unary` and `Function::Binary` to take `scalar` instead of `double`.
* Changed `public Function::root` to `protected Function::_root` and it is now a smart pointer (`FL_unique_ptr`).
* Added method `Function::root()` to return pointer to `Function::root`.
* **(EXTREMELY important)** Moved built-in functions and operators from `Function` to a `FunctionFactory`.
#### <a name="new-norms-hedges">[T|S]Norms and Hedges</a>
+ **(important)** Fixed operation when using multiple hedges to operate from right-most to left-most, e.g. `if Ambient is not very extremely bright`, now evaluates as follows `not(very(extremely(bright)))`.
+ Added `TNorm` nilpotent minimum and `SNorm` nilpotent maximum.
* Added clone methods to every `Norm`.
* Added clone methods to every `Hedge`.
* **(VERY important)** Moved `Engine::hedges` to `Rule::hedges`.
#### <a name="new-rules">Rules</a>
* **(VERY important)** Moved `Engine::hedges` (and methods) to `Rule::hedges`.
* Added method `Rule::isLoaded()` to determine whether a rule was properly parsed and thus can be activated.
* Added method `Rule::unload()` to allow the existence of a rule in an inactive state (useful for invalid rules).
* **(important)** Removed variable `Rule::FL_ASSIGNS` and method `Rule::assignsKeyword()`, for which the symbol `=` in rules is no longer valid.
* Changed visibility of method `Rule::setText()` to `public`.
* Added method `Rule::load(const Engine*)`.
* Changed `Rule::[antecedent|consequent]` to smart pointers (`FL_unique_ptr`).
* **(important)** Renamed method `Antecedent::[get|set]Root()` to `Antecedent::[get|set]Expression()`.
* Added methods `[Antecedent|Consequent]::[get|set]Text()`.
* **(important)** Added methods `[Antecedent|Consequent]::[load|unload]()`, with the same objective as `Rule::[load|unload]()`.
#### <a name="new-ruleblocks">Rule Blocks</a>
* Added method `RuleBlock::reloadRules()`.
* Added method `RuleBlock::setRules(std::vector)`.
* Added method `RuleBlock::rules()` to return mutable reference.
* Removed `const` from `TNorm` and `SNorm` in `RuleBlock::[get|set][Conjunction|Disjunction|Activation]()`, respectively.
* Changed `RuleBlock::[conjunction|disjunction|activation]` to smart pointers (`FL_unique_ptr`).
* **(VERY important)** Added basic rule chaining such that an `OutputVariable` can be utilized in the `Antecedent` of a `Rule`. For example, considering the rule `if Power is high then InversePower is low`, where `Power` and `InversePower` are both output variables, the activation degree of the `Antecedent` will correspond to the accumulated activation degree of the term `high` in the fuzzy output of `Power`. If `Power::accumulation = none`, the accumulated activation degree of the term `high` will be computed as the regular sum of the activation degrees of term `high` in the fuzzy output of `Power`. Otherwise, the accumulated activation degree is computed utilizing the `Power::accumulation` operator.
#### <a name="new-weighted">Weighted Defuzzifiers</a>
+ **(VERY important)** Performance improvements of Takagi-Sugeno controllers by over 55% (with respect to v4.0) based on the average performance on the examples included.
* **(important)** Created class `WeightedDefuzzifier` from which classes `Weighted[Average|Sum]` are derived.
* **(important)** Added enumeration `WeightedDefuzzifier::Type{Automatic, TakagiSugeno, Tsukamoto}` and respective methods `WeightedDefuzzifier::[get|set]Type()` and `WeightedDefuzzifer::getTypeName()`.
* Added method `WeightedDefuzzifier::inferType(Term*)` to automatically determine the `WeightedDefuzzifier::Type` based on the class of `Term`.
* **(important)** By default, `WeightedDefuzzifier::type = Automatic`, which automatically infers the type based on the `WeightedDefuzzifier::inferType()`.
* **(important)** There is a small performance penalty when using `WeightedDefuzzifier::type = Automatic` because `WeightedDefuzzifier::inferType()` performs three `dynamic_cast<>`.
* **(important)** Deleted class `Tsukamoto`. Its method `static tsukamoto()` was moved to `virtual WeightedDefuzzifier::tsukamoto()`, which allows to be overriden
* Added support for `Tsukamoto` with `Concave` terms.
+ **(EXTREMELY important)** In version 5.0, the traditional operation of Takagi-Sugeno and Tsukamoto controllers is achieved by setting `OutputVariable::accumulation = none`. Unlike version 4.0, the `RuleBlock::activation` will not have any effect on Takagi-Sugeno nor Tsukamoto controllers, for which `RuleBlock::activation` should also be set to `none`. More information about the roles of the `OutputVariable::accumulation` and `RuleBlock::activation` operators are detailed as follows. Refer to [sciweavers](http://www.sciweavers.org/free-online-latex-equation-editor) to convert LaTeX equations.
+ **(VERY important)** In version 5.0, the role of the `RuleBlock::activation` `TNorm` on the `Weighted[Average|Sum]` always performs a regular multiplication of the weights and the values (i.e., $w_i \times z_j$) regardless of the `TNorm` chosen. In other words, selecting any `RuleBlock::activation` for `Weighted[Average|Sum]` is irrelevant, and should be set to `none` as every `TNorm` will have the same multiplication effect. This operation is different from `fuzzylite` version 4.0, where the `RuleBlock::activation` operator was utilized to multiply the weights and values (i.e. $w_i \otimes z_j$), and therefore the traditional operation of the `Weighted[Average|Sum]` was achieved when `RuleBlock::activation = AlgebraicProduct;`.
+ **(VERY important)** In version 5.0, the role of the `OutputVariable::accumulation = none` on the `Weighted[Average|Sum]` results in a regular sum of the multiplied weights and values, i.e., $\dfrac{\sum_i^n w_i \times z_j}{\sum_i^n w_i}$. However, if the `OutputVariable::accumulation != none`, the role of the `SNorm` will be to accumulate the activation degrees of the *repeated* terms in the fuzzy output of the variable. For example, considering the rules `if Ambient is dark then Power is high` and `if Ambient is medium then Power is high`, for any input value of `Ambient` that activates both rules, the fuzzy output of `Power` will have the term `high` activated with the degree from `Rule 1`, and the term `high` activated with the degree from `Rule 2`. Since the term `high` appears twice in the fuzzy output, the role of the accumulation operator will be to accumulate the activation degree of `high` resulting in $\dfrac{(w_1 \oplus w_2) \times z_{high}}{(w_1 \oplus w_2)}$. If another term were activated, the result would be $\dfrac{(w_1 \oplus w_2) \times z_{high} + w_i \times z_j}{(w_1 \oplus w_2) + w_i}$. In version 4.0, the accumulation operator had no effect on the `Weighted[Average|Sum]`.
#### <a name="new-integral">Integral Defuzzifiers</a>
* **(important)** Proper handling of indefinite integral defuzzification, that is, returning `fl::nan` when `[minimum|maximum]=[NaN|Inf]`.
* Default resolution of integration is defined as `static int IntegralDefuzzifier::defaultResolution=200`, and can be changed via `static IntegralDefuzzifier::setDefaultResolution()`.
+ **(important)** In `fuzzylite`, the accumulation operator has been for several versions associated with the output variables and **not** with the rule blocks, despite that the FCL format and other fuzzy logic control libraries associate the accumulation operator with the rule blocks. The argument for such a decision is that `fuzzylite` provides **coherent** support for multiple rule blocks operating on the same engine and on the same output variables. For example, if multiple rule blocks operate on the same output variables, it only makes sense to have a single accumulation operator associated with each output variable such that the defuzzifier can naturally operate over the accumulated fuzzy output. Differently, if the accumulation operator were associated with the rule block, the possibility of having different accumulation operators in different rule blocks questions (1) **the possibility of having multiple rule blocks operating over the same output variables**; and (2) **the usage of different accumulation operators over the accumulation and defuzzification processes**. Certainly, if (1) is not possible, i.e, different rule blocks only operate on different output variables, then (2) is not a problem because the accumulation process and defuzzification of each variable will only have a single accumulation operator. It is therefore that the association of the accumulation operator with the output variable in `fuzzylite` provides a **better design** and an additional feature that allows having multiple rule blocks operating over the same output variables.
* Added copy constructors, assignment operators, move constructors and move operators.
* Added method `Defuzzifier::clone()`.
####<a name="new-imex">Importers and Exporters</a>
* **(EXTREMELY important)** Since terms have a new `height` property, `[Fll|Fis|Fcl]Exporter` exports terms with an additional `scalar` at the end, which indicates the `height` of the term. However, if `height=1.0`, the additional scalar is not exported.
* **(EXTREMELY important)** In `[Fll|Fis|Fcl]Importer`, when importing terms, if there is an additional `scalar` it will be assumed as the `height` of the term. For example, `term: high Gaussian 1.0 0.5 0.75` will create a `Gaussian` term with mean `1.0`, standard deviation `0.5` and height `0.75`. This is **extremely important** because there are some examples from Matlab in `fis` format that append a useless `0.0` to some terms.
* **(EXTREMELY important)** In `FisExporter`, if the Takagi-Sugeno controller has no `activation` or `accumulation` operators (as it should generally be the case), Octave and Matlab will not be able to import the `fis` file. To overcome this issue, you will have to set `ImpMethod="min"` and `AggMethod="max"`, where `ImpMethod` and `AggMethod` are just dummy operators that can be set to any `TNorm` and `SNorm`, respectively.
+ **(important)** Improved compatibility of the exported code obtained with `[Fis|Fcl]Exporter` by exporting the additional features of `fuzzylite` only when these are different from the default operation. For example, the following features will not be exported given their values: `[Input|Output]Variable::enabled = true;`, `OutputVariable::lock-previous = false;`, `OutputVariable::lock-range = false;`, amongst others.
* **(important)** Renamed FLL property `'lock-valid'` to `'lock-previous'`.
* **(important)** Renamed FIS property `'LockValid'` to `'LockPrevious'`.
* **(important)** Renamed FCL property `'LOCK: VALID'` to `'LOCK: PREVIOUS'`.
+ **(important)** Export your controllers to files using `[Fll|Fld|Fis|Fcl]Exporter::toFile()`.
+ **(important)** Import your controllers from files using `[Fll|Fis|Fcl]Importer::fromFile()`.
+ **(important)** `FldExporter` exports the FuzzyLite Dataset of an engine utilizing the input values of another FuzzyLite Dataset.
* `FldExporter` no longer restarts the engine when exporting.
* **(important)** Renamed method `FldExporter::toWriter()` to `FldExporter::write()`.
* Removed variable and methods for property `int FldExporter::_maximum`.
* Added option in `CppExporter` to prepend the namespace prefix `fl::` to the classes, and by default it does not prepend prefix.
* Improvement accuracy of `FisImporter` when importing `fis` files whose scalar values have more than three decimal numbers.
* Renamed methods in `[Fis|Fcl]Importer::extract*` to `[Fis|Fcl]Importer::parse*`.
#### <a name="new-factories">Factories</a>
* Created a generic `CloningFactory<T>` to create clones of objects.
* **(important)** Created `FunctionFactory` based on `CloningFactory<Function::Element>` where function operators and methods are stored to be cloned as necessary by `Function`. Additional functions and operators can be easily registered.
* **(VERY important)** Moved built-in functions and operators from `Function` to `FunctionFactory`.
* Renamed methods `Factory<T>::[register|deregister]Class()` to `Factory<T>::[register|deregister]Constructor()`.
* **(important)** Renamed `Factory<T>` to `ConstructionFactory<T>`.
* Renamed `typedef Factory::Creator` to `typedef Factory::Constructor`.
* Changed pointers of `FactoryManager` to smart pointers (`FL_unique_ptr`).
#### <a name="new-examples">Examples</a>
* **(important)** Added two examples for basic rule chaining: `mamdani/SimpleDimmerInverse.fll` and `mamdani/Laundry.fll`.
* Included the `original` example files in `fis` format.
* Added conversion of `examples/original/*.fis` to `examples/original/*.fll`.
* Modified `original/takagi-sugeno` examples to reflect `activation: none; accumulation: none;`.
* Updated FLD examples produced from the `original` examples.
+ **(important)** Added file [`fuzzylite/src/m/compare.m`](/fuzzylite/src/m/compare.m) <!---check link--> to compare the output values of your `fuzzylite` engines with the evaluation of the same engine in Octave/Matlab.
+ **(important)** Added file [`examples/examples.mat`](/examples/examples.mat) <!---check link--> containing the comparison of the output values between `fuzzylite` and Matlab's Fuzzy Logic Toolbox.
* Added code to perform benchmarks in Linux.
#### <a name="new-console">Console</a>
* **(important)** Console includes option to import custom input dataset from file an export its respective output values.
* **(important)** Created the FuzzyLite Interactive Console, which can be started by specifying an input file and the output format, e.g., `fuzzylite -i SimpleDimmer.fll -of fld`.
* Console provides more information about its usage.
####<a name="new-fixes"> Fixes Bugs and Leaks</a>
+ **(important)** Fixed operation when using multiple hedges to operate from right-most to left-most, e.g. `if Ambient is not very extremely bright` evaluates as follows `not(very(extremely(bright)))`.
* **(important)** Fixed membership functions of specific cases of `Triangle` when `a=b` or `b=c`, and `Trapezoid` when `a=b` or `c=d`.
* Fixed minor memory leak at `~RuleBlock::[conjunction|disjunction|activation]`.
* Fixed minor memory leak at `~Accumulated::accumulation`.
* Fixed minor memory leak at `~OutputVariable::defuzzifier`.
* Fixed minor memory leak at `~Function::Node`.
* Fixed minor memory leak at `~FactoryManager::[factories]`.
* Fixed some rethrowing of exceptions to provide proper information about errors. Specifically, changed some rethrown exceptions from `throw ex;` to just `throw;`
* Fixed building using `-DFL_USE_FLOAT=ON`
***
For more information, visit [www.fuzzylite.com](http://www.fuzzylite.com).
fuzzylite&trade; is a trademark of FuzzyLite Limited.
Copyright &#xa9; 2010-2014 FuzzyLite Limited. All rights reserved.

View File

@ -1,36 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "OutputLVar.h"
namespace fl {
OutputLVar::OutputLVar() : LinguisticVariable(),
_output(new CompoundTerm("output")){
}
OutputLVar::OutputLVar(const std::string& name) : LinguisticVariable(name),
_output(new CompoundTerm("output")) {
}
OutputLVar::~OutputLVar() {
delete _output;
}
CompoundTerm& OutputLVar::output() const {
return *this->_output;
}
}

View File

@ -1,44 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* File: OutputLVar.h
* Author: jcrada
*
* Created on November 1, 2009, 2:30 PM
*/
#ifndef FL_OUTPUTLVAR_H
#define FL_OUTPUTLVAR_H
#include "LinguisticVariable.h"
#include "CompoundTerm.h"
namespace fl {
class OutputLVar : public LinguisticVariable {
private:
CompoundTerm* _output;
public:
OutputLVar();
OutputLVar(const std::string& name);
virtual ~OutputLVar();
virtual CompoundTerm& output() const;
};
}
#endif /* FL_OUTPUTLVAR_H */

454
AI/FuzzyLite/README.md Normal file
View File

@ -0,0 +1,454 @@
fuzzylite &trade; <img src="https://github.com/fuzzylite/fuzzylite/raw/master/fuzzylite.png" align="right" alt="fuzzylite">
===========
A Fuzzy Logic Control Library in C++
------------------------------------
By: [Juan Rada-Vilela](http://www.fuzzylite.com/jcrada), Ph.D.
***
### Table of Contents
[License](#license) &nbsp;
[Introduction](#introduction) &nbsp;
[Features](#features) &nbsp;
[Example](#example) &nbsp;
[What's new](#whatsnew) : [General](#new-general), [Macros](#new-macros), [Operation](#new-operation), [Engine](#new-engine), [Input Variables and Output Variables](#new-inoutvars), [Linguistic Terms](#new-terms), [Linear and Discrete Terms](#new-linear-discrete), [Function Term](#new-function), [[T|S]Norms and Hedges](#new-norms-hedges), [Rules](#new-rules), [Rule Blocks](#new-ruleblocks), [Weighted Defuzzifiers](#new-weighted), [Integral Defuzzifiers](#new-integral), [Importers and Exporters](#new-imex), [Examples](#new-examples), [Console](#new-console), [Fixed Bugs and Leaks](#new-fixes)
[What's next](#whatsnext) &nbsp;
[Migrating to v5.0](#migrating) &nbsp;
[Bulding from source](#building) &nbsp;
[Binaries](#binaries)
### <a name="license">License</a>
`fuzzylite` will **always** be free and open source. However, `fuzzylite` is **no** longer released under the Apache License. Since version 5.0, `fuzzylite` is **dual-licensed** under the [**GNU Lesser General Public License (LGPL) v3.0**](https://www.gnu.org/licenses/lgpl.html) and a **paid commercial license**.
In brief, an important restriction the LGPL imposes on your closed-source application is that **you are no longer allowed to statically link** against `fuzzylite`. If your application requires static linking, **you will need to purchase a commercial license** from FuzzyLite Limited. Please, contact [sales@fuzzylite.com](mailto:sales@fuzzylite.com) for commercial licenses, and refer to the [GNU LGPL](https://www.gnu.org/licenses/lgpl.html) for further information on your rights.
The change of license is an attempt to raise funds in order to be able to work part-time in the development of the `fuzzylite` family of products, namely `fuzzylite` (C++), `jfuzzylite` (Java), `pyfuzzylite` (Python), and `QtFuzzyLite` (Windows/Linux/Mac).
**There are still many things to do!**
Besides [donations](http://www.fuzzylite.com/donations/), you can significantly contribute by **purchasing a license** of the entirely new [`QtFuzzyLite`](http://www.fuzzylite.com/QtFuzzyLite/) commercial application. In addition, if you require (paid) private support, please contact [jcrada@fuzzylite.com](mailto:jcrada@fuzzylite.com).
***
### <a name="introduction">Introduction</a>
`fuzzylite` is a free and open-source fuzzy logic control library programmed in C++ for multiple platforms (Windows, Linux, Mac, iOS). Its goal is to allow you to easily create fuzzy logic controllers in a few steps utilizing object-oriented programming without requiring any third-party libraries.
#### Reference
If you are using `fuzzylite`, please cite the following reference in your article:
Juan Rada-Vilela. fuzzylite: a fuzzy logic control library, 2014. URL http://www.fuzzylite.com.
```bibtex
@misc{fl::fuzzylite,
author={Juan Rada-Vilela},
title={fuzzylite: a fuzzy logic control library},
url={http://www.fuzzylite.com},
year={2014}}
```
***
### <a name="features">Features</a>
**Controllers** *Types* (5) Mamdani, Takagi-Sugeno, Larsen, Tsukamoto, Inverse Tsukamoto
**Linguistic terms** *Basic* (4) triangle, trapezoid, rectangle, discrete. *Extended* (9) bell, cosine, gaussian, gaussian product, pi-shape, sigmoid difference, sigmoid product, spike. *Edges* (4) concave, ramp, sigmoid, s-shape, z-shape. *Functions* (3) constant, linear, function.
**Conjunction and Activation** *T-Norm* (7) minimum, algebraic product, bounded difference, drastic product, einstein product, hamacher product, nilpotent minimum.
**Disjunction and Accumulation** *S-Norm* (8) maximum, algebraic sum, bounded sum, normalized sum, drastic sum, einstein sum, hamacher sum, nilpotent maximum.
**Defuzzifiers** *Integral* (5) centroid, bisector, smallest of maximum, largest of maximum, mean of maximum, *Weighted* (2) weighted average, weighted sum.
**Hedges** *Types* (6) any, not, extremely, seldom, somewhat, very.
**Import** *Types* (3) FuzzyLite Language `fll`, Fuzzy Inference System `fis`, Fuzzy Control Language `fcl`.
**Export** *Types* (6) `C++`, `Java`, FuzzyLite Language `fll`, FuzzyLite Dataset `fld`, Fuzzy Inference System `fis`, Fuzzy Control Language `fcl`.
**Examples** (30+) of Mamdani, Takagi-Sugeno and Tsukamoto controllers from `fuzzylite`, Octave and Matlab, each included in the following formats: `C++`, `Java`, `fll`, `fld`, `fis`, and `fcl`.
***
### <a name="example">Example</a>
```cpp
#include "fl/Headers.h"
int main(int argc, char* argv[]){
using namespace fl;
Engine* engine = new Engine("simple-dimmer");
InputVariable* ambient = new InputVariable;
ambient->setName("Ambient");
ambient->setRange(0.000, 1.000);
ambient->addTerm(new Triangle("DARK", 0.000, 0.500));
ambient->addTerm(new Triangle("MEDIUM", 0.250, 0.750));
ambient->addTerm(new Triangle("BRIGHT", 0.500, 1.000));
engine->addInputVariable(ambient);
OutputVariable* power = new OutputVariable;
power->setName("Power");
power->setRange(0.000, 2.000);
power->setDefaultValue(fl::nan);
power->addTerm(new Triangle("LOW", 0.000, 1.000));
power->addTerm(new Triangle("MEDIUM", 0.500, 1.500));
power->addTerm(new Triangle("HIGH", 1.000, 2.000));
engine->addOutputVariable(power);
RuleBlock* ruleblock = new RuleBlock;
ruleblock->addRule(Rule::parse("if Ambient is DARK then Power is HIGH", engine));
ruleblock->addRule(Rule::parse("if Ambient is MEDIUM then Power is MEDIUM", engine));
ruleblock->addRule(Rule::parse("if Ambient is BRIGHT then Power is LOW", engine));
engine->addRuleBlock(ruleblock);
engine->configure("", "", "Minimum", "Maximum", "Centroid");
std::string status;
if (not engine->isReady(&status))
throw Exception("Engine not ready. "
"The following errors were encountered:\n" + status, FL_AT);
for (int i = 0; i < 50; ++i){
scalar light = ambient->getMinimum() + i * (ambient->range() / 50);
ambient->setInputValue(light);
engine->process();
FL_LOG("Ambient.input = " << Op::str(light) << " -> " <<
"Power.output = " << Op::str(power->getOutputValue()));
}
}
```
***
### <a name="whatsnew">What's New?</a>
The entire `fuzzylite` library has been thoroughly revised, refactored, validated, and significantly improved. The following sections detail the changes and enhancements of version 5.0. Users of previous versions are **strongly** encouraged to carefully read the list before migrating to version 5.0. Important changes and enhancements are marked as **(important)**, **(VERY important)** and **(EXTREMELY important)**.
#### <a name="new-general">General</a>
+ **(important)** `fuzzylite v5.0` is dual-licensed under the [GNU LGPL v3.0](https://www.gnu.org/licenses/lgpl.html) and a paid commercial license.
+ Support for both `C++98` and `C++11` using the latest features.
+ Support for multiple compilers `g++`, `Clang`, `MSVC`.
+ Refactoring of many classes to improve design and performance.
+ **(important)** Performance improvements of Takagi-Sugeno controllers by over 55% with respect to v4.0 (estimate based on the average performance on the examples included).
+ Smart pointers in many classes take care of automatically deleting objects when setting new pointers (`Accumulated`, `FactoryManager`, `Function`, `OutputVariable`, `Rule`, and `RuleBlock`).
* **(important)** Exceptions are thrown when any of the following `RuleBlock::[conjunction|disjunction|activation]`, `Accumulated::accumulation`, and `OutputVariable::defuzzifier` are required but set to `fl::null`, thereby replacing the operations that would lead to `[signal 11] Segmentation fault` to operations that throw a `fl::Exception` instead.
+ Automatic build script to build `fuzzylite` in `debug` and `release` mode.
+ Binaries of debug libraries are renamed to append the letter `d` (e.g.,`fuzzylited.dll`, `libfuzzylited.so`).
+ **(important)** New file [`fuzzylite/src/m/compare.m`](/fuzzylite/src/m/compare.m) <!---check link--> to compare the output values of your `fuzzylite` engines with the evaluation of the same engine in Octave/Matlab.
+ **(important)** There is practically no difference between the output values obtained with `fuzzylite` and those obtained with Octave/Matlab. Based on the examples, the average mean square error (MSE) between the output values is less than `7.3e-12` (or `0.0000000000073`) due to negligible differences in floating-point arithmetic. The results and comparison can be found in [`examples/examples.mat`](/examples/examples.mat) <!---check link-->.
+ **(important)** Source code of applications based on version 4.0 will most likely not compile with version 5.0.
+ Minor bugs and memory leaks fixed.
####<a name="new-macros">Macros</a>
* **(important)** Added support for `C++11` with smart pointers, method identifiers, move constructors and move operators as follows. For precise information, refer to file [`fuzzylite/fl/fuzzylite.h`](/fuzzylite/fl/fuzzylite.h). <!---check link-->
* **(important)** Macros for identifiers are defined as `FL_IOVERRIDE override`, `FL_IFINAL final`, `FL_IDEFAULT = default`, `FL_IDELETE = delete`, `FL_INOEXCEPT noexcept`, `FL_DEFAULT_COPY(Class)`, `FL_DEFAULT_MOVE(Class)`, and `FL_DEFAULT_COPY_AND_MOVE(Class)`.
* **(important)** Added macro `FL_unique_ptr` to refer to `std::auto_ptr` (`C++98`) or `std::unique_ptr` (`C++11`), and its respective `FL_move_ptr(x)` to move a smart pointer, albeit `FL_move_ptr(x)` is not used within the library as it is not needed.
* **(important)** Added global variables `const long fl::null = 0L` to refer to the null pointer in `C++98` and `const std::nullptr_t null = nullptr` to refer to the null pointer in `C++11`.
* **(important)** Renamed macro `FL_DEBUG` to `FL_DBG`.
* **(important)** Renamed macros `FL_BEGIN_DEBUG_BLOCK` and `FL_END_DEBUG_BLOCK` to `FL_DEBUG_BEGIN` and `FL_DEBUG_END`, respectively.
* **(important)** Renamed macro `FL_EXPORT` to `FL_API`
* **(EXTREMELY important)** Added macro definitions `FL_EXPORT_LIBRARY` and `FL_IMPORT_LIBRARY`. If you are building `fuzzylite` as a **shared library**, you need to define `FL_EXPORT_LIBRARY`. If you are building `fuzzylite` **executable** *and* it utilizes the `fuzzylite` **shared library**, you need to define `FL_IMPORT_LIBRARY`. If you are building `fuzzylite` as a **static library** and/or building `fuzzylite` **executable** using the `fuzzylite` **static library**, then you do not need to define either `FL_[IMPORT|EXPORT]_LIBRARY`. Note that the same conditions apply for your application. This is particularly important in Windows platforms, as `FL_IMPORT_LIBRARY` and `FL_EXPORT_LIBRARY` define `FL_API` to `__declspec(dllimport)` and `__declspec(dllexport)`, respectively. If in doubt, please check [`fuzzylite/CMakeLists.txt`](/fuzzylite/CMakeLists.txt)<!---check link-->
#### <a name="new-operation">Operation</a>
* **(important)** Added method `Operation::toScalar(std::string x, scalar alternative) FL_INOEXCEPT` which returns `alternative` if `x` is not a valid `scalar`, and never throws an exception.
* **(important)** Added method `Operation::toScalar(std::string x)` that returns the scalar value of `x` or throws a `fl::Exception` if `x` is not a valid `scalar`.
* **(VERY important)** Marked method (from v4.0) `Operation::toScalar(std::string, bool, scalar) FL_IDELETE;` and removed its implementation such that its usage is prevented at compile time in `C++11` and at linker time in `C++98`. Please, use the appropriate `Op::toScalar` methods mentioned above.
+ Renamed method `Op::isNan` to `Op::isNaN`.
* Added method `fl::Op::isFinite(x)` which returns `not (isNaN(x) or isInf(x))`.
* Changed `fl::Op::isEq(a,b)` to return `true` if `a == b == NaN`.
* Changed `fl::Op::isEq(a,b)` to return `true` if `a == b == Inf`.
* Changes to `fl::Op::isEq` affect other comparison methods `fl::Op::is[Lt|LEq|GEq|Gt]`.
* Added shortcuts of comparisons `fl::Op::[gt,lt,ge,le,eq,neq](scalar a, scalar b)`, mostly to provide binary versions (without `macheps`) for term `Function`.
* Deleted method `Op::repeat`.
* Removed method `fuzzylite::configuration()`.
* Changed default `fuzzylite::_macheps = 1e-6;`.
* Renamed method `Op::makeValidId` to `Op::validName`, which now returns `"unnamed"` for empty strings.
####<a name="new-engine">Engine</a>
* **(VERY important)** Moved `Engine::hedges` (and relevant methods) to `Rule::hedges`.
* Added enumeration for the type of engine: `enum Engine::Type{Mamdani, Larsen, TakagiSugeno, Tsukamoto, InverseTsukamoto, Hybrid, Unknown}`.
* Added method `Type Engine::type(std::string* name, std::string* reason)` to infer the type of the engine based on its configuration, additionally provides the name of the type and the inference reasons for its type.
* **(important)** Changed method `Engine::isReady(std::string)` to satisfy the default operation of controllers. The method `Engine::isReady(std::string)` was initially conceived to provide information before a potential `[signal 11] Segmentation fault` happened due to improper configuration. However, given the improved handling of signals and exceptions mentioned in Section [General](#new-general), using method `Engine::isReady(std::string)` is not necessary except for providing suggestions of what could potentially cause an error.
* Added methods `Engine::set[Input|Output]Variables(std::vector)` and `Engine::setRuleBlocks(std::vector)`.
* Added methods `Engine::[input|output]Variables()` and `Engine::ruleBlocks()` to return mutable references.
* Added method `Engine::variables()` to retrieve a vector (copy) containing the `InputVariables` followed by the `OutputVariables`.
* Added method `Engine::updateReferences()` to update the references to the engine in all the necessary linguistic terms (i.e., `Linear` and `Function`).
* Added method `Engine::clone()`.
* Added copy constructors, assignment operators, and default move constructor to `Engine`.
####<a name="new-inoutvars">Input Variables and Output Variables</a>
* **(important)** Added methods `OutputVariable::[get|set]OutputValue()` to [retrieve|store] value from defuzzification
* **(important)** Changed return type of `scalar OutputVariable::defuzzify()` to `void OutputVariable::defuzzify()` because now it automatically stores the defuzzified output value, and also stores the previous *valid* output value regardless of locks. Like in version 4.0, if `OutputVariable::lockPreviousOutputValue=true`, and the defuzzified output value is not valid (i.e., `[NaN|Inf]`) or no rules were activated, then the defuzzified output value is replaced for the previous valid output value.
* Removed method `OutputVariable::defuzzifyNoLocks()`.
* Renamed variable `OutputVariable::lastValidOutputValue` to `OutputVariable::previousOutputValue`.
* **(important)** Renamed method `OutputVariable::[get|set]LastValidOutput()` to `OutputVariable::[get|set]PreviousOutputValue()`.
* Renamed variable `OutputVariable::lockValidOutput` to `OutputVariable::lockPreviousOutputValue`.
* **(important)** Renamed method `OutputVariable::setLockValidOutput()` to `OutputVariable::setLockPreviousOutputValue()`.
* **(important)** Renamed method `OutputVariable::isLockingValidOutput()` to `OutputVariable::isLockedPreviousOutputValue()`.
* Renamed variable `OutputVariable::lockOutputRange` to `OutputVariable::lockOutputValueInRange`.
* **(important)** Renamed method `OutputVariable::setLockOutputRange()` to `OutputVariable::setLockOutputValueInRange()`.
* **(important)** Renamed method `OutputVariable::isLockingOutputRange()` to `OutputVariable::isLockedOutputValueInRange()`.
* Added methods `std::string InputVariable::fuzzyInputValue()` and `std::string OutputVariable::fuzzyOutputValue()`.
* Added method `OutputVariable::clear()` to clear the fuzzy output, and set `OutputVariable::previousOutputValue = fl::nan` and set `OutputVariable::outputValue = fl::nan`.
* Added copy constructors, assignment operators, move constructors and move operators to [Input|Output]Variable.
* Added method `Variable::terms()` to return mutable reference.
* **(important)** Changed `OutputVariable::[defuzzifier|fuzzyOutput]` to smart pointers (`FL_unique_ptr`).
#### <a name="new-terms">Linguistic Terms</a>
* **(VERY important)** Added Term::[get|set]Height to define the height of *integral* terms, and multiply their respective membership functions accordingly.
* Added copy constructors, assignment operators, move constructors and move operators to every `Term`.
* **(VERY important)** Parameters of all terms are set by default to `fl::nan`.
* **(important)** Renamed method `Term::copy()` to `Term::clone()` in every `Term`.
* Added method `Term::updateReference(Term*, Engine*)` to ensure `Linear` and `Function` terms have updated pointers to the `Engine` (useful when cloning and copy-constructing).
+ **(important)** Added linguistic terms `Concave`, `Cosine` and `Spike`.
* **(important)** Changed `Accumulated` to take `Activated*` terms instead of `const Terms*`.
* Removed `const` from return type of method `SNorm* Accumulated::[get|set]Accumulation()`.
* Changed `Accumulated::accumulation` to a smart pointer (`FL_unique_ptr`).
* Added method `Accumulated::terms()` to return mutable reference.
* **(important)** Renamed methods `Triangle::[set|get][A|B|C]` to `::[set|get]Vertex[A|B|C]`.
* **(important)** Renamed methods `Trapezoid::[set|get][A|B|C|D]` to `::[set|get]Vertex[A|B|C|D]`.
* **(important)** Renamed term `Thresholded` to `Activated`.
* **(important)** Renamed methods `Thresholded::[set|get]Threshold()` to `Activated::[set|get]Degree()`.
* Added enumeration `[Ramp|Sigmoid]::Direction{ NEGATIVE, ZERO, POSITIVE }` to refer to the slope.
* Added methods `Ramp::direction()` and `Sigmoid::direction()` to retrieve direction of slope.
* Removed Exception Specification from methods in `Discrete`, `Linear` and `Function` terms.
#### <a name="new-linear-discrete">Linear and Discrete Terms</a>
* **(important)** Changed `Linear` from having pointers to the input variables to having a pointer to the `Engine`.
* Changed visibility of `Linear::coefficients` to `protected`.
* **(important)** Added methods `Linear::coefficients()`, `Linear::setCoefficients()`.
* `Linear` term no longer throws exception when `inputVariables != |coefficients|`.
* **(important)** Removed public vector of variables `Discrete::[x|y]`.
* **(important)** Added a `typedef std::pair<scalar, scalar> Discrete::Pair`.
* **(important)** Changed representation of `Discrete::[x|y]` from `std::vector<scalar>` to `std::vector<Discrete::Pair>`.
* Added methods `Discrete::setXY()` and `Discrete::xy()` to set and get the new representation of pairs.
* Added methods `Discrete::xy(int index)` to retrieve `Discrete::Pair` at `index`.
* **(important)** Added methods `Discrete::toPairs(std::vector<scalar>)` which throws an exception if the vector is missing a value (i.e., `std::vector<scalar>.size() % 2 != 0`), and `Discrete::toPairs(std::vector<scalar>, scalar missingValue)` which adds `missingValue` in case `std::vector<scalar>.size() %2 == 1`, hence never throwing an exception.
* Added method `Discrete::toVector(std::vector<Discrete::Pair>)` to convert `std::vector<Discrete::Pair>` to a `std::vector<scalar>`.
* Added method `Discrete::formatXY()` to get pairs `(x,y)` nicely formatted.
####<a name="new-function">Function Term</a>
* **(important)** Merged structs `Function::Operator` and `Function::BuiltInFunction` into a single `struct Function::Element`.
* **(EXTREMELY important)** Changed the precedence of all built-in instances of `Function::Element` of type `Operator` starting from `100` and decreasing by `10`. The precedence of built-in operators is the following: `(100)` Logical not `[!]` and Negation `[~]`; `(90)` Power `[^]`; `(80)` Multiplication `[*]`, Division `[/]` and Modulo `[%]`; `(70)` Addition `[+]` and Subtraction `[-]`; `(60)` Logical AND `[and]` and Logical OR `[or]`. If you have registered your own operators, please adjust their precedence as required.
* Added to `Function` built-in comparison functions `gt,lt,ge,le,eq` and operator logical not `!`.
* Modified typedefs `Function::Unary` and `Function::Binary` to take `scalar` instead of `double`.
* Changed `public Function::root` to `protected Function::_root` and it is now a smart pointer (`FL_unique_ptr`).
* Added method `Function::root()` to return pointer to `Function::root`.
* **(EXTREMELY important)** Moved built-in functions and operators from `Function` to a `FunctionFactory`.
#### <a name="new-norms-hedges">[T|S]Norms and Hedges</a>
+ **(important)** Fixed operation when using multiple hedges to operate from right-most to left-most, e.g. `if Ambient is not very extremely bright`, now evaluates as follows `not(very(extremely(bright)))`.
+ Added `TNorm` nilpotent minimum and `SNorm` nilpotent maximum.
* Added clone methods to every `Norm`.
* Added clone methods to every `Hedge`.
* **(VERY important)** Moved `Engine::hedges` to `Rule::hedges`.
#### <a name="new-rules">Rules</a>
* **(VERY important)** Moved `Engine::hedges` (and methods) to `Rule::hedges`.
* Added method `Rule::isLoaded()` to determine whether a rule was properly parsed and thus can be activated.
* Added method `Rule::unload()` to allow the existence of a rule in an inactive state (useful for invalid rules).
* **(important)** Removed variable `Rule::FL_ASSIGNS` and method `Rule::assignsKeyword()`, for which the symbol `=` in rules is no longer valid.
* Changed visibility of method `Rule::setText()` to `public`.
* Added method `Rule::load(const Engine*)`.
* Changed `Rule::[antecedent|consequent]` to smart pointers (`FL_unique_ptr`).
* **(important)** Renamed method `Antecedent::[get|set]Root()` to `Antecedent::[get|set]Expression()`.
* Added methods `[Antecedent|Consequent]::[get|set]Text()`.
* **(important)** Added methods `[Antecedent|Consequent]::[load|unload]()`, with the same objective as `Rule::[load|unload]()`.
#### <a name="new-ruleblocks">Rule Blocks</a>
* Added method `RuleBlock::reloadRules()`.
* Added method `RuleBlock::setRules(std::vector)`.
* Added method `RuleBlock::rules()` to return mutable reference.
* Removed `const` from `TNorm` and `SNorm` in `RuleBlock::[get|set][Conjunction|Disjunction|Activation]()`, respectively.
* Changed `RuleBlock::[conjunction|disjunction|activation]` to smart pointers (`FL_unique_ptr`).
* **(VERY important)** Added basic rule chaining such that an `OutputVariable` can be utilized in the `Antecedent` of a `Rule`. For example, considering the rule `if Power is high then InversePower is low`, where `Power` and `InversePower` are both output variables, the activation degree of the `Antecedent` will correspond to the accumulated activation degree of the term `high` in the fuzzy output of `Power`. If `Power::accumulation = none`, the accumulated activation degree of the term `high` will be computed as the regular sum of the activation degrees of term `high` in the fuzzy output of `Power`. Otherwise, the accumulated activation degree is computed utilizing the `Power::accumulation` operator.
#### <a name="new-weighted">Weighted Defuzzifiers</a>
+ **(VERY important)** Performance improvements of Takagi-Sugeno controllers by over 55% (with respect to v4.0) based on the average performance on the examples included.
* **(important)** Created class `WeightedDefuzzifier` from which classes `Weighted[Average|Sum]` are derived.
* **(important)** Added enumeration `WeightedDefuzzifier::Type{Automatic, TakagiSugeno, Tsukamoto}` and respective methods `WeightedDefuzzifier::[get|set]Type()` and `WeightedDefuzzifer::getTypeName()`.
* Added method `WeightedDefuzzifier::inferType(Term*)` to automatically determine the `WeightedDefuzzifier::Type` based on the class of `Term`.
* **(important)** By default, `WeightedDefuzzifier::type = Automatic`, which automatically infers the type based on the `WeightedDefuzzifier::inferType()`.
* **(important)** There is a small performance penalty when using `WeightedDefuzzifier::type = Automatic` because `WeightedDefuzzifier::inferType()` performs three `dynamic_cast<>`.
* **(important)** Deleted class `Tsukamoto`. Its method `static tsukamoto()` was moved to `virtual WeightedDefuzzifier::tsukamoto()`, which allows to be overriden
* Added support for `Tsukamoto` with `Concave` terms.
+ **(EXTREMELY important)** In version 5.0, the traditional operation of Takagi-Sugeno and Tsukamoto controllers is achieved by setting `OutputVariable::accumulation = none`. Unlike version 4.0, the `RuleBlock::activation` will not have any effect on Takagi-Sugeno nor Tsukamoto controllers, for which `RuleBlock::activation` should also be set to `none`. More information about the roles of the `OutputVariable::accumulation` and `RuleBlock::activation` operators are detailed as follows. Refer to [sciweavers](http://www.sciweavers.org/free-online-latex-equation-editor) to convert LaTeX equations.
+ **(VERY important)** In version 5.0, the role of the `RuleBlock::activation` `TNorm` on the `Weighted[Average|Sum]` always performs a regular multiplication of the weights and the values (i.e., $w_i \times z_j$) regardless of the `TNorm` chosen. In other words, selecting any `RuleBlock::activation` for `Weighted[Average|Sum]` is irrelevant, and should be set to `none` as every `TNorm` will have the same multiplication effect. This operation is different from `fuzzylite` version 4.0, where the `RuleBlock::activation` operator was utilized to multiply the weights and values (i.e. $w_i \otimes z_j$), and therefore the traditional operation of the `Weighted[Average|Sum]` was achieved when `RuleBlock::activation = AlgebraicProduct;`.
+ **(VERY important)** In version 5.0, the role of the `OutputVariable::accumulation = none` on the `Weighted[Average|Sum]` results in a regular sum of the multiplied weights and values, i.e., $\dfrac{\sum_i^n w_i \times z_j}{\sum_i^n w_i}$. However, if the `OutputVariable::accumulation != none`, the role of the `SNorm` will be to accumulate the activation degrees of the *repeated* terms in the fuzzy output of the variable. For example, considering the rules `if Ambient is dark then Power is high` and `if Ambient is medium then Power is high`, for any input value of `Ambient` that activates both rules, the fuzzy output of `Power` will have the term `high` activated with the degree from `Rule 1`, and the term `high` activated with the degree from `Rule 2`. Since the term `high` appears twice in the fuzzy output, the role of the accumulation operator will be to accumulate the activation degree of `high` resulting in $\dfrac{(w_1 \oplus w_2) \times z_{high}}{(w_1 \oplus w_2)}$. If another term were activated, the result would be $\dfrac{(w_1 \oplus w_2) \times z_{high} + w_i \times z_j}{(w_1 \oplus w_2) + w_i}$. In version 4.0, the accumulation operator had no effect on the `Weighted[Average|Sum]`.
#### <a name="new-integral">Integral Defuzzifiers</a>
* **(important)** Proper handling of indefinite integral defuzzification, that is, returning `fl::nan` when `[minimum|maximum]=[NaN|Inf]`.
* Default resolution of integration is defined as `static int IntegralDefuzzifier::defaultResolution=200`, and can be changed via `static IntegralDefuzzifier::setDefaultResolution()`.
+ **(important)** In `fuzzylite`, the accumulation operator has been for several versions associated with the output variables and **not** with the rule blocks, despite that the FCL format and other fuzzy logic control libraries associate the accumulation operator with the rule blocks. The argument for such a decision is that `fuzzylite` provides **coherent** support for multiple rule blocks operating on the same engine and on the same output variables. For example, if multiple rule blocks operate on the same output variables, it only makes sense to have a single accumulation operator associated with each output variable such that the defuzzifier can naturally operate over the accumulated fuzzy output. Differently, if the accumulation operator were associated with the rule block, the possibility of having different accumulation operators in different rule blocks questions (1) **the possibility of having multiple rule blocks operating over the same output variables**; and (2) **the usage of different accumulation operators over the accumulation and defuzzification processes**. Certainly, if (1) is not possible, i.e, different rule blocks only operate on different output variables, then (2) is not a problem because the accumulation process and defuzzification of each variable will only have a single accumulation operator. It is therefore that the association of the accumulation operator with the output variable in `fuzzylite` provides a **better design** and an additional feature that allows having multiple rule blocks operating over the same output variables.
* Added copy constructors, assignment operators, move constructors and move operators.
* Added method `Defuzzifier::clone()`.
####<a name="new-imex">Importers and Exporters</a>
* **(EXTREMELY important)** Since terms have a new `height` property, `[Fll|Fis|Fcl]Exporter` exports terms with an additional `scalar` at the end, which indicates the `height` of the term. However, if `height=1.0`, the additional scalar is not exported.
* **(EXTREMELY important)** In `[Fll|Fis|Fcl]Importer`, when importing terms, if there is an additional `scalar` it will be assumed as the `height` of the term. For example, `term: high Gaussian 1.0 0.5 0.75` will create a `Gaussian` term with mean `1.0`, standard deviation `0.5` and height `0.75`. This is **extremely important** because there are some examples from Matlab in `fis` format that append a useless `0.0` to some terms.
* **(EXTREMELY important)** In `FisExporter`, if the Takagi-Sugeno controller has no `activation` or `accumulation` operators (as it should generally be the case), Octave and Matlab will not be able to import the `fis` file. To overcome this issue, you will have to set `ImpMethod="min"` and `AggMethod="max"`, where `ImpMethod` and `AggMethod` are just dummy operators that can be set to any `TNorm` and `SNorm`, respectively.
+ **(important)** Improved compatibility of the exported code obtained with `[Fis|Fcl]Exporter` by exporting the additional features of `fuzzylite` only when these are different from the default operation. For example, the following features will not be exported given their values: `[Input|Output]Variable::enabled = true;`, `OutputVariable::lock-previous = false;`, `OutputVariable::lock-range = false;`, amongst others.
* **(important)** Renamed FLL property `'lock-valid'` to `'lock-previous'`.
* **(important)** Renamed FIS property `'LockValid'` to `'LockPrevious'`.
* **(important)** Renamed FCL property `'LOCK: VALID'` to `'LOCK: PREVIOUS'`.
+ **(important)** Export your controllers to files using `[Fll|Fld|Fis|Fcl]Exporter::toFile()`.
+ **(important)** Import your controllers from files using `[Fll|Fis|Fcl]Importer::fromFile()`.
+ **(important)** `FldExporter` exports the FuzzyLite Dataset of an engine utilizing the input values of another FuzzyLite Dataset.
* `FldExporter` no longer restarts the engine when exporting.
* **(important)** Renamed method `FldExporter::toWriter()` to `FldExporter::write()`.
* Removed variable and methods for property `int FldExporter::_maximum`.
* Added option in `CppExporter` to prepend the namespace prefix `fl::` to the classes, and by default it does not prepend prefix.
* Improvement accuracy of `FisImporter` when importing `fis` files whose scalar values have more than three decimal numbers.
* Renamed methods in `[Fis|Fcl]Importer::extract*` to `[Fis|Fcl]Importer::parse*`.
#### <a name="new-factories">Factories</a>
* Created a generic `CloningFactory<T>` to create clones of objects.
* **(important)** Created `FunctionFactory` based on `CloningFactory<Function::Element>` where function operators and methods are stored to be cloned as necessary by `Function`. Additional functions and operators can be easily registered.
* **(VERY important)** Moved built-in functions and operators from `Function` to `FunctionFactory`.
* Renamed methods `Factory<T>::[register|deregister]Class()` to `Factory<T>::[register|deregister]Constructor()`.
* **(important)** Renamed `Factory<T>` to `ConstructionFactory<T>`.
* Renamed `typedef Factory::Creator` to `typedef Factory::Constructor`.
* Changed pointers of `FactoryManager` to smart pointers (`FL_unique_ptr`).
#### <a name="new-examples">Examples</a>
* **(important)** Added two examples for basic rule chaining: `mamdani/SimpleDimmerInverse.fll` and `mamdani/Laundry.fll`.
* Included the `original` example files in `fis` format.
* Added conversion of `examples/original/*.fis` to `examples/original/*.fll`.
* Modified `original/takagi-sugeno` examples to reflect `activation: none; accumulation: none;`.
* Updated FLD examples produced from the `original` examples.
+ **(important)** Added file [`fuzzylite/src/m/compare.m`](/fuzzylite/src/m/compare.m) <!---check link--> to compare the output values of your `fuzzylite` engines with the evaluation of the same engine in Octave/Matlab.
+ **(important)** Added file [`examples/examples.mat`](/examples/examples.mat) <!---check link--> containing the comparison of the output values between `fuzzylite` and Matlab's Fuzzy Logic Toolbox.
* Added code to perform benchmarks in Linux.
#### <a name="new-console">Console</a>
* **(important)** Console includes option to import custom input dataset from file an export its respective output values.
* **(important)** Created the FuzzyLite Interactive Console, which can be started by specifying an input file and the output format, e.g., `fuzzylite -i SimpleDimmer.fll -of fld`.
* Console provides more information about its usage.
####<a name="new-fixes"> Fixes Bugs and Leaks</a>
+ **(important)** Fixed operation when using multiple hedges to operate from right-most to left-most, e.g. `if Ambient is not very extremely bright` evaluates as follows `not(very(extremely(bright)))`.
* **(important)** Fixed membership functions of specific cases of `Triangle` when `a=b` or `b=c`, and `Trapezoid` when `a=b` or `c=d`.
* Fixed minor memory leak at `~RuleBlock::[conjunction|disjunction|activation]`.
* Fixed minor memory leak at `~Accumulated::accumulation`.
* Fixed minor memory leak at `~OutputVariable::defuzzifier`.
* Fixed minor memory leak at `~Function::Node`.
* Fixed minor memory leak at `~FactoryManager::[factories]`.
* Fixed some rethrowing of exceptions to provide proper information about errors. Specifically, changed some rethrown exceptions from `throw ex;` to just `throw;`
* Fixed building using `-DFL_USE_FLOAT=ON`
***
### <a name="whatsnext">What's Next?</a>
+ Source code documentation
+ Type-2 Fuzzy Logic Controllers
+ Adaptive Neuro-Fuzzy Inference System (ANFIS)
+ Fuzzy C-means data clustering
***
### <a name="building">Building from Source</a>
Building from source requires you to have CMake installed.
The files [`fuzzylite/build.bat`](/fuzzylite/build.bat) and [`fuzzylite/build.sh`](/fuzzylite/build.sh) are automatic build scripts for Windows and Unix platforms, respectively. The usage of these scripts is presented as follows.
#### Windows
```bash
> build.bat help
Usage: build.bat [options]
where [options] can be any of the following:
all builds fuzzylite in debug and release mode (default)
debug builds fuzzylite in debug mode
release builds fuzzylite in release mode
clean erases previous builds
help shows this information
```
#### Unix
```bash
$ ./build.sh help
Usage: [bash] ./build.sh [options]
where [options] can be any of the following:
all builds fuzzylite in debug and release mode (default)
debug builds fuzzylite in debug mode
release builds fuzzylite in release mode
clean erases previous builds
help shows this information
```
**(important)** After executing the building script, the binaries will be built and stored in the sub-folders `release/bin` and `debug/bin`.
#### Advanced Building Options
For more advanced building options, please check the contents of [`fuzzylite/build.bat`](/fuzzylite/build.bat) or [`fuzzylite/build.sh`](/fuzzylite/build.sh), and the contents of [`fuzzylite/CMakeLists.txt`](/fuzzylite/CMakeLists.txt).
The following building options are available:
`-DFL_USE_FLOAT=ON` builds the binaries using `typedef float fl::scalar` instead of `typedef double fl::scalar` (default is OFF, i.e., double is used)
`-DFL_BACKTRACE=OFF` disables the backtrace information in case of errors (default in Unix platforms is ON, and in Windows platforms is OFF). In Windows, the backtrace information requires the library `dbghelp`, which should be available in your system.
`-DFL_CPP11=ON` builds `fuzzylite` utilizing `C++11` features (default is OFF, i.e., `C++98`)
`-DCMAKE_BUILD_TYPE=[Debug|Release]` sets the mode of your build. You can only build one mode at a time with a single CMake script.
***
### <a name="binaries">Binaries</a>
After building from source, the following are the relevant binaries that will be created in `release` mode. In `debug` mode, binaries will append a `d` at the end of the name (e.g., `fuzzylited.dll`).
#### Windows
- console application: `fuzzylite.exe`
- shared library: `fuzzylite.dll`, `fuzzylite.lib`
- static library: `fuzzylite-static.lib`
#### Linux
- console application: `fuzzylite`
- shared library: `libfuzzylite.so`
- static library: `libfuzzylite.a`
#### Mac
- console application: `fuzzylite`
- shared library: `libfuzzylite.dylib`
- static library: `libfuzzylite.a`
The console application of `fuzzylite` allows you to import and export your controllers. Its usage can be obtained executing the console binary. In addition, the FuzzyLite Interactive Console is activated when exporting to `fld` without providing an output file. The interactive console allows you to evaluate any controller by manually providing the input the values.
***
For more information, visit [www.fuzzylite.com](http://www.fuzzylite.com).
fuzzylite&trade; is a trademark of FuzzyLite Limited.
Copyright &#xa9; 2010-2014 FuzzyLite Limited. All rights reserved.

View File

@ -1,69 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* RectangularTerm.cpp
*
* Created on: Jan 7, 2010
* Author: jcrada
*/
#include "RectangularTerm.h"
namespace fl {
RectangularTerm::RectangularTerm() :
LinguisticTerm() {
}
RectangularTerm::RectangularTerm(const std::string& name, flScalar minimum,
flScalar maximum) :
LinguisticTerm(name, minimum, maximum) {
}
RectangularTerm::RectangularTerm(const FuzzyOperator& fuzzy_op,
const std::string& name, flScalar minimum, flScalar maximum) :
LinguisticTerm(fuzzy_op, name, minimum, maximum) {
}
RectangularTerm::~RectangularTerm() {
}
RectangularTerm* RectangularTerm::clone() const {
return new RectangularTerm(*this);
}
flScalar RectangularTerm::membership(flScalar crisp) const {
if (crisp > maximum() || crisp < minimum()) {
return flScalar(0.0);
}
return fuzzyOperator().modulation().execute(1.0, modulation());
}
LinguisticTerm::eMembershipFunction RectangularTerm::type() const {
return MF_RECTANGULAR;
}
std::string RectangularTerm::toString() const {
std::stringstream ss;
ss << LinguisticTerm::toString();
ss << "Rectangular (" << minimum() << " " << maximum() << ")";
return ss.str();
}
} // namespace fl

View File

@ -1,49 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* RectangularTerm.h
*
* Created on: Jan 7, 2010
* Author: jcrada
*/
#ifndef FL_RECTANGULARTERM_H_
#define FL_RECTANGULARTERM_H_
#include "LinguisticTerm.h"
namespace fl {
class RectangularTerm : public LinguisticTerm {
public:
RectangularTerm();
RectangularTerm(const std::string& name, flScalar minimum = -INFINITY,
flScalar maximum = INFINITY);
RectangularTerm(const FuzzyOperator& fuzzy_op, const std::string& name,
flScalar minimum = -INFINITY, flScalar maximum = INFINITY);
virtual ~RectangularTerm();
virtual RectangularTerm* clone() const;
virtual flScalar membership(flScalar crisp) const;
virtual eMembershipFunction type() const;
virtual std::string toString() const;
};
} // namespace fl
#endif /* FL_RECTANGULARTERM_H_ */

View File

@ -1,94 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "RuleBlock.h"
#include "FuzzyRule.h"
#include <iosfwd>
namespace fl {
RuleBlock::RuleBlock(const std::string& name)
: _name(name) {
setFuzzyOperator(FuzzyOperator::DefaultFuzzyOperator());
}
RuleBlock::RuleBlock(const std::string& name, const FuzzyOperator& fuzzy_operator)
: _name(name), _fuzzy_operator(&fuzzy_operator) {
}
RuleBlock::~RuleBlock() {
reset();
}
void RuleBlock::setName(const std::string& name) {
this->_name = name;
}
std::string RuleBlock::name() const {
return this->_name;
}
FuzzyRule* RuleBlock::rule(int index) const {
return this->_rules[index];
}
void RuleBlock::addRule(FuzzyRule* rule) {
this->_rules.push_back(rule);
}
FuzzyRule* RuleBlock::removeRule(int index) {
FuzzyRule* result = rule(index);
this->_rules.erase(this->_rules.begin() + index);
return result;
}
int RuleBlock::numberOfRules() const {
return this->_rules.size();
}
const FuzzyOperator& RuleBlock::fuzzyOperator() const {
return *this->_fuzzy_operator;
}
void RuleBlock::setFuzzyOperator(const FuzzyOperator& fuzzy_op) {
this->_fuzzy_operator = &fuzzy_op;
for (int i = 0; i < numberOfRules(); ++i) {
rule(i)->setFuzzyOperator(fuzzy_op);
}
}
void RuleBlock::fireRules() {
for (int i = 0; i < numberOfRules(); ++i) {
rule(i)->fire(rule(i)->firingStrength());
}
}
void RuleBlock::reset() {
for (int i = numberOfRules() - 1; i >= 0; --i) {
delete removeRule(i);
}
}
std::string RuleBlock::toString() const{
std::stringstream ss;
ss << "RULEBLOCK " << name() << "\n";
for (int i = 0 ; i < numberOfRules() ; ++i){
ss << " RULE " << i + 1 << ": " << rule(i)->toString() << ";\n";
}
ss << "END_RULEBLOCK";
return ss.str();
}
}

View File

@ -1,61 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* RuleBlock.h
*
* Created on: Jan 2, 2010
* Author: jcrada
*/
#ifndef FL_RULEBLOCK_H_
#define FL_RULEBLOCK_H_
#include "FuzzyOperator.h"
#include <vector>
#include <string>
namespace fl {
class FuzzyRule;
class RuleBlock {
private:
std::string _name;
const FuzzyOperator* _fuzzy_operator;
std::vector<FuzzyRule*> _rules;
public:
RuleBlock(const std::string& name = "");
RuleBlock(const std::string& name, const FuzzyOperator& fuzzy_operator);
virtual ~RuleBlock();
virtual void setName(const std::string& name);
virtual std::string name() const;
virtual FuzzyRule* rule(int index) const;
virtual void addRule(FuzzyRule* rule);
virtual FuzzyRule* removeRule(int index);
virtual int numberOfRules() const;
virtual const FuzzyOperator& fuzzyOperator() const;
virtual void setFuzzyOperator(const FuzzyOperator& fuzzy_op);
virtual void fireRules();
virtual void reset();
virtual std::string toString() const;
};
} // namespace fl
#endif /* FL_RULEBLOCK_H_ */

View File

@ -1,133 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* ShoulderTerm.cpp
*
* Created on: Dec 13, 2009
* Author: jcrada
*/
#include "ShoulderTerm.h"
namespace fl {
ShoulderTerm::ShoulderTerm() :
LinguisticTerm(), _left(true) {
}
ShoulderTerm::ShoulderTerm(const std::string& name, flScalar minimum,
flScalar maximum, bool left) :
LinguisticTerm(name, minimum, maximum), _left(left) {
}
ShoulderTerm::ShoulderTerm(const FuzzyOperator& fuzzy_op, const std::string& name,
flScalar minimum, flScalar maximum, bool left) :
LinguisticTerm(fuzzy_op, name, minimum, maximum), _left(left) {
}
ShoulderTerm::~ShoulderTerm() {
}
void ShoulderTerm::setLeft(bool left) {
this->_left = left;
}
bool ShoulderTerm::isLeft() const {
return this->_left;
}
void ShoulderTerm::setRight(bool right) {
this->_left = !right;
}
bool ShoulderTerm::isRight() const {
return !this->_left;
}
ShoulderTerm* ShoulderTerm::clone() const {
return new ShoulderTerm(*this);
}
flScalar ShoulderTerm::membership(flScalar crisp) const {
if (isLeft()) {
if (crisp < minimum())
return flScalar(1.0);
if (crisp > maximum())
return flScalar(0.0);
return FuzzyOperation::Scale(minimum(), maximum(), crisp, 1, 0);
} else {
if (crisp < minimum())
return flScalar(0.0);
if (crisp > maximum())
return flScalar(1.0);
return FuzzyOperation::Scale(minimum(), maximum(), crisp, 0, 1);
}
}
LinguisticTerm::eMembershipFunction ShoulderTerm::type() const {
return MF_SHOULDER;
}
std::string ShoulderTerm::toString() const {
std::stringstream ss;
ss << LinguisticTerm::toString();
ss << "Shoulder " << (isLeft() ? "left" : "right") << "(" << minimum() << " " << maximum() << ")";
return ss.str();
}
//**********Right and left...
RightShoulderTerm::RightShoulderTerm() : ShoulderTerm() {
setRight(true);
}
RightShoulderTerm::RightShoulderTerm(const std::string& name, flScalar minimum, flScalar maximum)
: ShoulderTerm(name, minimum, maximum) {
setRight(true);
}
RightShoulderTerm::RightShoulderTerm(const FuzzyOperator& fuzzy_op, const std::string& name, flScalar minimum, flScalar maximum)
: ShoulderTerm(fuzzy_op, name, minimum, maximum) {
setRight(true);
}
RightShoulderTerm::~RightShoulderTerm() {
}
LeftShoulderTerm::LeftShoulderTerm() : ShoulderTerm() {
setLeft(true);
}
LeftShoulderTerm::LeftShoulderTerm(const std::string& name, flScalar minimum, flScalar maximum)
: ShoulderTerm(name, minimum, maximum) {
setLeft(true);
}
LeftShoulderTerm::LeftShoulderTerm(const FuzzyOperator& fuzzy_op, const std::string& name, flScalar minimum, flScalar maximum)
: ShoulderTerm(fuzzy_op, name, minimum, maximum) {
setLeft(true);
}
LeftShoulderTerm::~LeftShoulderTerm() {
}
} // namespace fuzzy_lite

View File

@ -1,77 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* ShoulderTerm.h
*
* Created on: Dec 13, 2009
* Author: jcrada
*/
#ifndef FL_SHOULDERTERM_H_
#define FL_SHOULDERTERM_H_
#include "LinguisticTerm.h"
#include <math.h>
namespace fl {
class ShoulderTerm : public LinguisticTerm {
private:
bool _left;
public:
ShoulderTerm();
ShoulderTerm(const std::string& name, flScalar minimum = -INFINITY,
flScalar maximum = INFINITY, bool left = true);
ShoulderTerm(const FuzzyOperator& fuzzy_op, const std::string& name,
flScalar minimum = -INFINITY, flScalar maximum = INFINITY, bool left = true);
virtual ~ShoulderTerm();
virtual void setLeft(bool left);
virtual bool isLeft() const;
virtual void setRight(bool right);
virtual bool isRight() const;
virtual ShoulderTerm* clone() const;
virtual flScalar membership(flScalar crisp) const;
virtual eMembershipFunction type() const;
virtual std::string toString() const;
};
class RightShoulderTerm : public ShoulderTerm{
public:
RightShoulderTerm();
RightShoulderTerm(const std::string& name, flScalar minimum = -INFINITY,
flScalar maximum = INFINITY);
RightShoulderTerm(const FuzzyOperator& fuzzy_op, const std::string& name,
flScalar minimum = -INFINITY, flScalar maximum = INFINITY);
virtual ~RightShoulderTerm();
};
class LeftShoulderTerm : public ShoulderTerm{
public:
LeftShoulderTerm();
LeftShoulderTerm(const std::string& name, flScalar minimum = -INFINITY,
flScalar maximum = INFINITY);
LeftShoulderTerm(const FuzzyOperator& fuzzy_op, const std::string& name,
flScalar minimum = -INFINITY, flScalar maximum = INFINITY);
virtual ~LeftShoulderTerm();
};
} // namespace fuzzy_lite
#endif /* FL_SHOULDERTERM_H_ */

View File

@ -1,77 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* SingletonTerm.cpp
*
* Created on: Jan 7, 2010
* Author: jcrada
*/
#include "SingletonTerm.h"
namespace fl {
SingletonTerm::SingletonTerm() :
LinguisticTerm() {
}
SingletonTerm::SingletonTerm(const std::string& name, flScalar value) :
LinguisticTerm(name, value - 5 * FL_EPSILON, value + 5 * FL_EPSILON), _value(value) {
}
SingletonTerm::SingletonTerm(const FuzzyOperator& fuzzy_op, const std::string& name,
flScalar value) :
LinguisticTerm(fuzzy_op, name, value - 5 * FL_EPSILON, value + 5 * FL_EPSILON), _value(
value) {
}
SingletonTerm::~SingletonTerm() {
}
void SingletonTerm::setValue(flScalar value) {
this->_value = value;
setMinimum(value - 5 * FL_EPSILON);
setMaximum(value + 5 * FL_EPSILON);
}
flScalar SingletonTerm::value() const {
return this->_value;
}
SingletonTerm* SingletonTerm::clone() const {
return new SingletonTerm(*this);
}
flScalar SingletonTerm::membership(flScalar crisp) const {
return fuzzyOperator().modulation().execute(modulation(), FuzzyOperation::IsEq(crisp, value())
? flScalar(1.0) : flScalar(0.0));
}
LinguisticTerm::eMembershipFunction SingletonTerm::type() const {
return MF_SINGLETON;
}
std::string SingletonTerm::toString() const {
std::stringstream ss;
ss << LinguisticTerm::toString();
ss << "Singleton (" << value() << ")";
return ss.str();
}
} // namespace fl

View File

@ -1,52 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* SingletonTerm.h
*
* Created on: Jan 7, 2010
* Author: jcrada
*/
#ifndef FL_SINGLETONTERM_H_
#define FL_SINGLETONTERM_H_
#include "LinguisticTerm.h"
namespace fl {
class SingletonTerm : public LinguisticTerm {
private:
flScalar _value;
public:
SingletonTerm();
SingletonTerm(const std::string& name, flScalar value = NAN);
SingletonTerm(const FuzzyOperator& fuzzy_op, const std::string& name,
flScalar value = NAN);
virtual ~SingletonTerm();
virtual void setValue(flScalar value);
virtual flScalar value() const;
virtual SingletonTerm* clone() const;
virtual flScalar membership(flScalar crisp) const;
virtual eMembershipFunction type() const;
virtual std::string toString() const;
};
} // namespace fl
#endif /* FL_SINGLETONTERM_H_ */

View File

@ -1,149 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "StrOp.h"
#include <iomanip>
#include <sstream>
#include <algorithm>
#include <iosfwd>
namespace fl {
bool StrOp::AscendantSorter(const std::string &left, const std::string &right) {
for (std::string::const_iterator lit = left.begin(), rit = right.begin();
lit != left.end() && rit != right.end();
++lit, ++rit) {
if (tolower(*lit) < tolower(*rit))
return true;
else if (tolower(*lit) > tolower(*rit))
return false;
}
if (left.size() < right.size()) {
return true;
}
return false;
}
bool StrOp::DescendantSorter(const std::string &left, const std::string &right) {
for (std::string::const_iterator lit = left.begin(), rit = right.begin();
lit != left.end() && rit != right.end();
++lit, ++rit) {
if (tolower(*lit) < tolower(*rit))
return false;
else if (tolower(*lit) > tolower(*rit))
return true;
}
if (left.size() < right.size()) {
return false;
}
return true;
}
void StrOp::LeftTrim(std::string& text) {
text.erase(text.begin(), text.begin() + text.find_first_not_of(" "));
}
void StrOp::RightTrim(std::string& text) {
text.erase(text.find_last_not_of(" ") + 1);
}
void StrOp::Trim(std::string& text) {
RightTrim(text);
LeftTrim(text);
}
// std::string StrOp::Substring(const std::string& text,
// const std::string substring) throw (OutOfRangeException) {
// int index = text.find_last_of(substring) - substring.size();
// OutOfRangeException::CheckArray(FL_AT, index, text.size());
// return text.substr(index);
// }
std::string StrOp::IntToString(int value) {
std::stringstream ss;
ss << value;
return ss.str();
}
std::string StrOp::ScalarToString(flScalar value, int precision) {
std::stringstream ss;
ss << std::fixed << std::setprecision(precision) << value;
return ss.str();
}
void StrOp::Sort(std::vector<std::string>& vector, bool asc) {
std::sort(vector.begin(), vector.end(), (asc ? AscendantSorter : DescendantSorter));
}
std::vector<std::string> StrOp::Tokenize(const std::string& str, const std::string delimiters) {
std::vector<std::string> result;
std::string::size_type last_pos = str.find_first_not_of(delimiters, 0);
// Find first "non-delimiter".
std::string::size_type pos = str.find_first_of(delimiters, last_pos);
while (std::string::npos != pos || std::string::npos != last_pos) {
// Found a token, add it to the vector.
result.push_back(str.substr(last_pos, pos - last_pos));
// Skip delimiters. Note the "not_of"
last_pos = str.find_first_not_of(delimiters, pos);
// Find next "non-delimiter"
pos = str.find_first_of(delimiters, last_pos);
}
return result;
}
std::vector<std::string> StrOp::SplitByWord(const std::string& str, const std::string word) {
std::vector<std::string> result;
std::stringstream ss(str);
std::string accum_token;
std::string token;
while (ss >> token) {
if (token == word) {
if (accum_token != "") {
result.push_back(accum_token);
}
accum_token = "";
} else {
accum_token += " " + token;
}
}
if (accum_token != "") {
result.push_back(accum_token);
}
return result;
}
int StrOp::FindReplace(std::string& str, const std::string& find,
const std::string& replace, bool all) {
if (find.length() == 0) return 0;
int result = 0;
size_t index = -abs((int)(find.length() - replace.length()));
do {
index = str.find(find, index + abs((int)(find.length() - replace.length())));
if (index != std::string::npos) {
str.replace(index, find.length(), replace);
++result;
}
} while (all && index != std::string::npos);
return result;
}
void StrOp::main(int argc, char** argv) {
std::string x = "Esto es= que y=o diga t=d=o= sin ='s =D";
FL_LOG(x);
FindReplace(x,"="," = ");
FL_LOG(x);
}
}

View File

@ -1,63 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* File: StrOp.h
* Author: jcrada
*
* Created on November 5, 2009, 12:23 PM
*/
#ifndef FL_STROP_H
#define FL_STROP_H
#include "defs.h"
#include "flScalar.h"
#include "FuzzyExceptions.h"
#include <string>
#include <vector>
namespace fl {
class StrOp {
protected:
static bool AscendantSorter(const std::string &left, const std::string &right);
static bool DescendantSorter(const std::string &left, const std::string &right);
public:
static void LeftTrim(std::string& text);
static void RightTrim(std::string& text);
static void Trim(std::string& text);
// static std::string Substring(const std::string& text,
// const std::string substring) throw (OutOfRangeException);
static std::string IntToString(int value) ;
static std::string ScalarToString(flScalar value, int precision = 3);
static void Sort(std::vector<std::string>& vector, bool asc = true);
static std::vector<std::string> Tokenize(const std::string& str, const std::string delimiter = " ");
static std::vector<std::string> SplitByWord(const std::string& str, const std::string word);
static int FindReplace(std::string& str, const std::string& find, const std::string& replace, bool all = true);
static void main(int args, char** argv);
};
}
#endif /* FL_STROP_H */

View File

@ -1,121 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "TakagiSugenoConsequent.h"
#include <stack>
#include <iosfwd>
#include "FunctionTerm.h"
#include "SingletonTerm.h"
#include "TakagiSugenoTerm.h"
namespace fl {
TakagiSugenoConsequent::TakagiSugenoConsequent() {
_infix2postfix.loadMathOperators();
}
TakagiSugenoConsequent::~TakagiSugenoConsequent() {
}
const FuzzyEngine& TakagiSugenoConsequent::fuzzyEngine() const {
return *this->_fuzzy_engine;
}
void TakagiSugenoConsequent::setFuzzyEngine(const FuzzyEngine& fuzzy_engine) {
this->_fuzzy_engine = &fuzzy_engine;
}
std::string TakagiSugenoConsequent::consequent() const {
return this->_consequent;
}
void TakagiSugenoConsequent::setConsequent(const std::string& consequent) {
this->_consequent = consequent;
}
std::string TakagiSugenoConsequent::postfixFunction() const {
return this->_postfix_function;
}
void TakagiSugenoConsequent::setPostfixFunction(const std::string& postfix) {
this->_postfix_function = postfix;
}
void TakagiSugenoConsequent::parse(const std::string& consequent,
const FuzzyEngine& engine) throw (ParsingException) {
setFuzzyEngine(engine);
setConsequent(consequent);
std::stringstream ss(consequent);
std::string output_lvar;
ss >> output_lvar;
if (!fuzzyEngine().outputLVar(output_lvar)) {
throw ParsingException(FL_AT, "Output variable <" + output_lvar +
"> not found in fuzzy engine");
}
setOutputLVar(fuzzyEngine().outputLVar(output_lvar));
std::string equal;
ss >> equal;
if (equal != "=") {
throw ParsingException(FL_AT, "<=> expected but found <" + equal + ">");
}
std::string right_side;
std::string token;
while (ss >> token) {
right_side += token + " ";
}
setPostfixFunction(_infix2postfix.transform(right_side));
std::map<std::string, flScalar> variables;
for (int i = 0; i < fuzzyEngine().numberOfInputLVars(); ++i) {
variables[fuzzyEngine().inputLVar(i)->name()] =
fuzzyEngine().inputLVar(i)->input();
}
for (int i = 0; i < fuzzyEngine().numberOfOutputLVars(); ++i) {
variables[fuzzyEngine().outputLVar(i)->name()] =
fuzzyEngine().outputLVar(i)->output().defuzzify();
}
try {
_infix2postfix.evaluate(postfixFunction(), &variables);
} catch (FuzzyException& e) {
throw ParsingException(FL_AT, e.message(), e);
}
}
void TakagiSugenoConsequent::execute(flScalar degree) {
std::map<std::string, flScalar> variables;
for (int i = 0; i < fuzzyEngine().numberOfInputLVars(); ++i) {
variables[fuzzyEngine().inputLVar(i)->name()] =
fuzzyEngine().inputLVar(i)->input();
}
for (int i = 0; i < fuzzyEngine().numberOfOutputLVars(); ++i) {
variables[fuzzyEngine().outputLVar(i)->name()] =
fuzzyEngine().outputLVar(i)->output().defuzzify();
}
TakagiSugenoTerm result(fuzzyEngine().fuzzyOperator(), postfixFunction());
result.setValue(_infix2postfix.evaluate(postfixFunction(), &variables));
result.setWeight(degree);
outputLVar()->output().addTerm(result);
}
std::string TakagiSugenoConsequent::toString() const {
return consequent();
}
void TakagiSugenoConsequent::main(int args, char** argv) {
}
}

View File

@ -1,64 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* File: TakagiSugenoConsequent.h
* Author: jcrada
*
* Created on March 4, 2010, 12:18 AM
*/
#ifndef FL_TAKAGISUGENOCONSEQUENT_H
#define FL_TAKAGISUGENOCONSEQUENT_H
#include "FuzzyConsequent.h"
#include "InfixToPostfix.h"
namespace fl {
class TakagiSugenoConsequent : public FuzzyConsequent {
private:
const FuzzyEngine* _fuzzy_engine;
std::string _consequent;
std::string _postfix_function;
InfixToPostfix _infix2postfix;
protected:
const FuzzyEngine& fuzzyEngine() const;
void setFuzzyEngine(const FuzzyEngine& fuzzy_engine);
std::string consequent() const;
void setConsequent(const std::string& consequent);
std::string postfixFunction() const;
void setPostfixFunction(const std::string& postfix);
public:
TakagiSugenoConsequent();
virtual ~TakagiSugenoConsequent();
virtual void parse(const std::string& consequent,
const FuzzyEngine& engine) throw (ParsingException);
virtual void execute(flScalar degree);
virtual std::string toString() const;
static void main(int args, char** argv);
};
}
#endif /* FL_TAKAGISUGENOCONSEQUENT_H */

View File

@ -1,63 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "TakagiSugenoRule.h"
#include "TakagiSugenoConsequent.h"
#include "DescriptiveAntecedent.h"
#include "StrOp.h"
namespace fl {
TakagiSugenoRule::TakagiSugenoRule() : FuzzyRule() {
}
TakagiSugenoRule::TakagiSugenoRule(const std::string& rule, const FuzzyEngine& engine)
: FuzzyRule() {
try {
parse(rule, engine);
} catch (ParsingException& e) {
FL_LOG(e.toString());
}
}
TakagiSugenoRule::~TakagiSugenoRule() {
}
void TakagiSugenoRule::parse(const std::string& rule, const FuzzyEngine& engine) {
std::string str_antecedent, str_consequent;
ExtractFromRule(rule, str_antecedent, str_consequent);
DescriptiveAntecedent* obj_antecedent = new DescriptiveAntecedent;
obj_antecedent->parse(str_antecedent, engine);
setAntecedent(obj_antecedent);
std::vector<std::string> consequents = StrOp::SplitByWord(str_consequent, FuzzyRule::FR_AND);
TakagiSugenoConsequent* obj_consequent = NULL;
for (size_t i = 0; i < consequents.size(); ++i) {
obj_consequent = new TakagiSugenoConsequent;
try {
std::string x = consequents[i];
StrOp::FindReplace(x,"="," = ");
obj_consequent->parse(x, engine);
} catch (ParsingException& e) {
delete obj_consequent;
throw e;
}
addConsequent(obj_consequent);
}
}
}

View File

@ -1,40 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* File: TakagiSugenoRule.h
* Author: jcrada
*
* Created on March 4, 2010, 12:22 AM
*/
#ifndef FL_TAKAGISUGENORULE_H
#define FL_TAKAGISUGENORULE_H
#include "FuzzyRule.h"
namespace fl {
class TakagiSugenoRule : public FuzzyRule {
public:
TakagiSugenoRule();
TakagiSugenoRule(const std::string& rule, const FuzzyEngine& engine);
virtual ~TakagiSugenoRule();
virtual void parse(const std::string& rule, const FuzzyEngine& engine);
};
}
#endif /* FL_TAKAGISUGENORULE_H */

View File

@ -1,61 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "TakagiSugenoTerm.h"
namespace fl {
TakagiSugenoTerm::TakagiSugenoTerm() : SingletonTerm() {
}
TakagiSugenoTerm::TakagiSugenoTerm(const std::string& name, flScalar value,
flScalar weight)
: SingletonTerm(name, value), _weight(weight) {
}
TakagiSugenoTerm::TakagiSugenoTerm(const FuzzyOperator& fuzzy_op, const std::string& name,
flScalar value, flScalar weight)
: SingletonTerm(fuzzy_op, name, value), _weight(weight) {
}
TakagiSugenoTerm::~TakagiSugenoTerm() {
}
void TakagiSugenoTerm::setWeight(flScalar weight) {
this->_weight = weight;
}
flScalar TakagiSugenoTerm::weight() const {
return this->_weight;
}
TakagiSugenoTerm* TakagiSugenoTerm::clone() const {
return new TakagiSugenoTerm(*this);
}
LinguisticTerm::eMembershipFunction TakagiSugenoTerm::type() const {
return MF_TAKAGI_SUGENO;
}
std::string TakagiSugenoTerm::toString() const {
std::stringstream ss;
ss << LinguisticTerm::toString();
ss << "TakagiSugeno (" << value() << " " << weight() << ")";
return ss.str();
}
}

View File

@ -1,48 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* File: TakagiSugenoTerm.h
* Author: jcrada
*
* Created on March 10, 2010, 7:28 PM
*/
#ifndef FL_TAKAGISUGENOTERM_H
#define FL_TAKAGISUGENOTERM_H
#include "SingletonTerm.h"
namespace fl{
class TakagiSugenoTerm : public SingletonTerm{
private:
flScalar _weight;
public:
TakagiSugenoTerm();
TakagiSugenoTerm(const std::string& name, flScalar value = NAN, flScalar weight = 1.0);
TakagiSugenoTerm(const FuzzyOperator& fuzzy_op, const std::string& name,
flScalar value = NAN, flScalar weight = 1.0);
virtual ~TakagiSugenoTerm();
virtual void setWeight(flScalar weight);
virtual flScalar weight() const;
virtual TakagiSugenoTerm* clone() const;
virtual eMembershipFunction type() const;
virtual std::string toString() const;
};
}
#endif /* FL_TAKAGISUGENOTERM_H */

View File

@ -1,113 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* TrapezoidalTerm.cpp
*
* Created on: Dec 13, 2009
* Author: jcrada
*/
#include "TrapezoidalTerm.h"
namespace fl {
TrapezoidalTerm::TrapezoidalTerm() :
LinguisticTerm(), _b(0), _c(0) {
}
TrapezoidalTerm::TrapezoidalTerm(const std::string& name, flScalar minimum,
flScalar maximum) :
LinguisticTerm(name, minimum, maximum), _b(0), _c(0) {
setB(minimum + (maximum - minimum) * 1 / 5);
setC(minimum + (maximum - minimum) * 4 / 5);
}
TrapezoidalTerm::TrapezoidalTerm(const FuzzyOperator& fuzzy_op,
const std::string& name, flScalar minimum, flScalar maximum) :
LinguisticTerm(fuzzy_op, name, minimum, maximum), _b(0), _c(0) {
setB(minimum + (maximum - minimum) * 1 / 5);
setC(minimum + (maximum - minimum) * 4 / 5);
}
TrapezoidalTerm::~TrapezoidalTerm() {
}
void TrapezoidalTerm::setA(flScalar a) {
setMinimum(a);
}
flScalar TrapezoidalTerm::a() const {
return minimum();
}
void TrapezoidalTerm::setB(flScalar b) {
this->_b = b;
}
flScalar TrapezoidalTerm::b() const {
return this->_b;
}
void TrapezoidalTerm::setC(flScalar c) {
this->_c = c;
}
flScalar TrapezoidalTerm::c() const {
return this->_c;
}
void TrapezoidalTerm::setD(flScalar d) {
setMaximum(d);
}
flScalar TrapezoidalTerm::d() const {
return maximum();
}
TrapezoidalTerm* TrapezoidalTerm::clone() const {
return new TrapezoidalTerm(*this);
}
flScalar TrapezoidalTerm::membership(flScalar crisp) const {
if (crisp < minimum() || crisp > maximum()) {
return flScalar(0);
}
if (crisp < b()) {
return fuzzyOperator().modulation().execute(modulation(),
FuzzyOperation::Scale(a(), b(), crisp, 0, 1));
}
if (crisp < c()) {
return fuzzyOperator().modulation().execute(modulation(), flScalar(1.0));
}
if (crisp < d()) {
return fuzzyOperator().modulation().execute(modulation(),
FuzzyOperation::Scale(c(), d(), crisp, 1, 0));
}
return flScalar(0.0);
}
LinguisticTerm::eMembershipFunction TrapezoidalTerm::type() const {
return MF_TRAPEZOIDAL;
}
std::string TrapezoidalTerm::toString() const {
std::stringstream ss;
ss << LinguisticTerm::toString();
ss << "Trapezoidal (" << a() << " " << b() << " " << c() << " " << d() << ")";
return ss.str();
}
} // namespace fuzzy_lite

View File

@ -1,63 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* TrapezoidalTerm.h
*
* Created on: Dec 13, 2009
* Author: jcrada
*/
#ifndef FL_TRAPEZOIDALTERM_H_
#define FL_TRAPEZOIDALTERM_H_
#include "LinguisticTerm.h"
namespace fl {
class TrapezoidalTerm : public LinguisticTerm {
private:
flScalar _b;
flScalar _c;
public:
TrapezoidalTerm();
TrapezoidalTerm(const std::string& name, flScalar minimum = -INFINITY,
flScalar maximum = INFINITY);
TrapezoidalTerm(const FuzzyOperator& fuzzy_op, const std::string& name,
flScalar minimum = -INFINITY, flScalar maximum = INFINITY);
virtual ~TrapezoidalTerm();
virtual void setA(flScalar a);
virtual flScalar a() const;
virtual void setB(flScalar b);
virtual flScalar b() const;
virtual void setC(flScalar c);
virtual flScalar c() const;
virtual void setD(flScalar d);
virtual flScalar d() const;
virtual TrapezoidalTerm* clone() const;
virtual flScalar membership(flScalar crisp) const;
virtual eMembershipFunction type() const;
virtual std::string toString() const;
};
} // namespace fuzzy_lite
#endif /* FL_TRAPEZOIDALTERM_H_ */

View File

@ -1,94 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* TriangularTerm.cpp
*
* Created on: Dec 13, 2009
* Author: jcrada
*/
#include "TriangularTerm.h"
namespace fl {
TriangularTerm::TriangularTerm() :
LinguisticTerm(), _b(0) {
}
TriangularTerm::TriangularTerm(const std::string& name, flScalar minimum,
flScalar maximum) :
LinguisticTerm(name, minimum, maximum), _b((minimum + maximum) / 2) {
}
TriangularTerm::TriangularTerm(const FuzzyOperator& fuzzy_op,
const std::string& name, flScalar minimum, flScalar maximum) :
LinguisticTerm(fuzzy_op, name, minimum, maximum), _b((minimum + maximum) / 2) {
}
TriangularTerm::~TriangularTerm() {
}
void TriangularTerm::setA(flScalar a) {
setMinimum(a);
}
flScalar TriangularTerm::a() const {
return minimum();
}
void TriangularTerm::setB(flScalar b) {
this->_b = b;
}
flScalar TriangularTerm::b() const {
return this->_b;
}
void TriangularTerm::setC(flScalar c) {
setMaximum(c);
}
flScalar TriangularTerm::c() const {
return maximum();
}
TriangularTerm* TriangularTerm::clone() const {
return new TriangularTerm(*this);
}
flScalar TriangularTerm::membership(flScalar crisp) const {
if (crisp > maximum() || crisp < minimum()) {
return flScalar(0.0);
}
flScalar result = crisp < b() ? FuzzyOperation::Scale(a(), b(), crisp, 0, 1)
: FuzzyOperation::Scale(b(), c(), crisp, 1, 0);
return fuzzyOperator().modulation().execute(result, modulation());
}
LinguisticTerm::eMembershipFunction TriangularTerm::type() const {
return MF_TRIANGULAR;
}
std::string TriangularTerm::toString() const {
std::stringstream ss;
ss << LinguisticTerm::toString();
ss << "Triangular (" << a() << " " << b() << " " << c() << ")";
return ss.str();
}
} // namespace fuzzy_lite

View File

@ -1,60 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* TriangularTerm.h
*
* Created on: Dec 13, 2009
* Author: jcrada
*/
#ifndef FL_TRIANGULARTERM_H_
#define FL_TRIANGULARTERM_H_
#include "LinguisticTerm.h"
namespace fl {
class TriangularTerm : public LinguisticTerm {
private:
flScalar _b;
public:
TriangularTerm();
TriangularTerm(const std::string& name, flScalar minimum = -INFINITY,
flScalar maximum = INFINITY);
TriangularTerm(const FuzzyOperator& fuzzy_op, const std::string& name,
flScalar minimum = -INFINITY, flScalar maximum = INFINITY);
virtual ~TriangularTerm();
virtual void setA(flScalar a);
virtual flScalar a() const;
virtual void setB(flScalar b);
virtual flScalar b() const;
virtual void setC(flScalar c);
virtual flScalar c() const;
virtual TriangularTerm* clone() const;
virtual flScalar membership(flScalar crisp) const;
virtual eMembershipFunction type() const;
virtual std::string toString() const;
};
} // namespace fuzzy_lite
#endif /* FL_TRIANGULARTERM_H_ */

View File

@ -1,97 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* File: defs.h
* Author: jcrada
*
* Created on October 30, 2009, 7:09 PM
*/
#ifndef FL_DEFS_H
#define FL_DEFS_H
#if defined(_MSC_VER) && _MSC_VER < 1800
#ifndef NAN
static const unsigned long __nan[2] = {0xffffffff, 0x7fffffff};
#define NAN (*(const float *) __nan)
#endif
#ifndef INFINITY
union MSVC_FL
{
unsigned __int8 Bytes[4];
float Value;
};
static union MSVC_FL INFINITY_HACK = {{0x00, 0x00, 0x80, 0x7F}};
#define INFINITY (INFINITY_HACK.Value)
#endif
#define isnan(x) ((x) != (x))
template <typename T> bool isinf (T val)
{
return val == INFINITY || val == -INFINITY;
}
//#include <windows.h> //nees for S
#endif
#include <iostream>
#include <sstream>
#include <assert.h>
namespace fl {
#define FL_AT __FILE__, __LINE__, __FUNCTION__
#ifdef FL_USE_INLINE
#define FL_INLINE inline
#else
#define FL_INLINE
#endif
#ifdef FL_USE_ASSERT
#define FL_ASSERT(assertion) assert(assertion);
#define FL_ASSERTM(value,assertion) if (!(assertion)){FL_LOGM(value);} assert(assertion);
#else
#define FL_ASSERT(assertion)
#define FL_ASSERTM(value,assertion)
#endif
#ifdef FL_USE_LOG
#define FL_LOG_PREFIX __FILE__ << " [" << __LINE__ << "]:"
#define FL_LOG(message) std::cout << FL_LOG_PREFIX << message << std::endl
#define FL_LOGW(message) std::cout << FL_LOG_PREFIX << "WARNING: " << message << std::endl
#else
#define FL_LOG(message)
#define FL_LOGW(message)
#endif
#ifdef FL_USE_DEBUG
#define FL_DEBUG_PREFIX __FILE__ << " [" << __LINE__ << "]::" << __FUNCTION__ << ": "
#define FL_DEBUG(message) std::cout << FL_DEBUG_PREFIX << message << std::endl
#define FL_DEBUGI std::cout << FL_DEBUG_PREFIX << ++FL_DEBUG_COUNTER << std::endl
#else
#define FL_DEBUG(message)
#define FL_DEBUGI
#endif
#ifndef FL_SAMPLE_SIZE
#define FL_SAMPLE_SIZE 100
#endif
}
#endif /* FL_DEFS_H */

View File

@ -1,37 +0,0 @@
/* Copyright 2010 Juan Rada-Vilela
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* File: flScalar.h
* Author: jcrada
*
* Created on October 30, 2009, 7:11 PM
*/
#ifndef FL_FLSCALAR_H
#define FL_FLSCALAR_H
namespace fl {
#ifdef FL_USE_DOUBLE_PRECISION
typedef double flScalar;
#define FL_EPSILON 1e-14
#else
typedef float flScalar;
#define FL_EPSILON 1e-5
#endif
}
#endif /* FL_FLSCALAR_H */

BIN
AI/FuzzyLite/fuzzylite.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

View File

@ -0,0 +1,149 @@
cmake_minimum_required(VERSION 2.8)
project(fuzzylite CXX)
set(CMAKE_VERBOSE_MAKEFILE false)
set(FL_VERSION 5.0)
add_definitions(-DFL_VERSION="${FL_VERSION}")
set(FL_DATE "1408")
add_definitions(-DFL_DATE="${FL_DATE}")
add_definitions(-DFL_BUILD_PATH="${CMAKE_SOURCE_DIR}") #used to determine FL__FILE__
option(FL_USE_FLOAT "Use fl::scalar as float" OFF)
option(FL_BACKTRACE "Provide backtrace information in case of errors" OFF)
option(FL_CPP11 "Builds utilizing C++11, i.e., passing -std=c++11" OFF)
if(FL_USE_FLOAT)
add_definitions(-DFL_USE_FLOAT)
endif(FL_USE_FLOAT)
if(NOT FL_BACKTRACE)
add_definitions(-DFL_BACKTRACE_OFF)
endif()
if(FL_CPP11)
add_definitions(-DFL_CPP11)
if(UNIX)
add_definitions(-std=c++11)
endif(UNIX)
endif(FL_CPP11)
if(WIN32)
message("Windows")
add_definitions(-DFL_WINDOWS)
endif()
if (UNIX)
message("Unix")
add_definitions(-DFL_UNIX)
endif()
if (APPLE)
message("Apple")
add_definitions(-DFL_APPLE)
endif()
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY bin)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY bin)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY bin)
if(UNIX)
set(CMAKE_CXX_FLAGS "-pedantic -Werror -Wall -Wextra")
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG}")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE}")
if(NOT APPLE)
set(CMAKE_SHARED_LINKER_FLAGS "-Wl,--no-undefined") #To avoid undefined methods in library
endif()
endif()
if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-non-literal-null-conversion")
endif()
set(FL_LIBS)
if(WIN32)
set(CMAKE_CXX_FLAGS "/WX /W4 /EHsc")
#Wx: Treat warnings as errors. W4: All warnings
#http://msdn.microsoft.com/en-us/library/thxezb7y.aspx
#EHsc: call destructors on __try __catch, and to ignore C4530: C++ exception handler used. Note, unwind semantics are not enabled
#/wd4251 disable warning 4251 #http://www.unknownroad.com/rtfm/VisualStudio/warningC4251.html
#To avoid issues from disabling warning 4251, MSVCRT.lib is statically linked to resolve external references
#http://msdn.microsoft.com/en-us/library/2kzt1wy3.aspx
#set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /MD")
#set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /MDd")
#By default, MD is selected.
if (FL_BACKTRACE)
set(FL_LIBS dbghelp)
endif()
endif()
include_directories(.)
cmake_policy(SET CMP0015 OLD)
link_directories(.)
file(STRINGS FL_HEADERS fl-headers)
file(STRINGS FL_SOURCES fl-sources)
string(REGEX REPLACE "\n" " " ${fl-headers} ${fl-headers})
string(REGEX REPLACE "\n" " " ${fl-sources} ${fl-sources})
message("${exepath}")
set(CMAKE_DEBUG_POSTFIX d)
add_library(fl-shared SHARED ${fl-headers} ${fl-sources})
set_target_properties(fl-shared PROPERTIES OUTPUT_NAME fuzzylite)
set_target_properties(fl-shared PROPERTIES DEBUG_POSTFIX d)
set_target_properties(fl-shared PROPERTIES COMPILE_DEFINITIONS "FL_EXPORT_LIBRARY")
target_link_libraries(fl-shared ${FL_LIBS})
add_library(fl-static STATIC ${fl-headers} ${fl-sources})
set_target_properties(fl-static PROPERTIES OUTPUT_NAME fuzzylite-static)
set_target_properties(fl-static PROPERTIES DEBUG_POSTFIX d)
target_link_libraries(fl-static ${FL_LIBS})
add_executable(fl-bin src/main.cpp)
set_target_properties(fl-bin PROPERTIES OUTPUT_NAME fuzzylite)
set_target_properties(fl-bin PROPERTIES OUTPUT_NAME fuzzylite IMPORT_PREFIX tmp-) #To prevent LNK1149 in Windows
set_target_properties(fl-bin PROPERTIES DEBUG_POSTFIX d)
#set_target_properties(fl-bin PROPERTIES COMPILE_DEFINITIONS "FL_IMPORT_LIBRARY")
#target_link_libraries(fl-bin fl-shared ${FL_LIBS})
target_link_libraries(fl-bin fl-static ${FL_LIBS})
install(TARGETS fl-bin fl-shared fl-static
RUNTIME DESTINATION bin
LIBRARY DESTINATION lib
ARCHIVE DESTINATION lib
)
install(DIRECTORY fl/ DESTINATION include/fl)
message("=====================================")
message("fuzzylite v.${FL_VERSION}b${FL_DATE}\n")
message("FL_USE_FLOAT=${FL_USE_FLOAT}")
message("FL_BACKTRACE=${FL_BACKTRACE}")
message("FL_CPP11=${FL_CPP11}")
message("Build=${CMAKE_BUILD_TYPE}")
message("=====================================\n")
# uninstall target
#configure_file(
#"${CMAKE_CURRENT_SOURCE_DIR}/cmake_uninstall.cmake.in"
#"${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake"
#IMMEDIATE @ONLY)
#add_custom_target(uninstall
#COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/uninstall.cmake)
#unix uninstall
#xargs rm < install_manifest.txt

View File

@ -0,0 +1,92 @@
fl/Console.h
fl/defuzzifier/Bisector.h
fl/defuzzifier/Centroid.h
fl/defuzzifier/Defuzzifier.h
fl/defuzzifier/IntegralDefuzzifier.h
fl/defuzzifier/LargestOfMaximum.h
fl/defuzzifier/MeanOfMaximum.h
fl/defuzzifier/SmallestOfMaximum.h
fl/defuzzifier/WeightedAverage.h
fl/defuzzifier/WeightedDefuzzifier.h
fl/defuzzifier/WeightedSum.h
fl/Engine.h
fl/Exception.h
fl/factory/CloningFactory.h
fl/factory/ConstructionFactory.h
fl/factory/DefuzzifierFactory.h
fl/factory/FactoryManager.h
fl/factory/FunctionFactory.h
fl/factory/HedgeFactory.h
fl/factory/SNormFactory.h
fl/factory/TermFactory.h
fl/factory/TNormFactory.h
fl/fuzzylite.h
fl/Headers.h
fl/hedge/Any.h
fl/hedge/Extremely.h
fl/hedge/Hedge.h
fl/hedge/Not.h
fl/hedge/Seldom.h
fl/hedge/Somewhat.h
fl/hedge/Very.h
fl/imex/CppExporter.h
fl/imex/Exporter.h
fl/imex/FclExporter.h
fl/imex/FclImporter.h
fl/imex/FisExporter.h
fl/imex/FisImporter.h
fl/imex/FldExporter.h
fl/imex/FllExporter.h
fl/imex/FllImporter.h
fl/imex/Importer.h
fl/imex/JavaExporter.h
fl/norm/Norm.h
fl/norm/s/AlgebraicSum.h
fl/norm/s/BoundedSum.h
fl/norm/s/DrasticSum.h
fl/norm/s/EinsteinSum.h
fl/norm/s/HamacherSum.h
fl/norm/s/Maximum.h
fl/norm/s/NilpotentMaximum.h
fl/norm/s/NormalizedSum.h
fl/norm/SNorm.h
fl/norm/t/AlgebraicProduct.h
fl/norm/t/BoundedDifference.h
fl/norm/t/DrasticProduct.h
fl/norm/t/EinsteinProduct.h
fl/norm/t/HamacherProduct.h
fl/norm/t/Minimum.h
fl/norm/t/NilpotentMinimum.h
fl/norm/TNorm.h
fl/Operation.h
fl/rule/Antecedent.h
fl/rule/Consequent.h
fl/rule/Expression.h
fl/rule/RuleBlock.h
fl/rule/Rule.h
fl/term/Accumulated.h
fl/term/Activated.h
fl/term/Bell.h
fl/term/Concave.h
fl/term/Constant.h
fl/term/Cosine.h
fl/term/Discrete.h
fl/term/Function.h
fl/term/Gaussian.h
fl/term/GaussianProduct.h
fl/term/Linear.h
fl/term/PiShape.h
fl/term/Ramp.h
fl/term/Rectangle.h
fl/term/SigmoidDifference.h
fl/term/Sigmoid.h
fl/term/SigmoidProduct.h
fl/term/Spike.h
fl/term/SShape.h
fl/term/Term.h
fl/term/Trapezoid.h
fl/term/Triangle.h
fl/term/ZShape.h
fl/variable/InputVariable.h
fl/variable/OutputVariable.h
fl/variable/Variable.h

View File

@ -0,0 +1,87 @@
src/Console.cpp
src/defuzzifier/Bisector.cpp
src/defuzzifier/Centroid.cpp
src/defuzzifier/IntegralDefuzzifier.cpp
src/defuzzifier/LargestOfMaximum.cpp
src/defuzzifier/MeanOfMaximum.cpp
src/defuzzifier/SmallestOfMaximum.cpp
src/defuzzifier/WeightedAverage.cpp
src/defuzzifier/WeightedDefuzzifier.cpp
src/defuzzifier/WeightedSum.cpp
src/Engine.cpp
src/Exception.cpp
src/factory/CloningFactory.cpp
src/factory/ConstructionFactory.cpp
src/factory/DefuzzifierFactory.cpp
src/factory/FactoryManager.cpp
src/factory/FunctionFactory.cpp
src/factory/HedgeFactory.cpp
src/factory/SNormFactory.cpp
src/factory/TermFactory.cpp
src/factory/TNormFactory.cpp
src/fuzzylite.cpp
src/hedge/Any.cpp
src/hedge/Extremely.cpp
src/hedge/Not.cpp
src/hedge/Seldom.cpp
src/hedge/Somewhat.cpp
src/hedge/Very.cpp
src/imex/CppExporter.cpp
src/imex/Exporter.cpp
src/imex/FclExporter.cpp
src/imex/FclImporter.cpp
src/imex/FisExporter.cpp
src/imex/FisImporter.cpp
src/imex/FldExporter.cpp
src/imex/FllExporter.cpp
src/imex/FllImporter.cpp
src/imex/Importer.cpp
src/imex/JavaExporter.cpp
src/main.cpp
src/norm/s/AlgebraicSum.cpp
src/norm/s/BoundedSum.cpp
src/norm/s/DrasticSum.cpp
src/norm/s/EinsteinSum.cpp
src/norm/s/HamacherSum.cpp
src/norm/s/Maximum.cpp
src/norm/s/NilpotentMaximum.cpp
src/norm/s/NormalizedSum.cpp
src/norm/t/AlgebraicProduct.cpp
src/norm/t/BoundedDifference.cpp
src/norm/t/DrasticProduct.cpp
src/norm/t/EinsteinProduct.cpp
src/norm/t/HamacherProduct.cpp
src/norm/t/Minimum.cpp
src/norm/t/NilpotentMinimum.cpp
src/Operation.cpp
src/rule/Antecedent.cpp
src/rule/Consequent.cpp
src/rule/Expression.cpp
src/rule/RuleBlock.cpp
src/rule/Rule.cpp
src/term/Accumulated.cpp
src/term/Activated.cpp
src/term/Bell.cpp
src/term/Concave.cpp
src/term/Constant.cpp
src/term/Cosine.cpp
src/term/Discrete.cpp
src/term/Function.cpp
src/term/Gaussian.cpp
src/term/GaussianProduct.cpp
src/term/Linear.cpp
src/term/PiShape.cpp
src/term/Ramp.cpp
src/term/Rectangle.cpp
src/term/Sigmoid.cpp
src/term/SigmoidDifference.cpp
src/term/SigmoidProduct.cpp
src/term/Spike.cpp
src/term/SShape.cpp
src/term/Term.cpp
src/term/Trapezoid.cpp
src/term/Triangle.cpp
src/term/ZShape.cpp
src/variable/InputVariable.cpp
src/variable/OutputVariable.cpp
src/variable/Variable.cpp

View File

@ -0,0 +1,104 @@
@echo off
setlocal EnableDelayedExpansion
set argc=0
set valid="no"
for %%a in (%*) do (
set /A argc+=1
if /I "%%a"=="help" (
call:usage
goto:eof
)
if /I "%%a"=="all" set valid="yes"
if /I "%%a"=="release" set valid="yes"
if /I "%%a"=="debug" set valid="yes"
if /I "%%a"=="clean" set valid="yes"
if !valid!=="no" (
echo Invalid option: %%a
call:usage
goto:eof
)
)
if %argc%==0 echo Building schedule: all
if not %argc%==0 echo Building schedule: %*
echo Starting in 3 seconds...
ping 1.1.1.1 -n 1 -w 3000 > nul
rem sleep 3 ::This function makes command line DOS-esque C:\Archiv~1
if %argc%==0 (call:all)
for %%a in (%*) do (call:%%a)
goto:eof
:debug
echo.
echo.
echo ****************************************
echo STARTING: debug
if not exist debug mkdir debug
cd debug
cmake .. -G"NMake Makefiles" -DCMAKE_BUILD_TYPE=Debug -DFL_BACKTRACE=ON -DFL_USE_FLOAT=OFF -DFL_CPP11=OFF
nmake
cd ..
echo.
echo FINISHED: debug
echo ****************************************
goto:eof
:release
echo.
echo.
echo ****************************************
echo STARTING: release
if not exist release mkdir release
cd release
cmake .. -G"NMake Makefiles" -DCMAKE_BUILD_TYPE=Release -DFL_BACKTRACE=OFF -DFL_USE_FLOAT=OFF -DFL_CPP11=OFF
nmake
cd ..
echo.
echo FINISHED: release
echo ****************************************
goto:eof
:all
echo.
echo.
echo ****************************************
echo STARTING: all
call:debug
call:release
echo.
echo FINISHED: all
echo ****************************************
goto:eof
:clean
echo.
echo.
echo ****************************************
echo STARTING: clean
if exist debug rmdir /S /Q debug
if exist release rmdir /S /Q release
echo.
echo FINISHED: clean
echo ****************************************
goto:eof
:usage
echo Usage: build.bat [options]
echo where [options] can be any of the following:
echo ^ all builds fuzzylite in debug and release mode (default)
echo ^ debug builds fuzzylite in debug mode
echo ^ release builds fuzzylite in release mode
echo ^ clean erases previous builds
echo ^ help shows this information
echo.
ENDLOCAL

70
AI/FuzzyLite/fuzzylite/build.sh Executable file
View File

@ -0,0 +1,70 @@
#!/bin/bash
debug(){
mkdir -p debug
cd debug
cmake .. -G"Unix Makefiles" -DCMAKE_BUILD_TYPE=Debug -DFL_BACKTRACE=ON -DFL_USE_FLOAT=OFF -DFL_CPP11=OFF
make
cd ..
}
release(){
mkdir -p release
cd release
cmake .. -G"Unix Makefiles" -DCMAKE_BUILD_TYPE=Release -DFL_BACKTRACE=ON -DFL_USE_FLOAT=OFF -DFL_CPP11=OFF
make
cd ..
}
all(){
debug
release
}
clean(){
rm -rf release debug
}
usage(){
printf 'Usage:\t[bash] ./build.sh [options]\n'
printf "where\t[options] can be any of the following:\n"
printf "\tall\t\t builds fuzzylite in debug and release mode (default)\n"
printf "\tdebug\t\t builds fuzzylite in debug mode\n"
printf "\trelease\t\t builds fuzzylite in release mode\n"
printf "\tclean\t\t erases previous builds\n"
printf "\thelp\t\t shows this information\n"
printf "\n"
}
#############################
OPTIONS=( "all" "debug" "release" "clean" "help")
BUILD=( )
for arg in "$@"
do
if [[ "$arg" == "help" ]]; then usage && exit 0; fi
if [[ "$arg" == "all" || "$arg" == "debug" || "$arg" == "release" || "$arg" == "clean" ]];
then BUILD+=( $arg ); else echo "Invalid option: $arg" && usage && exit 2;
fi
done
if [ ${#BUILD[@]} -eq 0 ]; then BUILD+=( "all" ); fi
echo "Building schedule: ${BUILD[@]}"
echo "Starting in 3 seconds..."
sleep 3
for option in "${BUILD[@]}"
do
printf "\n\n"
printf "******************************\n"
printf "STARTING: $option\n"
eval ${option}
printf "\nFINISHED: $option\n"
printf "******************************\n\n"
done

View File

@ -0,0 +1,89 @@
/*
Author: Juan Rada-Vilela, Ph.D.
Copyright (C) 2010-2014 FuzzyLite Limited
All rights reserved
This file is part of fuzzylite.
fuzzylite is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option)
any later version.
fuzzylite 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 Lesser General Public License
for more details.
You should have received a copy of the GNU Lesser General Public License
along with fuzzylite. If not, see <http://www.gnu.org/licenses/>.
fuzzylite is a trademark of FuzzyLite Limited.
*/
#ifndef FL_CONSOLE_H
#define FL_CONSOLE_H
#include "fl/fuzzylite.h"
#include <map>
#include <string>
#include <vector>
namespace fl {
class Engine;
class FL_API Console {
public:
struct Option {
std::string key, value, description;
Option(const std::string& key = "", const std::string& value = "", const std::string& description = "") :
key(key), value(value), description(description) {
}
};
static const std::string KW_INPUT_FILE;
static const std::string KW_INPUT_FORMAT;
static const std::string KW_OUTPUT_FILE;
static const std::string KW_OUTPUT_FORMAT;
static const std::string KW_EXAMPLE;
static const std::string KW_DECIMALS;
static const std::string KW_DATA_INPUT;
static const std::string KW_DATA_MAXIMUM;
static const std::string KW_DATA_EXPORT_HEADER;
static const std::string KW_DATA_EXPORT_INPUTS;
static Engine* mamdani();
static Engine* takagiSugeno();
protected:
static std::map<std::string, std::string> parse(int argc, char** argv);
static void process(const std::map<std::string, std::string>& options);
static void process(const std::string& input, std::ostream& writer,
const std::string& inputFormat, const std::string& outputFormat,
const std::map<std::string, std::string>& options);
static int readCharacter();
static void interactive(std::ostream& writer, Engine* engine);
static std::string interactiveHelp();
static void exportAllExamples(const std::string& from, const std::string& to);
#if defined(FL_UNIX) && ! defined(FL_APPLE)
static void benchmarkExamples(int runs);
#endif
public:
static std::string usage();
static std::vector<Option> availableOptions();
static int main(int argc, char** argv);
};
}
#endif /* FL_CONSOLE_H */

View File

@ -0,0 +1,151 @@
/*
Author: Juan Rada-Vilela, Ph.D.
Copyright (C) 2010-2014 FuzzyLite Limited
All rights reserved
This file is part of fuzzylite.
fuzzylite is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option)
any later version.
fuzzylite 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 Lesser General Public License
for more details.
You should have received a copy of the GNU Lesser General Public License
along with fuzzylite. If not, see <http://www.gnu.org/licenses/>.
fuzzylite is a trademark of FuzzyLite Limited.
*/
#ifndef FL_ENGINE_H
#define FL_ENGINE_H
#include "fl/fuzzylite.h"
#include "fl/defuzzifier/IntegralDefuzzifier.h"
#include <string>
#include <vector>
namespace fl {
class InputVariable;
class OutputVariable;
class Variable;
class RuleBlock;
class Hedge;
class TNorm;
class SNorm;
class Defuzzifier;
class FL_API Engine {
private:
void copyFrom(const Engine& source);
protected:
std::string _name;
std::vector<InputVariable*> _inputVariables;
std::vector<OutputVariable*> _outputVariables;
std::vector<RuleBlock*> _ruleblocks;
void updateReferences() const;
public:
Engine(const std::string& name = "");
Engine(const Engine& other);
Engine& operator=(const Engine& other);
virtual ~Engine();
FL_DEFAULT_MOVE(Engine)
virtual void configure(const std::string& conjunctionT,
const std::string& disjunctionS,
const std::string& activationT,
const std::string& accumulationS,
const std::string& defuzzifier,
int resolution = IntegralDefuzzifier::defaultResolution());
virtual void configure(TNorm* conjunction, SNorm* disjunction,
TNorm* activation, SNorm* accumulation,
Defuzzifier* defuzzifier);
virtual bool isReady(std::string* status = fl::null) const;
virtual void process();
virtual void restart();
virtual void setName(const std::string& name);
virtual std::string getName() const;
virtual void setInputValue(const std::string& name, scalar value);
virtual scalar getOutputValue(const std::string& name);
virtual std::string toString() const;
enum Type {
Mamdani, Larsen, TakagiSugeno,
Tsukamoto, InverseTsukamoto, Hybrid, Unknown
};
virtual Type type(std::string* name = fl::null, std::string* reason = fl::null) const;
virtual Engine* clone() const;
virtual std::vector<Variable*> variables() const;
/**
* Operations for iterable datatype _inputVariables
*/
virtual void addInputVariable(InputVariable* inputVariable);
virtual InputVariable* setInputVariable(InputVariable* inputVariable, int index);
virtual void insertInputVariable(InputVariable* inputVariable, int index);
virtual InputVariable* getInputVariable(int index) const;
virtual InputVariable* getInputVariable(const std::string& name) const;
virtual InputVariable* removeInputVariable(int index);
virtual InputVariable* removeInputVariable(const std::string& name);
virtual bool hasInputVariable(const std::string& name) const;
virtual int numberOfInputVariables() const;
virtual const std::vector<InputVariable*>& inputVariables() const;
virtual void setInputVariables(const std::vector<InputVariable*>& inputVariables);
virtual std::vector<InputVariable*>& inputVariables();
/**
* Operations for iterable datatype _outputVariables
*/
virtual void addOutputVariable(OutputVariable* outputVariable);
virtual OutputVariable* setOutputVariable(OutputVariable* outputVariable, int index);
virtual void insertOutputVariable(OutputVariable* outputVariable, int index);
virtual OutputVariable* getOutputVariable(int index) const;
virtual OutputVariable* getOutputVariable(const std::string& name) const;
virtual bool hasOutputVariable(const std::string& name) const;
virtual OutputVariable* removeOutputVariable(int index);
virtual OutputVariable* removeOutputVariable(const std::string& name);
virtual int numberOfOutputVariables() const;
virtual const std::vector<OutputVariable*>& outputVariables() const;
virtual void setOutputVariables(const std::vector<OutputVariable*>& outputVariables);
virtual std::vector<OutputVariable*>& outputVariables();
/**
* Operations for iterable datatype _ruleblocks
*/
virtual void addRuleBlock(RuleBlock* ruleblock);
virtual RuleBlock* setRuleBlock(RuleBlock* ruleBlock, int index);
virtual void insertRuleBlock(RuleBlock* ruleblock, int index);
virtual RuleBlock* getRuleBlock(int index) const;
virtual RuleBlock* getRuleBlock(const std::string& name) const;
virtual bool hasRuleBlock(const std::string& name) const;
virtual RuleBlock* removeRuleBlock(int index);
virtual RuleBlock* removeRuleBlock(const std::string& name);
virtual int numberOfRuleBlocks() const;
virtual const std::vector<RuleBlock*>& ruleBlocks() const;
virtual void setRuleBlocks(const std::vector<RuleBlock*>& ruleBlocks);
virtual std::vector<RuleBlock*>& ruleBlocks();
};
}
#endif /* FL_ENGINE_H */

View File

@ -0,0 +1,66 @@
/*
Author: Juan Rada-Vilela, Ph.D.
Copyright (C) 2010-2014 FuzzyLite Limited
All rights reserved
This file is part of fuzzylite.
fuzzylite is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option)
any later version.
fuzzylite 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 Lesser General Public License
for more details.
You should have received a copy of the GNU Lesser General Public License
along with fuzzylite. If not, see <http://www.gnu.org/licenses/>.
fuzzylite is a trademark of FuzzyLite Limited.
*/
#ifndef FL_EXCEPTION_H
#define FL_EXCEPTION_H
#include "fl/fuzzylite.h"
#include <exception>
#include <string>
#include <vector>
namespace fl {
class FL_API Exception : public std::exception {
protected:
std::string _what;
public:
Exception(const std::string& what);
Exception(const std::string& what, const std::string& file, int line,
const std::string& function);
virtual ~Exception() FL_INOEXCEPT FL_IOVERRIDE;
FL_DEFAULT_COPY_AND_MOVE(Exception)
virtual void setWhat(const std::string& what);
virtual std::string getWhat() const;
virtual const char* what() const FL_INOEXCEPT FL_IOVERRIDE;
virtual void append(const std::string& whatElse);
virtual void append(const std::string& file, int line, const std::string& function);
virtual void append(const std::string& whatElse,
const std::string& file, int line, const std::string& function);
static std::string btCallStack();
static void signalHandler(int signal);
static void convertToException(int signal);
static void terminate();
static void catchException(const std::exception& exception);
};
}
#endif /* FL_EXCEPTION_H */

View File

@ -0,0 +1,131 @@
/*
Author: Juan Rada-Vilela, Ph.D.
Copyright (C) 2010-2014 FuzzyLite Limited
All rights reserved
This file is part of fuzzylite.
fuzzylite is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option)
any later version.
fuzzylite 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 Lesser General Public License
for more details.
You should have received a copy of the GNU Lesser General Public License
along with fuzzylite. If not, see <http://www.gnu.org/licenses/>.
fuzzylite is a trademark of FuzzyLite Limited.
*/
#ifndef FL_HEADERS_H
#define FL_HEADERS_H
#include "fl/fuzzylite.h"
#include "fl/Console.h"
#include "fl/Engine.h"
#include "fl/Exception.h"
#include "fl/defuzzifier/Bisector.h"
#include "fl/defuzzifier/Centroid.h"
#include "fl/defuzzifier/Defuzzifier.h"
#include "fl/defuzzifier/IntegralDefuzzifier.h"
#include "fl/defuzzifier/SmallestOfMaximum.h"
#include "fl/defuzzifier/LargestOfMaximum.h"
#include "fl/defuzzifier/MeanOfMaximum.h"
#include "fl/defuzzifier/WeightedAverage.h"
#include "fl/defuzzifier/WeightedDefuzzifier.h"
#include "fl/defuzzifier/WeightedSum.h"
#include "fl/factory/CloningFactory.h"
#include "fl/factory/ConstructionFactory.h"
#include "fl/factory/FactoryManager.h"
#include "fl/factory/FunctionFactory.h"
#include "fl/factory/DefuzzifierFactory.h"
#include "fl/factory/HedgeFactory.h"
#include "fl/factory/SNormFactory.h"
#include "fl/factory/TNormFactory.h"
#include "fl/factory/TermFactory.h"
#include "fl/imex/CppExporter.h"
#include "fl/imex/FclImporter.h"
#include "fl/imex/FclExporter.h"
#include "fl/imex/FisImporter.h"
#include "fl/imex/FisExporter.h"
#include "fl/imex/FldExporter.h"
#include "fl/imex/FllImporter.h"
#include "fl/imex/FllExporter.h"
#include "fl/imex/JavaExporter.h"
#include "fl/hedge/Any.h"
#include "fl/hedge/Extremely.h"
#include "fl/hedge/Hedge.h"
#include "fl/hedge/Not.h"
#include "fl/hedge/Seldom.h"
#include "fl/hedge/Somewhat.h"
#include "fl/hedge/Very.h"
#include "fl/Operation.h"
#include "fl/norm/Norm.h"
#include "fl/norm/SNorm.h"
#include "fl/norm/TNorm.h"
#include "fl/norm/s/AlgebraicSum.h"
#include "fl/norm/s/BoundedSum.h"
#include "fl/norm/s/DrasticSum.h"
#include "fl/norm/s/EinsteinSum.h"
#include "fl/norm/s/HamacherSum.h"
#include "fl/norm/s/Maximum.h"
#include "fl/norm/s/NilpotentMaximum.h"
#include "fl/norm/s/NormalizedSum.h"
#include "fl/norm/t/AlgebraicProduct.h"
#include "fl/norm/t/BoundedDifference.h"
#include "fl/norm/t/DrasticProduct.h"
#include "fl/norm/t/EinsteinProduct.h"
#include "fl/norm/t/HamacherProduct.h"
#include "fl/norm/t/Minimum.h"
#include "fl/norm/t/NilpotentMinimum.h"
#include "fl/rule/Antecedent.h"
#include "fl/rule/Consequent.h"
#include "fl/rule/Rule.h"
#include "fl/rule/RuleBlock.h"
#include "fl/rule/Expression.h"
#include "fl/term/Accumulated.h"
#include "fl/term/Bell.h"
#include "fl/term/Concave.h"
#include "fl/term/Constant.h"
#include "fl/term/Cosine.h"
#include "fl/term/Discrete.h"
#include "fl/term/Function.h"
#include "fl/term/Gaussian.h"
#include "fl/term/GaussianProduct.h"
#include "fl/term/Linear.h"
#include "fl/term/PiShape.h"
#include "fl/term/Ramp.h"
#include "fl/term/Rectangle.h"
#include "fl/term/SShape.h"
#include "fl/term/Sigmoid.h"
#include "fl/term/SigmoidDifference.h"
#include "fl/term/SigmoidProduct.h"
#include "fl/term/Spike.h"
#include "fl/term/Term.h"
#include "fl/term/Activated.h"
#include "fl/term/Trapezoid.h"
#include "fl/term/Triangle.h"
#include "fl/term/ZShape.h"
#include "fl/variable/InputVariable.h"
#include "fl/variable/OutputVariable.h"
#include "fl/variable/Variable.h"
#endif /* FL_HEADERS_H */

View File

@ -0,0 +1,144 @@
/*
Author: Juan Rada-Vilela, Ph.D.
Copyright (C) 2010-2014 FuzzyLite Limited
All rights reserved
This file is part of fuzzylite.
fuzzylite is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option)
any later version.
fuzzylite 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 Lesser General Public License
for more details.
You should have received a copy of the GNU Lesser General Public License
along with fuzzylite. If not, see <http://www.gnu.org/licenses/>.
fuzzylite is a trademark of FuzzyLite Limited.
*/
#ifndef FL_OPERATION_H
#define FL_OPERATION_H
#include "fl/fuzzylite.h"
#include "fl/Exception.h"
#include <string>
#include <vector>
namespace fl {
class FL_API Operation {
public:
template <typename T>
static T min(T a, T b);
template <typename T>
static T max(T a, T b);
template <typename T>
static T bound(T x, T min, T max);
template <typename T>
static bool in(T x, T min, T max, bool geq = true, bool leq = true);
template <typename T>
static bool isInf(T x);
template <typename T>
static bool isNaN(T x);
template <typename T>
static bool isFinite(T x);
//Is less than
static bool isLt(scalar a, scalar b, scalar macheps = fl::fuzzylite::macheps());
static bool isLE(scalar a, scalar b, scalar macheps = fl::fuzzylite::macheps());
static bool isEq(scalar a, scalar b, scalar macheps = fl::fuzzylite::macheps());
static bool isGt(scalar a, scalar b, scalar macheps = fl::fuzzylite::macheps());
static bool isGE(scalar a, scalar b, scalar macheps = fl::fuzzylite::macheps());
static scalar scale(scalar x, scalar fromMin, scalar fromMax,
scalar toMin, scalar toMax, bool bounded = false);
static scalar add(scalar a, scalar b);
static scalar subtract(scalar a, scalar b);
static scalar multiply(scalar a, scalar b);
static scalar divide(scalar a, scalar b);
static scalar modulo(scalar a, scalar b);
static scalar logicalAnd(scalar a, scalar b);
static scalar logicalOr(scalar a, scalar b);
static scalar logicalNot(scalar a);
static scalar negate(scalar a);
static scalar round(scalar x);
//greater than
static scalar gt(scalar a, scalar b);
//greater than or equal to
static scalar ge(scalar a, scalar b);
//equal to
static scalar eq(scalar a, scalar b);
//not equal to
static scalar neq(scalar a, scalar b);
//less than or equal to
static scalar le(scalar a, scalar b);
//less than
static scalar lt(scalar a, scalar b);
static bool increment(std::vector<int>& x, std::vector<int>& min, std::vector<int>& max);
static bool increment(std::vector<int>& x, int position, std::vector<int>& min, std::vector<int>& max);
static double mean(const std::vector<scalar>& x);
static double variance(const std::vector<scalar>& x);
static double variance(const std::vector<scalar>& x, scalar mean);
static double standardDeviation(const std::vector<scalar>& x);
static double standardDeviation(const std::vector<scalar>& x, scalar mean);
static std::string validName(const std::string& name);
static int isValidForName(int character);
static std::string findReplace(const std::string& str, const std::string& find,
const std::string& replace, bool replaceAll = true);
static std::vector<std::string> split(const std::string& str,
const std::string& delimiter = " ", bool ignoreEmpty = true);
static std::string trim(const std::string& text);
static std::string format(const std::string& text, int matchesChar(int),
const std::string& replacement = "");
//Intentionally results in a compiler error in C++11, or linker error in C++98
//in order to avoid the deprecated usage of this method from version 4.0
static scalar toScalar(const std::string& x, bool quiet,
scalar alternative = fl::nan) FL_IDELETE;
static scalar toScalar(const std::string& x); //throws fl::Exception
static scalar toScalar(const std::string& x, scalar alternative) FL_INOEXCEPT;
static bool isNumeric(const std::string& x);
template <typename T>
static std::string str(T x, int decimals = fuzzylite::decimals());
template <typename T>
static std::string join(const std::vector<T>& x, const std::string& separator);
template <typename T>
static std::string join(int items, const std::string& separator, T first, ...);
};
typedef Operation Op;
}
#endif /* FL_OPERATION_H */

View File

@ -0,0 +1,49 @@
/*
Author: Juan Rada-Vilela, Ph.D.
Copyright (C) 2010-2014 FuzzyLite Limited
All rights reserved
This file is part of fuzzylite.
fuzzylite is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option)
any later version.
fuzzylite 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 Lesser General Public License
for more details.
You should have received a copy of the GNU Lesser General Public License
along with fuzzylite. If not, see <http://www.gnu.org/licenses/>.
fuzzylite is a trademark of FuzzyLite Limited.
*/
#ifndef FL_BISECTOR_H
#define FL_BISECTOR_H
#include "fl/defuzzifier/IntegralDefuzzifier.h"
namespace fl {
class FL_API Bisector : public IntegralDefuzzifier {
public:
Bisector(int resolution = defaultResolution());
virtual ~Bisector() FL_IOVERRIDE;
FL_DEFAULT_COPY_AND_MOVE(Bisector)
virtual std::string className() const FL_IOVERRIDE;
virtual scalar defuzzify(const Term* term,
scalar minimum, scalar maximum) const FL_IOVERRIDE;
virtual Bisector* clone() const FL_IOVERRIDE;
static Defuzzifier* constructor();
};
}
#endif /* FL_BISECTOR_H */

View File

@ -0,0 +1,47 @@
/*
Author: Juan Rada-Vilela, Ph.D.
Copyright (C) 2010-2014 FuzzyLite Limited
All rights reserved
This file is part of fuzzylite.
fuzzylite is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option)
any later version.
fuzzylite 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 Lesser General Public License
for more details.
You should have received a copy of the GNU Lesser General Public License
along with fuzzylite. If not, see <http://www.gnu.org/licenses/>.
fuzzylite is a trademark of FuzzyLite Limited.
*/
#ifndef FL_CENTROID_H
#define FL_CENTROID_H
#include "fl/defuzzifier/IntegralDefuzzifier.h"
namespace fl {
class FL_API Centroid : public IntegralDefuzzifier {
public:
Centroid(int resolution = defaultResolution());
virtual ~Centroid() FL_IOVERRIDE;
FL_DEFAULT_COPY_AND_MOVE(Centroid)
virtual std::string className() const FL_IOVERRIDE;
virtual scalar defuzzify(const Term* term,
scalar minimum, scalar maximum) const FL_IOVERRIDE;
virtual Centroid* clone() const FL_IOVERRIDE;
static Defuzzifier* constructor();
};
}
#endif /* FL_CENTROID_H */

Some files were not shown because too many files have changed in this diff Show More