Initial git init

in the future I may add the SVN history
This commit is contained in:
Yann Esposito (Yogsototh) 2011-05-17 22:24:18 +02:00
commit 919d4a1006
63 changed files with 20095 additions and 0 deletions

BIN
.DS_Store vendored Normal file

Binary file not shown.

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
.svn

37
apprend.sh Executable file
View File

@ -0,0 +1,37 @@
#! /bin/bash
if [ $# -lt 3 ]; then
echo "utilisation : $0 fichier_automate nombre_d_essais nombre_de_base [nb_repetitions]"
exit -1
fi
options="-v -p .5 --maxmots 10"
# options="-v -p .2"
if [ $# -gt 3 ]; then
nombre_repetitions=$4
else
nombre_repetitions=1
fi
cible=$1
name=`basename $cible`
svgrep="test/svg"
dist=$svgrep/dist-$name
cat /dev/null > $dist
k=1
while [ $k -le $2 ]; do
i=$(( $k * $3 ))
realTaille=$(( $i * $2 ))
for j in `seq $nombre_repetitions`; do
id=$name-$realTaille-$j
sample=$svgrep/sample-$id
log=$svgrep/log-$id
ma=$svgrep/ma-$id.ma
./dees --sample $cible $realTaille $sample
./dees --deesha $options -o $ma $sample > $log
./dees --dist $cible $ma >> $dist 2>/dev/null
done
k=$(( $k + 1 ))
done

1
dees Symbolic link
View File

@ -0,0 +1 @@
build/Debug/dees

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,751 @@
// !$*UTF8*$!
{
08FB7793FE84155DC02AAC07 /* Project object */ = {
activeBuildConfigurationName = Debug;
activeExecutable = F878A30309F3A36A00225D95 /* dees */;
activeTarget = 8DD76F620486A84900D96B5E /* dees */;
addToTargets = (
8DD76F620486A84900D96B5E /* dees */,
);
codeSenseManager = F878A30A09F3A37400225D95 /* Code sense */;
executables = (
F878A30309F3A36A00225D95 /* dees */,
);
perUserDictionary = {
PBXConfiguration.PBXFileTableDataSource3.PBXExecutablesDataSource = {
PBXFileTableDataSourceColumnSortingDirectionKey = "-1";
PBXFileTableDataSourceColumnSortingKey = PBXExecutablesDataSource_NameID;
PBXFileTableDataSourceColumnWidthsKey = (
22,
300,
400,
);
PBXFileTableDataSourceColumnsKey = (
PBXExecutablesDataSource_ActiveFlagID,
PBXExecutablesDataSource_NameID,
PBXExecutablesDataSource_CommentsID,
);
};
PBXConfiguration.PBXFileTableDataSource3.PBXFileTableDataSource = {
PBXFileTableDataSourceColumnSortingDirectionKey = 1;
PBXFileTableDataSourceColumnSortingKey = PBXFileDataSource_Filename_ColumnID;
PBXFileTableDataSourceColumnWidthsKey = (
20,
540,
20,
48,
43,
43,
20,
);
PBXFileTableDataSourceColumnsKey = (
PBXFileDataSource_FiletypeID,
PBXFileDataSource_Filename_ColumnID,
PBXFileDataSource_Built_ColumnID,
PBXFileDataSource_ObjectSize_ColumnID,
PBXFileDataSource_Errors_ColumnID,
PBXFileDataSource_Warnings_ColumnID,
PBXFileDataSource_Target_ColumnID,
);
};
PBXConfiguration.PBXFileTableDataSource3.PBXSymbolsDataSource = {
PBXFileTableDataSourceColumnSortingDirectionKey = "-1";
PBXFileTableDataSourceColumnSortingKey = PBXSymbolsDataSource_SymbolNameID;
PBXFileTableDataSourceColumnWidthsKey = (
16,
200,
50,
200,
);
PBXFileTableDataSourceColumnsKey = (
PBXSymbolsDataSource_SymbolTypeIconID,
PBXSymbolsDataSource_SymbolNameID,
PBXSymbolsDataSource_SymbolTypeID,
PBXSymbolsDataSource_ReferenceNameID,
);
};
PBXPerProjectTemplateStateSaveDate = 202045661;
PBXWorkspaceStateSaveDate = 202045661;
};
perUserProjectItems = {
F80E92B009F4496F00850979 /* PBXTextBookmark */ = F80E92B009F4496F00850979 /* PBXTextBookmark */;
F80E92B109F4496F00850979 /* PBXTextBookmark */ = F80E92B109F4496F00850979 /* PBXTextBookmark */;
F80E92B309F4496F00850979 /* PBXTextBookmark */ = F80E92B309F4496F00850979 /* PBXTextBookmark */;
F84488190C0B4B5000D2870A /* PBXTextBookmark */ = F84488190C0B4B5000D2870A /* PBXTextBookmark */;
F844881A0C0B4B5000D2870A /* PBXTextBookmark */ = F844881A0C0B4B5000D2870A /* PBXTextBookmark */;
F844881B0C0B4B5000D2870A /* PBXTextBookmark */ = F844881B0C0B4B5000D2870A /* PBXTextBookmark */;
F860B02609F402D50027FF1E /* PBXTextBookmark */ = F860B02609F402D50027FF1E /* PBXTextBookmark */;
F860B02709F402D50027FF1E /* PBXTextBookmark */ = F860B02709F402D50027FF1E /* PBXTextBookmark */;
F860B03109F402D50027FF1E /* PBXTextBookmark */ = F860B03109F402D50027FF1E /* PBXTextBookmark */;
F860B03609F402D50027FF1E /* PBXTextBookmark */ = F860B03609F402D50027FF1E /* PBXTextBookmark */;
F860B03C09F402D50027FF1E /* PBXTextBookmark */ = F860B03C09F402D50027FF1E /* PBXTextBookmark */;
F860B0CA09F40B5F0027FF1E /* PBXTextBookmark */ = F860B0CA09F40B5F0027FF1E /* PBXTextBookmark */;
F860B0D109F40B5F0027FF1E /* PBXTextBookmark */ = F860B0D109F40B5F0027FF1E /* PBXTextBookmark */;
F860B0D309F40B5F0027FF1E /* PBXTextBookmark */ = F860B0D309F40B5F0027FF1E /* PBXTextBookmark */;
F860B0D409F40B5F0027FF1E /* PBXTextBookmark */ = F860B0D409F40B5F0027FF1E /* PBXTextBookmark */;
F860B0D509F40B5F0027FF1E /* PBXTextBookmark */ = F860B0D509F40B5F0027FF1E /* PBXTextBookmark */;
F860B0D609F40B5F0027FF1E /* PBXTextBookmark */ = F860B0D609F40B5F0027FF1E /* PBXTextBookmark */;
F860B0D809F40B5F0027FF1E /* PBXTextBookmark */ = F860B0D809F40B5F0027FF1E /* PBXTextBookmark */;
F871D10509F4E5D7001A8E9E /* PBXTextBookmark */ = F871D10509F4E5D7001A8E9E /* PBXTextBookmark */;
F871D17609F4F4A6001A8E9E /* PBXTextBookmark */ = F871D17609F4F4A6001A8E9E /* PBXTextBookmark */;
F871D17709F4F4A6001A8E9E /* PBXTextBookmark */ = F871D17709F4F4A6001A8E9E /* PBXTextBookmark */;
F871D17F09F4F4A6001A8E9E /* PBXTextBookmark */ = F871D17F09F4F4A6001A8E9E /* PBXTextBookmark */;
F876431509F7F5E500BAAC93 /* PBXTextBookmark */ = F876431509F7F5E500BAAC93 /* PBXTextBookmark */;
F896E5800BFB0BC400C659C6 /* PBXTextBookmark */ = F896E5800BFB0BC400C659C6 /* PBXTextBookmark */;
F896E5810BFB0BC400C659C6 /* PBXTextBookmark */ = F896E5810BFB0BC400C659C6 /* PBXTextBookmark */;
F896E5820BFB0BC400C659C6 /* PBXTextBookmark */ = F896E5820BFB0BC400C659C6 /* PBXTextBookmark */;
F896E5830BFB0BC400C659C6 /* PBXTextBookmark */ = F896E5830BFB0BC400C659C6 /* PBXTextBookmark */;
F896E5840BFB0BC400C659C6 /* PBXTextBookmark */ = F896E5840BFB0BC400C659C6 /* PBXTextBookmark */;
F896E5850BFB0BC400C659C6 /* PBXTextBookmark */ = F896E5850BFB0BC400C659C6 /* PBXTextBookmark */;
F896E5880BFB0BC400C659C6 /* PBXTextBookmark */ = F896E5880BFB0BC400C659C6 /* PBXTextBookmark */;
F8A1460C09F7E54200584BA4 /* PBXTextBookmark */ = F8A1460C09F7E54200584BA4 /* PBXTextBookmark */;
F8B74EFF09F9512000D55E52 /* PBXTextBookmark */ = F8B74EFF09F9512000D55E52 /* PBXTextBookmark */;
F8D16C060A2517DD00264622 /* PBXTextBookmark */ = F8D16C060A2517DD00264622 /* PBXTextBookmark */;
F8D93E540B8EE67900D2768C /* PBXTextBookmark */ = F8D93E540B8EE67900D2768C /* PBXTextBookmark */;
F8F48D780A243553009DE375 /* PBXTextBookmark */ = F8F48D780A243553009DE375 /* PBXTextBookmark */;
F8F48D790A243553009DE375 /* PBXTextBookmark */ = F8F48D790A243553009DE375 /* PBXTextBookmark */;
F8F48D7B0A243553009DE375 /* PBXTextBookmark */ = F8F48D7B0A243553009DE375 /* PBXTextBookmark */;
F8F48D7C0A243553009DE375 /* PBXTextBookmark */ = F8F48D7C0A243553009DE375 /* PBXTextBookmark */;
F8F48D7D0A243553009DE375 /* PBXTextBookmark */ = F8F48D7D0A243553009DE375 /* PBXTextBookmark */;
F8F48D7F0A243553009DE375 /* PBXTextBookmark */ = F8F48D7F0A243553009DE375 /* PBXTextBookmark */;
F8F48D800A243553009DE375 /* PBXTextBookmark */ = F8F48D800A243553009DE375 /* PBXTextBookmark */;
F8F48D810A243553009DE375 /* PBXTextBookmark */ = F8F48D810A243553009DE375 /* PBXTextBookmark */;
};
sourceControlManager = F878A30909F3A37400225D95 /* Source Control */;
userBuildSettings = {
};
};
08FB7796FE84155DC02AAC07 /* main.cpp */ = {
uiCtxt = {
sepNavIntBoundsRect = "{{0, 0}, {1268, 18536}}";
sepNavSelRange = "{39687, 1}";
sepNavVisRect = "{{0, 18111}, {775, 417}}";
sepNavWindowFrame = "{{38, 39}, {947, 681}}";
};
};
8DD76F620486A84900D96B5E /* dees */ = {
activeExec = 0;
executables = (
F878A30309F3A36A00225D95 /* dees */,
);
};
C6859E8B029090EE04C91782 /* dees.1 */ = {
uiCtxt = {
sepNavIntBoundsRect = "{{0, 0}, {908, 1106}}";
sepNavSelRange = "{0, 0}";
sepNavVisRect = "{{0, 554}, {908, 552}}";
sepNavWindowFrame = "{{15, 60}, {947, 681}}";
};
};
F80E92B009F4496F00850979 /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F878A31309F3A48B00225D95 /* test.cpp */;
name = "test.cpp: 382";
rLen = 0;
rLoc = 1105;
rType = 0;
vrLen = 978;
vrLoc = 0;
};
F80E92B109F4496F00850979 /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F878A32309F3A4A100225D95 /* test.H */;
name = "test.H: 1";
rLen = 0;
rLoc = 0;
rType = 0;
vrLen = 256;
vrLoc = 0;
};
F80E92B309F4496F00850979 /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F878A32909F3A4A100225D95 /* main.H */;
name = "main.H: 1";
rLen = 0;
rLoc = 0;
rType = 0;
vrLen = 1246;
vrLoc = 0;
};
F84488190C0B4B5000D2870A /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F878A32A09F3A4A100225D95 /* ma.H */;
name = "ma.H: coherent";
rLen = 0;
rLoc = 11662;
rType = 0;
vrLen = 1058;
vrLoc = 10967;
};
F844881A0C0B4B5000D2870A /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F878A32A09F3A4A100225D95 /* ma.H */;
name = "ma.H: coherent";
rLen = 0;
rLoc = 11662;
rType = 0;
vrLen = 1058;
vrLoc = 10967;
};
F844881B0C0B4B5000D2870A /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F878A32409F3A4A100225D95 /* spfa.H */;
name = "spfa.H: 1";
rLen = 0;
rLoc = 0;
rType = 0;
vrLen = 1434;
vrLoc = 0;
};
F860AF3809F3D8430027FF1E /* simplex.cpp */ = {
uiCtxt = {
sepNavIntBoundsRect = "{{0, 0}, {775, 2758}}";
sepNavSelRange = "{506, 14}";
sepNavVisRect = "{{0, 0}, {775, 417}}";
sepNavWindowFrame = "{{38, 39}, {947, 681}}";
};
};
F860B02609F402D50027FF1E /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F878A32509F3A4A100225D95 /* simplex.H */;
name = "simplex.H: add_absolute_constraint_with_parameters";
rLen = 0;
rLoc = 1834;
rType = 0;
vrLen = 558;
vrLoc = 0;
};
F860B02709F402D50027FF1E /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F860AF3809F3D8430027FF1E /* simplex.cpp */;
name = "simplex.cpp: 12";
rLen = 0;
rLoc = 5023;
rType = 0;
vrLen = 162;
vrLoc = 0;
};
F860B03109F402D50027FF1E /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = 08FB7796FE84155DC02AAC07 /* main.cpp */;
name = "main.cpp: 1";
rLen = 0;
rLoc = 0;
rType = 0;
vrLen = 2141;
vrLoc = 0;
};
F860B03609F402D50027FF1E /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F878A32709F3A4A100225D95 /* pprfa.H */;
name = "pprfa.H: 1";
rLen = 0;
rLoc = 0;
rType = 0;
vrLen = 1849;
vrLoc = 1358;
};
F860B03C09F402D50027FF1E /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F878A32609F3A4A100225D95 /* sample.H */;
name = "sample.H: 1";
rLen = 0;
rLoc = 0;
rType = 0;
vrLen = 1370;
vrLoc = 0;
};
F860B0CA09F40B5F0027FF1E /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F878A32C09F3A4A100225D95 /* general.H */;
name = "general.H: 1";
rLen = 0;
rLoc = 0;
rType = 0;
vrLen = 1277;
vrLoc = 0;
};
F860B0D109F40B5F0027FF1E /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F878A31709F3A48B00225D95 /* pprfa.cpp */;
name = "pprfa.cpp: 1478";
rLen = 0;
rLoc = 4256;
rType = 0;
vrLen = 1161;
vrLoc = 702;
};
F860B0D309F40B5F0027FF1E /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F878A32C09F3A4A100225D95 /* general.H */;
name = "general.H: 1";
rLen = 0;
rLoc = 0;
rType = 0;
vrLen = 1277;
vrLoc = 0;
};
F860B0D409F40B5F0027FF1E /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F878A31809F3A48B00225D95 /* pfa.cpp */;
name = T_M;
rLen = 3;
rLoc = 6126;
rType = 0;
vrLen = 788;
vrLoc = 5819;
};
F860B0D509F40B5F0027FF1E /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F878A31909F3A48B00225D95 /* ma.cpp */;
name = "ma.cpp: 1602";
rLen = 0;
rLoc = 45081;
rType = 0;
vrLen = 924;
vrLoc = 44822;
};
F860B0D609F40B5F0027FF1E /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F878A32A09F3A4A100225D95 /* ma.H */;
name = "ma.H: 1";
rLen = 0;
rLoc = 0;
rType = 0;
vrLen = 1530;
vrLoc = 0;
};
F860B0D809F40B5F0027FF1E /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F878A32809F3A4A100225D95 /* pfa.H */;
name = "pfa.H: 32";
rLen = 0;
rLoc = 1490;
rType = 0;
vrLen = 1250;
vrLoc = 1244;
};
F871D10509F4E5D7001A8E9E /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F878A31409F3A48B00225D95 /* spfa.cpp */;
name = "spfa.cpp: 1";
rLen = 0;
rLoc = 0;
rType = 0;
vrLen = 1567;
vrLoc = 0;
};
F871D15409F4F14C001A8E9E /* pprfa_dees.cpp */ = {
uiCtxt = {
sepNavIntBoundsRect = "{{0, 0}, {812, 7504}}";
sepNavSelRange = "{5026, 0}";
sepNavVisRect = "{{0, 2187}, {775, 417}}";
};
};
F871D16009F4F3D6001A8E9E /* pprfa_bm.cpp */ = {
uiCtxt = {
sepNavIntBoundsRect = "{{0, 0}, {800, 5922}}";
sepNavSelRange = "{161, 0}";
sepNavVisRect = "{{0, 199}, {775, 417}}";
};
};
F871D17609F4F4A6001A8E9E /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F878A31609F3A48B00225D95 /* sample.cpp */;
name = "sample.cpp: 1";
rLen = 0;
rLoc = 0;
rType = 0;
vrLen = 1511;
vrLoc = 0;
};
F871D17709F4F4A6001A8E9E /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F871D15409F4F14C001A8E9E /* pprfa_dees.cpp */;
name = "pprfa_dees.cpp: 1";
rLen = 0;
rLoc = 0;
rType = 0;
vrLen = 168;
vrLoc = 0;
};
F871D17F09F4F4A6001A8E9E /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F871D16009F4F3D6001A8E9E /* pprfa_bm.cpp */;
name = "pprfa_bm.cpp: 10";
rLen = 0;
rLoc = 158;
rType = 0;
vrLen = 161;
vrLoc = 0;
};
F876431509F7F5E500BAAC93 /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F878A32909F3A4A100225D95 /* main.H */;
name = "main.H: 1";
rLen = 0;
rLoc = 0;
rType = 0;
vrLen = 1125;
vrLoc = 0;
};
F878A30309F3A36A00225D95 /* dees */ = {
isa = PBXExecutable;
activeArgIndex = 0;
activeArgIndices = (
YES,
);
argumentStrings = (
"--deesha test/sample",
);
autoAttachOnCrash = 1;
configStateDict = {
"PBXLSLaunchAction-0" = {
PBXLSLaunchAction = 0;
PBXLSLaunchStartAction = 1;
PBXLSLaunchStdioStyle = 2;
PBXLSLaunchStyle = 0;
class = PBXLSRunLaunchConfig;
displayName = "Executable Runner";
identifier = com.apple.Xcode.launch.runConfig;
remoteHostInfo = "";
startActionInfo = "";
};
};
customDataFormattersEnabled = 1;
debuggerPlugin = GDBDebugging;
disassemblyDisplayState = 0;
dylibVariantSuffix = "";
enableDebugStr = 1;
environmentEntries = (
);
executableSystemSymbolLevel = 0;
executableUserSymbolLevel = 0;
libgmallocEnabled = 0;
name = dees;
savedGlobals = {
};
sourceDirectories = (
);
startupPath = "<<ProjectDirectory>>";
};
F878A30909F3A37400225D95 /* Source Control */ = {
isa = PBXSourceControlManager;
fallbackIsa = XCSourceControlManager;
isSCMEnabled = 0;
scmConfiguration = {
};
scmType = "";
};
F878A30A09F3A37400225D95 /* Code sense */ = {
isa = PBXCodeSenseManager;
indexTemplatePath = "";
};
F878A31309F3A48B00225D95 /* test.cpp */ = {
uiCtxt = {
sepNavIntBoundsRect = "{{0, 0}, {775, 1302}}";
sepNavSelRange = "{202, 339}";
sepNavVisRect = "{{0, 199}, {775, 417}}";
sepNavWindowFrame = "{{38, 39}, {947, 681}}";
};
};
F878A31409F3A48B00225D95 /* spfa.cpp */ = {
uiCtxt = {
sepNavIntBoundsRect = "{{0, 0}, {775, 17990}}";
sepNavSelRange = "{13975, 1446}";
sepNavVisRect = "{{0, 6177}, {775, 417}}";
};
};
F878A31609F3A48B00225D95 /* sample.cpp */ = {
uiCtxt = {
sepNavIntBoundsRect = "{{0, 0}, {775, 10682}}";
sepNavSelRange = "{0, 0}";
sepNavVisRect = "{{0, 199}, {775, 417}}";
};
};
F878A31709F3A48B00225D95 /* pprfa.cpp */ = {
uiCtxt = {
sepNavIntBoundsRect = "{{0, 0}, {775, 4760}}";
sepNavSelRange = "{2882, 0}";
sepNavVisRect = "{{0, 1330}, {775, 417}}";
};
};
F878A31809F3A48B00225D95 /* pfa.cpp */ = {
uiCtxt = {
sepNavIntBoundsRect = "{{0, 0}, {775, 9996}}";
sepNavSelRange = "{8783, 0}";
sepNavVisRect = "{{0, 4592}, {775, 417}}";
};
};
F878A31909F3A48B00225D95 /* ma.cpp */ = {
uiCtxt = {
sepNavIntBoundsRect = "{{0, 0}, {908, 35882}}";
sepNavSelRange = "{56358, 0}";
sepNavVisRect = "{{0, 27211}, {775, 417}}";
};
};
F878A31A09F3A48B00225D95 /* interface.cpp */ = {
uiCtxt = {
sepNavIntBoundsRect = "{{0, 0}, {775, 9744}}";
sepNavSelRange = "{13429, 0}";
sepNavVisRect = "{{0, 7462}, {775, 417}}";
};
};
F878A32309F3A4A100225D95 /* test.H */ = {
uiCtxt = {
sepNavIntBoundsRect = "{{0, 0}, {775, 417}}";
sepNavSelRange = "{0, 0}";
sepNavVisRect = "{{0, 0}, {775, 417}}";
sepNavWindowFrame = "{{15, 60}, {947, 681}}";
};
};
F878A32409F3A4A100225D95 /* spfa.H */ = {
uiCtxt = {
sepNavIntBoundsRect = "{{0, 0}, {738, 2366}}";
sepNavSelRange = "{0, 0}";
sepNavVisRect = "{{0, 0}, {738, 391}}";
};
};
F878A32509F3A4A100225D95 /* simplex.H */ = {
uiCtxt = {
sepNavIntBoundsRect = "{{0, 0}, {775, 1092}}";
sepNavSelRange = "{1213, 0}";
sepNavVisRect = "{{0, 499}, {775, 417}}";
sepNavWindowFrame = "{{61, 18}, {947, 681}}";
};
};
F878A32609F3A4A100225D95 /* sample.H */ = {
uiCtxt = {
sepNavIntBoundsRect = "{{0, 0}, {775, 2856}}";
sepNavSelRange = "{0, 0}";
sepNavVisRect = "{{0, 0}, {775, 417}}";
};
};
F878A32709F3A4A100225D95 /* pprfa.H */ = {
uiCtxt = {
sepNavIntBoundsRect = "{{0, 0}, {854, 2520}}";
sepNavSelRange = "{1574, 25}";
sepNavVisRect = "{{0, 384}, {337, 199}}";
sepNavWindowFrame = "{{15, 60}, {947, 681}}";
};
};
F878A32809F3A4A100225D95 /* pfa.H */ = {
uiCtxt = {
sepNavIntBoundsRect = "{{0, 0}, {775, 1582}}";
sepNavSelRange = "{4161, 0}";
sepNavVisRect = "{{0, 919}, {775, 417}}";
sepNavWindowFrame = "{{15, 60}, {947, 681}}";
};
};
F878A32909F3A4A100225D95 /* main.H */ = {
uiCtxt = {
sepNavIntBoundsRect = "{{0, 0}, {775, 490}}";
sepNavSelRange = "{0, 0}";
sepNavVisRect = "{{0, 0}, {775, 417}}";
};
};
F878A32A09F3A4A100225D95 /* ma.H */ = {
uiCtxt = {
sepNavIntBoundsRect = "{{0, 0}, {2390, 3906}}";
sepNavSelRange = "{11662, 0}";
sepNavVisRect = "{{0, 3515}, {738, 391}}";
};
};
F878A32C09F3A4A100225D95 /* general.H */ = {
uiCtxt = {
sepNavIntBoundsRect = "{{0, 0}, {775, 1904}}";
sepNavSelRange = "{0, 0}";
sepNavVisRect = "{{0, 0}, {775, 417}}";
};
};
F896E5800BFB0BC400C659C6 /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F860AF3809F3D8430027FF1E /* simplex.cpp */;
name = realNotBounded;
rLen = 14;
rLoc = 506;
rType = 0;
vrLen = 735;
vrLoc = 0;
};
F896E5810BFB0BC400C659C6 /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F878A32309F3A4A100225D95 /* test.H */;
name = "test.H: 1";
rLen = 0;
rLoc = 0;
rType = 0;
vrLen = 256;
vrLoc = 0;
};
F896E5820BFB0BC400C659C6 /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F878A32509F3A4A100225D95 /* simplex.H */;
name = "simplex.H: 51";
rLen = 0;
rLoc = 1213;
rType = 0;
vrLen = 831;
vrLoc = 833;
};
F896E5830BFB0BC400C659C6 /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F878A32609F3A4A100225D95 /* sample.H */;
name = "sample.H: 1";
rLen = 0;
rLoc = 0;
rType = 0;
vrLen = 1370;
vrLoc = 0;
};
F896E5840BFB0BC400C659C6 /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F878A31309F3A48B00225D95 /* test.cpp */;
name = "test.cpp: test_PSe";
rLen = 339;
rLoc = 202;
rType = 0;
vrLen = 553;
vrLoc = 224;
};
F896E5850BFB0BC400C659C6 /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F878A32409F3A4A100225D95 /* spfa.H */;
name = "spfa.H: 1";
rLen = 0;
rLoc = 0;
rType = 0;
vrLen = 1839;
vrLoc = 1668;
};
F896E5880BFB0BC400C659C6 /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F878A32409F3A4A100225D95 /* spfa.H */;
name = "spfa.H: 1";
rLen = 0;
rLoc = 0;
rType = 0;
vrLen = 1450;
vrLoc = 0;
};
F8A1460C09F7E54200584BA4 /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F878A31A09F3A48B00225D95 /* interface.cpp */;
name = "interface.cpp: Apprentissage_unique";
rLen = 0;
rLoc = 13429;
rType = 0;
vrLen = 793;
vrLoc = 15362;
};
F8B74EFF09F9512000D55E52 /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F878A32709F3A4A100225D95 /* pprfa.H */;
name = "pprfa.H: 58";
rLen = 0;
rLoc = 2418;
rType = 0;
vrLen = 1427;
vrLoc = 1631;
};
F8D16C060A2517DD00264622 /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F878A31909F3A48B00225D95 /* ma.cpp */;
name = "ma.cpp: 1968";
rLen = 0;
rLoc = 56358;
rType = 0;
vrLen = 1109;
vrLoc = 55440;
};
F8D93E540B8EE67900D2768C /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F878A31409F3A48B00225D95 /* spfa.cpp */;
name = "spfa.cpp: 455";
rLen = 1446;
rLoc = 13975;
rType = 0;
vrLen = 657;
vrLoc = 13736;
};
F8F48D780A243553009DE375 /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = 08FB7796FE84155DC02AAC07 /* main.cpp */;
name = "}";
rLen = 1;
rLoc = 39687;
rType = 0;
vrLen = 762;
vrLoc = 38926;
};
F8F48D790A243553009DE375 /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F878A32809F3A4A100225D95 /* pfa.H */;
name = "pfa.H: perplexite";
rLen = 0;
rLoc = 4161;
rType = 0;
vrLen = 1560;
vrLoc = 3595;
};
F8F48D7B0A243553009DE375 /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F871D15409F4F14C001A8E9E /* pprfa_dees.cpp */;
name = "pprfa_dees.cpp: 176";
rLen = 0;
rLoc = 5026;
rType = 0;
vrLen = 1001;
vrLoc = 4451;
};
F8F48D7C0A243553009DE375 /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F871D16009F4F3D6001A8E9E /* pprfa_bm.cpp */;
name = "pprfa_bm.cpp: becomeQuasiPrefixTree";
rLen = 0;
rLoc = 161;
rType = 0;
vrLen = 561;
vrLoc = 289;
};
F8F48D7D0A243553009DE375 /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F878A31A09F3A48B00225D95 /* interface.cpp */;
name = "interface.cpp: Apprentissage_unique";
rLen = 0;
rLoc = 13429;
rType = 0;
vrLen = 534;
vrLoc = 15362;
};
F8F48D7F0A243553009DE375 /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F878A31809F3A48B00225D95 /* pfa.cpp */;
name = "pfa.cpp: 332";
rLen = 0;
rLoc = 8783;
rType = 0;
vrLen = 611;
vrLoc = 8734;
};
F8F48D800A243553009DE375 /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F878A31709F3A48B00225D95 /* pprfa.cpp */;
name = "pprfa.cpp: 99";
rLen = 0;
rLoc = 2882;
rType = 0;
vrLen = 627;
vrLoc = 2817;
};
F8F48D810A243553009DE375 /* PBXTextBookmark */ = {
isa = PBXTextBookmark;
fRef = F878A31609F3A48B00225D95 /* sample.cpp */;
name = "sample.cpp: 1";
rLen = 0;
rLoc = 0;
rType = 0;
vrLen = 656;
vrLoc = 855;
};
}

View File

@ -0,0 +1,318 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 42;
objects = {
/* Begin PBXBuildFile section */
8DD76F650486A84900D96B5E /* main.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 08FB7796FE84155DC02AAC07 /* main.cpp */; settings = {ATTRIBUTES = (); }; };
8DD76F6A0486A84900D96B5E /* dees.1 in CopyFiles */ = {isa = PBXBuildFile; fileRef = C6859E8B029090EE04C91782 /* dees.1 */; };
F860AF3909F3D8430027FF1E /* simplex.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F860AF3809F3D8430027FF1E /* simplex.cpp */; };
F871D15509F4F14C001A8E9E /* pprfa_dees.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F871D15409F4F14C001A8E9E /* pprfa_dees.cpp */; };
F871D16109F4F3D6001A8E9E /* pprfa_bm.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F871D16009F4F3D6001A8E9E /* pprfa_bm.cpp */; };
F878A31B09F3A48B00225D95 /* test.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F878A31309F3A48B00225D95 /* test.cpp */; };
F878A31C09F3A48B00225D95 /* spfa.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F878A31409F3A48B00225D95 /* spfa.cpp */; };
F878A31E09F3A48B00225D95 /* sample.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F878A31609F3A48B00225D95 /* sample.cpp */; };
F878A31F09F3A48B00225D95 /* pprfa.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F878A31709F3A48B00225D95 /* pprfa.cpp */; };
F878A32009F3A48B00225D95 /* pfa.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F878A31809F3A48B00225D95 /* pfa.cpp */; };
F878A32109F3A48B00225D95 /* ma.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F878A31909F3A48B00225D95 /* ma.cpp */; };
F878A32209F3A48B00225D95 /* interface.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F878A31A09F3A48B00225D95 /* interface.cpp */; };
F878A32D09F3A4A100225D95 /* test.H in CopyFiles */ = {isa = PBXBuildFile; fileRef = F878A32309F3A4A100225D95 /* test.H */; };
F878A32E09F3A4A100225D95 /* spfa.H in CopyFiles */ = {isa = PBXBuildFile; fileRef = F878A32409F3A4A100225D95 /* spfa.H */; };
F878A32F09F3A4A100225D95 /* simplex.H in CopyFiles */ = {isa = PBXBuildFile; fileRef = F878A32509F3A4A100225D95 /* simplex.H */; };
F878A33009F3A4A100225D95 /* sample.H in CopyFiles */ = {isa = PBXBuildFile; fileRef = F878A32609F3A4A100225D95 /* sample.H */; };
F878A33109F3A4A100225D95 /* pprfa.H in CopyFiles */ = {isa = PBXBuildFile; fileRef = F878A32709F3A4A100225D95 /* pprfa.H */; };
F878A33209F3A4A100225D95 /* pfa.H in CopyFiles */ = {isa = PBXBuildFile; fileRef = F878A32809F3A4A100225D95 /* pfa.H */; };
F878A33309F3A4A100225D95 /* main.H in CopyFiles */ = {isa = PBXBuildFile; fileRef = F878A32909F3A4A100225D95 /* main.H */; };
F878A33409F3A4A100225D95 /* ma.H in CopyFiles */ = {isa = PBXBuildFile; fileRef = F878A32A09F3A4A100225D95 /* ma.H */; };
F878A33509F3A4A100225D95 /* interface.H in CopyFiles */ = {isa = PBXBuildFile; fileRef = F878A32B09F3A4A100225D95 /* interface.H */; };
F878A33609F3A4A100225D95 /* general.H in CopyFiles */ = {isa = PBXBuildFile; fileRef = F878A32C09F3A4A100225D95 /* general.H */; };
F878A33809F3A4B700225D95 /* liblpsolve55.a in Frameworks */ = {isa = PBXBuildFile; fileRef = F878A33709F3A4B700225D95 /* liblpsolve55.a */; };
F878A33A09F3A4D300225D95 /* lp_lib.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = F878A33909F3A4D200225D95 /* lp_lib.h */; };
/* End PBXBuildFile section */
/* Begin PBXCopyFilesBuildPhase section */
8DD76F690486A84900D96B5E /* CopyFiles */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 8;
dstPath = /usr/share/man/man1/;
dstSubfolderSpec = 0;
files = (
8DD76F6A0486A84900D96B5E /* dees.1 in CopyFiles */,
F878A32D09F3A4A100225D95 /* test.H in CopyFiles */,
F878A32E09F3A4A100225D95 /* spfa.H in CopyFiles */,
F878A32F09F3A4A100225D95 /* simplex.H in CopyFiles */,
F878A33009F3A4A100225D95 /* sample.H in CopyFiles */,
F878A33109F3A4A100225D95 /* pprfa.H in CopyFiles */,
F878A33209F3A4A100225D95 /* pfa.H in CopyFiles */,
F878A33309F3A4A100225D95 /* main.H in CopyFiles */,
F878A33409F3A4A100225D95 /* ma.H in CopyFiles */,
F878A33509F3A4A100225D95 /* interface.H in CopyFiles */,
F878A33609F3A4A100225D95 /* general.H in CopyFiles */,
F878A33A09F3A4D300225D95 /* lp_lib.h in CopyFiles */,
);
runOnlyForDeploymentPostprocessing = 1;
};
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
08FB7796FE84155DC02AAC07 /* main.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = main.cpp; sourceTree = "<group>"; };
8DD76F6C0486A84900D96B5E /* dees */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = dees; sourceTree = BUILT_PRODUCTS_DIR; };
C6859E8B029090EE04C91782 /* dees.1 */ = {isa = PBXFileReference; lastKnownFileType = text.man; path = dees.1; sourceTree = "<group>"; };
F860AF3809F3D8430027FF1E /* simplex.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = simplex.cpp; sourceTree = "<group>"; };
F871D15409F4F14C001A8E9E /* pprfa_dees.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = pprfa_dees.cpp; sourceTree = "<group>"; };
F871D16009F4F3D6001A8E9E /* pprfa_bm.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = pprfa_bm.cpp; sourceTree = "<group>"; };
F878A31309F3A48B00225D95 /* test.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = test.cpp; sourceTree = "<group>"; };
F878A31409F3A48B00225D95 /* spfa.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = spfa.cpp; sourceTree = "<group>"; };
F878A31609F3A48B00225D95 /* sample.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = sample.cpp; sourceTree = "<group>"; };
F878A31709F3A48B00225D95 /* pprfa.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = pprfa.cpp; sourceTree = "<group>"; };
F878A31809F3A48B00225D95 /* pfa.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = pfa.cpp; sourceTree = "<group>"; };
F878A31909F3A48B00225D95 /* ma.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ma.cpp; sourceTree = "<group>"; };
F878A31A09F3A48B00225D95 /* interface.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = interface.cpp; sourceTree = "<group>"; };
F878A32309F3A4A100225D95 /* test.H */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = test.H; sourceTree = "<group>"; };
F878A32409F3A4A100225D95 /* spfa.H */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = spfa.H; sourceTree = "<group>"; };
F878A32509F3A4A100225D95 /* simplex.H */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = simplex.H; sourceTree = "<group>"; };
F878A32609F3A4A100225D95 /* sample.H */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = sample.H; sourceTree = "<group>"; };
F878A32709F3A4A100225D95 /* pprfa.H */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = pprfa.H; sourceTree = "<group>"; };
F878A32809F3A4A100225D95 /* pfa.H */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = pfa.H; sourceTree = "<group>"; };
F878A32909F3A4A100225D95 /* main.H */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = main.H; sourceTree = "<group>"; };
F878A32A09F3A4A100225D95 /* ma.H */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = ma.H; sourceTree = "<group>"; };
F878A32B09F3A4A100225D95 /* interface.H */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = interface.H; sourceTree = "<group>"; };
F878A32C09F3A4A100225D95 /* general.H */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = general.H; sourceTree = "<group>"; };
F878A33709F3A4B700225D95 /* liblpsolve55.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = liblpsolve55.a; path = lib/liblpsolve55.a; sourceTree = "<group>"; };
F878A33909F3A4D200225D95 /* lp_lib.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = lp_lib.h; path = include/lp_lib.h; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
8DD76F660486A84900D96B5E /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
F878A33809F3A4B700225D95 /* liblpsolve55.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
08FB7794FE84155DC02AAC07 /* dees */ = {
isa = PBXGroup;
children = (
F878A31209F3A46500225D95 /* include */,
F878A31109F3A45600225D95 /* lib */,
F878A31009F3A44A00225D95 /* Headers */,
08FB7795FE84155DC02AAC07 /* Source */,
C6859E8C029090F304C91782 /* Documentation */,
1AB674ADFE9D54B511CA2CBB /* Products */,
);
name = dees;
sourceTree = "<group>";
};
08FB7795FE84155DC02AAC07 /* Source */ = {
isa = PBXGroup;
children = (
F878A31309F3A48B00225D95 /* test.cpp */,
F878A31409F3A48B00225D95 /* spfa.cpp */,
F878A31609F3A48B00225D95 /* sample.cpp */,
F878A31709F3A48B00225D95 /* pprfa.cpp */,
F878A31809F3A48B00225D95 /* pfa.cpp */,
F878A31909F3A48B00225D95 /* ma.cpp */,
F878A31A09F3A48B00225D95 /* interface.cpp */,
08FB7796FE84155DC02AAC07 /* main.cpp */,
F860AF3809F3D8430027FF1E /* simplex.cpp */,
F871D15409F4F14C001A8E9E /* pprfa_dees.cpp */,
F871D16009F4F3D6001A8E9E /* pprfa_bm.cpp */,
);
name = Source;
sourceTree = "<group>";
};
1AB674ADFE9D54B511CA2CBB /* Products */ = {
isa = PBXGroup;
children = (
8DD76F6C0486A84900D96B5E /* dees */,
);
name = Products;
sourceTree = "<group>";
};
C6859E8C029090F304C91782 /* Documentation */ = {
isa = PBXGroup;
children = (
C6859E8B029090EE04C91782 /* dees.1 */,
);
name = Documentation;
sourceTree = "<group>";
};
F878A31009F3A44A00225D95 /* Headers */ = {
isa = PBXGroup;
children = (
F878A32309F3A4A100225D95 /* test.H */,
F878A32409F3A4A100225D95 /* spfa.H */,
F878A32509F3A4A100225D95 /* simplex.H */,
F878A32609F3A4A100225D95 /* sample.H */,
F878A32709F3A4A100225D95 /* pprfa.H */,
F878A32809F3A4A100225D95 /* pfa.H */,
F878A32909F3A4A100225D95 /* main.H */,
F878A32A09F3A4A100225D95 /* ma.H */,
F878A32B09F3A4A100225D95 /* interface.H */,
F878A32C09F3A4A100225D95 /* general.H */,
);
name = Headers;
sourceTree = "<group>";
};
F878A31109F3A45600225D95 /* lib */ = {
isa = PBXGroup;
children = (
F878A33709F3A4B700225D95 /* liblpsolve55.a */,
);
name = lib;
sourceTree = "<group>";
};
F878A31209F3A46500225D95 /* include */ = {
isa = PBXGroup;
children = (
F878A33909F3A4D200225D95 /* lp_lib.h */,
);
name = include;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
8DD76F620486A84900D96B5E /* dees */ = {
isa = PBXNativeTarget;
buildConfigurationList = 1DEB923108733DC60010E9CD /* Build configuration list for PBXNativeTarget "dees" */;
buildPhases = (
8DD76F640486A84900D96B5E /* Sources */,
8DD76F660486A84900D96B5E /* Frameworks */,
8DD76F690486A84900D96B5E /* CopyFiles */,
);
buildRules = (
);
dependencies = (
);
name = dees;
productInstallPath = "$(HOME)/bin";
productName = dees;
productReference = 8DD76F6C0486A84900D96B5E /* dees */;
productType = "com.apple.product-type.tool";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
08FB7793FE84155DC02AAC07 /* Project object */ = {
isa = PBXProject;
buildConfigurationList = 1DEB923508733DC60010E9CD /* Build configuration list for PBXProject "dees" */;
hasScannedForEncodings = 1;
mainGroup = 08FB7794FE84155DC02AAC07 /* dees */;
projectDirPath = "";
targets = (
8DD76F620486A84900D96B5E /* dees */,
);
};
/* End PBXProject section */
/* Begin PBXSourcesBuildPhase section */
8DD76F640486A84900D96B5E /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
8DD76F650486A84900D96B5E /* main.cpp in Sources */,
F878A31B09F3A48B00225D95 /* test.cpp in Sources */,
F878A31C09F3A48B00225D95 /* spfa.cpp in Sources */,
F878A31E09F3A48B00225D95 /* sample.cpp in Sources */,
F878A31F09F3A48B00225D95 /* pprfa.cpp in Sources */,
F878A32009F3A48B00225D95 /* pfa.cpp in Sources */,
F878A32109F3A48B00225D95 /* ma.cpp in Sources */,
F878A32209F3A48B00225D95 /* interface.cpp in Sources */,
F860AF3909F3D8430027FF1E /* simplex.cpp in Sources */,
F871D15509F4F14C001A8E9E /* pprfa_dees.cpp in Sources */,
F871D16109F4F3D6001A8E9E /* pprfa_bm.cpp in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin XCBuildConfiguration section */
1DEB923208733DC60010E9CD /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
COPY_PHASE_STRIP = NO;
GCC_DYNAMIC_NO_PIC = NO;
GCC_ENABLE_FIX_AND_CONTINUE = YES;
GCC_MODEL_TUNING = G5;
GCC_OPTIMIZATION_LEVEL = 0;
INSTALL_PATH = "$(HOME)/bin";
LIBRARY_SEARCH_PATHS = (
"$(LIBRARY_SEARCH_PATHS)",
"$(SRCROOT)/lib",
);
PRODUCT_NAME = dees;
ZERO_LINK = YES;
};
name = Debug;
};
1DEB923308733DC60010E9CD /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ARCHS = (
ppc,
i386,
);
GCC_GENERATE_DEBUGGING_SYMBOLS = NO;
GCC_MODEL_TUNING = G5;
INSTALL_PATH = "$(HOME)/bin";
LIBRARY_SEARCH_PATHS = (
"$(LIBRARY_SEARCH_PATHS)",
"$(SRCROOT)/lib",
);
PRODUCT_NAME = dees;
};
name = Release;
};
1DEB923608733DC60010E9CD /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
PREBINDING = NO;
SDKROOT = /Developer/SDKs/MacOSX10.4u.sdk;
};
name = Debug;
};
1DEB923708733DC60010E9CD /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
PREBINDING = NO;
SDKROOT = /Developer/SDKs/MacOSX10.4u.sdk;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
1DEB923108733DC60010E9CD /* Build configuration list for PBXNativeTarget "dees" */ = {
isa = XCConfigurationList;
buildConfigurations = (
1DEB923208733DC60010E9CD /* Debug */,
1DEB923308733DC60010E9CD /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
1DEB923508733DC60010E9CD /* Build configuration list for PBXProject "dees" */ = {
isa = XCConfigurationList;
buildConfigurations = (
1DEB923608733DC60010E9CD /* Debug */,
1DEB923708733DC60010E9CD /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 08FB7793FE84155DC02AAC07 /* Project object */;
}

135
general.H Normal file
View File

@ -0,0 +1,135 @@
/***************************************************************************
general.h - This file must be included in all Project
-------------------
begin : Thu Jul 18 2002
copyright : (C) 2002 by Yann Esposito
email : esposito@cmi.univ-mrs.fr
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#ifndef GENERAL_H
#define GENERAL_H
using namespace std;
#include <string>
#include <set>
#include <map>
//#include <vector>
//#include <hash_set>
#include <iostream> // pour cout <<
#include <fstream> // pour fic <<
#include <cmath>
// ------------- pour le portage --------------
// pour compiler sur le ppc
#ifdef __ppc__
#define isnan __isnan
#define isinf __isinf
#endif
// pour utiliser les hash_map
#ifdef __GNUC__
#if __GNUC__ < 3
#include <hash_map.h>
namespace hmext
{
using ::hash_map;
}
; // inherit globals
#else
#include <ext/hash_map>
#if __GNUC_MINOR__ == 0
namespace hmext = std; // GCC 3.0
#else
namespace hmext = ::__gnu_cxx; // GCC 3.1 and later
#endif
#endif
#else // ... there are other compilers, right?
namespace hmext = std;
#endif
// ------------------------------------------------
// Make DEBUG false to disable the debug mode (faster but you'll lose all error messages).
const bool PFA_DEBUG = true;
// Make VERBOSE false to disable the verbose mode (less messages)
const bool PFA_VERBOSE = true;
// Make SAFE false to disable the SAFE mode (faster but DANGEROUS !!!!)
const bool PFA_SAFE = true;
// Definition of the RESULT type.
typedef int RESULT;
// Test if the result of a function is OK.
inline RESULT
OK (RESULT x)
{
return x >= 0;
}
inline RESULT
VAL (RESULT x)
{
return x;
}
inline RESULT
ERR (RESULT x)
{
if (x >= 0)
return -1 - x;
else
return -1 + x;
}
// =============== Définition des types necessaires aux structures de données ==============
// ___ Située hors des classes pour éviter l'utilisation de l'opérateur de résolution ___
typedef int State; // Le type état
typedef char Lettre; // Le type lettre
typedef basic_string< Lettre > Word; // Le type Word
//~ class Word : public basic_string < Lettre > // Le type mot
//~ {
//~ public:
//~ inline Lettre pop_back() {
//~ iterator e=end();
//~ --e;
//~ Lettre a=*e;
//~ erase(e);
//~ return a;
//~ }
//~ };
typedef set< Lettre > Alphabet; // type Alphabet
typedef string TrueLettre; // real letters.
//typedef hash_map < Lettre, TrueLettre > Dictionnaire; // type Dictionnaire
typedef map < Lettre, TrueLettre > Dictionnaire; // type Dictionnaire (association lettre et vraie lettre)
//typedef hmext::hash_map < State, double >PreciseSFunc; // Type fonction State --> IR, plus précise
typedef map < State, double >PreciseSFunc; // Type fonction State --> IR, plus précise
// Le type transition n'est pas forcement necessaire mais il est joli
// Type transition est un triplet State x Lettre x State
typedef struct str_Transition
{
State qdep;
Lettre a;
State qarr;
}
Transition;
#endif

39
help/help.txt Normal file
View File

@ -0,0 +1,39 @@
Usage :
dees OPTIONS
OPTIONS :
-H affiche l'aide étendue (options)
-Y ou -I envoie la fonction Y (mode interactif)
--- APPRENTISSAGE ---
--dees algorithme DEES
--dees2 algorithme DEES2
--deesbm algorithme DEES avec Baum Welch
--alergia algorithme alergia
--mdi algorithme mdi
--bm algorithme Baum Welch
--learn apprend avec validation croisée
--learnbm apprentissage avec ensemble test avec methode deesBM
--learnmdi apprentissage avec MDI
--learnalergia apprentissage avec alergia
--bestlearn plusieurs apprentissages pour trouver le meilleur
--- MANIPULATION DE FICHIERS ---
--export exporte vers des formats d'automates differents
--convert convertit des echantillons
--- OUTILS DE DIAGNOSTICS ---
--dist affiche la distance entre deux MA
--class affiche la classe d'un PFA
--affiche affiche un automate sur la sortie standard
--test fait un test à partir de l'automate
--proba show probabilities of words of a sample
-P or --showps affichage postscript
--- MANIPULATION DE MA ---
--deletetransitions delete transitions of some value
--sample genere un échantillon
--grp genere un automate probabiliste
--random generate a random automaton

22
include/declare.h Normal file
View File

@ -0,0 +1,22 @@
#ifndef __DECLARE_H__
#define __DECLARE_H__
#if !defined ANSI_PROTOTYPES
# if defined MSDOS || defined __BORLANDC__ || defined __HIGHC__ || defined SCO_UNIX || defined AViiON
# define ANSI_PROTOTYPES 1
# endif
#endif
#if ANSI_PROTOTYPES!=0
# define __OF(args) args
#else
# define __OF(args) ()
#endif
#if defined __HIGHC__
# define VARARG ...
#else
# define VARARG
#endif
#endif

183
include/fortify.h Normal file
View File

@ -0,0 +1,183 @@
#ifndef __FORTIFY_H__
#define __FORTIFY_H__
/*
* FILE:
* fortify.h
*
* DESCRIPTION:
* Header file for fortify.c - A fortified shell for malloc, realloc,
* calloc, strdup, getcwd, tempnam & free
*
* WRITTEN:
* spb 29/4/94
*
* VERSION:
* 1.0 29/4/94
*/
#include <stdlib.h>
#include "declare.h"
#if defined HP9000 || defined AViiON || defined ALPHA || defined SIGNED_UNKNOWN
# define signed
#endif
#ifdef __cplusplus
extern "C" {
#endif
#ifdef FORTIFY
typedef void (*OutputFuncPtr) __OF((char *));
extern char *_Fortify_file;
extern int _Fortify_line;
#define Fortify_FILE(file) _Fortify_file=file
#define Fortify_LINE(line) _Fortify_line=line
#define _Fortify_FILE (_Fortify_file==(char *) 0 ? __FILE__ : _Fortify_file)
#define _Fortify_LINE (_Fortify_line==0 ? __LINE__ : _Fortify_line)
void _Fortify_Init __OF((char *file, unsigned long line));
void *_Fortify_malloc __OF((size_t size, char *file, unsigned long line));
void *_Fortify_realloc __OF((void *ptr, size_t new_size, char *file, unsigned long line));
void *_Fortify_calloc __OF((size_t nitems, size_t size, char *file, unsigned long line));
char *_Fortify_strdup __OF((char *str, char *file, unsigned long line));
void *_Fortify_memcpy __OF((void *to, void *from, size_t size, char *file, unsigned long line));
void *_Fortify_memmove __OF((void *to, void *from, size_t size, char *file, unsigned long line));
void *_Fortify_memset __OF((void *buffer, int c, size_t size, char *file, unsigned long line));
void *_Fortify_memchr __OF((void *buffer, int c, size_t size, char *file, unsigned long line));
int _Fortify_memcmp __OF((void *buffer1, void *buffer2, size_t size, char *file, unsigned long line));
char *_Fortify_strchr __OF((char *buffer, int c, char *file, unsigned long line));
char *_Fortify_strset __OF((char *buffer, int c, char *file, unsigned long line));
char *_Fortify_strcpy __OF((char *to, char *from, char *file, unsigned long line));
char *_Fortify_strncpy __OF((char *to, char *from, size_t size, char *file, unsigned long line));
int _Fortify_strncmp __OF((char *buffer1, char *buffer2, size_t size, char *file, unsigned long line));
char *_Fortify_strcat __OF((char *buffer1, char *buffer2, char *file, unsigned long line));
size_t _Fortify_strlen __OF((char *buffer, char *file, unsigned long line));
char *_Fortify_getcwd __OF((char *buf, int size, char *file, unsigned long line));
char *_Fortify_tempnam __OF((char *dir, char *pfx, char *file, unsigned long line));
void _Fortify_free __OF((void *uptr, char *file, unsigned long line));
int _Fortify_OutputAllMemory __OF((char *file, unsigned long line));
int _Fortify_CheckAllMemory __OF((char *file, unsigned long line));
int _Fortify_CheckPointer __OF((void *uptr, char *file, unsigned long line));
int _Fortify_Disable __OF((char *file, unsigned long line, int how));
int _Fortify_SetMallocFailRate __OF((int Percent));
int _Fortify_EnterScope __OF((char *file, unsigned long line));
int _Fortify_LeaveScope __OF((char *file, unsigned long line));
int _Fortify_DumpAllMemory __OF((int scope, char *file, unsigned long line));
typedef void (*Fortify_OutputFuncPtr) __OF((/* const */ char *));
Fortify_OutputFuncPtr _Fortify_SetOutputFunc __OF((Fortify_OutputFuncPtr Output));
#endif /* FORTIFY */
#ifdef __cplusplus
}
#endif
#ifndef __FORTIFY_C__ /* Only define the macros if we're NOT in fortify.c */
#ifdef FORTIFY /* Add file and line information to the fortify calls */
#if defined malloc
# undef malloc
#endif
#if defined realloc
# undef realloc
#endif
#if defined calloc
# undef calloc
#endif
#if defined strdup
# undef strdup
#endif
#if defined memcpy
# undef memcpy
#endif
#if defined memmove
# undef memmove
#endif
#if defined memset
# undef memset
#endif
#if defined memchr
# undef memchr
#endif
#if defined memcmp
# undef memcmp
#endif
#if defined strncmp
# undef strncmp
#endif
#if defined strchr
# undef strchr
#endif
#if defined strcat
# undef strcat
#endif
#if defined strset
# undef strset
#endif
#if defined strlen
# undef strlen
#endif
#if defined getcwd
# undef getcwd
#endif
#if defined tempnam
# undef tempnam
#endif
#if defined free
# undef free
#endif
#define malloc(size) _Fortify_malloc(size, _Fortify_FILE, _Fortify_LINE)
#define realloc(ptr,new_size) _Fortify_realloc(ptr, new_size, _Fortify_FILE, _Fortify_LINE)
#define calloc(num,size) _Fortify_calloc(num, size, _Fortify_FILE, _Fortify_LINE)
#define strdup(str) _Fortify_strdup(str, _Fortify_FILE, _Fortify_LINE)
#define memcpy(to,from,size) _Fortify_memcpy(to,from,size, _Fortify_FILE, _Fortify_LINE)
#define memmove(to,from,size) _Fortify_memmove(to,from,size, _Fortify_FILE, _Fortify_LINE)
#define memset(buffer,c,size) _Fortify_memset(buffer,c,size, _Fortify_FILE, _Fortify_LINE)
#define memchr(buffer,c,size) _Fortify_memchr(buffer,c,size, _Fortify_FILE, _Fortify_LINE)
#define memcmp(buffer1,buffer2,size) _Fortify_memcmp(buffer1,buffer2,size, _Fortify_FILE, _Fortify_LINE)
#define strchr(buffer,c) _Fortify_strchr(buffer,c, _Fortify_FILE, _Fortify_LINE)
#define strset(buffer,c) _Fortify_strset(buffer,c, _Fortify_FILE, _Fortify_LINE)
#define strcpy(to,from) _Fortify_strcpy(to,from, _Fortify_FILE, _Fortify_LINE)
#define strncpy(to,from,size) _Fortify_strncpy(to,from,size, _Fortify_FILE, _Fortify_LINE)
#define strncmp(buffer1,buffer2,size) _Fortify_strncmp(buffer1,buffer2,size, _Fortify_FILE, _Fortify_LINE)
#define strcat(buffer1,buffer2) _Fortify_strcat(buffer1,buffer2, _Fortify_FILE, _Fortify_LINE)
#define strlen(buffer) _Fortify_strlen(buffer, _Fortify_FILE, _Fortify_LINE)
#define getcwd(buf,size) _Fortify_getcwd(buf, size, _Fortify_FILE, _Fortify_LINE)
#define tempnam(dir,pfx) _Fortify_tempnam(dir, pfx, _Fortify_FILE, _Fortify_LINE)
#define free(ptr) _Fortify_free(ptr, _Fortify_FILE, _Fortify_LINE)
#define Fortify_Init() _Fortify_Init(_Fortify_FILE, _Fortify_LINE)
#define Fortify_OutputAllMemory() _Fortify_OutputAllMemory(_Fortify_FILE, _Fortify_LINE)
#define Fortify_CheckAllMemory() _Fortify_CheckAllMemory(_Fortify_FILE, _Fortify_LINE)
#define Fortify_CheckPointer(ptr) _Fortify_CheckPointer(ptr, _Fortify_FILE, _Fortify_LINE)
#define Fortify_Disable(how) _Fortify_Disable(_Fortify_FILE, _Fortify_LINE,how)
#define Fortify_EnterScope() _Fortify_EnterScope(_Fortify_FILE, _Fortify_LINE)
#define Fortify_LeaveScope() _Fortify_LeaveScope(_Fortify_FILE, _Fortify_LINE)
#define Fortify_DumpAllMemory(s) _Fortify_DumpAllMemory(s,_Fortify_FILE, _Fortify_LINE)
#else /* FORTIFY Define the special fortify functions away to nothing */
#define Fortify_FILE(file)
#define Fortify_LINE(line)
#define Fortify_Init()
#define Fortify_OutputAllMemory() 0
#define Fortify_CheckAllMemory() 0
#define Fortify_CheckPointer(ptr) 1
#define Fortify_Disable(how) 1
#define Fortify_SetOutputFunc() 0
#define Fortify_SetMallocFailRate(p) 0
#define Fortify_EnterScope() 0
#define Fortify_LeaveScope() 0
#define Fortify_DumpAllMemory(s) 0
#endif /* FORTIFY */
#endif /* __FORTIFY_C__ */
#endif /* __FORTIFY_H__ */

9
include/ini.h Normal file
View File

@ -0,0 +1,9 @@
#include <stdio.h>
extern FILE *ini_create(char *filename);
extern FILE *ini_open(char *filename);
extern void ini_writecomment(FILE *fp, char *comment);
extern void ini_writeheader(FILE *fp, char *header, int addnewline);
extern void ini_writedata(FILE *fp, char *name, char *data);
extern int ini_readdata(FILE *fp, char *data, int szdata, int withcomment);
extern void ini_close(FILE *fp);

43
include/lp_Hash.h Normal file
View File

@ -0,0 +1,43 @@
#ifndef HEADER_lp_hash
#define HEADER_lp_hash
/* For row and column name hash tables */
typedef struct _hashelem
{
char *name;
int index;
struct _hashelem *next;
struct _hashelem *nextelem;
} hashelem;
typedef struct _hashtable
{
hashelem **table;
int size;
int base;
int count;
struct _hashelem *first;
struct _hashelem *last;
} hashtable;
#ifdef __cplusplus
extern "C" {
#endif
STATIC hashtable *create_hash_table(int size, int base);
STATIC void free_hash_table(hashtable *ht);
STATIC hashelem *findhash(const char *name, hashtable *ht);
STATIC hashelem *puthash(const char *name, int index, hashelem **list, hashtable *ht);
STATIC void drophash(const char *name, hashelem **list, hashtable *ht);
STATIC void free_hash_item(hashelem **hp);
STATIC hashtable *copy_hash_table(hashtable *ht, hashelem **list, int newsize);
STATIC int find_var(lprec *lp, char *name, MYBOOL verbose);
STATIC int find_row(lprec *lp, char *name, MYBOOL Unconstrained_rows_found);
#ifdef __cplusplus
}
#endif
#endif /* HEADER_lp_hash */

18
include/lp_MDO.h Normal file
View File

@ -0,0 +1,18 @@
#ifndef HEADER_MDO
#define HEADER_MDO
#include "lp_types.h"
#ifdef __cplusplus
extern "C" {
#endif
int __WINAPI getMDO(lprec *lp, MYBOOL *usedpos, int *colorder, int *size, MYBOOL symmetric);
#ifdef __cplusplus
}
#endif
#endif /* HEADER_MDO */

37
include/lp_MPS.h Normal file
View File

@ -0,0 +1,37 @@
#ifndef HEADER_lp_MPS
#define HEADER_lp_MPS
#include "lp_types.h"
/* For MPS file reading and writing */
#define ROWNAMEMASK "R%d"
#define ROWNAMEMASK2 "r%d"
#define COLNAMEMASK "C%d"
#define COLNAMEMASK2 "c%d"
#define MPSFIXED 1
#define MPSFREE 2
#ifdef __cplusplus
extern "C" {
#endif
/* Read an MPS file */
MYBOOL MPS_readfile(lprec **newlp, char *filename, int typeMPS, int verbose);
MYBOOL __WINAPI MPS_readhandle(lprec **newlp, FILE *filehandle, int typeMPS, int verbose);
/* Write a MPS file to output */
MYBOOL MPS_writefile(lprec *lp, int typeMPS, char *filename);
MYBOOL MPS_writehandle(lprec *lp, int typeMPS, FILE *output);
/* Read and write BAS files */
MYBOOL MPS_readBAS(lprec *lp, int typeMPS, char *filename, char *info);
MYBOOL MPS_writeBAS(lprec *lp, int typeMPS, char *filename);
#ifdef __cplusplus
}
#endif
#endif /* HEADER_lp_MPS */

108
include/lp_SOS.h Normal file
View File

@ -0,0 +1,108 @@
#ifndef HEADER_lp_SOS
#define HEADER_lp_SOS
/* Specially Ordered Sets (SOS) prototypes and settings */
/* ------------------------------------------------------------------------- */
#include "lp_types.h"
#include "lp_utils.h"
#include "lp_matrix.h"
/* SOS constraint defines */
/* ------------------------------------------------------------------------- */
#define SOS1 1
#define SOS2 2
#define SOS3 -1
#define SOSn MAXINT32
#define SOS_START_SIZE 10 /* Start size of SOS_list array; realloced if needed */
/* Define SOS_is_feasible() return values */
/* ------------------------------------------------------------------------- */
#define SOS3_INCOMPLETE -2
#define SOS_INCOMPLETE -1
#define SOS_COMPLETE 0
#define SOS_INFEASIBLE 1
#define SOS_INTERNALERROR 2
typedef struct _SOSgroup SOSgroup;
typedef struct _SOSrec
{
SOSgroup *parent;
int tagorder;
char *name;
int type;
MYBOOL isGUB;
int size;
int priority;
int *members;
REAL *weights;
int *membersSorted;
int *membersMapped;
} SOSrec;
/* typedef */ struct _SOSgroup
{
lprec *lp; /* Pointer to owner */
SOSrec **sos_list; /* Array of pointers to SOS lists */
int sos_alloc; /* Size allocated to specially ordered sets (SOS1, SOS2...) */
int sos_count; /* Number of specially ordered sets (SOS1, SOS2...) */
int maxorder; /* The highest-order SOS in the group */
int sos1_count; /* Number of the lowest order SOS in the group */
int *membership; /* Array of variable-sorted indeces to SOSes that the variable is member of */
int *memberpos; /* Starting positions of the each column's membership list */
} /* SOSgroup */;
#ifdef __cplusplus
extern "C" {
#endif
/* SOS storage structure */
STATIC SOSgroup *create_SOSgroup(lprec *lp);
STATIC void resize_SOSgroup(SOSgroup *group);
STATIC int append_SOSgroup(SOSgroup *group, SOSrec *SOS);
STATIC int clean_SOSgroup(SOSgroup *group, MYBOOL forceupdatemap);
STATIC void free_SOSgroup(SOSgroup **group);
STATIC SOSrec *create_SOSrec(SOSgroup *group, char *name, int type, int priority, int size, int *variables, REAL *weights);
STATIC MYBOOL delete_SOSrec(SOSgroup *group, int sosindex);
STATIC int append_SOSrec(SOSrec *SOS, int size, int *variables, REAL *weights);
STATIC void free_SOSrec(SOSrec *SOS);
/* SOS utilities */
STATIC int make_SOSchain(lprec *lp, MYBOOL forceresort);
STATIC int SOS_member_updatemap(SOSgroup *group);
STATIC MYBOOL SOS_member_sortlist(SOSgroup *group, int sosindex);
STATIC MYBOOL SOS_shift_col(SOSgroup *group, int sosindex, int column, int delta, LLrec *usedmap, MYBOOL forceresort);
int SOS_member_delete(SOSgroup *group, int sosindex, int member);
int SOS_get_type(SOSgroup *group, int sosindex);
int SOS_infeasible(SOSgroup *group, int sosindex);
int SOS_member_index(SOSgroup *group, int sosindex, int member);
int SOS_member_count(SOSgroup *group, int sosindex);
int SOS_memberships(SOSgroup *group, int column);
int *SOS_get_candidates(SOSgroup *group, int sosindex, int column, MYBOOL excludetarget, REAL *upbound, REAL *lobound);
int SOS_is_member(SOSgroup *group, int sosindex, int column);
MYBOOL SOS_is_member_of_type(SOSgroup *group, int column, int sostype);
MYBOOL SOS_set_GUB(SOSgroup *group, int sosindex, MYBOOL state);
MYBOOL SOS_is_GUB(SOSgroup *group, int sosindex);
MYBOOL SOS_is_marked(SOSgroup *group, int sosindex, int column);
MYBOOL SOS_is_active(SOSgroup *group, int sosindex, int column);
MYBOOL SOS_is_full(SOSgroup *group, int sosindex, int column, MYBOOL activeonly);
MYBOOL SOS_can_activate(SOSgroup *group, int sosindex, int column);
MYBOOL SOS_set_marked(SOSgroup *group, int sosindex, int column, MYBOOL asactive);
MYBOOL SOS_unmark(SOSgroup *group, int sosindex, int column);
int SOS_fix_unmarked(SOSgroup *group, int sosindex, int variable, REAL *bound, REAL value,
MYBOOL isupper, int *diffcount, DeltaVrec *changelog);
int SOS_fix_list(SOSgroup *group, int sosindex, int variable, REAL *bound,
int *varlist, MYBOOL isleft, DeltaVrec *changelog);
int SOS_is_satisfied(SOSgroup *group, int sosindex, REAL *solution);
MYBOOL SOS_is_feasible(SOSgroup *group, int sosindex, REAL *solution);
#ifdef __cplusplus
}
#endif
#endif /* HEADER_lp_SOS */

29
include/lp_crash.h Normal file
View File

@ -0,0 +1,29 @@
#ifndef HEADER_lp_crash
#define HEADER_lp_crash
#include "lp_types.h"
#define CRASH_SIMPLESCALE /* Specify if we should use a simple absolute scaling threshold */
#define CRASH_THRESHOLD 0.167
#define CRASH_SPACER 10
#define CRASH_WEIGHT 0.500
#ifdef __cplusplus
__EXTERN_C {
#endif
STATIC MYBOOL crash_basis(lprec *lp);
STATIC MYBOOL guess_basis(lprec *lp, REAL *guessvector, int *basisvector);
#ifdef __cplusplus
}
#endif
#endif /* HEADER_lp_crash */

1016
include/lp_explicit.h Normal file

File diff suppressed because it is too large Load Diff

5
include/lp_fortify.h Normal file
View File

@ -0,0 +1,5 @@
#ifdef FORTIFY
#include "fortify.h"
#endif

2266
include/lp_lib.h Normal file

File diff suppressed because it is too large Load Diff

257
include/lp_matrix.h Normal file
View File

@ -0,0 +1,257 @@
#ifndef HEADER_lp_matrix
#define HEADER_lp_matrix
#include "lp_types.h"
#include "lp_utils.h"
/* Sparse matrix element (ordered columnwise) */
typedef struct _MATitem
{
int rownr;
int colnr;
REAL value;
} MATitem;
/* Constants for matrix product rounding options */
#define MAT_ROUNDNONE 0
#define MAT_ROUNDABS 1
#define MAT_ROUNDREL 2
#define MAT_ROUNDABSREL (MAT_ROUNDABS + MAT_ROUNDREL)
#define MAT_ROUNDRC 4
#define MAT_ROUNDRCMIN 1.0 /* lp->epspivot */
#if 1
#define MAT_ROUNDDEFAULT MAT_ROUNDREL /* Typically increases performance */
#else
#define MAT_ROUNDDEFAULT MAT_ROUNDABS /* Probably gives more precision */
#endif
/* Compiler option development features */
/*#define DebugInv*/ /* Report array values at factorization/inversion */
#define NoLoopUnroll /* Do not do loop unrolling */
#define DirectArrayOF /* Reference lp->obj[] array instead of function call */
/* Matrix column access macros to be able to easily change storage model */
#define CAM_Record 0
#define CAM_Vector 1
#if 0
#define MatrixColAccess CAM_Record
#else
#define MatrixColAccess CAM_Vector
#endif
#if MatrixColAccess==CAM_Record
#define SET_MAT_ijA(item,i,j,A) mat->col_mat[item].rownr = i; \
mat->col_mat[item].colnr = j; \
mat->col_mat[item].value = A
#define COL_MAT_COLNR(item) (mat->col_mat[item].colnr)
#define COL_MAT_ROWNR(item) (mat->col_mat[item].rownr)
#define COL_MAT_VALUE(item) (mat->col_mat[item].value)
#define COL_MAT_COPY(left,right) mat->col_mat[left] = mat->col_mat[right]
#define COL_MAT_MOVE(to,from,rec) MEMMOVE(&(mat->col_mat[to]),&(mat->col_mat[from]),rec)
#define COL_MAT2_COLNR(item) (mat2->col_mat[item].colnr)
#define COL_MAT2_ROWNR(item) (mat2->col_mat[item].rownr)
#define COL_MAT2_VALUE(item) (mat2->col_mat[item].value)
#define matRowColStep (sizeof(MATitem)/sizeof(int))
#define matValueStep (sizeof(MATitem)/sizeof(REAL))
#else /* if MatrixColAccess==CAM_Vector */
#define SET_MAT_ijA(item,i,j,A) mat->col_mat_rownr[item] = i; \
mat->col_mat_colnr[item] = j; \
mat->col_mat_value[item] = A
#define COL_MAT_COLNR(item) (mat->col_mat_colnr[item])
#define COL_MAT_ROWNR(item) (mat->col_mat_rownr[item])
#define COL_MAT_VALUE(item) (mat->col_mat_value[item])
#define COL_MAT_COPY(left,right) COL_MAT_COLNR(left) = COL_MAT_COLNR(right); \
COL_MAT_ROWNR(left) = COL_MAT_ROWNR(right); \
COL_MAT_VALUE(left) = COL_MAT_VALUE(right)
#define COL_MAT_MOVE(to,from,rec) MEMMOVE(&COL_MAT_COLNR(to),&COL_MAT_COLNR(from),rec); \
MEMMOVE(&COL_MAT_ROWNR(to),&COL_MAT_ROWNR(from),rec); \
MEMMOVE(&COL_MAT_VALUE(to),&COL_MAT_VALUE(from),rec)
#define COL_MAT2_COLNR(item) (mat2->col_mat_colnr[item])
#define COL_MAT2_ROWNR(item) (mat2->col_mat_rownr[item])
#define COL_MAT2_VALUE(item) (mat2->col_mat_value[item])
#define matRowColStep 1
#define matValueStep 1
#endif
/* Matrix row access macros to be able to easily change storage model */
#define RAM_Index 0
#define RAM_FullCopy 1
#define MatrixRowAccess RAM_Index
#if MatrixRowAccess==RAM_Index
#define ROW_MAT_COLNR(item) COL_MAT_COLNR(mat->row_mat[item])
#define ROW_MAT_ROWNR(item) COL_MAT_ROWNR(mat->row_mat[item])
#define ROW_MAT_VALUE(item) COL_MAT_VALUE(mat->row_mat[item])
#elif MatrixColAccess==CAM_Record
#define ROW_MAT_COLNR(item) (mat->row_mat[item].colnr)
#define ROW_MAT_ROWNR(item) (mat->row_mat[item].rownr)
#define ROW_MAT_VALUE(item) (mat->row_mat[item].value)
#else /* if MatrixColAccess==CAM_Vector */
#define ROW_MAT_COLNR(item) (mat->row_mat_colnr[item])
#define ROW_MAT_ROWNR(item) (mat->row_mat_rownr[item])
#define ROW_MAT_VALUE(item) (mat->row_mat_value[item])
#endif
typedef struct _MATrec
{
/* Owner reference */
lprec *lp;
/* Active dimensions */
int rows;
int columns;
/* Allocated memory */
int rows_alloc;
int columns_alloc;
int mat_alloc; /* The allocated size for matrix sized structures */
/* Sparse problem matrix storage */
#if MatrixColAccess==CAM_Record
MATitem *col_mat; /* mat_alloc : The sparse data storage */
#else /*MatrixColAccess==CAM_Vector*/
int *col_mat_colnr;
int *col_mat_rownr;
REAL *col_mat_value;
#endif
int *col_end; /* columns_alloc+1 : col_end[i] is the index of the
first element after column i; column[i] is stored
in elements col_end[i-1] to col_end[i]-1 */
int *col_tag; /* user-definable tag associated with each column */
#if MatrixRowAccess==RAM_Index
int *row_mat; /* mat_alloc : From index 0, row_mat contains the
row-ordered index of the elements of col_mat */
#elif MatrixColAccess==CAM_Record
MATitem *row_mat; /* mat_alloc : From index 0, row_mat contains the
row-ordered copy of the elements in col_mat */
#else /*if MatrixColAccess==CAM_Vector*/
int *row_mat_colnr;
int *row_mat_rownr;
REAL *row_mat_value;
#endif
int *row_end; /* rows_alloc+1 : row_end[i] is the index of the
first element in row_mat after row i */
int *row_tag; /* user-definable tag associated with each row */
REAL *colmax; /* Array of maximum values of each column */
REAL *rowmax; /* Array of maximum values of each row */
REAL epsvalue; /* Zero element rejection threshold */
REAL infnorm; /* The largest absolute value in the matrix */
REAL dynrange;
MYBOOL row_end_valid; /* TRUE if row_end & row_mat are valid */
MYBOOL is_roworder; /* TRUE if the current (temporary) matrix order is row-wise */
} MATrec;
typedef struct _DeltaVrec
{
lprec *lp;
int activelevel;
MATrec *tracker;
} DeltaVrec;
#ifdef __cplusplus
__EXTERN_C {
#endif
/* Sparse matrix routines */
STATIC MATrec *mat_create(lprec *lp, int rows, int columns, REAL epsvalue);
STATIC MYBOOL mat_memopt(MATrec *mat, int rowextra, int colextra, int nzextra);
STATIC void mat_free(MATrec **matrix);
STATIC MYBOOL inc_matrow_space(MATrec *mat, int deltarows);
STATIC int mat_mapreplace(MATrec *mat, LLrec *rowmap, LLrec *colmap, MATrec *insmat);
STATIC int mat_matinsert(MATrec *mat, MATrec *insmat);
STATIC int mat_zerocompact(MATrec *mat);
STATIC int mat_rowcompact(MATrec *mat, MYBOOL dozeros);
STATIC int mat_colcompact(MATrec *mat, int prev_rows, int prev_cols);
STATIC MYBOOL inc_matcol_space(MATrec *mat, int deltacols);
STATIC MYBOOL inc_mat_space(MATrec *mat, int mindelta);
STATIC int mat_shiftrows(MATrec *mat, int *bbase, int delta, LLrec *varmap);
STATIC int mat_shiftcols(MATrec *mat, int *bbase, int delta, LLrec *varmap);
STATIC MATrec *mat_extractmat(MATrec *mat, LLrec *rowmap, LLrec *colmap, MYBOOL negated);
STATIC int mat_appendrow(MATrec *mat, int count, REAL *row, int *colno, REAL mult, MYBOOL checkrowmode);
STATIC int mat_appendcol(MATrec *mat, int count, REAL *column, int *rowno, REAL mult, MYBOOL checkrowmode);
MYBOOL mat_get_data(lprec *lp, int matindex, MYBOOL isrow, int **rownr, int **colnr, REAL **value);
MYBOOL mat_set_rowmap(MATrec *mat, int row_mat_index, int rownr, int colnr, int col_mat_index);
STATIC MYBOOL mat_indexrange(MATrec *mat, int index, MYBOOL isrow, int *startpos, int *endpos);
STATIC MYBOOL mat_validate(MATrec *mat);
STATIC MYBOOL mat_equalRows(MATrec *mat, int baserow, int comprow);
STATIC int mat_findelm(MATrec *mat, int row, int column);
STATIC int mat_findins(MATrec *mat, int row, int column, int *insertpos, MYBOOL validate);
STATIC void mat_multcol(MATrec *mat, int col_nr, REAL mult);
STATIC REAL mat_getitem(MATrec *mat, int row, int column);
STATIC MYBOOL mat_setitem(MATrec *mat, int row, int column, REAL value);
STATIC MYBOOL mat_additem(MATrec *mat, int row, int column, REAL delta);
STATIC MYBOOL mat_setvalue(MATrec *mat, int Row, int Column, REAL Value, MYBOOL doscale);
STATIC int mat_nonzeros(MATrec *mat);
STATIC int mat_collength(MATrec *mat, int colnr);
STATIC int mat_rowlength(MATrec *mat, int rownr);
STATIC void mat_multrow(MATrec *mat, int row_nr, REAL mult);
STATIC void mat_multadd(MATrec *mat, REAL *lhsvector, int varnr, REAL mult);
STATIC MYBOOL mat_setrow(MATrec *mat, int rowno, int count, REAL *row, int *colno, MYBOOL doscale, MYBOOL checkrowmode);
STATIC MYBOOL mat_setcol(MATrec *mat, int colno, int count, REAL *column, int *rowno, MYBOOL doscale, MYBOOL checkrowmode);
STATIC MYBOOL mat_mergemat(MATrec *target, MATrec *source, MYBOOL usecolmap);
STATIC int mat_checkcounts(MATrec *mat, int *rownum, int *colnum, MYBOOL freeonexit);
STATIC int mat_expandcolumn(MATrec *mat, int colnr, REAL *column, int *nzlist, MYBOOL signedA);
STATIC MYBOOL mat_computemax(MATrec *mat);
STATIC MYBOOL mat_transpose(MATrec *mat);
/* Refactorization and recomputation routine */
MYBOOL __WINAPI invert(lprec *lp, MYBOOL shiftbounds, MYBOOL final);
/* Vector compression and expansion routines */
STATIC MYBOOL vec_compress(REAL *densevector, int startpos, int endpos, REAL epsilon, REAL *nzvector, int *nzindex);
STATIC MYBOOL vec_expand(REAL *nzvector, int *nzindex, REAL *densevector, int startpos, int endpos);
/* Sparse matrix products */
STATIC MYBOOL get_colIndexA(lprec *lp, int varset, int *colindex, MYBOOL append);
STATIC int prod_Ax(lprec *lp, int *coltarget, REAL *input, int *nzinput, REAL roundzero, REAL ofscalar, REAL *output, int *nzoutput, int roundmode);
STATIC int prod_xA(lprec *lp, int *coltarget, REAL *input, int *nzinput, REAL roundzero, REAL ofscalar, REAL *output, int *nzoutput, int roundmode);
STATIC MYBOOL prod_xA2(lprec *lp, int *coltarget, REAL *prow, REAL proundzero, int *pnzprow,
REAL *drow, REAL droundzero, int *dnzdrow, REAL ofscalar, int roundmode);
/* Equation solution */
STATIC MYBOOL fimprove(lprec *lp, REAL *pcol, int *nzidx, REAL roundzero);
STATIC void ftran(lprec *lp, REAL *rhsvector, int *nzidx, REAL roundzero);
STATIC MYBOOL bimprove(lprec *lp, REAL *rhsvector, int *nzidx, REAL roundzero);
STATIC void btran(lprec *lp, REAL *rhsvector, int *nzidx, REAL roundzero);
/* Combined equation solution and matrix product for simplex operations */
STATIC MYBOOL fsolve(lprec *lp, int varin, REAL *pcol, int *nzidx, REAL roundzero, REAL ofscalar, MYBOOL prepareupdate);
STATIC MYBOOL bsolve(lprec *lp, int row_nr, REAL *rhsvector, int *nzidx, REAL roundzero, REAL ofscalar);
STATIC void bsolve_xA2(lprec *lp, int* coltarget,
int row_nr1, REAL *vector1, REAL roundzero1, int *nzvector1,
int row_nr2, REAL *vector2, REAL roundzero2, int *nzvector2, int roundmode);
/* Change-tracking routines (primarily for B&B and presolve) */
STATIC DeltaVrec *createUndoLadder(lprec *lp, int levelitems, int maxlevels);
STATIC int incrementUndoLadder(DeltaVrec *DV);
STATIC MYBOOL modifyUndoLadder(DeltaVrec *DV, int itemno, REAL target[], REAL newvalue);
STATIC int countsUndoLadder(DeltaVrec *DV);
STATIC int restoreUndoLadder(DeltaVrec *DV, REAL target[]);
STATIC int decrementUndoLadder(DeltaVrec *DV);
STATIC MYBOOL freeUndoLadder(DeltaVrec **DV);
/* Specialized presolve undo functions */
STATIC MYBOOL appendUndoPresolve(lprec *lp, MYBOOL isprimal, REAL beta, int colnrDep);
STATIC MYBOOL addUndoPresolve(lprec *lp, MYBOOL isprimal, int colnrElim, REAL alpha, REAL beta, int colnrDep);
#ifdef __cplusplus
}
#endif
#endif /* HEADER_lp_matrix */

64
include/lp_mipbb.h Normal file
View File

@ -0,0 +1,64 @@
#ifndef HEADER_lp_mipbb
#define HEADER_lp_mipbb
#include "lp_types.h"
#include "lp_utils.h"
/* Bounds storage for B&B routines */
typedef struct _BBrec
{
struct _BBrec *parent;
struct _BBrec *child;
lprec *lp;
int varno;
int vartype;
int lastvarcus; /* Count of non-int variables of the previous branch */
int lastrcf;
int nodesleft;
int nodessolved;
int nodestatus;
REAL noderesult;
REAL lastsolution; /* Optimal solution of the previous branch */
REAL sc_bound;
REAL *upbo, *lowbo;
REAL UPbound, LObound;
int UBtrack, LBtrack; /* Signals that incoming bounds were changed */
MYBOOL contentmode; /* Flag indicating if we "own" the bound vectors */
MYBOOL sc_canset;
MYBOOL isSOS;
MYBOOL isGUB;
int *varmanaged; /* Extended list of variables managed by this B&B level */
MYBOOL isfloor; /* State variable indicating the active B&B bound */
MYBOOL UBzerobased; /* State variable indicating if bounds have been rebased */
} BBrec;
#ifdef __cplusplus
extern "C" {
#endif
STATIC BBrec *create_BB(lprec *lp, BBrec *parentBB, MYBOOL dofullcopy);
STATIC BBrec *push_BB(lprec *lp, BBrec *parentBB, int varno, int vartype, int varcus);
STATIC MYBOOL initbranches_BB(BBrec *BB);
STATIC MYBOOL fillbranches_BB(BBrec *BB);
STATIC MYBOOL nextbranch_BB(BBrec *BB);
STATIC MYBOOL strongbranch_BB(lprec *lp, BBrec *BB, int varno, int vartype, int varcus);
STATIC MYBOOL initcuts_BB(lprec *lp);
STATIC int updatecuts_BB(lprec *lp);
STATIC MYBOOL freecuts_BB(lprec *lp);
STATIC BBrec *findself_BB(BBrec *BB);
STATIC int solve_LP(lprec *lp, BBrec *BB);
STATIC int rcfbound_BB(BBrec *BB, int varno, MYBOOL isINT, REAL *newbound, MYBOOL *isfeasible);
STATIC MYBOOL findnode_BB(BBrec *BB, int *varno, int *vartype, int *varcus);
STATIC int solve_BB(BBrec *BB);
STATIC MYBOOL free_BB(BBrec **BB);
STATIC BBrec *pop_BB(BBrec *BB);
STATIC int run_BB(lprec *lp);
#ifdef __cplusplus
}
#endif
#endif /* HEADER_lp_mipbb */

126
include/lp_presolve.h Normal file
View File

@ -0,0 +1,126 @@
#ifndef HEADER_lp_presolve
#define HEADER_lp_presolve
#include "lp_types.h"
#include "lp_matrix.h"
/* -------------------------------------------------------------------------------------------- */
/* Defines for various presolve options */
/* -------------------------------------------------------------------------------------------- */
#define MAX_PSMERGELOOPS 2 /* Max loops to merge compatible constraints */
#define MAX_PSLINDEPLOOPS 1 /* Max loops to detect linearly dependendent constraints */
#define MAX_PSBOUNDTIGHTENLOOPS 5 /* Maximumn number of loops to allow bound tightenings */
#define MIN_SOS1LENGTH 4 /* Minimum length of a constraint for conversion to SOS1 */
#if 1
#define PRESOLVE_EPSVALUE (0.1*lp->epsprimal)
#else
#define PRESOLVE_EPSVALUE lp->epsvalue
#endif
#define PRESOLVE_EPSPIVOT 1.0e-3 /* Looses robustness at values smaller than ~1.0e-3 */
#define PRESOLVE_BOUNDSLACK 10 /* Extra error recovery/tolerance margin */
#define DoPresolveRounding /* Use absolute and directed rounding (disable at own risk) */
/*#define DoPresolveRelativeTest*/
/*#define PresolveForceUpdateMax*/
/*#define DualFeasibilityLogicEQ2*/ /* Add low-order feasibility/accuracy logic to elimEQ2 */
#define DivisorIntegralityLogicEQ2 /* Always prefer integer divisors */
#define FindImpliedEqualities /* Detect equalities (default is enabled) */
#define Eq2Reldiff
/*#define SavePresolveEliminated */ /* Enable to activate storage of eliminated matrix data */
/*#define UseDualPresolve */ /* Enable to use full dual information for presolve */
typedef struct _psrec
{
LLrec *varmap;
int **next;
int *empty;
int *plucount;
int *negcount;
int *pluneg;
int *infcount;
REAL *plulower;
REAL *neglower;
REAL *pluupper;
REAL *negupper;
int allocsize;
} psrec;
typedef struct _presolverec
{
psrec *rows;
psrec *cols;
LLrec *EQmap;
LLrec *LTmap;
LLrec *INTmap;
REAL *pv_upbo;
REAL *pv_lobo;
REAL *dv_upbo;
REAL *dv_lobo;
lprec *lp;
REAL epsvalue;
REAL epspivot;
int innerloops;
int middleloops;
int outerloops;
int nzdeleted;
MYBOOL forceupdate;
} presolverec;
#ifdef __cplusplus
extern "C" {
#endif
/* Put function headers here */
STATIC MYBOOL presolve_createUndo(lprec *lp);
STATIC MYBOOL presolve_rebuildUndo(lprec *lp, MYBOOL isprimal);
STATIC MYBOOL inc_presolve_space(lprec *lp, int delta, MYBOOL isrows);
STATIC MYBOOL presolve_setOrig(lprec *lp, int orig_rows, int orig_cols);
STATIC MYBOOL presolve_colfix(presolverec *psdata, int colnr, REAL newvalue, MYBOOL remove, int *tally);
STATIC MYBOOL presolve_fillUndo(lprec *lp, int orig_rows, int orig_cols, MYBOOL setOrig);
STATIC MYBOOL presolve_freeUndo(lprec *lp);
STATIC MYBOOL presolve_updatesums(presolverec *psdata);
INLINE int presolve_nextrow(presolverec *psdata, int colnr, int *previtem);
INLINE int presolve_nextcol(presolverec *psdata, int rownr, int *previtem);
STATIC presolverec *presolve_init(lprec *lp);
STATIC void presolve_free(presolverec **psdata);
STATIC int presolve_shrink(presolverec *psdata, int *nConRemove, int *nVarRemove);
STATIC void presolve_rowremove(presolverec *psdata, int rownr, MYBOOL allowcoldelete);
STATIC int presolve_colremove(presolverec *psdata, int colnr, MYBOOL allowrowdelete);
STATIC MYBOOL presolve_colfixdual(presolverec *psdata, int colnr, REAL *fixValue, int *status);
INLINE int presolve_rowlength(presolverec *psdata, int rownr)
{
int *items = psdata->rows->next[rownr];
if(items == NULL)
return( 0 );
else
return( items[0] );
}
INLINE int presolve_collength(presolverec *psdata, int colnr)
{
int *items = psdata->cols->next[colnr];
if(items == NULL)
return( 0 );
else
return( items[0] );
}
STATIC int presolve(lprec *lp);
STATIC MYBOOL postsolve(lprec *lp, int status);
#ifdef __cplusplus
}
#endif
#endif /* HEADER_lp_presolve */

99
include/lp_price.h Normal file
View File

@ -0,0 +1,99 @@
#ifndef HEADER_lp_price
#define HEADER_lp_price
/* Local defines */
/* ------------------------------------------------------------------------- */
#define UseSortOnBound_Improve
/*#define UseSortOnBound_Substitute*/
#if 0 /* Stricter feasibility-preserving tolerance; use w/ *_UseRejectionList */
#define UseRelativeFeasibility /* Use machine-precision and A-scale data */
#endif
#if 0 /* Stricter pivot-selection criteria; use w/ *UseRejectionList */
#define UseRelativePivot_Primal /* In rowprim based on A-scale data */
#define UseRelativePivot_Dual /* In coldual based on A-scale data */
#endif
/* Include required library headers */
/* ------------------------------------------------------------------------- */
#include "lp_types.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Comparison and validity routines */
int CMP_CALLMODEL compareImprovementVar(const pricerec *current, const pricerec *candidate);
int CMP_CALLMODEL compareSubstitutionVar(const pricerec *current, const pricerec *candidate);
int CMP_CALLMODEL compareBoundFlipVar(const pricerec *current, const pricerec *candidate);
STATIC int addCandidateVar(pricerec *candidate, multirec *multi, findCompare_func findCompare, MYBOOL allowSortedExpand);
STATIC MYBOOL collectMinorVar(pricerec *candidate, multirec *longsteps, MYBOOL isphase2, MYBOOL isbatch);
STATIC MYBOOL validImprovementVar(pricerec *candidate);
STATIC MYBOOL validSubstitutionVar(pricerec *candidate);
/* Row+column selection routines */
STATIC MYBOOL findImprovementVar(pricerec *current, pricerec *candidate, MYBOOL collectMP, int *candidatecount);
STATIC MYBOOL findSubstitutionVar(pricerec *current, pricerec *candidate, int *candidatecount);
INLINE REAL normalizeEdge(lprec *lp, int item, REAL edge, MYBOOL isdual);
STATIC void makePriceLoop(lprec *lp, int *start, int *end, int *delta);
/* Computation of reduced costs */
STATIC void update_reducedcosts(lprec *lp, MYBOOL isdual, int leave_nr, int enter_nr, REAL *prow, REAL *drow);
STATIC void compute_reducedcosts(lprec *lp, MYBOOL isdual, int row_nr, int *coltarget, MYBOOL dosolve,
REAL *prow, int *nzprow,
REAL *drow, int *nzdrow,
int roundmode);
/* Leaving variable selection and entering column pricing loops */
STATIC int find_rowReplacement(lprec *lp, int rownr, REAL *prow, int *nzprow);
STATIC int colprim(lprec *lp, REAL *drow, int *nzdrow,
MYBOOL skipupdate, int partialloop, int *candidatecount, MYBOOL updateinfeas, REAL *xviol);
STATIC int rowprim(lprec *lp, int colnr, LREAL *theta, REAL *pcol, int *nzpcol, MYBOOL forceoutEQ, REAL *xviol);
STATIC int rowdual(lprec *lp, REAL *rhvec, MYBOOL forceoutEQ, MYBOOL updateinfeas, REAL *xviol);
STATIC int coldual(lprec *lp, int row_nr,
REAL *prow, int *nzprow, REAL *drow, int *nzdrow,
MYBOOL dualphase1, MYBOOL skipupdate,
int *candidatecount, REAL *xviol);
/* Partial pricing management routines */
STATIC partialrec *partial_createBlocks(lprec *lp, MYBOOL isrow);
STATIC int partial_countBlocks(lprec *lp, MYBOOL isrow);
STATIC int partial_activeBlocks(lprec *lp, MYBOOL isrow);
STATIC void partial_freeBlocks(partialrec **blockdata);
/* Partial pricing utility routines */
STATIC int partial_findBlocks(lprec *lp, MYBOOL autodefine, MYBOOL isrow);
STATIC int partial_blockStart(lprec *lp, MYBOOL isrow);
STATIC int partial_blockEnd(lprec *lp, MYBOOL isrow);
STATIC int partial_blockNextPos(lprec *lp, int block, MYBOOL isrow);
STATIC MYBOOL partial_blockStep(lprec *lp, MYBOOL isrow);
STATIC MYBOOL partial_isVarActive(lprec *lp, int varno, MYBOOL isrow);
/* Multiple pricing / dual long step management routines */
STATIC multirec *multi_create(lprec *lp, MYBOOL truncinf);
STATIC MYBOOL multi_resize(multirec *multi, int blocksize, int blockdiv, MYBOOL doVlist, MYBOOL doIset);
STATIC int multi_restart(multirec *multi);
STATIC int multi_size(multirec *multi);
STATIC int multi_used(multirec *multi);
STATIC MYBOOL multi_truncatingvar(multirec *multi, int varnr);
STATIC MYBOOL multi_mustupdate(multirec *multi);
STATIC void multi_valueInit(multirec *multi, REAL step_base, REAL obj_base);
STATIC REAL *multi_valueList(multirec *multi);
STATIC int *multi_indexSet(multirec *multi, MYBOOL regenerate);
STATIC int multi_getvar(multirec *multi, int item);
STATIC MYBOOL multi_recompute(multirec *multi, int index, MYBOOL isphase2, MYBOOL fullupdate);
STATIC MYBOOL multi_removevar(multirec *multi, int varnr);
STATIC int multi_enteringvar(multirec *multi, pricerec *current, int priority);
STATIC REAL multi_enteringtheta(multirec *multi);
STATIC void multi_free(multirec **multi);
STATIC int multi_populateSet(multirec *multi, int **list, int excludenr);
#ifdef __cplusplus
}
#endif
#endif /* HEADER_lp_price */

28
include/lp_pricePSE.h Normal file
View File

@ -0,0 +1,28 @@
#ifndef HEADER_lp_pricePSE
#define HEADER_lp_pricePSE
#include "lp_types.h"
#define ApplySteepestEdgeMinimum
#ifdef __cplusplus
extern "C" {
#endif
/* Price norm management routines */
STATIC MYBOOL initPricer(lprec *lp);
INLINE MYBOOL applyPricer(lprec *lp);
STATIC void simplexPricer(lprec *lp, MYBOOL isdual);
STATIC void freePricer(lprec *lp);
STATIC MYBOOL resizePricer(lprec *lp);
STATIC REAL getPricer(lprec *lp, int item, MYBOOL isdual);
STATIC MYBOOL restartPricer(lprec *lp, MYBOOL isdual);
STATIC MYBOOL updatePricer(lprec *lp, int rownr, int colnr, REAL *pcol, REAL *prow, int *nzprow);
STATIC MYBOOL verifyPricer(lprec *lp);
#ifdef __cplusplus
}
#endif
#endif /* HEADER_lp_pricePSE */

42
include/lp_report.h Normal file
View File

@ -0,0 +1,42 @@
#ifndef HEADER_lp_report
#define HEADER_lp_report
#ifdef __cplusplus
extern "C" {
#endif
/* General information functions */
char * __VACALL explain(lprec *lp, char *format, ...);
void __VACALL report(lprec *lp, int level, char *format, ...);
/* Prototypes for debugging and general data dumps */
void debug_print(lprec *lp, char *format, ...);
void debug_print_solution(lprec *lp);
void debug_print_bounds(lprec *lp, REAL *upbo, REAL *lowbo);
void blockWriteLREAL(FILE *output, char *label, LREAL *vector, int first, int last);
void blockWriteAMAT(FILE *output, const char *label, lprec* lp, int first, int last);
void blockWriteBMAT(FILE *output, const char *label, lprec* lp, int first, int last);
/* Model reporting headers */
void REPORT_objective(lprec *lp);
void REPORT_solution(lprec *lp, int columns);
void REPORT_constraints(lprec *lp, int columns);
void REPORT_duals(lprec *lp);
void REPORT_extended(lprec *lp);
/* Other rarely used, but sometimes extremely useful reports */
void REPORT_constraintinfo(lprec *lp, char *datainfo);
void REPORT_modelinfo(lprec *lp, MYBOOL doName, char *datainfo);
void REPORT_lp(lprec *lp);
MYBOOL REPORT_tableau(lprec *lp);
void REPORT_scales(lprec *lp);
MYBOOL REPORT_debugdump(lprec *lp, char *filename, MYBOOL livedata);
MYBOOL REPORT_mat_mmsave(lprec *lp, char *filename, int *colndx, MYBOOL includeOF, char *infotext);
#ifdef __cplusplus
}
#endif
#endif /* HEADER_lp_report */

1901
include/lp_rlp.h Normal file

File diff suppressed because it is too large Load Diff

31
include/lp_scale.h Normal file
View File

@ -0,0 +1,31 @@
#ifndef HEADER_lp_scale
#define HEADER_lp_scale
#include "lp_types.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Put function headers here */
STATIC MYBOOL scale_updatecolumns(lprec *lp, REAL *scalechange, MYBOOL updateonly);
STATIC MYBOOL scale_updaterows(lprec *lp, REAL *scalechange, MYBOOL updateonly);
STATIC MYBOOL scale_rows(lprec *lp, REAL *scaledelta);
STATIC MYBOOL scale_columns(lprec *lp, REAL *scaledelta);
STATIC void unscale_columns(lprec *lp);
STATIC REAL scale(lprec *lp, REAL *scaledelta);
STATIC REAL scaled_mat(lprec *lp, REAL value, int rownr, int colnr);
STATIC REAL unscaled_mat(lprec *lp, REAL value, int rownr, int colnr);
STATIC REAL scaled_value(lprec *lp, REAL value, int index);
STATIC REAL unscaled_value(lprec *lp, REAL value, int index);
STATIC MYBOOL scaleCR(lprec *lp, REAL *scaledelta);
STATIC MYBOOL finalize_scaling(lprec *lp, REAL *scaledelta);
STATIC REAL auto_scale(lprec *lp);
void undoscale(lprec *lp);
#ifdef __cplusplus
}
#endif
#endif /* HEADER_lp_scale */

34
include/lp_simplex.h Normal file
View File

@ -0,0 +1,34 @@
#ifndef HEADER_lp_simplex
#define HEADER_lp_simplex
#include "lp_types.h"
#define ForceDualSimplexInBB /* Force use/switch of dual simplex in B&B */
#define AssumeHighAccuracyInBB /* No iteration of simplex solves at infeasibility */
/*#define UseLongStepPruning*/
/*#define UseLongStepDualPhase1*/
#define primal_UseRejectionList
#define dual_UseRejectionList
#define dual_RemoveBasicFixedVars
/*#define dual_Phase1PriceEqualities */ /* Force elimination of equality slacks */
#define AcceptMarginalAccuracy
#ifdef __cplusplus
extern "C" {
#endif
/* Put function headers here */
STATIC int primloop(lprec *lp, MYBOOL primalfeasible, REAL primaloffset);
STATIC int dualloop(lprec *lp, MYBOOL dualfeasible, int dualinfeasibles[], REAL dualoffset);
STATIC int spx_run(lprec *lp, MYBOOL validInvB);
STATIC int spx_solve(lprec *lp);
STATIC int lag_solve(lprec *lp, REAL start_bound, int num_iter);
STATIC int heuristics(lprec *lp, int mode);
STATIC int lin_solve(lprec *lp);
#ifdef __cplusplus
}
#endif
#endif /* HEADER_lp_simplex */

24
include/lp_solveDLL.h Normal file
View File

@ -0,0 +1,24 @@
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#if !defined(AFX_STDAFX_H__22BF6D92_917F_4BDF_B806_0954721EBA95__INCLUDED_)
#define AFX_STDAFX_H__22BF6D92_917F_4BDF_B806_0954721EBA95__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// Insert your headers here
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#include <windows.h>
// TODO: reference additional headers your program requires here
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_STDAFX_H__22BF6D92_917F_4BDF_B806_0954721EBA95__INCLUDED_)

326
include/lp_types.h Normal file
View File

@ -0,0 +1,326 @@
#ifndef HEADER_lp_types
#define HEADER_lp_types
/* Define data types */
/* ------------------------------------------------------------------------- */
#ifndef LLONG
#if defined __BORLANDC__
#define LLONG __int64
#elif !defined _MSC_VER || _MSC_VER >= 1310
#define LLONG long long
#else
#define LLONG __int64
#endif
#endif
#ifndef COUNTER
#define COUNTER LLONG
#endif
#ifndef REAL
#define REAL double
#endif
#ifndef REALXP
#if 1
#define REALXP long double /* Set local accumulation variable as long double */
#else
#define REALXP REAL /* Set local accumulation as default precision */
#endif
#endif
#ifndef LREAL
#if 0
#define LREAL long double /* Set global solution update variable as long double */
#else
#define LREAL REAL /* Set global solution update variable as default precision */
#endif
#endif
#define RESULTVALUEMASK "%18.12g" /* Set fixed-format real-valued output precision;
suggested width: ABS(exponent of DEF_EPSVALUE)+6. */
#define INDEXVALUEMASK "%8d" /* Set fixed-format integer-valued output width */
#ifndef DEF_STRBUFSIZE
#define DEF_STRBUFSIZE 512
#endif
#ifndef MAXINT32
#define MAXINT32 2147483647
#endif
#ifndef MAXUINT32
#define MAXUINT32 4294967295
#endif
#ifndef MAXINT64
#if defined _LONGLONG || defined __LONG_LONG_MAX__ || defined LLONG_MAX
#define MAXINT64 9223372036854775807ll
#else
#define MAXINT64 9223372036854775807l
#endif
#endif
#ifndef MAXUINT64
#if defined _LONGLONG || defined __LONG_LONG_MAX__ || defined LLONG_MAX
#define MAXUINT64 18446744073709551616ll
#else
#define MAXUINT64 18446744073709551616l
#endif
#endif
#ifndef CHAR_BIT
#define CHAR_BIT 8
#endif
#ifndef MYBOOL
#define MYBOOL unsigned char /* Conserve memory, could be unsigned int */
#endif
/* Constants */
/* ------------------------------------------------------------------------- */
#ifndef NULL
#define NULL 0
#endif
/* Byte-sized Booleans and extended options */
#define FALSE 0
#define TRUE 1
#define AUTOMATIC 2
#define DYNAMIC 4
/* Sorting and comparison constants */
#define COMP_PREFERCANDIDATE 1
#define COMP_PREFERNONE 0
#define COMP_PREFERINCUMBENT -1
/* Library load status values */
#define LIB_LOADED 0
#define LIB_NOTFOUND 1
#define LIB_NOINFO 2
#define LIB_NOFUNCTION 3
#define LIB_VERINVALID 4
#define LIB_STR_LOADED "Successfully loaded"
#define LIB_STR_NOTFOUND "File not found"
#define LIB_STR_NOINFO "No version data"
#define LIB_STR_NOFUNCTION "Missing function header"
#define LIB_STR_VERINVALID "Incompatible version"
#define LIB_STR_MAXLEN 23
/* Compiler/target settings */
/* ------------------------------------------------------------------------- */
#if (defined _WIN32) || (defined WIN32) || (defined _WIN64) || (defined WIN64)
# define __WINAPI WINAPI
#else
# define __WINAPI
#endif
#if (defined _WIN32) || (defined WIN32) || (defined _WIN64) || (defined WIN64)
# define __VACALL __cdecl
#else
# define __VACALL
#endif
#ifndef __BORLANDC__
#ifdef _USRDLL
#if 1
#define __EXPORT_TYPE __declspec(dllexport)
#else
/* Set up for the Microsoft compiler */
#ifdef LP_SOLVE_EXPORTS
#define __EXPORT_TYPE __declspec(dllexport)
#else
#define __EXPORT_TYPE __declspec(dllimport)
#endif
#endif
#else
#define __EXPORT_TYPE
#endif
#ifdef __cplusplus
#define __EXTERN_C extern "C"
#else
#define __EXTERN_C
#endif
#else /* Otherwise set up for the Borland compiler */
#ifdef __DLL__
#define _USRDLL
#define __EXTERN_C extern "C"
#ifdef __READING_THE_DLL
#define __EXPORT_TYPE __import
#else
#define __EXPORT_TYPE __export
#endif
#else
#define __EXPORT_TYPE
#define __EXTERN_C extern "C"
#endif
#endif
#if 0
#define STATIC static
#else
#define STATIC
#endif
#if !defined INLINE
#if defined __cplusplus
#define INLINE inline
#elif (defined _WIN32) || (defined WIN32) || (defined _WIN64) || (defined WIN64)
#define INLINE __inline
#else
#define INLINE static
#endif
#endif
/* Function macros */
/* ------------------------------------------------------------------------- */
#define my_limitrange(x, lo, hi) ((x) < (lo) ? (lo) : ((x) > (hi) ? (hi) : (x)))
#ifndef my_mod
#define my_mod(n, m) ((n) % (m))
#endif
#define my_if(t, x, y) ((t) ? (x) : (y))
#define my_sign(x) ((x) < 0 ? -1 : 1)
#if 0
#define my_chsign(t, x) ( ((t) && ((x) != 0)) ? -(x) : (x))
#else
#define my_chsign(t, x) ( (2*((t) == 0) - 1) * (x) ) /* "Pipelined" */
#endif
#define my_flipsign(x) ( fabs((REAL) (x)) == 0 ? 0 : -(x) )
#define my_roundzero(val, eps) if (fabs((REAL) (val)) < eps) val = 0
#define my_avoidtiny(val, eps) (fabs((REAL) (val)) < eps ? 0 : val)
#if 1
#define my_infinite(lp, val) ( (MYBOOL) (fabs(val) >= lp->infinite) )
#else
#define my_infinite(lp, val) is_infinite(lp, val)
#endif
#define my_inflimit(lp, val) ( my_infinite(lp, val) ? lp->infinite * my_sign(val) : (val) )
#if 0
#define my_precision(val, eps) ((fabs((REAL) (val))) < (eps) ? 0 : (val))
#else
#define my_precision(val, eps) restoreINT(val, eps)
#endif
#define my_reldiff(x, y) (((x) - (y)) / (1.0 + fabs((REAL) (y))))
#define my_boundstr(x) (fabs(x) < lp->infinite ? sprintf("%g",x) : ((x) < 0 ? "-Inf" : "Inf") )
#ifndef my_boolstr
#define my_boolstr(x) (!(x) ? "FALSE" : "TRUE")
#endif
#define my_basisstr(isbasic) ((isbasic) ? "BASIC" : "NON-BASIC")
#define my_simplexstr(isdual) ((isdual) ? "DUAL" : "PRIMAL")
#define my_plural_std(count) (count == 1 ? "" : "s")
#define my_plural_y(count) (count == 1 ? "y" : "ies")
#define my_lowbound(x) ((FULLYBOUNDEDSIMPLEX) ? (x) : 0)
/* Bound macros usable for both the standard and fully bounded simplex */
/* ------------------------------------------------------------------------- */
/*
#define my_lowbo(lp, varnr) ( lp->isfullybounded ? lp->lowbo[varnr] : 0.0 )
#define my_upbo(lp, varnr) ( lp->isfullybounded ? lp->upbo[varnr] : lp->lowbo[varnr] + lp->upbo[varnr] )
#define my_rangebo(lp, varnr) ( lp->isfullybounded ? lp->upbo[varnr] - lp->lowbo[varnr] : lp->upbo[varnr] )
*/
#define my_lowbo(lp, varnr) ( 0.0 )
#define my_upbo(lp, varnr) ( lp->lowbo[varnr] + lp->upbo[varnr] )
#define my_rangebo(lp, varnr) ( lp->upbo[varnr] )
#define my_unbounded(lp, varnr) ((lp->upbo[varnr] >= lp->infinite) && (lp->lowbo[varnr] <= -lp->infinite))
#define my_bounded(lp, varnr) ((lp->upbo[varnr] < lp->infinite) && (lp->lowbo[varnr] > -lp->infinite))
/* Forward declarations */
/* ------------------------------------------------------------------------- */
typedef struct _lprec lprec;
typedef struct _INVrec INVrec;
union QSORTrec;
#ifndef UNIONTYPE
#ifdef __cplusplus
#define UNIONTYPE
#else
#define UNIONTYPE union
#endif
#endif
/* B4 factorization optimization data */
typedef struct _B4rec
{
int *B4_var; /* Position of basic columns in the B4 basis */
int *var_B4; /* Variable in the B4 basis */
int *B4_row; /* B4 position of the i'th row */
int *row_B4; /* Original position of the i'th row */
REAL *wcol;
int *nzwcol;
} B4rec;
#define OBJ_STEPS 5
typedef struct _OBJmonrec {
lprec *lp;
int oldpivstrategy,
oldpivrule, pivrule, ruleswitches,
limitstall[2], limitruleswitches,
idxstep[OBJ_STEPS], countstep, startstep, currentstep,
Rcycle, Ccycle, Ncycle, Mcycle, Icount;
REAL thisobj, prevobj,
objstep[OBJ_STEPS],
thisinfeas, previnfeas,
epsvalue;
char spxfunc[10];
MYBOOL pivdynamic;
MYBOOL isdual;
MYBOOL active;
} OBJmonrec;
typedef struct _edgerec
{
REAL *edgeVector;
} edgerec;
typedef struct _pricerec
{
REAL theta;
REAL pivot;
REAL epspivot;
int varno;
lprec *lp;
MYBOOL isdual;
} pricerec;
typedef struct _multirec
{
lprec *lp;
int size; /* The maximum number of multiply priced rows/columns */
int used; /* The current / active number of multiply priced rows/columns */
int limit; /* The active/used count at which a full update is triggered */
pricerec *items; /* Array of best multiply priced rows/columns */
int *freeList; /* The indeces of available positions in "items" */
UNIONTYPE QSORTrec *sortedList; /* List of pointers to "pricerec" items in sorted order */
REAL *stepList; /* Working array (values in sortedList order) */
REAL *valueList; /* Working array (values in sortedList order) */
int *indexSet; /* The final exported index list of pivot variables */
int active; /* Index of currently active multiply priced row/column */
int retries;
REAL step_base;
REAL step_last;
REAL obj_base;
REAL obj_last;
REAL epszero;
REAL maxpivot;
REAL maxbound;
MYBOOL sorted;
MYBOOL truncinf;
MYBOOL objcheck;
MYBOOL dirty;
} multirec;
#endif /* HEADER_lp_types */

159
include/lp_utils.h Normal file
View File

@ -0,0 +1,159 @@
#ifndef HEADER_lp_utils
#define HEADER_lp_utils
#ifdef FORTIFY
#include "lp_fortify.h"
#define allocCHAR allocCHAR_FORTIFY
#define allocMYBOOL allocMYBOOL_FORTIFY
#define allocINT allocINT_FORTIFY
#define allocREAL allocREAL_FORTIFY
#define allocLREAL allocLREAL_FORTIFY
#endif
#include "lp_types.h"
/* Temporary data storage arrays */
typedef struct _workarraysrec
{
lprec *lp;
int size;
int count;
char **vectorarray;
int *vectorsize;
} workarraysrec;
typedef struct _LLrec
{
int size; /* The allocated list size */
int count; /* The current entry count */
int firstitem;
int lastitem;
int *map; /* The list of forward and backward-mapped entries */
} LLrec;
typedef struct _PVrec
{
int count; /* The allocated list item count */
int *startpos; /* Starting index of the current value */
REAL *value; /* The list of forward and backward-mapped entries */
struct _PVrec *parent; /* The parent record in a pushed chain */
} PVrec;
#ifdef __cplusplus
extern "C" {
#endif
/* Put function headers here */
STATIC MYBOOL allocCHAR(lprec *lp, char **ptr, int size, MYBOOL clear);
STATIC MYBOOL allocMYBOOL(lprec *lp, MYBOOL **ptr, int size, MYBOOL clear);
STATIC MYBOOL allocINT(lprec *lp, int **ptr, int size, MYBOOL clear);
STATIC MYBOOL allocREAL(lprec *lp, REAL **ptr, int size, MYBOOL clear);
STATIC MYBOOL allocLREAL(lprec *lp, LREAL **ptr, int size, MYBOOL clear);
STATIC MYBOOL allocFREE(lprec *lp, void **ptr);
REAL *cloneREAL(lprec *lp, REAL *origlist, int size);
MYBOOL *cloneMYBOOL(lprec *lp, MYBOOL *origlist, int size);
int *cloneINT(lprec *lp, int *origlist, int size);
#if defined INLINE
INLINE void set_biton(MYBOOL *bitarray, int item)
{
bitarray[item / 8] |= (1 << (item % 8));
}
INLINE void set_bitoff(MYBOOL *bitarray, int item)
{
bitarray[item / 8] &= ~(1 << (item % 8));
}
INLINE MYBOOL is_biton(MYBOOL *bitarray, int item)
{
return( (MYBOOL) ((bitarray[item / 8] & (1 << (item % 8))) != 0) );
}
#else
void set_biton(MYBOOL *bitarray, int item);
MYBOOL set_bitoff(MYBOOL *bitarray, int item);
MYBOOL is_biton(MYBOOL *bitarray, int item);
#endif
int comp_bits(MYBOOL *bitarray1, MYBOOL *bitarray2, int items);
STATIC workarraysrec *mempool_create(lprec *lp);
STATIC char *mempool_obtainVector(workarraysrec *mempool, int count, int unitsize);
STATIC MYBOOL mempool_releaseVector(workarraysrec *mempool, char *memvector, MYBOOL forcefree);
STATIC MYBOOL mempool_free(workarraysrec **mempool);
STATIC void roundVector(LREAL *myvector, int endpos, LREAL roundzero);
STATIC REAL normalizeVector(REAL *myvector, int endpos);
STATIC void swapINT(int *item1, int *item2);
STATIC void swapREAL(REAL *item1, REAL *item2);
STATIC void swapPTR(void **item1, void **item2);
STATIC REAL restoreINT(REAL valREAL, REAL epsilon);
STATIC REAL roundToPrecision(REAL value, REAL precision);
STATIC int searchFor(int target, int *attributes, int size, int offset, MYBOOL absolute);
STATIC MYBOOL isINT(lprec *lp, REAL value);
STATIC MYBOOL isOrigFixed(lprec *lp, int varno);
STATIC void chsign_bounds(REAL *lobound, REAL *upbound);
STATIC REAL rand_uniform(lprec *lp, REAL range);
/* Doubly linked list routines */
STATIC int createLink(int size, LLrec **linkmap, MYBOOL *usedpos);
STATIC MYBOOL freeLink(LLrec **linkmap);
STATIC int sizeLink(LLrec *linkmap);
STATIC MYBOOL isActiveLink(LLrec *linkmap, int itemnr);
STATIC int countActiveLink(LLrec *linkmap);
STATIC int countInactiveLink(LLrec *linkmap);
STATIC int firstActiveLink(LLrec *linkmap);
STATIC int lastActiveLink(LLrec *linkmap);
STATIC MYBOOL appendLink(LLrec *linkmap, int newitem);
STATIC MYBOOL insertLink(LLrec *linkmap, int afteritem, int newitem);
STATIC MYBOOL setLink(LLrec *linkmap, int newitem);
STATIC MYBOOL fillLink(LLrec *linkmap);
STATIC int nextActiveLink(LLrec *linkmap, int backitemnr);
STATIC int prevActiveLink(LLrec *linkmap, int forwitemnr);
STATIC int firstInactiveLink(LLrec *linkmap);
STATIC int lastInactiveLink(LLrec *linkmap);
STATIC int nextInactiveLink(LLrec *linkmap, int backitemnr);
STATIC int prevInactiveLink(LLrec *linkmap, int forwitemnr);
STATIC int removeLink(LLrec *linkmap, int itemnr);
STATIC LLrec *cloneLink(LLrec *sourcemap, int newsize, MYBOOL freesource);
STATIC int compareLink(LLrec *linkmap1, LLrec *linkmap2);
STATIC MYBOOL verifyLink(LLrec *linkmap, int itemnr, MYBOOL doappend);
/* Packed vector routines */
STATIC PVrec *createPackedVector(int size, REAL *values, int *workvector);
STATIC void pushPackedVector(PVrec *PV, PVrec *parent);
STATIC MYBOOL unpackPackedVector(PVrec *PV, REAL **target);
STATIC REAL getvaluePackedVector(PVrec *PV, int index);
STATIC PVrec *popPackedVector(PVrec *PV);
STATIC MYBOOL freePackedVector(PVrec **PV);
#ifdef __cplusplus
}
#endif
#endif /* HEADER_lp_utils */
#ifdef FORTIFY
#ifdef CODE_lp_utils
int _Fortify_ret;
#else
extern int _Fortify_ret;
# undef allocCHAR
# undef allocMYBOOL
# undef allocINT
# undef allocREAL
# undef allocLREAL
# define allocCHAR(lp, ptr, size, clear) (Fortify_LINE(__LINE__), Fortify_FILE(__FILE__), _Fortify_ret = allocCHAR_FORTIFY(lp, ptr, size, clear), Fortify_LINE(0), Fortify_FILE(NULL), _Fortify_ret)
# define allocMYBOOL(lp, ptr, size, clear) (Fortify_LINE(__LINE__), Fortify_FILE(__FILE__), _Fortify_ret = allocMYBOOL_FORTIFY(lp, ptr, size, clear), Fortify_LINE(0), Fortify_FILE(NULL), _Fortify_ret)
# define allocINT(lp, ptr, size, clear) (Fortify_LINE(__LINE__), Fortify_FILE(__FILE__), _Fortify_ret = allocINT_FORTIFY(lp, ptr, size, clear), Fortify_LINE(0), Fortify_FILE(NULL), _Fortify_ret)
# define allocREAL(lp, ptr, size, clear) (Fortify_LINE(__LINE__), Fortify_FILE(__FILE__), _Fortify_ret = allocREAL_FORTIFY(lp, ptr, size, clear), Fortify_LINE(0), Fortify_FILE(NULL), _Fortify_ret)
# define allocLREAL(lp, ptr, size, clear) (Fortify_LINE(__LINE__), Fortify_FILE(__FILE__), _Fortify_ret = allocLREAL_FORTIFY(lp, ptr, size, clear), Fortify_LINE(0), Fortify_FILE(NULL), _Fortify_ret)
#endif
#endif

21
include/lp_wlp.h Normal file
View File

@ -0,0 +1,21 @@
#ifndef HEADER_lp_lp
#define HEADER_lp_lp
#include "lp_types.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Put function headers here */
MYBOOL LP_writefile(lprec *lp, char *filename);
MYBOOL LP_writehandle(lprec *lp, FILE *output);
#ifdef __cplusplus
}
#endif
#endif /* HEADER_lp_lp */

32
include/lpkit.h Normal file
View File

@ -0,0 +1,32 @@
#include "lp_lib.h"
#include "lp_report.h"
#define MALLOC(ptr, nr, type)\
((((nr) == 0) || ((ptr = (type *) malloc((size_t)((nr) * sizeof(*ptr)))) == NULL)) ? \
report(NULL, CRITICAL, "malloc of %d bytes failed on line %d of file %s\n",\
(nr) * sizeof(*ptr), __LINE__, __FILE__), (ptr = NULL /* (void *) 0 */) : \
ptr\
)
#define CALLOC(ptr, nr, type)\
((((nr) == 0) || ((ptr = (type *) calloc((size_t)(nr), sizeof(*ptr))) == NULL)) ? \
report(NULL, CRITICAL, "calloc of %d bytes failed on line %d of file %s\n",\
(nr) * sizeof(*ptr), __LINE__, __FILE__), (ptr = NULL /* (void *) 0 */) : \
ptr\
)
#define REALLOC(ptr, nr, type)\
((((nr) == 0) || ((ptr = (type *) realloc(ptr, (size_t)((nr) * sizeof(*ptr)))) == NULL)) ? \
report(NULL, CRITICAL, "realloc of %d bytes failed on line %d of file %s\n",\
(nr) * sizeof(*ptr), __LINE__, __FILE__), (ptr = NULL /* (void *) 0 */) : \
ptr\
)
#if defined FREE
# undef FREE
#endif
#define FREE(ptr) if (ptr != NULL) {free(ptr), ptr = NULL;} else
#define MALLOCCPY(nptr, optr, nr, type)\
(MALLOC(nptr, nr, type), (nptr != NULL) ? memcpy(nptr, optr, (size_t)((nr) * sizeof(*optr))) : 0, nptr)

24
include/lpsolve.h Normal file
View File

@ -0,0 +1,24 @@
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#if !defined(AFX_STDAFX_H__22BF6D92_917F_4BDF_B806_0954721EBA95__INCLUDED_)
#define AFX_STDAFX_H__22BF6D92_917F_4BDF_B806_0954721EBA95__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// Insert your headers here
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#include <windows.h>
// TODO: reference additional headers your program requires here
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_STDAFX_H__22BF6D92_917F_4BDF_B806_0954721EBA95__INCLUDED_)

63
include/ufortify.h Normal file
View File

@ -0,0 +1,63 @@
/*
* FILE:
* ufortify.h
*
* DESCRIPTION:
* User options for fortify. Changes to this file require fortify.c to be
* recompiled, but nothing else.
*/
#ifndef __UFORTIFY_H__
#define __UFORTIFY_H__
#define FORTIFY_STORAGE
#if defined MSDOS || defined __BORLANDC__ || defined __HIGHC__
# define KNOWS_POINTER_TYPE
#endif
#define FORTIFY_WAIT_FOR_KEY /* Pause after message */
#if !defined FORTIFY_BEFORE_SIZE
# define FORTIFY_BEFORE_SIZE 16 /* Bytes to allocate before block */
#endif
#if !defined FORTIFY_BEFORE_VALUE
# define FORTIFY_BEFORE_VALUE 0xA3 /* Fill value before block */
#endif
#if !defined FORTIFY_AFTER_SIZE
# define FORTIFY_AFTER_SIZE 16 /* Bytes to allocate after block */
#endif
#if !defined FORTIFY_AFTER_VALUE
# define FORTIFY_AFTER_VALUE 0xA5 /* Fill value after block */
#endif
#define FILL_ON_MALLOC /* Nuke out malloc'd memory */
#if !defined FILL_ON_MALLOC_VALUE
# define FILL_ON_MALLOC_VALUE 0xA7 /* Value to initialize with */
#endif
#define FILL_ON_FREE /* free'd memory is cleared */
#if !defined FILL_ON_FREE_VALUE
# define FILL_ON_FREE_VALUE 0xA9 /* Value to de-initialize with */
#endif
#define FORTIFY_CheckInterval 1 /* seconds */
/* #define CHECK_ALL_MEMORY_ON_MALLOC */
#define CHECK_ALL_MEMORY_ON_FREE
#define PARANOID_FREE
#define WARN_ON_MALLOC_FAIL /* A debug is issued on a failed malloc */
#define WARN_ON_ZERO_MALLOC /* A debug is issued on a malloc(0) */
#define WARN_ON_FALSE_FAIL /* See Fortify_SetMallocFailRate */
#define WARN_ON_SIZE_T_OVERFLOW/* Watch for breaking the 64K limit in */
/* some braindead architectures... */
#define FORTIFY_LOCK()
#define FORTIFY_UNLOCK()
#endif

24
include/yacc_read.h Normal file
View File

@ -0,0 +1,24 @@
/* prototypes of functions used in the parser */
#ifndef __READ_H__
#define __READ_H__
void lex_fatal_error(char *msg);
int set_title(char *name);
int add_constraint_name(char *name);
int store_re_op(char *yytext, int HadConstraint, int HadVar, int Had_lineair_sum);
void null_tmp_store(int init_Lin_term_count);
int store_bounds(int warn);
void storevarandweight(char *name);
int set_sos_type(int SOStype);
int set_sos_weight(double weight, int sos_decl);
int rhs_store(REAL value, int HadConstraint, int HadVar, int Had_lineair_sum);
int var_store(char *var, REAL value, int HadConstraint, int HadVar, int Had_lineair_sum);
int negate_constraint(void);
void add_row(void);
void set_obj_dir(int maximise);
void read_error(char *);
void check_int_sec_sos_decl(int, int, int);
lprec *yacc_read(lprec *lp, int verbose, char *lp_name, int *_lineno, int (*parse) (void), void (*delete_allocated_memory) (void));
#endif

5
interface.H Normal file
View File

@ -0,0 +1,5 @@
#ifndef _INTERFACE_H
#define INTERFACE_H
#include "main.H"
void Y();
#endif

695
interface.cpp Normal file
View File

@ -0,0 +1,695 @@
#include "interface.H"
extern PPRFA A;
extern Sample S;
extern int nb_tours;
extern float epsprime;
extern bool verbose;
void genere_aleatoire_unique()
{
int nbetats;
int nblettres;
int numgraphe;
int nb_succ, nb_init, nb_term;
PFA A;
cout << "Nombre d'Ètat : ";
cin >> nbetats;
cout << "Nombre de lettres : ";
cin >> nblettres;
cout << "Numero du graphe : ";
cin >> numgraphe;
cout << "nombre de successeurs par couple (etat-lettre) : ";
cin >> nb_succ;
cout << "nombre maximal d'etats initiaux : ";
cin >> nb_init;
cout << "nombre maximal d'etats terminaux : ";
cin >> nb_term;
A.becomeRandomMax (nbetats, nblettres, numgraphe, nb_succ, nb_init, nb_term);
string fichier_ps = "_tmp.ps";
string fichier_tmp = "_temporary_file";
export_to_pdf (A, fichier_ps, fichier_tmp);
show_ps (fichier_ps);
if (A.isPFA ())
{
if (A.isPRFA (true))
cout << "is PRFA" << endl;
else
cout << "is PFA" << endl;
}
else
{
cout << "not PFA" << endl;
}
}
void proportion_PRFA()
{
//------------ Proportion de PRFA -----------
int max_nb_states; // max number of states
int nb_try; // number of tests
map < int, int >Tableau;
map < int, int >nbPFA;
int i; // taille du tableau
int j; // nombre d'essais
int nb_moy_succ; // nombre moyen de successeurs
unsigned int taille_auto; // taille de l'automate
cout << "Nb d'Ètat maximal : ";
cin >> max_nb_states;
cout << "Nb de PFAs par taille : ";
cin >> nb_try;
cout << "Nb moyen de successeurs par Ètat et par lettre : ";
cin >> nb_moy_succ;
for (i = 1; i <= max_nb_states; ++i)
{
nbPFA[i]=0;
Tableau[i]=0;
cout << "\ni = " << i << endl;
for (j = 0; j < nb_try; ++j)
{
A.becomeRandomMax(i,2,0,nb_moy_succ, 1, i);
taille_auto = A.size ();
if (taille_auto == (unsigned int) i)
{
if (A.isPFA ())
{
++nbPFA[taille_auto];
if (A.isPRFA (false))
{
++Tableau [taille_auto];
cout << "R" << taille_auto << ",";
}
else
{
cout << "P" << taille_auto << ",";
}
}
else
{
cout << "X";
}
}
}
}
// compte rendu
cout << "Nb d'Ètats\t% de PRFA\t(nb d'essais)" << endl;
map < int, int >::iterator t;
map < int, int >::iterator nbPFAi;
for (t = Tableau.begin (); t != Tableau.end (); ++t)
{
if (nbPFA[t->first] != 0)
{
cout << t->first << "\t\t" << (t->second * 100) /
nbPFA[t->first] << "%\t(" << t->
second << "/" << nbPFA[t->first] << ")" << endl;
}
}
//---------- Fin de la procedure de test de la proportion de PRFA
}
void prefixialisa_echantillon()
{
string ficin, ficout;
cout << "Entrez le fichier echantillon : ";
cin >> ficin;
cout << "Entrez le nom du fichier de sortie : ";
cin >> ficout;
cout << "load en cours..." << endl;
S.load (ficin);
cout << "save en cours..." << endl;
S.prefixialise();
S.save (ficout);
cout << "Voil‡ c'est fini" << endl;
}
void Choix_cysteines()
{
// = 1 ===================== on entre les noms des fichiers
string nom_base_pos;
cout << "Veuillez entrer les noms des fichiers de pfa,\n";
cout << "de l'echantillon positif associÈ,\n";
cout << "de l'Èchantillon nÈgatif associÈ,\n";
cout << "et enfin le nom de l'Èchantillon test associÈ.\n\n";
cout << "Finissez en entrant le nom ." << endl;
;
map < int, PPRFA > Modele;
map < int, Sample > PosSample;
map < int, Sample > NegSample;
map < int, Sample > TestSample;
string nom;
Sample S;
PPRFA A;
cout << "Nom du fichier pfa : ";
cin >> nom;
int i;
i = -1;
while (nom != ".")
{
++i;
A.load (nom);
Modele[i] = A;
cout << "Èchantillon positif associe : ";
cin >> nom;
S.load (nom);
PosSample[i] = S;
cout << "Èchantillon negatif associe : ";
cin >> nom;
S.load (nom);
NegSample[i] = S;
cout << "Èchantillon test associe : ";
cin >> nom;
S.load (nom);
TestSample[i] = S;
cout << "\nNom du fichier pfa : ";
cin >> nom;
}
// = 2 =============== on calcule les moyennes et ecart-types
map < int, float >moyenne_pos;
map < int, float >ecartype_pos;
map < int, float >moyenne_neg;
map < int, float >ecartype_neg;
Dictionnaire dico;
map < int, float >probabilite_pos;
map < int, float >probabilite_neg;
map < int, float >::const_iterator prob_it;
map < int, float >decalage_pos;
map < int, float >decalage_neg;
Sample::const_iterator w;
int j;
float min;
float val;
for (i = 0; i < (int) Modele.size (); ++i)
{ // pour tous les modËles
Modele[i].lisse();
// 1a - on calcule la probabilite minimale les mots positifs
dico = PosSample[i].dictionnaire ();
j=0;
min = 1;
for (w = PosSample[i].begin ();
w != PosSample[i].end (); ++w)
{
probabilite_pos[j] = Modele[i].plog (w->first, &dico);
if (probabilite_pos[j] < min)
min = probabilite_pos[j];
++j;
}
decalage_pos[i] = min;
// 1b - on calcule la probabilite minimale les mots negatifs
dico = NegSample[i].dictionnaire ();
j=0;
min = 1;
for (w = NegSample[i].begin (); w != NegSample[i].end (); ++w)
{
probabilite_neg[j] = Modele[i].plog (w->first, &dico);
if (probabilite_neg[j] < min)
min = probabilite_neg[j];
++j;
}
decalage_neg[i]= min;
if (decalage_neg[i]<decalage_pos[i])
decalage_pos[i]=decalage_neg[i];
else
decalage_neg[i]=decalage_pos[i];
// --- on a calcule le decalage ---
// 2 - on calcule la moyenne pour les mots positifs
moyenne_pos[i] = 0;
for (prob_it = probabilite_pos.begin() ;
prob_it != probabilite_pos.end(); ++prob_it)
{
moyenne_pos[i] += exp (prob_it->second - decalage_pos[i]);
}
moyenne_pos[i] /= PosSample[i].size();
// 3 - on calcule l'ecartype pour les mots positifs
ecartype_pos[i] = 0;
for (prob_it = probabilite_pos.begin() ;
prob_it != probabilite_pos.end() ; ++prob_it)
{
ecartype_pos[i] +=
pow (moyenne_pos[i] - exp (prob_it->second - decalage_pos[i]), 2);
}
ecartype_pos[i] /= PosSample[i].size();
ecartype_pos[i] = sqrt(ecartype_pos[i]);
// Maintenant, moyenne_pos[i] contient la valeur moyenne de la probabilite
// des mots positifs et ecartype_pos[i] contient l'ecart-type des mots pos.
// puis pareil pour les nÈgatifs
// 2 - on calcule la moyenne
moyenne_neg[i] = 0;
for (prob_it = probabilite_neg.begin() ;
prob_it != probabilite_neg.end(); ++prob_it)
{
moyenne_neg[i] += exp (prob_it->second - decalage_neg[i]);
}
moyenne_neg[i] /= NegSample[i].size();
// 3 - on calcule l'ecartype pour les mots positifs
ecartype_neg[i] = 0;
for (prob_it = probabilite_neg.begin() ;
prob_it != probabilite_neg.end() ; ++prob_it)
{
ecartype_neg[i] +=
pow (moyenne_neg[i] - exp (prob_it->second - decalage_neg[i]), 2);
}
ecartype_neg[i] /= NegSample[i].size();
ecartype_neg[i] = sqrt( ecartype_neg[i] );
// on a fini de calculer les moyennes et les ecartype pour le modele i
cout << "µ pos : " << moyenne_pos[i];
cout << ", sigma pos : " << ecartype_pos[i];
cout << ", decalage pos : " << decalage_pos[i] << "\n";
cout << "µ neg : " << moyenne_neg[i];
cout << ", sigma neg : " << ecartype_neg[i];
cout << ", decalage neg : " << decalage_neg[i] << endl;
}
// = 3 ==================================== evaluation
double p1, p2;
bool res;
map < int, float >probapos;
Word u;
res = 0;
i = 0;
for (i = 0; i < (int) Modele.size (); ++i)
{
u = TestSample[i].begin ()->first;
dico = TestSample[i].dictionnaire ();
val = Modele[i].plog (u, &dico);
cout << "val = " << exp( val - decalage_pos[i] ) << endl;
if (moyenne_pos[i] > moyenne_neg[i])
{
p1 = fonction (exp (val - decalage_pos[i]), moyenne_pos[i], ecartype_pos[i]); // ECRIRE fonction
p2 = fonction (moyenne_neg[i], exp (val - decalage_neg[i]) , ecartype_neg[i]); // !!!!!!!!!!!!!!!
}
else
{
p1 = fonction (moyenne_pos[i], exp (val - decalage_pos[i]), ecartype_pos[i]); // ECRIRE fonction
p2 = fonction (exp (val - decalage_neg[i]), moyenne_neg[i] , ecartype_neg[i]); // !!!!!!!!!!!!!!!
}
cout << "p_pos = " << p1;
cout << ", p_neg = " << p2;
probapos[i] = (p1 + (1 - p2)) / 2; // ???????
cout << ", probapos = " << probapos[i] << endl;
}
float probaposgenerale=0;
for (i=0 ; i< (int) probapos.size() ; ++i)
probaposgenerale += probapos[i];
probaposgenerale /= i;
cout << "probabilite d'etre positif = " << probaposgenerale << endl;
}
void Apprentissage_unique()
{
string ficech;
cout << "Veuillez entrer le nom du fichier contenant l'echantillon : ";
cin >> ficech;
Sample S;
if (!OK (S.load (ficech.c_str ())))
{
cerr << "impossible d'ouvrir " << ficech << endl;
throw 5;
}
PPRFA A;
string reponse;
unsigned int seuil;
string str;
float tmp;
float precision;
T_ModeReturn moderet=begin;
T_ModeEpsilon modeeps=epsfixed;
int max_etats=INT_MAX;
cout << "Les parametres necessaires a l'apprentissage sont : \n";
while (reponse != "0")
{
cout << "1 - La precision .................. : "
<< precision << "\n";
cout << "2 - Le mode de retour ............. : "
<< (moderet==begin?"begin":"end") << "\n";
cout << "3 - Le mode de gestion de epsilon . : "
<< (modeeps==epsfixed?"epsfixed":
(modeeps==variable?"variable":"word_variable"))
<< "\n";
cout << "4 - Seuil de suppression des aretes : "
<< epsprime << "\n";
cout << "5 - Verbose ....................... : "
<< verbose << "\n";
cout << "6 - La taille maximale de la cible : "
<< max_etats << "%\n";
cout << "7 - Nombre de successeurs par mot : "
<< seuil << "\n";
cout << "\n";
cout << "0 - Debut de l'apprentissage\n";
cout << "\n";
cout << "Votre choix : ";
cin >> reponse ;
if (reponse == "1")
{ // precision
cout << "nouvelle precision : ";
cin >> precision;
}
else if (reponse == "2")
{ // mode de retour
cout << "mode de retour (begin|end|b|e) : ";
cin >> str;
if ((str=="end") || (str == "e"))
moderet=end;
else
moderet=begin;
}
else if (reponse == "3")
{ // mode de gestion de epsilon
cout << "mode de gestion d'epsilon (fixed|variable|word_variable|f|v|w) : ";
cin >> str;
if ((str == "word_variable") || (str == "w"))
{
modeeps=word_variable;
}
else if ((str == "variable") || (str == "v"))
{
modeeps=variable;
}
else
{
modeeps=epsfixed;
}
}
else if (reponse == "4")
{ //seuil de suppression des aretes
cout << "seuil de suppression des aretes ([0;1]) : ";
cin >> tmp;
if ((tmp >=0) && (tmp <= 100))
epsprime = tmp;
}
else if (reponse == "5")
{ // verbose
verbose = !verbose;
}
else if (reponse == "6")
{ // nombre maximal d'etats
cout << "Nombre maximal d'etats : ";
cin >> max_etats;
}
else if (reponse == "7")
{ // nombre de successeur par mots
cout << "Nombre de successeurs necessaires par mot : ";
cin >> seuil;
}
else if (reponse == "0")
{}
else
{
cout << "Choix inconnu" << endl;
}
}
A.DEES (nonconstrained, S, precision, epsprime, verbose, moderet, modeeps, max_etats, seuil);
string ficffaA="test/A.ffa";
if (verbose)
cout << "saving A in " << ficffaA << endl;
A.save (ficffaA);
// affichage de l'automate
string ficpsA="test/A.ps";
string ficdotA="test/A.dot";
export_to_pdf (A, ficpsA, ficdotA);
show_ps (ficpsA);
}
void makePTA()
{
string ficech;
PPRFA A;
Sample S;
cout << "Donnez le fichier contenant l'echantillon : ";
cin >> ficech;
S.load(ficech);
A.becomePrefixTree(S);
string ficpsA = "test/tmp.ps";
string ficdotA= "test/tmp.dot";
export_to_pdf(A,ficpsA, ficdotA);
show_ps(ficpsA);
}
void TST_FD_BD() {
string ficpfa;
cout << "Donnez le fichier contenant le PFA : ";
cin >> ficpfa;
A.load(ficpfa);
Word w;
cout << "Donnez un mot : ";
cin >> w;
list<PreciseSFunc> F, B;
A.logforward(F,w);
A.logbackward(B,w);
list<PreciseSFunc>::const_iterator f;
list<PreciseSFunc>::const_reverse_iterator b;
PreciseSFunc::const_iterator x, y;
cout << "P(" << w << ")=" << A.p(w) << endl;
for (f = F.begin(), b=B.rbegin() ; f != F.end() ; ++f, ++b) {
for (x=f->begin() ; x != f->end() ; ++x) {
cout << "F[" << x->first << "]=" << exp(x->second) << ", ";
}
cout << "\n";
for (y=b->begin() ; y != b->end() ; ++y) {
cout << "B[" << y->first << "]=" << exp(y->second) << ", ";
}
cout << "\n\t----" << endl;
}
}
void TST1() {
S.load("sample");
SFunc solution;
WordSFunc XR;
XR[""]=1;
XR["a"]=2;
XR["b"]=3;
solution[1]=0.5;
solution[2]=0.5;
A.becomePrefixTree(S);
SFunc Iota,Tau;
A.allStates(Tau);
TransitionFunction T;
A.allTransitions(T);
A.BaumWelch(S,T,Iota,Tau,10 , false);
float x = S.AutoLikelihood();
float y = A.Likelihood(S);
A.save("test/res.ffa");
cout << S.size() << " "<< x << " "<< y << " :: " << (x-y)/S.size() << endl;
}
void TST(){
string entree;
string sortie;
cout << "Echantillon d'entrée : ";
cin >> entree;
cout << "Echantillon de sortie : ";
cin >> sortie;
Sample S;
S.load(entree);
S.save(sortie);
}
void TST4() {
SFunc solution;
SFunc Iota,Tau;
TransitionFunction T;
Transition t1,t2;
float x, y, x1, x2, y1, y2;
float xsum, val;
int i;
S.load("sample");
solution[1]=0.5;
solution[2]=0.5;
S.prefixialise();
int nb_sucb=S["b"];
cout << "prefixialisation..." << endl;
S.deprefixialise();
cout << "becomePrefixTree..." << endl;
A.becomePrefixTree(S);
A.save("test/pta");
cout << "becomeQPFT..." << endl;
A.becomeQuasiPrefixTree(S,"b",solution);
A.save("test/qpta");
A.allStates(Tau);
A.allTransitions(T);
t1.qdep=t2.qdep=1;
t1.a=t2.a='b';
t1.qarr=1;
t2.qarr=2;
A.BaumWelch(S,T,Iota,Tau,30, false);
x1=T[t1]; x2=T[t2];
xsum = x1+x2;
x1 /= xsum;
x2 /= xsum;
A.BaumWelch(S,T,Iota,Tau,1, false);
y1=T[t1]; y2=T[t2];
xsum = y1+y2;
y1 /= xsum;
y2 /= xsum;
val=abs(x1-y1)+abs(x2 - y2);
i=20;
while ((val > 0.001) && (--i != 0)) {
cout << ".";
x1=y1; x2=y2;
A.BaumWelch(S,T,Iota,Tau,1, true);
y1=T[t1]; y2=T[t2];
xsum = y1+y2;
y1 /= xsum;
y2 /= xsum;
val=abs(x1-y1)+abs(x2 - y2);
}
A.save("test/qptafinal.ffa");
A.save("test/res.ffa");
x = S.AutoLikelihood();
y = A.Likelihood(S);
val=abs((y-x)/float(S.size()));
cout << S.size() << " "<< x << " "<< y << " :: " << val << " " << nb_sucb;
cout << " " << val - 5/sqrt(float(nb_sucb)) << endl;
}
void TST3() {
S.load("sample");
A.load("test/tst3.ffa");
TransitionFunction T;
SFunc Iota, Tau;
A.allTransitions(T);
A.allStates(Iota);
A.allStates(Tau);
for (int i=1 ; i<200 ; ++i) {
A.BaumWelch(S,T,Iota,Tau,1,true);
cout << "." << flush;
cout << "\t" << A.Likelihood(S) << "\n";
}
cout << endl;
A.erase_bad_states();
A.save("test/res.ffa");
}
void TSTprime()
{
string ficech="sample";
// cout << "Donnez le fichier contentant l'echantillon : ";
// cin >> ficech;
S.load(ficech);
float precision, epsprime;
cout << "Donnez la precision : ";
cin >> precision;
cout << "Donnez le seuil de suppression des aretes : ";
cin >> epsprime;
cout << "Donnez le nombre de tours de BM : ";
int nb_tours;
cin >> nb_tours;
A.DEESBM(S,precision,epsprime,true,INT_MAX,0,nb_tours);
string ficpsA = "test/tmp.ps";
string ficdotA= "test/tmp.dot";
export_to_pdf(A,ficpsA, ficdotA);
show_ps(ficpsA);
}
void proba(void) {
string nomfic;
Word w;
cout << "entrez le fichier : ";
cin >> nomfic;
A.load(nomfic);
cout << "entrez le mot : ";
cin >> w;
cout << "p(" << w << ")= " << A.p(w) << endl;
}
void
Y (void)
{
int choix;
cout << "\t\t1 - BaumWelch sur test/tst3.ffa\n";
cout << "\t\t2 - Probabilite d'un mot\n";
cout << "\t\t3 - Prefixialise un echantillon\n";
cout << "\t\t4 - Choix pour les cysteines\n";
cout << "\t\t5 - Apprend ‡ partir d'un Èchantillon avec optimisation du paramËtre\n";
cout << "\t\t6 - Apprend ‡ partir d'un Èchantillon\n";
cout << "\t\t7 - Cree un PTA ‡ partir d'un Èchantillon\n";
cout << "\t\t8 - TST\n";
cout << "\n";
cout << "choix : ";
cin >> choix;
if (choix == 1) // Une generation aleatoire
{
TST3();
} else if (choix == 2) // Proportion des PRFAs
{
proba();
} else if (choix == 3) // Prefixialise un echantillon
{
prefixialisa_echantillon();
} else if (choix == 4) // Test pondere "intelligent" ?
{
Choix_cysteines();
} else if (choix == 5) //
{
cout << "Ce choix n'est plus valide !!!" << endl;
}
else if (choix == 6)
{
Apprentissage_unique();
}
else if (choix == 7)
{
makePTA();
}
else if (choix == 8)
{
TST();
}
else // mauvais choix
{
cout << "entree inconnue" << endl;
}
}

BIN
lib/liblpsolve55.a Normal file

Binary file not shown.

BIN
lib/liblpsolve55.dylib Executable file

Binary file not shown.

BIN
lib/linux_liblpsolve55.a Normal file

Binary file not shown.

278
ma.H Normal file
View File

@ -0,0 +1,278 @@
/***************************************************************************
ma.h - Multiplicity Automata
-------------------
begin : Tue Jul 16 2002
copyright : (C) 2002 by Yann Esposito
email : esposito@cmi.univ-mrs.fr
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
/*_________________________________________________________________________*\
Un automate fini fonctionnel se défini comme un quintuplet :
Sigma : l'alphabet, un ensemble fini de lettre.
Ici, les lettre seront des mots.
Q : L'ensemble des états. Pour l'instant on se limite aux entiers.
iota : une fonction de Q dans IR
tau : une fonction de Q dans IR
phi : une fonction de Q x Sigma x Q dans IR
\***************************************************************************/
#ifndef MA_H
#define MA_H
#include "general.H"
#include "sample.H"
#include <math.h>
typedef set < State > StateSet; // type Ensemble d'états
typedef map < State, float >SFunc; // Type fonction State --> IR
typedef map < Lettre, SFunc > LettreSFunc; // Type fonction Lettre x State --> IR
// typedef hmext::hash_map < State, LettreSFunc > Graph; // Le type Graph
typedef map < State, LettreSFunc > Graph; // Le type Graph
struct ordre_transition
{
bool operator()(const Transition t1, const Transition t2) const
{
return
(t1.qarr < t2.qarr) ||
(
(t1.qarr == t2.qarr) &&
(
(t1.a < t2.a) ||
(
(t1.a == t2.a) && (t1.qdep < t2.qdep)
)
)
);
}
};
typedef map<Transition, float, ordre_transition> TransitionFunction;
typedef enum { paffa, paalergia, pamdi} FormatSauvegarde;
class MA
{
// ---------------- Structure de donnée ------------------------
public:
// Le nom du MA
string name;
protected:
// Le dictionnaire
Dictionnaire alph; // permet d'associer des chaines de caractères aux lettre
// l'alphabet
Alphabet Sigma;
// L'ensemble d'états
StateSet Q;
// La fonction iota
SFunc iota;
// La fonction tau
SFunc tau;
// La fonction phi;
Graph phi;
// ------------------------- Méthodes ---------------------------
protected: // méthodes internes
// renvoie un flottant aleatoire compris entre min et max
float random (float min = 0, float max = 1) const;
// renvoie vrai si x est à peu près égal à 1;
inline bool simeqone (double x) const
{
return ((x > 0.9999) && (x < 1.0001));
}
// --- Constructeurs et destructeurs --
public:
MA (int nb_lettres = 0, int nb_etats = 0);
~MA ();
// --- Affichage ---
// Renvoie la chaine de caractère d'affichage
string message (void) const;
// Affichage sous la sortie standart
RESULT affiche (void) const;
// --- Input output ---
// Sauvegarde le MA dans Filename
RESULT save (ofstream &fp, const FormatSauvegarde c_format = paffa) const;
RESULT save (const char *Filename, const FormatSauvegarde format = paffa) const;
inline RESULT save (const string Filename) const {return save (Filename.c_str ());}
// Charge le MA de Filename
RESULT load (const char *Filename);
RESULT load (string Filename) {return load (Filename.c_str ());}
// save in dot format
RESULT save_dot (const char *Filename,
const int precision = 2,
const bool noms_etats = false,
const bool multiple_trans = false) const;
RESULT save_dot (const string Filename,
int precision = 2,
bool noms_etats = false,
bool multiple_trans = false) const;
// --- Accesseurs ---
// true if the MA is empty
inline bool empty() const {return Q.empty();}
// return the size of the MA
inline unsigned int size () const {return Q.size ();}
// return the number of letter of the MA
inline unsigned int nb_lettres () const {return Sigma.size ();}
// return safely iota[q] (even if iota[q]=0)
inline float val_iota (const State q) const {
SFunc::const_iterator i = iota.find (q);
return i == iota.end () ? 0 : i->second;
}
// return safely tau[q] (even if tau[q]=0)
inline float val_tau (const State q) const{
SFunc::const_iterator i = tau.find (q);
return i == tau.end () ? 0 : i->second;
}
// return safely phi[t] (even if phi(t)=0 )
inline float val_phi (const Transition &t) const {
return val_phi(t.qdep, t.a, t.qarr);
}
// return safely phi[t] (even if phi(t)=0 )
inline float val_phi (const State q, const Lettre a, const State s) const {
Graph::const_iterator qi = phi.find (q);
if (qi == phi.end ()) return 0;
LettreSFunc::const_iterator ai = qi->second.find (a);
if (ai == qi->second.end ()) return 0;
SFunc::const_iterator si = ai->second.find (s);
if (si == ai->second.end ()) return 0;
return si->second;
}
// The transitionFunction T is the set of all transitions of the MA
void allTransitions(TransitionFunction &T) const;
// The stateFucntion S is the set of all state of the MA
void allStates(SFunc &S) const;
// the delta function
StateSet delta(const State q, const Word &w) const;
StateSet delta(const StateSet &R, const Word &w) const;
// direct read only accessor
inline Dictionnaire dictionnaire(void) const {return alph;};
// --- Modifieurs ---
// Ajout une lettre par defaut à l'alphabet
Lettre addLettre (void);
// Add the letter buf
Lettre addLettre (const TrueLettre & buf);
// Ajoute un état
//State addState (const float init = 0, const float term = 1);
State addNewState (const float init, const float term);
// Ajout l'état q s'il n'existe pas déjà
State addState (const State q, const float init = 0, const float term = 1);
// Fonction qui ajoute une transition
RESULT addTransition (const Transition & t, const float val);
// Ajout d'une transition
RESULT addTransition (const State qdep, const Lettre a, const State qarr, const float val);
// erase badstate
RESULT erase (State badstate);
// clean transitions with parameter between minval and maxval
RESULT erase_transitions (const double maxval = 0, const double minval = 0);
// erase cleanly the transition phi(qbeg, l ,qend)
RESULT eraseTransition(const State qbeg, const Lettre l, const State qend);
// Become a Random MA
RESULT becomeRandom (const int nb_etats, // le nombre d'états
const int nb_lettres, // le nombre de lettres
const int num_graphe = 0, // le numero du graphe
const float densite = 0.3, // densité du ffa (0 ffa vide, 1 ffa complet)
const float prob_init = 0.3, // la probabilité pour un état d'etre initial
const float prob_term = 0.3, // probabilité pour un état d'être terminal
const float min_trans = 0, // la valeur minimale des transitions
const float max_trans = 1); // la valeur maximale des transitions
// Cree un MA prefixe aleatoire
RESULT becomeRandomPrefix (const int nb_etats, // le nombre d'états
const int nb_lettres, // le nombre de lettres
const int num_graphe = 0, // le numero du graphe
const float densite = 0.3, // densité du ffa (0 ffa vide, 1 ffa complet)
const float prob_init = 0.3, // la probabilité pour un état d'etre initial
const float prob_term = 0.3, // probabilité pour un état d'être terminal
const float min_trans = 0, // la valeur minimale des transitions
const float max_trans = 1); // la valeur maximale des transitions
// Cree un MA aleatoire avec un nombre d'aretes maximal fixé
RESULT becomeRandomMax (const int nb_etats, const int nb_lettres,
const int num_graphe=0, const int nb_succ=2,
const int nb_init=1, const int nb_term=INT_MAX,
const float min_trans=0, const float max_trans=1);
// Cree un MA aleatoire avec le maximum de controle
// nb_etats : number of states of the MA
// nb_lettres : number of letters of the alphabet of the MA
// num_graphe : if different of 0, the same number gives always the same MA
// max_nb_init : the maximal number of initial states
// max_nb_succ : the maximal number of successors by states-letter
// max_nb_term : the maximal number of terminal states
// min_trans : minimal value of transitions
// max_trans : maximal value of transitions
// min_iota : minimal value for iota(q)
// max_iota : maximal value for iota(q)
// min_tau : minimal value for tau(q)
// max_tau : maximal value for tau(q)
// nomalize : if different of 0, normalize sum of iota and sum of tau + successor transitions
// prob_init : probability for a state to be initial
// prob_trans : probability to create each transition
// prob_term : probability for a state to be terminal
RESULT becomeRandomControl (const int nb_etats, const int nb_lettres, const int num_graphe, const int max_nb_succ, const int max_nb_init, const int max_nb_term, const float min_trans, const float max_trans, const float min_iota, const float max_iota, const float min_tau, const float max_tau, const float normalization, const float prob_init, const float prob_trans, const float prob_term);
RESULT becomeComplete (const int nb_etats, const int nb_lettres);
// Fonction qui rend le MA vide (pas d'états pas de lettre)
void vide ();
// exactly as vide, clear the MA
inline void clear() { vide(); }
// emmonde the MA
// delete all reachable states and all states from which no state can be reached
RESULT emmonde(void);
// --- Fonctions dŽpendant de l'objet ---
// the next word using the alphabet Sigma
void next (Word & w) const;
// renvoie la chaine correspondant au mot
string affiche (const Word & w) const;
void normaliseVecteur(SFunc &V) const;
RESULT val_PSe(SFunc &PSe) const;
// generate a word from the model using the P_r function where r
// is the rationnal serie of the MA
// genere un mot en corelation avec la distribution P_r associe
// au MA
RESULT genere_mot(Word &w, const bool safe = true);
// genere un échantillon de mots
RESULT genere_echantillon(const int taille, Sample &S, const int num_echantillon=0);
// genere un échantillon de mots
RESULT genere_echantillon(const int taille, Sample &S, const char *Filename, const int num_echantillon=0);
// --- Test ---
// Teste la cohérence de la structure de donnée
bool coherent (void) const;
// Teste si le MA est coherent et est un SPFA. valeur de iota, tau et phi dans [0,1]
bool isSPFA (void) const ;
// renvoi vrai si le MA est un PFA
bool isPFA (void) const;
private:
RESULT renormalize_state(const State q, const float renormalization, const float min_tau, const float max_tau, const float min, const float max);
};
#endif

2562
ma.cpp Normal file

File diff suppressed because it is too large Load Diff

34
main.H Normal file
View File

@ -0,0 +1,34 @@
#ifndef _MAIN_H
#define _MAIN_H
#include "pprfa.H"
#include <sstream>
// affiche un mot
string affiche (const Word & w, const Dictionnaire & alph);
// La fonction qui va charger les info à partir d'un fichier
RESULT charge (char *nomFic);
// initialisation des arguments (ligne de commande)
int initialise_arguments (int argc, char *argv[]);
// La procédure qui initialise le random
int randomize (void);
int affiche_utilisation (void);
int affiche_options (void);
RESULT export_to_pdf (const MA & A,
const string & fic_ps,
const string & fic_tmp,
const int precision = 3,
const bool noms_etats = false,
const bool multiples_trans = false);
void show_ps (string & fic_ps);
// Affiche toutes les distances entre A et B
void affiche_distance (PFA & A, const PFA & B, const int taille_ech_test,
const string & flag);
void affiche_distance (PFA & A, const PFA & B, const int taille_ech,
const char *flag);
void affiche_classe (PFA & A);
// --- La procedure pour debbugger ---
float fonction (float val, float moy, float ecart);
// La procedure principale
int main (int argc, char *argv[]);
#endif

1324
main.cpp Normal file

File diff suppressed because it is too large Load Diff

31
oldsimplex.H Normal file
View File

@ -0,0 +1,31 @@
#include "general.H"
#include <math.h> // pour fabs
// ------- La classe ----------
class Simplex
{
public:
//hash_map<int, map <int, double> > a; // La matrice des contraintes
//hash_map<int, double> sol; // Le tableau des solutions
//hash_map<int, int> db; // Un tableau
//hash_map<int, int> hb; // un autre tableau
map<int, map <int, double> > a; // La matrice des contraintes
map<int, double> sol; // Le tableau des solutions
map<int, int> db; // Un tableau
map<int, int> hb; // un autre tableau
map<int, double>::iterator it; // un itérateur sur les colonnes de a.
public:
Simplex() {}
~Simplex(){}
private:
int ads_sortant(int m,int n,int phase);
int ads_entrant(int n,int l);
void pivotage(int m,int n,int l,int k);
int affiche(int ineq1, int ineq2, int nbeq, int nbvar);
public:
int simplexe_dual(int ineq1, int ineq2, int eq, int n);
int solve(int ineq1, int ineq2, int eq, int n, bool debug=false);
};

112
pfa.H Normal file
View File

@ -0,0 +1,112 @@
/***************************************************************************
pfa.h - Probabilistic Finite Automaton
-------------------
begin : 7 Dec 2002
copyright : (C) 2002 by Yann Esposito
email : esposito@cmi.univ-mrs.fr
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
/*________________________ DÈscription plus prÈcise ______________________*\
Classe qui hÈrite de la classe spfa, la seule diffÈrence est que l'on
peut gÈnÈrer des mots avec une distribution de probabilitÈ.
\***************************************************************************/
#ifndef PFA_H
#define PFA_H
#include "spfa.H"
#include "sample.H"
//#include "simplex.H"
// ------------------------ La Classe ----------------------------------
class PFA : public SPFA
{
public:
RESULT rend_PFA(void);
// cree un PFA aleatoire
RESULT becomeRandom(int num_etat, int num_lettre, // le nombre d'etats et le nombre de lettres
int num_graphe = 0, // le numero du graphe (donner deux fois le mÍme numero avec
// les memes paramËtres donne le mÍme graphe
float densite=0.3, // densitÈ du ffa (0 ffa vide, 1 ffa complet)
float prob_init=0.3, // probabilitÈ d'Ítre initial
float prob_term=0.3, // probabilitÈ d'Ítre terminal
float min_trans=0,
float max_trans=1); // valeur maximale des transitions
RESULT becomeRandomPrefix(const int nb_etats, // le nombre d'Ètats
const int nb_lettres, // le nombre de lettres
const int num_graphe = 0, // le numero du graphe
const float densite=0.3, // densitÈ du ffa (0 ffa vide, 1 ffa complet)
const float prob_init=0.3, // la probabilitÈ pour un Ètat d'etre initial
const float prob_term=0.3, // probabilitÈ pour un Ètat d'Ítre terminal
const float min_trans = 0, // la valeur minimale des transitions
const float max_trans = 1); // la valeur maximale des transitions
// Cree un MA aleatoire avec un nombre maximal d'aretes
RESULT becomeRandomMax (const int nb_etats, const int nb_lettres,
const int num_graphe=0, const int nb_succ=2,
const int nb_init=1, const int nb_term=INT_MAX,
const float min_trans=0, const float max_trans=1);
// genere un mot en corelation avec la distribution
RESULT genere_mot(Word &w, const bool safe = true);
// -- dans MA maintenant -- // genere un Èchantillon de mots
RESULT genere_echantillon(const int taille, Sample &S, const int num_echantillon=0);
// -- dans MA maintenant -- // genere un Èchantillon de mots
RESULT genere_echantillon(const int taille, Sample &S, const char *Filename, const int num_echantillon=0);
// transforme un MA avec valeurs positives en SPFA
RESULT rend_spfa(void);
// Lissage
RESULT lisse(int mode=0, float delta=0.01);
// become the PTA representing S
RESULT becomePrefixTree(Sample &S);
// ----------- DISTANCES ENTRE PFAs -----------
// renvoie la perplexitÈ du PFA par rappor ‡ l'echantillon S
double perplexite(const Sample &S) const;
// renvoie la divergence de Kullback Leibler relativemant ‡ l'Èchantillon S
double divKL(const PFA &B, const Sample &S);
// renvoie la divergence de Kullback Leibler relativemant ‡ l'Èchantillon S en utilisant B
double divKL (PFA &B, const Sample & S) const;
// renvoie la norme 2 entre ce PFA et le PTA correspondant ‡ S
double d_2(const Sample &S) const;
// renvoie la norme 2 entre ce PFA et un autre
double d_2(const PFA &B, const Sample &S) const;
// revoie la norme L1 entre ce PFA et un autre en fonction de l'Èchantillon
double L_1(const PFA &B, const Sample &S) const;
// renvoie la norme 2 entre ce PFA et un autre calculée sans passer par les logs
double d_2nlog(const PFA &B, const Sample &S) const;
// revoie la norme L1 entre ce PFA et un autre en fonction de l'Èchantillon calculé sans passer par les logs
double L_1nlog(const PFA &B, const Sample &S) const;
// renvoie la moyenne des Ècarts de log en fonction d'un Èchantillon S
double dlog(const PFA &B, const Sample &S) const;
// renvoie dlog sans prendre en compte les mots non gÈnÈrables par l'un des deux PFAs
double dlog_safe(const PFA &B, const Sample &S) const;
// renvoie la vraissemblance
float Likelihood(const Sample &S);
// return true if the MA is a PRFA
bool isPRFA(bool verbose=false);
// return true if the PFA is a PDFA
bool isPDFA();
};
#endif

713
pfa.cpp Normal file
View File

@ -0,0 +1,713 @@
/***************************************************************************
pfa.cpp
-------------------
begin : Mon 9 Dec 2002
copyright : (C) 2002 by Yann Esposito
email : esposito@cmi.univ-mrs.fr
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
/*
Pour les notes, voir le fichier "pfa.h".
See "pfa.h" file to view notes.
*/
#include "pfa.H"
//#include <list>
#include <assert.h>
// renvoi vrai si le MA est un PFA
RESULT
PFA::rend_PFA (void)
{
// on emmonde
MA::emmonde();
// renormalisation of all parameters
renormalise();
return VAL (0);
}
RESULT
PFA::becomeRandom (const int nb_etats, const int nb_lettres,
const int num_graphe, const float densite,
const float prob_init, const float prob_term,
const float min_trans, const float max_trans)
{
// on cree un SPFA
SPFA::becomeRandom (nb_etats, nb_lettres,
num_graphe, densite,
prob_init, prob_term,
min_trans, max_trans);
// puis on l'emmonde et on le renormalise.
return rend_PFA ();
}
// Cree un MA aleatoire avec un nombre maximal d'aretes
RESULT PFA::becomeRandomMax (const int nb_etats, const int nb_lettres,
const int num_graphe, const int nb_succ,
const int nb_init, const int nb_term,
const float min_trans, const float max_trans)
{
SPFA::becomeRandomMax(nb_etats, nb_lettres, num_graphe, nb_succ, nb_init, nb_term,min_trans,max_trans);
return rend_PFA();
}
RESULT
PFA::becomeRandomPrefix (const int nb_etats, const int nb_lettres,
const int num_graphe, const float densite, const float prob_init,
const float prob_term, const float min_trans,
const float max_trans)
{
// On gÈnËre un MA alÈatoire avec seulement des arÍtes positives
SPFA::becomeRandomPrefix (nb_etats, nb_lettres,
num_graphe, densite,
prob_init, prob_term,
min_trans, max_trans);
// on rend un SPFA
return rend_PFA ();
}
// Arbre prefixe
RESULT PFA::becomePrefixTree(Sample &S)
{
bool ispref = S.isprefixiel();
if (!ispref)
{
S.prefixialise();
}
vide(); // on vide la structure du PFA
Sample::const_iterator w;
Lettre a;
Word v;
Sigma=S.alphabet();
alph=S.dictionnaire();
map< Word, State > R;
w = S.begin();
R[w->first]=addNewState(1,0);
// on commence apres epsilon d'ou le ++w au debut du for
for (++w ; w != S.end() ; ++w)
{
v=w->first;
R[v]=addNewState(0,0);
a=*(v.rbegin());
v.erase(--v.end());
addTransition(R[v], a , R[w->first],(float)S[w->first]/(float)S[v]);
}
// on met ‡ jour iota et tau
StateSet::const_iterator e;
Graph::const_iterator q;
LettreSFunc::const_iterator x;
SFunc::const_iterator r;
float sum;
for (e=Q.begin() ; e != Q.end() ; ++e)
{
sum = 0;
q=phi.find(*e);
if (q != phi.end())
{
for (x=q->second.begin() ; x != q->second.end() ; ++x)
{
for (r=x->second.begin() ; r != x->second.end() ; ++r)
{
sum += r->second;
}
}
}
tau[*e]=1-sum;
}
if (!ispref)
{
S.deprefixialise();
}
return VAL(0);
}
// Lissage
RESULT PFA::lisse (int mode, float delta)
{
if (mode == 0)
{ // Mode sale !!!
SFunc::iterator q;
Alphabet::const_iterator a;
float val;
State s; // le nouvel etat
if (iota.empty ())
{
s = addNewState(1,delta);
}
else
{
q = iota.begin ();
val = q->second * delta;
q->second = q->second * (1 - delta);
s = addNewState (val, delta);
}
val = 1 - delta;
for (a = Sigma.begin (); a != Sigma.end (); ++a)
addTransition (s, *a, s, val / (Sigma.size ()));
return VAL(0);
}
else if (mode == 1)
{
cerr << "PFA::lisse(), mode " << mode << " non pris en compte"
<< endl;
return ERR (1);
}
else
{
cerr << "PFA::lisse(), mode" << mode << " non pris en compte" << endl;
return ERR (0);
}
}
// Vraissemblance
float PFA::Likelihood(const Sample &S)
{
if (S.isprefixiel()) {
cerr << "PFA::Likelihood(const Sample &S) : S is prefixial !" << endl;
return -1;
}
Sample::const_iterator w;
float result=0;
// cout.precision(19);
for (w=S.begin() ; w != S.end() ; ++w)
{
if (isnan(plog(w->first))) {
cerr << "ERREUR mot : " << w->first << endl;
}
else {
result += plog(w->first) * w->second;
}
}
return result;
}
// genere un mot ‡ l'aide du PFA.
RESULT
PFA::genere_mot (Word & w, const bool safe)
{
if (PFA_SAFE)
{
if (safe)
assert (isPFA ());
}
State jeton;
float alea;
float sum;
SFunc::const_iterator q;
LettreSFunc::const_iterator a;
// w = mot vide
w.clear ();
// choix de l'Ètat initial q
// on prend un nombre de [0,1[
alea = ((float) rand ()) / INT_MAX;
// on prend le premier etat qui fait dÈpasser le seuil
q = iota.begin ();
sum = q->second;
while (sum < alea)
{
sum += (++q)->second;
}
jeton = q->first; // on a fait notre choix
// Fin du choix : on commence dans l'Ètat jeton
// on genere le mot
// alea prend une valeur au hasard de [0,1[, puis tant que l'on ne s'arrete pas
// i.e. tant que alea > tau(jeton),
alea = ((float) rand ()) / INT_MAX;
while (alea >
(sum =
(tau.find (jeton) !=
tau.end ())? (tau.find (jeton)->second) : 0))
{
// on choisi une transition ‡ emprunter
a = (phi.find (jeton)->second).begin (); //On n'a pas besoin de faire un test sur le find !
while (sum < alea)
{
q = a->second.begin ();
while ((q != a->second.end ()) && (sum < alea))
{
if ((sum += q->second) < alea)
q++;
}
if (sum < alea)
a++;
}
// et on l'emprunte
jeton = q->first;
// on rajoute la lettre gÈnÈrÈe ‡ w
w += a->first;
//w.push_back (a->first);
// on est dans l'Ètat "jeton" et on a ajoute la lettre "a->first"
//puis on recommence
alea = ((float) rand ()) / INT_MAX;
}
return VAL (0);
}
// genere un Èchantillon de mots
RESULT
PFA::genere_echantillon (int taille, Sample & S,
const int num_echantillon)
{
if (isPFA()) {
int i;
Word w;
if (num_echantillon != 0)
{
srand (num_echantillon);
}
S = Sample (Sigma, alph, false);
for (i = 0; i < taille; i++)
{
genere_mot (w, false);
S.insert (w);
}
return VAL (0);
}
else {
return MA::genere_echantillon(taille, S, num_echantillon);
}
}
// genere un Èchantillon de mots : l'echantillon reste identique si lot est identique
RESULT PFA::genere_echantillon (const int taille,
Sample & S,
const char *Filename,
const int num_echantillon)
{
if (PFA_DEBUG)
{
if (Filename == NULL)
{
cerr << " PFA::echantillon(int taille, char *Filename) : Filename = NULL !!!" << endl;
}
}
genere_echantillon (taille, S, num_echantillon);
return S.save (Filename);
}
// ---------- DISTANCES ---------
// renvoie la perplexité du PFA par rapport à l'echantillon S
double
PFA::perplexite (const Sample & S) const
{
double res, sum;
Sample::const_iterator w;
if (isPFA()) {
res = sum = 0;
for (w = S.begin (); w != S.end (); S.next (w))
{
res += plog (w->first) * w->second;
sum += w->second;
}
}
else {
res = sum = 0;
for (w = S.begin (); w != S.end (); S.next (w))
{
res += log (r(w->first)) * w->second;
sum += w->second;
}
}
return -res / sum;
}
// renvoie la perplexitÈ du PFA par rappor ‡ l'echantillon S
double
PFA::divKL (PFA &B, const Sample & S) const
{
double res, res2, sum;
Sample::const_iterator w;
res = res2 = sum = 0;
for (w = S.begin (); w != S.end (); S.next (w))
{
res += plog (w->first) * w->second;
res2 += B.plog(w->first) * w->second;
sum += w->second;
}
return (res2 - res) / sum;
}
// renvoie la norme 2 entre ce PFA et le PTA correspondant ‡ S
double
PFA::d_2(const Sample &S) const {
Sample::const_iterator w;
double res, sum;
double pA, pB;
double taille=double(S.size());
res = sum = 0;
for (w = S.begin (); w != S.end (); w++)
{
if (w->second >= S.seuil)
{
pA = p (w->first);
pB = double(w->second)/taille;
res += (pA - pB) * (pA - pB) * pA;
sum += pA;
}
}
return sqrt (res / sum);
}
// renvoie la norme 2 entre ce PFA et un autre
double
PFA::d_2 (const PFA & B, const Sample & S) const
{
Sample::const_iterator w;
double res, sum;
double pA, pB;
res = sum = 0;
for (w = S.begin (); w != S.end (); w++)
{
if (w->second >= S.seuil)
{
pA = p (w->first);
pB = B.p (w->first);
res += (pA - pB) * (pA - pB) * pA;
sum += pA;
}
}
return sqrt (res / sum);
}
// renvoie la norme L1 entre ce PFA et un autre
double
PFA::L_1 (const PFA & B, const Sample & S) const
{
Sample::const_iterator w;
double res, sum;
double pA, pB;
res = sum = 0;
for (w = S.begin (); w != S.end (); w++)
{
if (w->second >= S.seuil)
{
pA = p (w->first);
pB = B.p (w->first);
res += (pA - pB >= 0) ? (pA - pB) * pA : (pB - pA) * pA; // |pA(w) - pB(w)|*pA(w)
sum += pA;
}
}
return sqrt (res / sum);
}
// renvoie la norme 2 entre ce PFA et un autre
double
PFA::d_2nlog (const PFA & B, const Sample & S) const
{
Sample::const_iterator w;
double res, sum;
double pA, pB;
res = sum = 0;
for (w = S.begin (); w != S.end (); w++)
{
if (w->second >= S.seuil)
{
pA = p_directe (w->first);
pB = B.p_directe (w->first);
res += (pA - pB) * (pA - pB) * pA;
sum += pA;
}
}
return sqrt (res / sum);
}
// renvoie la norme L1 entre ce PFA et un autre
double
PFA::L_1nlog (const PFA & B, const Sample & S) const
{
Sample::const_iterator w;
double res, sum;
double pA, pB;
res = sum = 0;
for (w = S.begin (); w != S.end (); w++)
{
if (w->second >= S.seuil)
{
pA = p_directe (w->first);
pB = B.p_directe (w->first);
res += (pA - pB >= 0) ? (pA - pB) * pA : (pB - pA) * pA; // |pA(w) - pB(w)|*pA(w)
sum += pA;
}
}
return sqrt (res / sum);
}
// renvoie la moyenne des Ècarts de log en fonction d'un Èchantillon S
double
PFA::dlog (const PFA & B, const Sample & S) const
{
Sample::const_iterator w;
double res, sum, pa;
res = sum = 0;
for (w = S.begin (); w != S.end (); w++)
{
sum += w->second;
pa = plog (w->first) - B.plog (w->first);
if (pa < 0)
pa = -pa;
res += pa * w->second;
}
return res / sum;
}
// renvoie la moyenne des Ècarts de log en fonction d'un Èchantillon S
double
PFA::dlog_safe (const PFA & B, const Sample & S) const
{
Sample::const_iterator w;
double res, pa;
int sum, nb_err, nb_mots;
res = sum = nb_err = nb_mots = 0;
for (w = S.begin (); w != S.end (); w++)
{
if (w->second >= S.seuil)
{
nb_mots++;
pa = plog (w->first) - B.plog (w->first);
if (!isnan (pa))
{
sum += w->second;
if (pa < 0)
pa = -pa;
res += pa * w->second;
}
else
{
if (PFA_VERBOSE)
{
cerr << "\tErreur : ";
Word::const_iterator va;
for (va = w->first.begin ();
va != w->first.end (); va++)
cerr << alph.find (*va)->
second << " ";
cerr << endl;
cerr << "\tpA = " << plog (w->
first) <<
" et pB = " << B.plog (w->
first)
<< endl;
}
nb_err++;
}
}
}
if (PFA_VERBOSE)
{
if (nb_err > 0)
cerr << nb_err * 100 /
nb_mots << "% d'erreur de structure." << endl;
}
return res / sum;
}
// renvoie la divergence de Kullback Leibler relativemant ‡ l'Èchantillon S
double
PFA::divKL (const PFA & B, const Sample & S)
{
return B.perplexite (S) - perplexite (S);
}
// return true if it is a PRFA
bool
PFA::isPRFA (bool verbose)
{
if (!isPFA())
{
return false;
}
// !!!!!!!!!!! VERSION NON DEFINITIVE !!!!!!!!!!!!!!
// !!!!! reduce is not yet implemented !!!!!!!!!
//reduce();
map < State, bool > resStates; // resStates[q]=true iff q is reach uniquely by some word.
set
< StateSet> Memory; // the set of states even founded.
StateSet QI; // l'ensemble des Ètats initiaux
StateSet R; // Un ensemble d'Ètats
StateSet Qm; // l'ensemble des Ètats dont on a dÈja trouvÈ un mot caractÈristique.
set
< StateSet >::const_iterator Ri;
set
< Word > W; // un ensemble de mots
Word w;
Word::iterator b;
StateSet::const_iterator q;
SFunc::iterator r;
Alphabet::const_iterator a;
//~ // -- //
//~ cout << "L'ensemble d'Ètats est : {";
//~ StateSet::const_iterator s;
//~ for (s=Q.begin() ; s != Q.end() ; ++s)
//~ cout << *s << ",";
//~ cout << "}" << endl;
//~ // -- //
// QI devient l'ensemble des Ètats initiaux
for (r=iota.begin();r != iota.end() ; ++r)
{
QI.insert(r->first);
}
//~ // -- //
//~ cout << "QI={";
//~ for (s=Q.begin() ; s != Q.end() ; ++s)
//~ cout << *s << ",";
//~ cout << "}" << endl;
//~ // -- //
// W = Sigma
for (a=Sigma.begin() ; a != Sigma.end() ; ++a)
{
w.clear();
w += *a;
//w.push_back(*a);
W.insert(w);
}
// Si il n'y a qu'un seul Ètat initial, alors
// son mot caractÈristique est epsilon
if (QI.size()==1)
{
Qm=QI;
if (verbose)
{
cout << "mot caractÈristique de " << *(Qm.begin()) << "\n";
cout << "epsilon\n";
cout << "longueur 0" << endl;
}
}
// QI est la premiËre partie possible
Memory.insert(QI);
while(!W.empty() && !(Qm==Q))
{
w=*(W.begin()); // w=min W
W.erase(W.begin()); // W <- W \ {w}
R=delta(QI,w);
//~ // -- Affichage de delta (QI, w) -- //
//~ cout << "delta(QI," << affiche(w) << ")={";
//~ for (s = R.begin() ; s != R.end() ; ++s)
//~ cout << *s << ",";
//~ cout << "}" << endl;
//~ // -- //
// si R \notin Memory
if (Memory.find(R) == Memory.end())
{
// on rajoute R ‡ Memory
Memory.insert(R);
// W = W \cup w\Sigma
for (a=Sigma.begin() ; a != Sigma.end() ; ++a)
{
w += *a;
//w.push_back(*a);
W.insert(w);
b=w.end();
w.erase(--b);
}
// Si R contient un seul Ètat
if (R.size() == 1)
{
// Si cet Ètat n'a pas dÈja eu un mot caractÈristique
if (Qm.find(*(R.begin())) == Qm.end())
{
// Alors on a trouver un nouvel Ètat dont on connait le
// mot caractÈristique (w)
Qm.insert(*(R.begin()));
if (verbose)
{
cout << "le mot caracteristique de l'Ètat " << *(R.begin()) << " est :\n";
cout << affiche(w) << "\n";
cout << "longueur " << w.size() << endl;
}
}
}
}
}
return Qm==Q;
}
bool PFA::isPDFA()
{
if (!isPFA())
{
return false;
}
erase_transitions(0,0); // erasing null transition
if (iota.size() != 1)
return false;
Graph::const_iterator q;
LettreSFunc::const_iterator a;
SFunc::const_iterator r;
for (q=phi.begin() ; q != phi.end() ; ++q)
{
for (a=q->second.begin() ; a!=q->second.end() ; ++a)
{
if (a->second.size() > 1)
return false;
}
}
return true;
}

179
pprfa.H Normal file
View File

@ -0,0 +1,179 @@
/***************************************************************************
pfa.h - Probabilistic Finite Automaton
-------------------
begin : 7 Dec 2002
copyright : (C) 2002 by Yann Esposito
email : esposito@cmi.univ-mrs.fr
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
/*________________________ DÈscription plus precise ______________________*\
Classe qui herite de la classe spfa, la seule diffÈrence est que l'on
peut generer des mots avec une distribution de probabilite.
\***************************************************************************/
#ifndef PPRFA_H
#define PPRFA_H
#include "pfa.H"
#include "simplex.H"
typedef enum {determinist, positive, nonconstrained} T_ModeVariables;
typedef enum {begin, end} T_ModeReturn;
typedef enum {epsfixed, variable, word_variable} T_ModeEpsilon;
class PPRFA : public PFA
{
protected:
WordSFunc XR;
public:
// become the PTA representing S but successor of v are returned
RESULT becomeQuasiPrefixTree ( const Sample &S, const Word &v, const SFunc &solution);
// erase the transition w,l,v
RESULT eraseTransition(const Word &w, const Lettre l, const Word &v);
// emmonde
RESULT emmonde(void);
protected:
// fonction necessaire ‡ sol
RESULT liste_mots_associes(WordSet &W,
const Word &v,
const Sample &S,
int maxmots = 10) const;
// fonction necessaire ‡ liste_mots_associes
RESULT ajoute_mots_associes(WordSet &W,
const Word &v,
const Sample &S,
int maxmots = INT_MAX) const;
// renvoie vide si le systËme lineaire I(v,R,S,precision) n'a pas de solution et
// sinon renvoie une solution de I i.e. un ensemble de variables X_q telles que
// v^{-1}P = \sum_{q \in R} X_qP_q -- en rappelant que R[w]=q => P_q = w^{-1}P
// on ne prend en compte que au plus max mots.
RESULT solmax(T_ModeVariables modeVariables,
SFunc &solution, // La solution
const Word &v,
const Sample &S,
Simplex &simplx,
const double precision,
const T_ModeReturn moderet,
const T_ModeEpsilon modeeps,
set
<Word, ordre_mot> &W,
unsigned int max) const;
// renvoie vide si le systËme lineaire I(v,R,S,precision) n'a pas de solution et
// sinon renvoie une solution de I i.e. un ensemble de variables X_q telles que
// v^{-1}P = \sum_{q \in R} X_qP_q -- en rappelant que R[w]=q => P_q = w^{-1}P
RESULT sol(T_ModeVariables modeVariables,
SFunc &solution, // La solution
const Word &v,
const Sample &S,
Simplex &simplx,
const double precision,
const T_ModeReturn moderet,
const T_ModeEpsilon modeeps,
set
<Word, ordre_mot> &W,
int maxmots=10,
bool Wcalculated = false) const;
inline RESULT addTransition(const Word &wdep, const Lettre a, const Word &warr, const float val)
{
return PFA::addTransition(XR[wdep], a, XR[warr], val);
}
inline RESULT addTransition(const Word &wdep, const Lettre a, const State qarr, const float val)
{
return PFA::addTransition(XR[wdep], a, qarr, val);
}
inline void vide()
{
XR.clear();
PFA::vide();
}
inline RESULT addState(const Word &w, const float init=0, const float term=0)
{
WordSFunc::const_iterator q;
q=XR.find(w);
if (q != XR.end()) {
return MA::addState( q->second, init, term);
}
else
{
return XR[w]=addNewState(init, term);
}
}
float best_transition_delete(Sample Stest, bool verbose = false);
public:
// become PTA
RESULT becomePrefixTree(Sample &S);
// Apprentissage de PRFA, renvoie un PRFA prefixe
// prec prend la precision, et mode est le mode d'apprentissage
RESULT DEES(T_ModeVariables modeVariables, // the learning space for variables
Sample &S, // The learning sample (data)
const double prec, // The precision parameter
const double epsprime, // The bound under which transition are erased
const bool verbose = false, // verbose mode (show the states during construction)
const T_ModeReturn moderet = end, // return mode (end of the tree or begin of the tree)
const T_ModeEpsilon modeeps = variable, // epsilon mode (epsfixed or variable)
unsigned int maxstates = INT_MAX, // The maximal states number after which learning is cancelled
unsigned int seuil=10, // La periodicitÈ minimum avant de ne plus considÈrer l'Ètat
int maxmots=10, // le nombre maximal de mots que l'on reconsidËre ‡ chaque Ètape
int maxsearches=0, // le nombre de recherche dichotomique pour trouver le meilleur epsilon
bool bestsearch=true, // vrai si on recherche le meilleur epsilon
bool stepssave=false); // vrai sauvegarde chaque etape de l'apprentissage
// Apprentissage de PRFA, renvoie un PRFA prefixe
// prend la precision, et mode est le mode d'apprentissage
RESULT DEESBM(Sample &S, // The learning sample (data)
const double prec, // The precision parameter
const double epsprime, // The bound under which transition are erased
const bool verbose = false, // verbose mode (show the states during construction)
const unsigned int maxstates = INT_MAX, // The maximal states number after which learning is cancelled
const unsigned int seuil=10, // La periodicitÈ minimum avant de ne plus considÈrer l'Ètat
const double seuilbm=0.0001, // Le seuil en dessous duquel on considère avoir trouver le MLM
const unsigned int nb_tours=10); // Le nombre de tours pour BM
Word word_of(const State x) const;
protected:
// ##### Pour la version Baum Welch #####
RESULT setRandomSolution(SFunc &solution, const StateSet &R) const ;
RESULT BMsol (SFunc &solution, const Word &v,const Sample &S, const Sample &Sdep, const float prec,int nb_tours, bool verbose = false);
// recupere la solution en fonction des valeurs recuperes apres Baum Welch
RESULT get_solution(const PPRFA &A,SFunc &solution, Transition &t,TransitionFunction &T,const StateSFunc &Trad);
// Ajoute les etats necessaires pour que tous les mots vS soient generables
RESULT put_prefix_tree(const Sample &S, const Word &v);
// Ajoute les etats necessaires pour que le mot w deviennent generable
RESULT add_word(const State q, const Word &w);
// Liste les successeurs d'elements de Q qui ne sont pas dans Q
RESULT choice(list<State> &X, const StateSet Q) const;
RESULT difference(const TransitionFunction T1, const TransitionFunction T2) const;
// Initialise la solution en utilisant une resolution de systeme d'equation
RESULT initSolution(SFunc &solution, const State x, const StateSet &R, const Sample &S) const;
// Construit un quasi pta et teste sa qualite par rapport a l'echantillon
bool TestQPTA(const Sample &S,const State x, const StateSet R,const double precision, const double seuilbm, bool verbose);
// remet a jour la liste des mots associes aux etats
RESULT compute_XR(void);
};
#endif

339
pprfa.cpp Normal file
View File

@ -0,0 +1,339 @@
/***************************************************************************
pprfa.C
-------------------
begin : Mon 9 Dec 2002
copyright : (C) 2002 by Yann Esposito
email : esposito@cmi.univ-mrs.fr
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
/*
Pour les notes, voir le fichier "pprfa.h".
See "pprfa.h" file to view notes.
*/
#include "pprfa.H"
// Best Suppression
float PPRFA::best_transition_delete(Sample Stest, bool verbose) {
if (phi.empty()) {
return ERR(0);
}
else if (phi.begin()->second.empty()) {
return ERR(1);
}
else if (phi.begin()->second.begin()->second.empty()) {
return ERR(2);
}
// Recherche des transitions à supprimer
Graph::iterator q;
LettreSFunc::iterator a;
SFunc::iterator s;
float min;
PPRFA C=*this;
float perplex;
float minperplex;
float epsprime;
lisse();
minperplex = perplexite(Stest);
if (verbose) {
cout << "\tepsprime = 0";
cout << ", distance = " << minperplex << endl;
}
min=0;
perplex=minperplex;
do
{
epsprime = min;
minperplex = perplex;
min = phi.begin()->second.begin()->second.begin()->second;
for (q = phi.begin(); q != phi.end(); ++q)
{
for (a = q->second.begin (); a != q->second.end (); ++a)
{
for (s = a->second.begin (); s != a->second.end (); ++s)
{
if ((s->second < min) && (s->second > epsprime))
{
min = s->second;
}
}
}
}
if (min == epsprime) {
break;
}
erase_transitions (min);
rend_PFA ();
lisse ();
perplex = perplexite (Stest);
*this = C;
if (verbose) {
cout << "\tepsprime = " << min;
cout << ", distance = " << perplex << endl;
}
}
while (perplex <= minperplex);
if (verbose) {
cout << "\t|| Meilleur epsprime trouve = " << epsprime;
cout << ", mindist = " << minperplex << " ||" << endl;
}
*this = C;
erase_transitions (epsprime);
rend_PFA();
return d_2(Stest);
}
RESULT PPRFA::eraseTransition(const Word &w, const Lettre l, const Word &v) {
return PFA::eraseTransition(XR[w],l,XR[v]);
}
// fonction qui associe ‡ un etat le mot correspondant
Word PPRFA::word_of(const State x) const {
WordSFunc::const_iterator r;
for (r=XR.begin() ; r != XR.end() ; r++) {
if (r->second == x)
return r->first;
}
// on sort de la boucle sans avoir trouve !!!
cerr << "WORD_OF !!! etat : " << x << endl;
return "";
}
RESULT PPRFA::compute_XR(void) {
StateSet W;
StateSet R;
State etat_cour;
Word u;
Graph::const_iterator q;
LettreSFunc::const_iterator a;
SFunc::const_iterator s;
StateWordFunction WS;
W.insert (iota.begin ()->first);
XR.clear();
XR[u]=iota.begin()->first;
WS[iota.begin()->first]=u;
while (!W.empty ())
{
etat_cour = *W.begin ();
W.erase (W.begin ());
q = phi.find (etat_cour);
if (q != phi.end ())
{
for (a = q->second.begin (); a != q->second.end (); ++a)
{
for (s = a->second.begin (); s != a->second.end (); ++s)
{
if (R.find(s->first) == R.end()) {
u=WS[etat_cour] + string(1,a->first);
XR[u]=s->first;
WS[s->first]=u;
W.insert (s->first);
R.insert(s->first);
}
}
}
}
}
return VAL(0);
}
// addStates from q to generate w from P_q(w)
RESULT PPRFA::add_word( const State q, const Word &w) {
if (w.empty()) {
if ((tau.find(q) == tau.end()) || (tau.find(q)->second == 0)) {
tau[q] = 0.01;
return VAL(1);
}
else {
return ERR(1);
}
}
else if (delta(q, string(1,*w.begin())).empty()) {
WordSFunc::const_iterator xr;
for (xr = XR.begin() ;
(xr != XR.end()) && (xr->second != q) ;
xr++)
;
if (xr == XR.end()) {
return ERR(2);
}
Word u=xr->first;
State r,s;
Word::const_iterator a;
r=q;
for (a = w.begin() ; a != w.end() ; a++) {
u+=*a;
s=addState(u,0,0);
PFA::addTransition(r, *a , s, 0.01);
r=s;
}
return VAL(0);
}
else {
return ERR(2);
}
}
RESULT PPRFA::emmonde(void) {
PFA::emmonde();
WordSFunc::iterator r,s;
for (r=XR.begin() ; r != XR.end() ; ) {
if (Q.find(r->second) == Q.end()) {
s=r;
s++;
XR.erase(r);
r=s;
}
else {
r++;
}
}
return VAL(0);
}
// Add Prefix many Tree in order to recognize all the sample
RESULT PPRFA::put_prefix_tree(const Sample &S, const Word &v) {
Sample::const_iterator w;
StateSet Q1;
StateSet::const_iterator q;
Word::const_iterator a;
for (w=S.begin() ;w != S.end() ; w++) {
//~ // ----
//~ cout << "Mot : " << w->first << endl;
//~ // ----
// we are in a PPRFA then there is exactly one initial state
Q1.clear();
Q1.insert(iota.begin()->first);
for (a=w->first.begin() ; a != w->first.end() ; a++) {
//~ // ----
//~ cout << "Q1={";
//~ for (StateSet::const_iterator s=Q1.begin() ; s != Q1.end() ; s++) {
//~ cout << *s << ",";
//~ }
//~ cout << "}" << endl;
//~ // ----
// si pour un q delta(q,a) est vide, on ajoute les etat
// a partir de q pour reconnaitre la fin du mot
for (q=Q1.begin() ;q != Q1.end() ;q++) {
if (delta(*q , string(1,*a)).empty()) {
//~ // ----
//~ cout << "add_word(" << *q << ",'" << flush;
//~ cout << string(a,w->first.end()) << "','" << flush;
//~ cout << string(w->first.begin(), a) << "')"<< endl;
//~ // ----
add_word(*q,string(a,w->first.end()));
}
}
Q1 = delta(Q1,string(1,*a));
}
//~ // ----
//~ cout << "Q1={";
//~ for (StateSet::const_iterator s=Q1.begin() ; s != Q1.end() ; s++) {
//~ cout << *s << ",";
//~ }
//~ cout << "}" << endl;
//~ // ----
for (q = Q1.begin() ; q != Q1.end() ; q++) {
if (tau.find(*q) == tau.end() || (tau.find(*q)->second == 0)) {
//~ // ----
//~ cout << "add_word(" << *q << ",'" << flush;
//~ cout << "','" << flush;
//~ cout << w->first << "')"<< endl;
//~ // ----
add_word(*q,"");
}
}
}
return VAL(0);
}
// Arbre prefixe
RESULT PPRFA::becomePrefixTree(Sample &S)
{
bool ispref = S.isprefixiel();
if (!ispref)
{
S.prefixialise();
}
vide(); // on vide la structure du PFA
Sample::const_iterator w;
Lettre a;
Word v;
Sigma=S.alphabet();
alph=S.dictionnaire();
w = S.begin();
XR[w->first]=addNewState(1,0);
// on commence apres epsilon d'ou le ++w au debut du for
for (++w ; w != S.end() ; ++w)
{
v=w->first;
XR[v]=addNewState(0,0);
a=*(v.rbegin());
v.erase(--v.end());
PFA::addTransition(XR[v], a , XR[w->first],(float)S[w->first]/(float)S[v]);
}
// on met ‡ jour iota et tau
StateSet::const_iterator e;
Graph::const_iterator q;
LettreSFunc::const_iterator x;
SFunc::const_iterator r;
float sum;
for (e=Q.begin() ; e != Q.end() ; ++e)
{
sum = 0;
q=phi.find(*e);
if (q != phi.end())
{
for (x=q->second.begin() ; x != q->second.end() ; ++x)
{
for (r=x->second.begin() ; r != x->second.end() ; ++r)
{
sum += r->second;
}
}
}
tau[*e]=1-sum;
}
if (!ispref)
{
S.deprefixialise();
}
return VAL(0);
}

422
pprfa_bm.cpp Normal file
View File

@ -0,0 +1,422 @@
/*
* pprfa_bm.cpp
* dees
*
* Created by Yann Esposito on 18/04/06.
* Copyright 2006 __MyCompanyName__. All rights reserved.
*
*/
#include "pprfa.H"
RESULT PPRFA::becomeQuasiPrefixTree (
const Sample &S, // les mots
const Word &v, // le mot de retour
const SFunc &solution) // les valeurs initiales pour le retour
{
Word w=v;
Lettre a;
SFunc::const_iterator s;
Transition t;
float val;
w=v;
a=*(w.rbegin());
w.erase(--w.end());
// on a v = wa
// val = w^{-1}P(a\Se)
val=exp(plog_bar(v) - plog_bar(w));
// on supprime la transition deterministe phi(w,a,v)
eraseTransition(w,a,v);
// on fait les retours
t.qdep = XR[w];
t.a = a;
for (s=solution.begin() ; s != solution.end() ; s++ ) {
t.qarr = s->first;
PFA::addTransition(t,s->second*val);
}
// on emmonde
emmonde();
put_prefix_tree(S,v);
return VAL(0);
}
RESULT PPRFA::setRandomSolution(SFunc &solution, const StateSet &R) const
{
StateSet::iterator q;
for (q = R.begin() ; q != R.end() ; ++q)
{
solution[*q] = random(0,1);
}
float sum=0;
SFunc::iterator s;
for (s=solution.begin() ; s != solution.end() ; ++s)
{
sum += s->second;
}
for (s=solution.begin() ; s!=solution.end() ; ++s)
{
s->second /= sum;
}
return VAL(0);
}
RESULT PPRFA::choice(list<State> &X, const StateSet R) const {
StateSet::const_iterator q;
Graph::const_iterator r;
LettreSFunc::const_iterator a;
SFunc::const_iterator s;
X.clear();
for (q=R.begin() ; q!= R.end() ; q++) {
r=phi.find(*q);
if (r != phi.end()) {
for (a=r->second.begin() ; a != r->second.end() ; a++) {
for (s=a->second.begin() ; s != a->second.end() ; s++) {
if (R.find(s->first) == R.end()) {
if (Q.find(s->first) != Q.end())
X.push_back(s->first);
else {
cerr << "Choice !!! automate non coherent, ";
cerr << "Etat : "<< s->first << endl;
cerr << "Sauvegarde dans test/uncoherent" << endl;
save("test/uncoherent");
}
}
}
}
}
}
return VAL(0);
}
RESULT PPRFA::difference(const TransitionFunction T1,
const TransitionFunction T2) const {
TransitionFunction::const_iterator t;
float res=0;
for (t=T1.begin() ; t != T1.end() ; t++) {
res+=abs(t->second - T2.find(t->first)->second);
}
res = res/float(T1.size());
return VAL(0);
}
// compte le nombre de fois que l'on passe par l'etat x en lisant S
float SPFA::count_nb_pass(const State x, const Sample &S) const {
TransitionFunction T;
SFunc Iota, Tau;
// on met dans T toutes les transitions qui arrivent
// dans l'etat x
Graph::const_iterator q;
LettreSFunc::const_iterator a;
SFunc::const_iterator r;
Transition t;
t.qarr=x;
for (q=phi.begin() ;q != phi.end() ; q++) {
t.qdep = q->first;
for (a = q->second.begin() ; a != q->second.end(); a ++) {
t.a=a->first;
if (a->second.find(x) != a->second.end()) {
T[t]=0;
}
}
}
TransitionCount(S,T,Iota,Tau);
TransitionFunction::const_iterator ti;
float res;
res = 0;
for (ti=T.begin() ; ti != T.end() ; ti++) {
res+=ti->second;
}
return res;
}
// init the state solution
RESULT PPRFA::initSolution(SFunc &solution, const State x, const StateSet &R, const Sample &S) const {
// a small security test
if (! S.isprefixiel()) {
cerr << "WARNING ! initSolution called with a not prefixialised Sample\n";
return setRandomSolution(solution,R);
}
Word v;
WordSet W;
StateWordFunction wordof;
StateSet::const_iterator r;
Simplex simplx; // simplx est juste l'objet Simplex qui permet de résoudre les problèmes
int i;
int it; // un iterateur
WordSet::const_iterator wr;
StateWordFunction::const_iterator q;
double s1;
double s2;
WordSet::const_iterator wi;
double pvw; // v^{-1}P(w)
double precision;
// --- Initialisation ---
v=word_of(x); // v est le mot initial
for (r=R.begin() ; r != R.end() ; r++) {
wordof[*r]=word_of(*r);
}
// wordof contient les les mots associes aux etats
ajoute_mots_associes(W,v,S,INT_MAX); // W contient les successeurs de v dans S
// -- Remplissage du Simplex ---
// number of variables = number of core states
//n = R.size();
simplx.set_number_of_unknown_to(R.size());
simplx.setval(1);
simplx.setparam(1,0);
for (q = wordof.begin(),it=1; q != wordof.end(); q++)
simplx.setparam(it++, 1);
simplx.add_equality_constraint();
simplx.setparam(1,1);
// inequations en <= (nb=ineq1), inequations en >= (nb=ineq2)
// les inequations X_q >= 0 sont deja
// prisent en comptent de manière implicite
s2=S[v];
precision= 2/sqrt(double(s2));
for (wi = W.begin(), i=1; wi != W.end () ; wi++, i++)
{
s1 = S[(v + *wi)];
pvw = (double) s1 / (double) s2;
simplx.setval(pvw);
for (q = wordof.begin(),it=1; q != wordof.end(); q++, it++)
{
s1 = S[q->second + *wi];
s2 = S[q->second];
if (s2 == 0) {
// cerr << "WARNING: " << q->second << ", random initialisation" << endl;
return setRandomSolution(solution,R);
}
simplx.setparam(it, s1/s2);
}
simplx.add_absolute_constraint();
}
map<int,float> preciseSol;
float epsilon;
bool err = simplx.has_solution(preciseSol,epsilon);
if ((! err) || (epsilon>precision))
{ // pas de solutions
setRandomSolution(solution,R);
return ERR(0);
}
else
{
solution.clear ();
for (q = wordof.begin(),it=2; q != wordof.end() ; q++, it++)
{
solution[q->first] = preciseSol[it];
// cout << q->first << " SSS=" << simplx.sol[it]<<endl;
}
return VAL(0);
}
}
// fonction qui teste si le retour semble plus avise
bool PPRFA::TestQPTA(const Sample &S,const State x,const StateSet R, const double precision, const double seuilbm, bool verbose) {
PPRFA A;
SFunc solution;
WordSFunc::const_iterator r;
Word v;
Simplex simplx;
StateSet::const_iterator s;
PreciseSFunc F;
int nb_tours;
double nprime;
// on recopie le PPRFA courant dans A
A=*this;
// on cherche le mot auquel correspond l'etat x
save("test/tst");
v=word_of(x);
if (v == "") {
cout << "compute_XR()" << endl;
emmonde();
compute_XR();
v=word_of(x);
cout << "v=" << affiche(v) << endl;
}
nprime=count_nb_pass(x,S);
//setRandomSolution(solution,R);
if (!S.isprefixiel()) {
Sample S2;
S2 = S;
S2.prefixialise();
initSolution(solution,x,R,S2);
}
else {
initSolution(solution,x,R,S);
}
// for (StateSet::const_iterator ri = R.begin(); ri != R.end() ; ri++) {
// cout << "sol[" << *ri << "]="<< solution[*ri] << endl;
// }
A.becomeQuasiPrefixTree(S,v,solution);
/*
// ----
int toto;
save("test/tst");
A.save("test/tstA");/*
cout << "lettre = " << v << endl;
cout << "entrez un chiffre pour continuer.";
cin >> toto;
// ----
*/
// on fait les BaumWelch
TransitionFunction T1,T2;
SFunc Iota,Tau;
A.allTransitions(T1);
T2=T1;
A.allStates(Tau);
A.BaumWelch(S,T1,Iota,Tau,1, verbose);
A.BaumWelch(S,T2,Iota,Tau,1, verbose);
nb_tours=20;
while ((difference(T1,T2)>seuilbm) && (nb_tours-- > 0)) {
T2=T1;
A.BaumWelch(S,T1,Iota,Tau,1, verbose);
if (verbose) {
cout << "." << flush;
}
}
if (verbose) {
cout << "\n";
}
if (verbose) {
cout << "validation de la solution (" << affiche(v) << "): ";
}
// Test pour la validation de T
// ----
// if (verbose) {
// float x1, x2, x3, x4;
// x1 = A.Likelihood(S);
// x2 = S.AutoLikelihood();
// x3 = nprime;
// x4 = S.size();
// cout << "Hyp L=" << x1 << ", ";
// cout << "PTA L="<< x2 << ", ";
// cout << "nb(v)=" << x3 << ", ";
// cout << "Ssize=" << x4 << ", ";
// cout << "seuil=" << (x2-x1)*(sqrt(double(nprime))/double(S.size()));
// cout << endl;
// }
// ----
float valtest=(abs( A.Likelihood(S) - S.AutoLikelihood() ) * sqrt(double(nprime))) / double(S.size());
if (verbose) {
cout << valtest << " < " << precision << endl;
}
if ( valtest > precision) {
return false;
}
else {
*this=A;
return true;
}
}
RESULT PPRFA::DEESBM(Sample &S, // The learning sample (data)
const double prec, // The precision parameter
const double epsprime, // The bound under which transition are erased
const bool verbose, // verbose mode (show the states during construction)
const unsigned int maxstates, // The maximal states number after which learning is cancelled
const unsigned int seuil, // La periodicitÈ minimum avant de ne plus considÈrer l'Ètat
const double seuilbm, // la dist à partir de laquelle on considere avoir trouver le MLM
const unsigned int nb_tours ) // Le nombre de tour de BM
{
try {
list<State> X; // the set of considered words
State x;
StateSet R; // the set of traited states
becomePrefixTree(S); // it's clear
R.insert(iota.begin()->first);
choice(X,R); // we add all states corresponding to letters
while (!X.empty()) {
x=*(X.begin()); X.pop_front();
if ((Q.find(x) != Q.end()) && ( !TestQPTA(S,x,R, prec, seuilbm, verbose)) ) { // si on ne fait pas de retour
R.insert(x);
choice(X,R);
}
}
erase_transitions(0.01,0);
rend_PFA();
return VAL(0);
}
catch (string e) {
cerr << "DEESBM() ";
cerr << e << endl;
return ERR(0);
}
}
RESULT PPRFA::get_solution(const PPRFA &A,
SFunc &solution,
Transition &t,
TransitionFunction &T,
const StateSFunc &Trad)
{
LettreSFunc::const_iterator a;
SFunc::const_iterator r;
SFunc::iterator s;
float sum;
a=A.phi.find(t.qdep)->second.find(t.a);
for (r = a->second.begin() ; r != a->second.end() ; ++r) {
t.qarr=r->first;
solution[Trad.find(r->first)->second]=T[t];
}
sum = 0;
for (s=solution.begin() ; s != solution.end() ; ++s) {
sum += s->second;
}
if (sum == 0) {
throw 1;
}
for (s = solution.begin() ; s != solution.end() ; ++s) {
s->second /= sum;
}
return VAL(0);
// ----
for (s=solution.begin() ; s != solution.end() ; ++s) {
cout << "sol[" << s->first << "] = " << s->second << " ";
}
cout << endl;
// ----
}

536
pprfa_dees.cpp Normal file
View File

@ -0,0 +1,536 @@
/*
* pprfa_dees.cpp
* dees
*
* Created by Yann Esposito on 18/04/06.
* Copyright 2006 __MyCompanyName__. All rights reserved.
*
*/
#include "pprfa.H"
// ================================================================
// === ===
// === DEES ===
// === ===
// ================================================================
// Methode d'apprentissage d'un PRFA prefixe
RESULT
PPRFA::DEES (T_ModeVariables modeVariables,
Sample & S,
double prec,
double epsprime,
bool verbose,
T_ModeReturn moderet,
T_ModeEpsilon modeeps,
unsigned int maxstates,
unsigned int seuil,
int maxmots,
int maxsearches,
bool bestsearch,
bool stepssave)
{
try {
// ------------------------- affichage des informations ---------------------- //
if (verbose)
{
cout << "\t\t=== DEES ===";
cout << "\nSample size = " << S.size ();
cout << "\nprecision = " << prec;
cout << "\nbound = " << epsprime;
cout << "\nmoderet = ";
switch (moderet)
{
case begin:
cout << "begin";
break;
case end:
cout << "end";
}
cout << "\nmodeeps = ";
switch (modeeps)
{
case epsfixed:
cout << "epsfixed";
break;
case variable:
cout << "variable";
break;
case word_variable:
cout << "word_variable";
break;
}
cout << "\nmaxstates = " << maxstates;
cout << "\nseuil = " << seuil;
cout << "\nmaxmots = " << maxmots << endl;
}
if (prec == 0) {
return becomePrefixTree(S);
}
// -------------------------- INITIALISATION ----------------------
vide (); // on initialise le PFA.
if (S.size () == 0)
throw 0; // on verifie que l'echantillon n'est pas vide.
S.prefixialise (); // Transformation de l'Èchantillon en echantillon prefixiel.
Sigma = S.alphabet (); // on met ‡† jour l'alphabet
alph = S.dictionnaire (); // et le dictionnaire associÈ.
// Declaration
Word v; // the word v which represent the word associated to the state to add.
list < Word > X; // The set of words which are potential prime residuals.
Sample::const_iterator u; // current word of the sample.
float val; // a floating value used to calculate tau.
Word w; // a word
Word ww; // another word
Lettre a; // a letter (we will have v=wa)
Alphabet::const_iterator b; // pour enumerer toutes les lettres
SFunc solution; // the system solution
SFunc solutiontemp; // a temporary solution
StateSet::iterator q; // Pour enumerer les états
Simplex simplx; // L'objet simplexe qui contient les algorithmes de resolution de systemes.
set < Word, ordre_mot > W; // L'ensemble de mots à tester
Word::iterator z; // last letter
// --- init variables ---
v.clear (); // v = epsilon (empty word)
// X is the set of one letter words of S when prefixialised
val = 0;
for (u = ++(S.begin ());
(u != S.end ()) && (u->first.size () < 2); ++u)
{
X.push_back (u->first);
val += u->second;
}
// We create the first state (epsilon)
addState (v, 1, 1 - (float(val) / float(S.size ())));
W.clear ();
// liste_mots_associes(W,v,S,maxmots);
ajoute_mots_associes(W,v,S,maxmots);
// There may be a general state
State generalstate = -1;
// Step saving
string svgfile="etape-";
// -------------------------- LEARNING LOOP -----------------------
if (verbose)
cout << "Ajout des états : " << endl;
// For each element in X (the temporary list)
while (!X.empty ())
{
v = *(X.begin ()); // v <-- min X;
X.pop_front (); // X <-- X\{v} ;
// wa=v
w = v;
a = *(w.rbegin ());
z = w.end ();
--z;
w.erase (z); //w.pop_back ();
//~ if (verbose) {
//~ cout << "[";
//~ cout << affiche(v) <<"]";
//~ cout.flush();
//~ }
if (stepssave) {
save(svgfile+affiche(v));
}
/// 3 possible cases :
/// (1) not enought data (make a loop to the general state)
/// (2) there is no solution (add a new state and update X)
/// (3) there is a solution (make a return of transitions)
if (S[v] < seuil) // case (1) not enought data
{
// cout << "CASE (1)" << endl;
if (generalstate == -1)
{ // if the general state was not created, we create it
generalstate = addState (v, 0, 1 / float(Sigma.size () + 1));
for (b = Sigma.begin (); b != Sigma.end (); ++b)
{
MA::addTransition (generalstate, *b, generalstate, 1 / float(Sigma.size () + 1));
}
}
addTransition (w, a, generalstate, ((double) S[v] / (double) S[w]));
XR[w + a] = generalstate;
if (verbose)
{
cout << "S";
cout.flush ();
}
}
else
{
solution.clear (); // init solutions
// calculate the solution of the linear system
sol (modeVariables, solution, v, S, simplx, prec / pow(float(S[v]), float(0.4)), moderet, modeeps, W, maxmots, false);
if (solution.empty ()) // if there is no solution (case (2) add a new state and update X
{
// cout << "CASE (2)" << endl;
// if there is no solution then we add the state associated with v
// updating X and tau (val will contain tau[v])
val = 0;
for (b = Sigma.begin (); b != Sigma.end (); b++)
{ // pour toute les lettres de l'alphabet
v += *b;
//v.push_back (*b); // on ajoute b a la fin de v
if (S.find (v) != S.end ())
{ // si vb appartient a l'echantillon, alors
X.push_back (v); // on l'ajoute a X
val += S[v]; // et val = val + S(vb\Sigma^*)
}
z = v.end ();
--z;
v.erase (z); //v.pop_back (); // on efface la derniere lettre pour que la variable v = le mot v.
}
if (verbose)
{
cout << "A";
cout.flush ();
}
addState (v,0, 1 - (val / (double) S[v])); // adding the new state
if (size () > maxstates)
throw 1;
addTransition (w, a, v, ((double) S[v] / (double) S[w])); // updating phi : phi(w,a,wa) = S(wa)/S(w)
}
else
{
// cout << "CASE (3)" << endl;
// else we return transitions
if (verbose)
{
cout << "R";
cout.flush ();
}
for (q = Q.begin (); q != Q.end (); q++)
{
val = (float) solution[*q] *
((double) S[v] / (double) S[w]);
if (val != 0)
{
addTransition (w, a, *q, val);
}
}
}
}
}
if (verbose)
cout << endl;
erase_transitions (epsprime, -epsprime); // deleting transitions less than epsprime
//best_transition_delete(S,verbose);
if (modeVariables == nonconstrained) {
return VAL(0);
}
else {
return renormalise (); // renormalisation in order to disable borders effects
}
}
catch (int erreur) {
if (PFA_VERBOSE)
{
if (erreur != 1)
{
cerr << "PFA::DEES(Sample S)" << endl;
}
switch (erreur)
{
case 0:
cerr << "Sample vide !!!" << endl;
break;
case 1: // il y a trop d'etats
erase_transitions (epsprime);
return renormalise ();
break;
default:
cerr << "Erreur n∞" << erreur << endl;
}
}
return ERR (erreur);
}
}
RESULT PPRFA::ajoute_mots_associes (set <Word, ordre_mot> &W,
const Word & v,
const Sample & S,
int maxmots) const
{
list < Word > L; // une liste de mot qui sert pour calculer W
Alphabet::const_iterator b; // pour enumerer toutes les lettres
Word w; // Le mot courant
w.clear(); // on initialise avec w <-- epsilon
// On ajoute tous les successeurs de v
L.push_back (w); // et L = { eps }
while ((!L.empty ()) && (maxmots != 0))
{ // tant que L n'est pas vide
w = L.front ();
L.pop_front (); // w = min(L) et L=L\{w}
if (W.find(w) == W.end()) {
--maxmots;
W.insert (w);
}
for (b = Sigma.begin (); b != Sigma.end (); b++)
{
w += *b; // w <-- wb
//W.insert(w);
if (S.find (v+w) != S.end ()) // si p_n(w)>0
{
L.push_back (w);
}
w.erase (--w.end()); //w.pop_back (); // wb <-- w
}
}
return VAL (0);
}
// Return the set of word used to construct the inequation system
// (the set W described in the paper in the definition of system I)
RESULT
PPRFA::liste_mots_associes (WordSet &W,
const Word & v,
const Sample & S,
int maxmots) const
{
map<Word, State>::const_iterator q; // L'etat courant
W.clear (); // on initialise W
// On ajoute tous les successeurs de v
ajoute_mots_associes (W, v, S);
// On ajoute tous les successeurs des elements de R
for (q = XR.begin (); q != XR.end (); q++)
{
ajoute_mots_associes (W, q->first, S, maxmots);
}
return VAL (0);
}
// renvoie vide si le systËme lineaire I(v,R,S,precision) n'a pas de solution et
// sinon renvoie une solution de I i.e. un ensemble de variables X_q telles que
// v^{-1}P = \sum_{q \in R} X_qP_q -- en rappelant que R[w]=q => P_q = w^{-1}P
// En prenant un maximum de max variables
RESULT PPRFA::solmax (T_ModeVariables modeVariables,
SFunc & solution, // La solution
const Word & v, // Le residuel a tester
const Sample & S, // L'echantillon
Simplex & simplx, // L'objet simplex qui permet de calculer la solution
double precision, // La precision (sa signification depend du mode)
T_ModeReturn moderet, // Le mode de retour : beg debut de l'arbre, end à la fin
T_ModeEpsilon modeeps, // Le mode : epsfixed avec epsilon fixe, variable avec epsilon variable.
WordSet &W, // L'ensemble de mots sur lesquels on teste,
// doit contenirs les mots des √©tapes prÈcÈdentes
unsigned int max) const
{
try
{
// cout << "\t\tcreation du systeme" << endl;
unsigned int i;
int n; // number of variables
int err;
WordSFunc::const_iterator q;
// number of variables = number of states
n = XR.size ();
/*
// ---------- Affichage de la liste de mots utilises --------------
set<Word, ordre_mot>::const_iterator wy;
map<Word, State>::const_iterator ri;
int compte = 1;
cout << "\nliste de mots associes à " << v << " et à {";
for (ri=XR.begin() ; ri != XR.end() ; ri++) {
if (ri->first.empty())
cout << "eps,";
else
cout << ri->first << ",";
}
cout << "}" << endl;
for (wy = W.begin() ; wy != W.end() ;wy++) {
if (wy->empty())
cout << "eps,";
else
cout << *wy << ",";
if (!(compte++ % 10))
cout << "\n";
}
cout << "\nNombre de mots : " << W.size();
cout << endl;
// --------------------------------------------------------------
*/
// avec l'entree 0 on traite tous les mots
if (max == 0)
max = W.size () + 1;
// inequations en <= (nb=ineq1), inequations en >= (nb=ineq2)
// les inequations X_q >= 0 sont deja
// prisent en comptent de manière implicite
double s1;
double s2;
set< Word, ordre_mot >::const_iterator wi;
double pvw = 0; // v^{-1}P(w)
s2 = S[v];
// Initialisation du simplexe
simplx.set_number_of_unknown_to(XR.size()+1);
// sum of all Xi is equal to 1
simplx.setparam(1,0); // --- la variable 1 est toujours epsilon ---
simplx.setval(1); //
for (q = XR.begin (); q != XR.end (); q++)
simplx.setparam(q->second+1,1);
simplx.add_equality_constraint();
// cout << "XR.size() = " << XR.size() << endl;
// loop for each word :
simplx.setparam(1,1); // --- la variable 1 est toujours epsilon ---
i=0;
for (wi = W.begin (); wi != W.end () && i <= max; wi++)
{
s1 = S[(v + *wi)];
pvw = (double) s1 / (double) s2;
simplx.setval(pvw);
for (q = XR.begin (); q != XR.end (); q++)
{
s1 = S[q->first + *wi];
simplx.setparam(q->second+1, (double) s1 / (double) S[q->first]);
}
simplx.add_absolute_constraint();
++i;
}
switch (modeeps)
{
// ---------------------------------------------------------- EPSFIXED -
case epsfixed:
simplx.set_minimize_epsilon_mode(precision);
break;
// ---------------------------------------------------------- VARIABLE -
case variable:
simplx.set_minimize_epsilon_mode(-1);
break;
default:
cerr << "!!! PFA::sol -- modeeps " << modeeps << " inconnu !!!" << endl;
}
switch(modeVariables) {
case determinist:
simplx.set_mode(ZeroOrOne);
break;
case positive:
simplx.set_mode(realZeroBounded);
break;
case nonconstrained:
simplx.set_mode(realNotBounded);
break;
}
map<int,float> preciseSol;
float epsilon;
// simplx.affiche();
err = simplx.has_solution(preciseSol, epsilon);
// cout << (err?"solution trouvée":"pas de solution") << ", epsilon = " << epsilon << endl;
if ((!err) || (epsilon>precision)) {
solution.clear();
return ERR(0);
}
else {
solution.clear();
float tmp;
for (map<int,float>::const_iterator q = preciseSol.begin() ; q != preciseSol.end() ; q++) {
if (q->first != 1) {
if ((tmp = (float) q->second) != 0) {
solution[q->first - 1] = (float) q->second;
}
}
}
return VAL(0);
}
}
catch (int erreur)
{
if (PFA_VERBOSE)
{
cerr << "ERREUR !!! PFA::solmax !!! n°" << erreur << endl;
}
solution.clear ();
return erreur;
}
}
// renvoie vide si le système lineaire I(v,R,S,precision) n'a pas de solution et
// sinon renvoie une solution de I i.e. un ensemble de variables X_q telles que
// v^{-1}P = \sum_{q \in R} X_qP_q -- en rappelant que R[w]=q => P_q = w^{-1}P
RESULT PPRFA::sol (T_ModeVariables modeVariables, // le mode dans lequel renvoyer les variables
SFunc & solution, // La solution
const Word & v, // Le residuel a tester
const Sample & S, // L'echantillon
Simplex & simplx, // L'objet simplex qui permet de calculer la solution
double precision, // La precision (sa signification dépend du mode)
T_ModeReturn moderet, // Le mode de retour : beg debut de l'arbre, end à la fin
T_ModeEpsilon modeeps, // Le mode : epsfixed avec epsilon fixe, variable avec epsilon variable.
WordSet &W, // L'ensemble de mots sur lesquels on teste,
// doit contenirs les mots des étapes précédentes
int maxmots, // le nombre de mots qu'on ajoute au maximum
bool Wcalculated // true if W is considered as calculated from outside
) const
{
// unsigned int n = 2 * Q.size () + 1;
// - Pour connaitre le nombre d'inequation, on doit
// - connaitre le nombre de mots qui sont successurs de v, et de tous
// - les ÈlÈments de R.
// - On met l'ensemble des successeurs de v et des éléments de R de l'echantillon dans W.
if (!Wcalculated)
{
ajoute_mots_associes (W, v, S, maxmots);
}
//liste_mots_associes(W,v,S,(int)((float)S.size()/(float)XR.size()));
return solmax (modeVariables,solution, v, S, simplx,precision, moderet, modeeps, W, INT_MAX);
/*
solret = solmax (modeVariables, solution, v, S, simplx, precision, moderet,modeeps, W, n);
if ( !solret || (n >= W.size ()))
return err;
else
{
n *= 5;
solret = solmax (modeVariables, solution, v, S, simplx, precision,moderet, modeeps, W, n);
if (!solret || (n >= W.size ()))
return err;
else
return solmax (modeVariables,solution, v, S, simplx,precision, moderet, modeeps, W, INT_MAX);
}
*/
}

203
sample.H Normal file
View File

@ -0,0 +1,203 @@
/***************************************************************************
echantillon.h - Sample de mots
-------------------
begin : 20 Jan 2003
copyright : (C) 2003 by Yann Esposito
email : esposito@cmi.univ-mrs.fr
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
/*_________________________________________________________________________*\
Classe échantillon, échantillon de mots.
\***************************************************************************/
#ifndef ECHANTILLON_H
#define ECHANTILLON_H
// le type de sortie
typedef enum {ffa, alergia, mdi} T_Format;
#include "general.H"
#include <list>
// ----------------------- Declaration ---------------------------------
// ordre naturel sur les mots
struct ordre_mot
{
bool operator()(const Word u, const Word v) const
{
if (u.size() < v.size())
return true;
else if (u.size() > v.size())
return false;
else
{
less<Word> infeq;
return infeq(u,v);
}
}
};
// Type echantillon qui suit l'ordre naturel sur les mots
typedef map<Word, int, ordre_mot> EnsWord; // Le type ensemble de mots
// ------------------------ La Classe ----------------------------------
class Sample
{
protected:
Alphabet Sigma; // Ensemble de lettre de l'echantillon
Dictionnaire alph; // permet d'associer des éléments plus complexes aux lettres.
EnsWord S; // l'ensemble de mots
unsigned int taille; // la taille de l'echantillon
bool prefixiel; // vrai si l'echantillon est prefixiel.
public:
int seuil; // Le seuil à partir duquel on permet de visualiser un élément de l'échantillon
public:
// --- Constructeur et Destructeurs ---
Sample() : taille(0), seuil(0)
{}
Sample(const Alphabet A, const Dictionnaire D, const bool pref=false, int n_seuil=0) :
Sigma(A), alph(D), taille(0), prefixiel(pref), seuil(n_seuil)
{}
~Sample(void)
{}
// --- Les accesseurs ---
// Renvoie le nombre de fois qu'est present le mot w
inline unsigned int count(const Word w) const
{
EnsWord::const_iterator s;
s = S.find(w);
return (s!=S.end())?s->second:0;
}
inline unsigned int operator[](const Word w) const
{
return count(w);
}
// Renvoie la taille de l'echantillon
inline unsigned int size() const
{
return taille;
}
// Renvoie l'alphabet de l'echantillon
inline Alphabet alphabet() const
{
return Sigma;
}
// Renvoie le dictionnaire
inline Dictionnaire dictionnaire() const
{
return alph;
}
// Renvoie l'ensemble de mot
inline EnsWord ensWord() const
{
return S;
}
// Renvoie le nombre de mots contenus dans S (pour la fct° precision)
inline unsigned int nb_mots() const
{
return S.size();
}
// Renvoie alph
inline Dictionnaire get_alph() const
{
return alph;
}
// Revoie vrai si l'echantillon est prefixiel
inline bool isprefixiel() const
{
return prefixiel;
}
// iterateurs
typedef EnsWord::const_iterator const_iterator;
inline const_iterator begin() const
{
return S.begin();
}
inline const_iterator end() const
{
return S.end();
}
inline const_iterator find(Word w) const
{
EnsWord::const_iterator u=S.find(w);
return ((u!=S.end()) && (u->second >= seuil))?u:S.end();
}
public:
// renvoie le prochain iterateur pointant vers un mot apparaissant
// un nombre supérieur de fois au seuil.
inline void next(const_iterator &w) const
{
do
w++;
while ((w->second < seuil) && (w != S.end()));
}
// --- Les méthodes ---
// Ajout une lettre par defaut à l'alphabet
Lettre addLettre(const Lettre l);
// Ajout de la lettre specifiee à l'alphabet
Lettre addLettre(const string l);
// Ajout de la lettre specifie a l'alphabet c etant la lettre associe pour les mots
Lettre addLettre (const Lettre c, const string l);
// Insere le mot w, si safe est vrai, on met à jour l'alphabet et le dictionnaire.
RESULT insert(const Word w, const unsigned int num=1, const bool safe=true);
// Rend l'echantillon vide
RESULT vide();
inline RESULT clear()
{
return vide();
};
// Sauvegarde l'echantillon dans le fichier Filename
RESULT save(const char *Filename, T_Format format=ffa) const;
inline RESULT save(const string Filename, T_Format format=ffa) const
{
return Sample::save(Filename.c_str(), format);
}
// Charge l'echantillon à partir d'un fichier
RESULT load(const char *Filename);
inline RESULT load(const string Filename)
{
return load((char *)Filename.c_str());
}
// Prefixialise l'echantillon
RESULT prefixialise();
// Deprefixialise l'echantillon
RESULT deprefixialise();
// Suppression des valeurs inferieures au seuil
inline RESULT seuille(const int n_seuil)
{
return seuil = n_seuil;
}
// Sépare un échantillon en un échantillon principal et un échantillon test
int separe(Sample &Stest, const float proportion);
// Ajoute un échantillon à un autre
Sample &operator+=(const Sample &Stest);
// return the likelihood of the MLM
float AutoLikelihood() const;
// return the list of words successor of v (in the prefixial sample)
Sample prefix_successor_of(const Word &v) ;
// return words begining by v
Sample begin_by(const Word &v);
// become S inter S2
void inter(const Sample &S2);
};
#endif

762
sample.cpp Normal file
View File

@ -0,0 +1,762 @@
/***************************************************************************
echantillon.C
-------------------
begin : 20 Jan 2003
copyright : (C) 2003 by Yann Esposito
email : esposito@cmi.univ-mrs.fr
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
/*
Pour les notes, voir le fichier "echantillon.h".
See "echantillon.h" file to view notes.
*/
#include "sample.H"
#include <algorithm>
// Ajout une lettre par defaut à l'alphabet
Lettre Sample::addLettre (const Lettre l)
{
Lettre a;
if (!Sigma.empty ())
{
a = *(--(Sigma.end ())) + 1;
}
else
{
a = 'a';
}
Sigma.insert (a);
alph[a] = l;
return a;
}
// Ajout de la lettre spécifiée à l'alphabet
Lettre Sample::addLettre (const string l)
{
Lettre a;
if (!Sigma.empty ())
{
a = *(--(Sigma.end ())) + 1;
}
else
{
a = 'a';
}
Sigma.insert (a);
alph[a] = l;
return a;
}
// Ajout de la lettre specifiee a l'alphabet
Lettre Sample::addLettre (const Lettre c, const string l)
{
Sigma.insert (c);
alph[c] = l;
return c;
}
// Insere num fois le mot w
RESULT Sample::insert (const Word w,
const unsigned int num,
const bool safe)
{
if (safe)
{
// on verifie si le mot contient des lettres en plus
Word::const_iterator a;
for (a = w.begin (); a != w.end (); a++)
{
if (Sigma.find (*a) == Sigma.end ())
{
addLettre (*a);
}
}
}
if (prefixiel)
{
Word u;
Word::const_iterator a;
u.clear ();
for (a = w.begin (); a != w.end (); a++)
{
u += *a;
S[u] += num;
}
}
else
{
S[w] += num;
}
taille += num;
return VAL (0);
}
// Rend l'echantillon vide
RESULT Sample::vide ()
{
S.clear ();
Sigma.clear ();
alph.clear ();
taille = 0;
prefixiel = false;
return VAL (0);
}
// Sauvegarde un echantillon dans le fichier Filename
RESULT Sample::save (const char *Filename, T_Format format) const
{
try
{
if (Filename == NULL)
throw -1;
ofstream
fp (Filename);
if (!fp.good ())
throw -2;
EnsWord::const_iterator w;
Word::const_iterator l;
Dictionnaire::const_iterator a;
string msg;
int i;
switch (format)
{
case ffa: // ========================= format ffa =============================
// Affichage de l'entete
fp << "Sample" << endl; // Affichage de Sample
// Affichage de la taille
fp << "Taille " << size () << endl;
// ---- ne pas modifier l'ordre Nb_Lettre puis Alphabet pour le "load" ---
// Affichage du nombre de lettres
fp << "Nb_Lettres " << alph.size () << endl;
// Affichage de l'alphabet
fp << "Alphabet" << endl;
for (a = alph.begin (); a != alph.end (); a++)
{
fp << a->first << " " << a->second << "\n";
}
fp << endl;
// Affichage du drapeau prefixiel
fp << "Prefixiel " << prefixiel << endl;
// Affichage de l'echantillon proprement dit
for (w = S.begin (); w != S.end (); w++)
{
for (l = w->first.begin ();
l != w->first.end (); l++)
{
fp << alph.find (*l)->
second << " ";
}
fp << ": " << w->second;
fp << endl;
}
break;
case alergia: // format alergia
for (w = S.begin (); w != S.end (); w++)
{
msg="";
for (l = w->first.begin (); l != w->first.end (); l++)
{
msg += alph.find (*l)->second;
}
for (i = 0; i < w->second; i++)
fp << msg << endl;
}
break;
case mdi: // format MDI
for (w = S.begin (); w != S.end (); w++) {
msg.clear ();
for (l = w->first.begin (); l != w->first.end (); l++) {
msg += alph.find(*l)->second;
msg += " ";
}
for (i = 0; i < w->second; i++) {
fp << msg << endl;
}
}
break;
default:
cerr << "Sample::save()" << endl;
cerr << "Format " << format << "inconnu !!!" <<
endl;
throw - 3;
}
return VAL (0);
}
catch (int e)
{
if (PFA_VERBOSE)
{
cerr << " PFA::echantillon(int taille, char *Filename)" << endl;
switch (e)
{
case -1:
cerr << " : Filename = NULL !!!" << endl;
break;
case -2:
cerr << "Impossible d'ecrire dans le fichier '" << Filename << "' !!!" << endl;
default:
cerr << "Unknown error" << endl;
}
}
return e;
}
catch (...)
{
cerr << " PFA::echantillon(int taille, char *Filename)"
<< endl;
cerr << "Unknown error !!!" << endl;
return -1;
}
}
// Charge un echantillon
RESULT Sample::load (const char *Filename)
{
// les échantillons sont sous la forme d'un liste de lignes
// mot : nb_apparitions
try
{
// on verifie qu'il n'y ai pas une erreur du passage du nom
if (Filename == NULL)
throw - 1;
ifstream
fp (Filename); // on declare le descripteur de fichier et on l'ouvre
// on verifie qu'il n'y ait pas d'erreur d'ouverture
if (!fp.good ())
throw - 2;
Word w; // le mot
map < string, Lettre > inv_alph; // le dictionnaire inversé
int i;
int nb_lettres;
bool safe; // des drapeaux fin de fichier et mode safe
char c;
string buf; // le buffer
// on vide la structure
vide ();
fp >> buf; // on lit le premier mot
if (buf == "Sample")
{ // ========================== TYPE de fichier echantillon interne =
safe = true;
// Tant que l'on est pas à la fin du fichier
while (!fp.eof ())
{ // boucle principale
fp >> buf;
if (buf == "%")
{ // -------------------- Commentaire
while ((fp.good ()) && (c != '\n'))
{
fp >> c;
}
}
else if (buf == "Taille")
{ // ------- Taille de l'echantillon
fp >> taille; // on lit la taille
}
else if (buf == "Nb_Lettres")
{ // --- On lit l'alphabet
fp >> nb_lettres; // on lit le nombre de lettres
fp >> buf;
if (buf != "Alphabet")
throw - 3;
Lettre c;
for (i = 0; (i < nb_lettres) && (fp.good ()); i++)
{
fp >> c;
fp >> buf; // on lit la lettre
addLettre (c,buf);
}
Dictionnaire::iterator x;
for (x = alph.begin ();
x != alph.end (); x++)
{
inv_alph[x->second] =
x->first;
}
safe = false; // pas besoin d'etre en mode safe pour le chargement de l'echantillon
}
else if (buf == "Prefixiel")
{ // ------ On regarde si l'echantillon est prefixiel
fp >> prefixiel; // on lit la valeur du drapeau "prefixiel"
}
else
{ // ------------------- On charge les données
while (fp.good ())
{
// on lit le mot
w.clear ();
while ((fp.good ())
&& (buf != ":"))
{
if (safe)
{ // si on ne connait pas l'alphabet, on verifie l'arrivee de nouvelles lettres.
if (inv_alph.
find (buf)
==
inv_alph.
end ())
{
inv_alph[buf] = addLettre (buf);
}
}
w += inv_alph.
find (buf)->
second;
// w.push_back(inv_alph.find(buf)->second);
fp >> buf; // on lit la prochaine lettre.
}
// on a fini de lire le mot
if (fp.good ())
fp >> S[w]; // on lit le nombre de fois qu'est apparu ce mot.
fp >> buf;
}
}
}
return VAL (0);
}
else if (buf == "Text_without_space")
{ // ================================ Mode mots (alergia et mdi)-
w.clear (); // on initialise le mot courant.
prefixiel = false;
fp.get(c); // on lit le caractere '\n'
while (!fp.eof())
{
fp.get(c);
// on ajoute si nécessaire les nouvelles lettres
if ((c != '\n') && (c != '\t') && (c != ' ')) // on lit une nouvelle lettre
{
if (Sigma.find (c) == Sigma.end ()) // si c \notin Sigma
{
Sigma.insert (c);
alph[c] = c;
}
w += c; // on ralonge le mot
} else // on est a la fin de la phrase
{
++S[w]; // on ajoute le mot un coup
w.clear(); // et on le réinitialise
}
}
// on supprime l'artefact pour epsilon
w.clear();
--S[w];
if (S.begin()->second == 0)
S.erase(S.begin());
EnsWord::iterator wi;
taille=0;
for (wi=S.begin() ; wi != S.end() ; ++wi)
{
taille += wi->second;
}
return VAL (0);
}
else if (buf == "Text_with_spaces")
{ // ========================== mode phrases ---
//caractere de separation : .
Word curmot;
Lettre curlettre = 'a';
curmot.clear ();
prefixiel = false;
Dictionnaire::const_iterator d;
while (fp.good ())
{
bool findephrase=false;
fp >> buf; // on lit la premiere lettre (un mot)
// cout << "lettre : " << buf << flush;
c = *(buf.rbegin ()); // c is the last letter of the string buf
if ((c == '.') || (c == '!') || (c='?')) {
buf.erase(--buf.end());
findephrase=true;
}
// on cherche a savoir si on a deja insere w
for (d = alph.begin ();(d != alph.end ()) && (d->second != buf); d++)
;
if (d == alph.end ())
{
// cout << ": jamais vue." << endl;
Sigma.insert (curlettre);
alph[curlettre] = buf;
curmot += curlettre;
++curlettre;
}
else
{
// cout << ": deja vue." << endl;
curmot += d->first;
}
c = *(buf.rbegin ()); // c is the last letter of the string buf
if (findephrase)
{
// si on arrive en fin de phrase
cout << "fin de la phrase : " << endl;
for (Word::const_iterator mi = curmot.begin() ; mi != curmot.end() ; ++mi)
cout << alph[*mi] << " ";
cout << endl;
++S[curmot];
++taille;
curmot.clear ();
findephrase=false;
}
}
return VAL (0);
}
else if (buf == "Amaury")
{ // ========================== mode phrases pour Amaury ---
//caractere de separation : .
Word curmot;
// Lettre curlettre = 'a';
curmot.clear ();
prefixiel = false;
Dictionnaire::const_iterator d;
while (fp.good ())
{
++S[curmot];
++taille;
curmot.clear ();
}
return VAL (0);
}
else
throw - 4;
}
catch (int e)
{
if (PFA_VERBOSE)
{
cerr << " Sample::load(char *Filename)" << endl;
switch (e)
{
case -1:
cerr << "Filename = NULL !!!" << endl;
break;
case -2:
cerr << Filename << "is unreadable !!!" <<
endl;
break;
case -3:
cerr << "Erreur de coherence lors du chargement du fichier :" << Filename << endl;
cerr << "\"Nb_Lettres\" n'est pas suivit d'un chiffre puis de \"Alphabet\"" << endl;
break;
case -4:
cerr << "Format of the file " << Filename <<
" is not recognized" << endl;
cerr << "Add 'Text_without_space' or 'Text_with_spaces' at the begining of the file" << endl;
cerr << "to make the file in a valid format."
<< endl;
break;
default:
cerr << "Erreur non repertoriée" << endl;
}
}
return e;
}
catch (...)
{
cerr << "Sample::load() Erreur non repertoriee et non traitee" << endl;
return -1;
}
}
// Genere l'echantillon prefixe associe à l'échantillon non prefixe S.
RESULT Sample::prefixialise ()
{
if (!prefixiel)
{
Word u;
Word::const_iterator a; // la lettre courante
EnsWord::const_iterator w; // le mot courant
EnsWord Spref; // l'echantillon prefixe
u.clear ();
Spref[u] = taille;
for (w = S.begin (); w != S.end (); ++w)
{
u.clear ();
for (a = w->first.begin (); a != w->first.end (); ++a)
{
u += *a;
Spref[u] += w->second;
}
}
S = Spref;
prefixiel = true;
return VAL (0);
}
else
{
return ERR (0);
}
}
// Deprefixialise
RESULT Sample::deprefixialise ()
{
if (!prefixiel)
{
return VAL (1);
}
else
{
EnsWord R;
EnsWord::const_iterator w, u;
Alphabet::const_iterator a;
int sum;
for (w = S.begin (); w != S.end (); w++)
{
sum = 0;
for (a = Sigma.begin (); a != Sigma.end (); a++)
{
u = S.find (w->first + *a);
if (u != S.end ())
sum += u->second;
}
if (w->second != sum) {
R[w->first] = w->second - sum;
}
}
S = R;
prefixiel = false;
return VAL (0);
}
}
// Sépare un échantillon en un échantillon principal et un échantillon test
int
Sample::separe (Sample & Stest, const float proportion)
{
deprefixialise();
Stest.clear();
Stest.alph=alph;
Stest.Sigma=Sigma;
int nb_suppr = int(float(taille) * proportion);
int num;
EnsWord::iterator w;
while (nb_suppr-- != 0) {
w=S.begin();
num = int(float(rand ())*float(taille) / float(INT_MAX));
num -= w->second;
while (num > 0) {
w++;
num -= w->second;
}
Stest.insert( w->first );
if (--(w->second) == 0) {
S.erase(w);
}
--taille;
}
return Stest.size();
//~ deprefixialise ();
//~ EnsWord::iterator w;
//~ int i;
//~ int nb_suppr;
//~ Stest.clear (); // first we clear the test sample
//~ Stest.alph = alph;
//~ Stest.Sigma = Sigma;
//~ for (w = S.begin (); w != S.end (); ++w)
//~ {
//~ nb_suppr = 0;
//~ for (i = 0; i < w->second; ++i)
//~ {
//~ float val;
//~ val = (float) ((float) random () / (float) INT_MAX);
//~ if (val < proportion)
//~ {
//~ Stest.insert (w->first);
//~ ++nb_suppr;
//~ }
//~ }
//~ w->second -= nb_suppr;
//~ taille -= nb_suppr;
//~ }
//~ // Suppression des mots effaces de l'echantillons
//~ EnsWord::iterator wtmp;
//~ for (w = S.begin (); w != S.end (); ++w)
//~ {
//~ if (w->second == 0)
//~ {
//~ wtmp = w;
//~ ++wtmp;
//~ S.erase (w);
//~ w = wtmp;
//~ }
//~ }
//~ return Stest.size ();
}
// Ajoute un échantillon à un autre
Sample & Sample::operator+= (const Sample & Stest)
{
// if (alph != Stest.alph) throw 1;
Sample::const_iterator w;
for (w = Stest.begin (); w != Stest.end (); ++w)
insert (w->first, w->second);
return *this;
}
float Sample::AutoLikelihood() const
{
if (prefixiel)
{
cerr << "Sample::AutoLikelihood() : echantillon prefixiel !" << endl;
return -1;
}
Sample::const_iterator w;
unsigned int si = size();
float result=0;
for (w=begin() ; w != end() ; ++w)
{
result += (log ( float(w->second) / float(si) )) * w->second;
}
return result;
}
Sample Sample::begin_by(const Word &v) {
bool waspref=prefixiel;
if (!prefixiel) {
prefixialise();
}
list<Word> W;
Sample X;
Word u;
X.Sigma=Sigma;
X.alph=alph;
X.prefixiel=true;
EnsWord::const_iterator w;
w=S.find(v);
if (w != S.end()) {
W.push_back(w->first);
X.S[w->first]=w->second;
}
Alphabet::const_iterator a;
while (!W.empty()) {
u=*(W.begin());
W.pop_front();
for (a=Sigma.begin() ; a!=Sigma.end() ;++a) {
u+=*a;
w=S.find(u);
if (w != S.end()) {
W.push_back(w->first);
X.S[w->first]=w->second;
}
u.erase(--u.end());
}
}
X.deprefixialise();
for (w=X.S.begin() ; w != X.S.end() ; ++w) {
X.taille += w->second;
}
if (!waspref) {
deprefixialise();
}
return X;
}
Sample Sample::prefix_successor_of(const Word &v) {
bool waspref=prefixiel;
if (!prefixiel) {
prefixialise();
}
list<Word> W;
Sample X;
Word u;
if (S.find(v) != S.end()) {
W.push_back(u); X.insert(u);
}
Alphabet::const_iterator a;
while (!W.empty()) {
u=*(W.begin()); W.pop_front();
for (a=Sigma.begin() ; a!=Sigma.end() ;++a) {
u+=*a;
if (S.find(v+u) != S.end()) {
W.push_back(u);
X.insert(u);
}
u.erase(--u.end());
}
}
if (!waspref) {
deprefixialise();
}
return X;
}
void Sample::inter(const Sample &S2) {
Sample::const_iterator u;
EnsWord::iterator w;
for (w = S.begin() ; w != S.end() ; ++w) {
w->second = 0;
}
for (w = S.begin() ; w!=S.end() ; ++w) {
u=S2.find(w->first);
if (u != S2.end()) {
w->second = u->second;
}
}
// erase for iota
EnsWord::iterator stmp;
for (w=S.begin() ; w != S.end() ; )
{
if (w->second == 0)
{
stmp = w;
++stmp;
S.erase (w);
w = stmp;
}
else
++w;
}
}

77
simplex.H Normal file
View File

@ -0,0 +1,77 @@
/*
* simplex.H
* dees
*
* Created by Yann Esposito on 17/04/06.
* Copyright 2006 __MyCompanyName__. All rights reserved.
*
*/
#include "general.H" // pour l'utilisation des map, hash_map...
#include "include/lp_lib.h"
typedef enum _simplexMode {realNotBounded, realZeroBounded, ZeroOrOne} simplexMode;
// this is a class used as a wrapper to other libraries
class Simplex {
private:
int n; // number of constraints
lprec *lp; // the linear programming variable (LP_SOLVE)
double *tmpbuf; // temporary buffer used to fill the problem
int tmpbufsize; // size of tmpbuf
double val; // temporary value for equations
void resize_tmpbuf(void); // update the size of tmpbuf
public:
Simplex(void) {
lp = NULL;
tmpbuf = NULL;
tmpbufsize=0;
n = 0;
val=0;
}
~Simplex(void) {
if (lp != NULL)
free_lp(&lp);
if (tmpbuf != NULL)
free(tmpbuf);
}
// print the linear system
inline void affiche(void) { print_lp(lp); }
// set the mode for the variables ({0,1}, or Q+ or Q)
int set_mode(const simplexMode newMode);
// set the nuber of constraints
inline lprec *set_number_of_unknown_to(const int newNumber) {
if (lp != NULL)
free(lp);
n = newNumber;
lp=make_lp(0,n);
if (lp)
set_verbose(lp,0);
return (lp);
}
int setval(double newval);
int setparam(int variable, double val);
int add_absolute_constraint(); // use the current values setted by setval and setparam
int add_equality_constraint();
int add_equality_constraint_with_parameters(double *constraints, double val);
// add a constraint of the form :
// | constraints[0]X0 + ... + constraints[n-1]Xn-1 - val| <= epsilon
int add_absolute_constraint_with_parameters(double *constraints, double val);
int add_absolute_constraint_with_parameters(const vector<double> constraints, double val);
int add_absolute_constraint_with_parameters(const map<int,double> constraints, double val);
// return the solution int the map solution
bool has_solution(map<int,float> &solution, float &epsilon);
// renvoie 0 si
int set_minimize_epsilon_mode (double epsilon = -1);
};

196
simplex.cpp Normal file
View File

@ -0,0 +1,196 @@
/*
* simplex.cpp
* dees
*
* Created by Yann Esposito on 17/04/06.
* Copyright 2006 __MyCompanyName__. All rights reserved.
*
*/
#include "simplex.H"
#include "include/lp_lib.h"
#include <math.h>
// set the mode for the variables ({0,1}, or Q+ or Q)
int Simplex::set_mode(const simplexMode newMode) {
switch (newMode) {
set_lowbo(lp,1,0.0); // pour epsilon c'est toujours 0
set_upbo(lp,1,-log(0.0)); // pour epsilon c'est toujours 1
set_int(lp,1,FALSE); // toujours real
case realNotBounded:
for (int i=2 ; i<=n ; i++) {
set_int(lp,i,FALSE);
set_lowbo(lp,i,log(0.0));
set_upbo(lp,i,-log(0.0));
}
break;
case realZeroBounded:
for (int i=2 ; i<=n ; i++) {
set_int(lp,i,FALSE);
set_lowbo(lp,i,0);
set_upbo(lp,i,-log(0.0));
}
break;
case ZeroOrOne:
for (int i=2 ; i<=n ; i++) {
set_binary(lp,i,TRUE);
}
break;
default:
cerr << "Simplex::set_mode : mode inconnu : " << newMode << endl;
throw -1;
}
return VAL(0);
}
// add a equality constraint of the form :
// tmpbuf[1]X1 + tmpbuf[2]X2 + ... + tmpbuf[n]Xn = val
// One can view X1 as an epsilon value
int Simplex::add_equality_constraint() {
return add_equality_constraint_with_parameters(tmpbuf,val);
}
// add a equality constraint of the form :
// constraints[1]X1 + constraints[2]X2 + ... + constraints[n]Xn = val
// One can view X1 as an epsilon value
int Simplex::add_equality_constraint_with_parameters(double *constraints,double val) {
set_add_rowmode(lp,TRUE);
add_constraint(lp,constraints,EQ,val);
set_add_rowmode(lp,FALSE);
return 0;
}
int Simplex::add_absolute_constraint(void) {
return add_absolute_constraint_with_parameters(tmpbuf,val);
}
// add a constraint of the form :
// | constraints[2]X2 + ... + constraints[n]Xn - val | <= constraints[1]*X1
// One can view X1 as an epsilon value
int Simplex::add_absolute_constraint_with_parameters(double *constraints,double val) {
set_add_rowmode(lp,TRUE);
if (constraints[1] != 1) {
cerr << "WARNING !!!! add_absolute_constratins_with_parameters\n";
cerr << "constraints[n] should be 1 and it is " << constraints[n] << endl;
}
// constraint of the form
// constraints[1]X1 + ... + constraints[n]Xn >= -val
add_constraint(lp,constraints,GE,val);
// constraint of the form
// -constraints[1]X1 + ... + constraints[n]Xn <= -val
constraints[1] = -constraints[1];
add_constraint(lp,constraints,LE,val);
constraints[1] = -constraints[1];
set_add_rowmode(lp,FALSE);
return 0;
}
int Simplex::add_absolute_constraint_with_parameters(const vector<double> constraints, double val) {
resize_tmpbuf();
vector<double>::const_iterator i;
int j;
for (i=constraints.begin(), j=2 ; i!=constraints.end() ; i++, j++) {
tmpbuf[j]=*i;
}
tmpbuf[1]=1;
return add_absolute_constraint_with_parameters(tmpbuf,val);
}
int Simplex::add_absolute_constraint_with_parameters(const map<int,double> constraints, double val) {
resize_tmpbuf();
map<int,double>::const_iterator i;
for (i=constraints.begin() ; i!=constraints.end() ; i++) {
tmpbuf[i->first]=i->second;
}
tmpbuf[1]=1;
return add_absolute_constraint_with_parameters(tmpbuf,val);
}
// set minimize epsilon mode or fixed epsilon mode
// if epsilon < 0 then minimize epsilon
// else fix the epsilon value
int Simplex::set_minimize_epsilon_mode (double epsilon) {
resize_tmpbuf();
for (int i=1;i<=n+1;i++) {
tmpbuf[i]=0;
}
// tmpbuf = 0 0 ... 0
if (epsilon < 0) { // minimize the value of epsilon
tmpbuf[1]=1;
set_obj_fn(lp,tmpbuf);
set_minim(lp); // minimize the objective function
} else {
set_add_rowmode(lp,TRUE);
set_obj_fn(lp,tmpbuf); // minimize the 0 function
set_minim(lp);
tmpbuf[1]=1;
add_constraint(lp,tmpbuf,EQ,epsilon); // add the constraint epsilon = given value
set_add_rowmode(lp,FALSE);
}
return VAL(0);
}
// répond oui ou non, il y a une solution
bool Simplex::has_solution(map<int,float> &solution, float &epsilon) {
int res = solve(lp);
// print_lp(lp);
int temp ;
if ((res == 0) ||
(res == 1) ||
(res == 3) ||
(res == 4) ||
(res == 12) ) {
temp = 2 + get_Nrows(lp) ;
if (tmpbufsize < temp + n ) {
if (tmpbufsize > 0) {
free(tmpbuf);
}
tmpbuf = new double [ temp + n ];
tmpbufsize = temp + n;
}
get_primal_solution(lp,tmpbuf);
epsilon = tmpbuf[0];
for (int i=1 ; i<= n ; i++) {
solution[i]=(float)tmpbuf[temp + i -2];
}
return true;
}
else {
solution.clear();
return false;
}
}
int Simplex::setval(double newval) {
val = newval;
return VAL(0);
}
void Simplex::resize_tmpbuf(void) {
if (tmpbufsize < n + 2) {
if (tmpbuf != NULL)
free(tmpbuf);
tmpbuf = new double[2*n+2];
tmpbufsize=2*n+2;
}
}
int Simplex::setparam(int variable, double val) {
resize_tmpbuf();
if (PFA_SAFE) {
if ((variable<1) || (variable>n+1)) {
cerr << "Aie Aie Aie !!! Simplex::setparam called with variable = " << variable << " where max should be ";
cerr << n-1 << " !!! " << endl;
}
}
tmpbuf[variable]=val;
return VAL(0);
}

168
spfa.H Normal file
View File

@ -0,0 +1,168 @@
/***************************************************************************
spfa.h - Semi-Probabilistic Finite Automaton
-------------------
begin : 7 Dec 2002
copyright : (C) 2002 by Yann Esposito
email : esposito@cmi.univ-mrs.fr
***************************************************************************
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************
____________ HISTORIQUE et Déscription plus précise _____________________
Classe qui hérite de la classe ffa, la seule différence est que les
valeurs de iota, phi et tau doivent être positives et
sum_{q} iota[q]=1.
pour tout etat q : tau[q] + sum_{a,r} phi[q][a][r] = 1
_________________________________________________________________________
*/
#ifndef SPFA_H
#define SPFA_H
#include "ma.H"
#include "sample.H"
#include <list>
typedef map<Word, State, ordre_mot> WordSFunc;
typedef map<State,State> StateSFunc;
typedef map<State,Word> StateWordFunction;
typedef set<Word,ordre_mot> WordSet;
class SPFA : public MA
{
public :
// Ajoute un état
//RESULT addState(const float init=0, const float term=1);
RESULT addNewState (const float init, const float term);
// Fonction qui ajoute une transition
RESULT addTransition(const Transition &t, const float val);
// Ajout d'une transition
RESULT addTransition(const State qdep, const Lettre a, const State qarr, const float val);
RESULT becomeRandom(const int num_etat, // le nombre d'états
const int num_lettre, // le nombre de lettres
const int num_graphe = 0, // le numero du graphe
const float densite=0.3, // densité du ffa (0 ffa vide, 1 ffa complet)
const float prob_init=0.3, // la probabilité pour un état d'etre initial
const float prob_term=0.3, // probabilité pour un état d'être terminal
const float min_trans = 0, // la valeur minimale des transitions
const float max_trans = 1); // la valeur maximale des transitions
RESULT becomeRandomPrefix(const int nb_etats, // le nombre d'états
const int nb_lettres, // le nombre de lettres
const int num_graphe = 0, // le numero du graphe
const float densite=0.3, // densité du ffa (0 ffa vide, 1 ffa complet)
const float prob_init=0.3, // la probabilité pour un état d'etre initial
const float prob_term=0.3, // probabilité pour un état d'être terminal
const float min_trans = 0, // la valeur minimale des transitions
const float max_trans = 1); // la valeur maximale des transitions
// Cree un MA aleatoire avec un nombre maximal d'aretes
RESULT becomeRandomMax (const int nb_etats, const int nb_lettres,
const int num_graphe, const int nb_succ,
const int nb_init, const int nb_term,
const float min_trans, const float max_trans);
// --- Output methods ---
protected:
// log (exp(p1) + exp(p2)) = p1 + log(1 + exp(p2-p1)) pour p1 > p2
// good approximation if p1=log(x1) and p2=log(x2) sumlog(p1,p2) return a good approximation
// of log(x1 + x2)
inline double sumlog(const double p1, const double p2) const
{
return (p1>p2)?(p1 + log(1+exp(p2-p1))):(p2 + log(1+exp(p1-p2)));
}
public:
// extension of the phi function to words
inline double phiext(const State q, const Word &u, const State s, const Dictionnaire *dico=NULL) const
{
return exp(philog(q,u,s,dico));
}
// logarith of the extended phi
double philog(const State q, const Word &u, const State s, const Dictionnaire *dico=NULL) const;
// la fonction p renvoie la valeur d'un mot (probabilité dans les PFAs)
inline double p(const Word &u, const Dictionnaire *dico=NULL) const
{
return exp(plog(u,dico));
}
// le logarithme de la fonction p
double plog(const Word &u, const Dictionnaire *dico=NULL) const;
// la fonction p calculŽe de fa<66>on directe !!! ATTENTION AUX ARRONDIS !!
double p_directe(const Word &u, const Dictionnaire *dico=NULL) const;
// probability to be in state q having read the word u
inline double p(const State q, const Word &u, const Dictionnaire *dico=NULL)
{
return exp(plog(q,u,dico));
}
// logarithm of the probability to be in state q having read the word u
double plog(const State q, const Word &u, const Dictionnaire *dico=NULL) const;
// return probability to begin by u
double p_bar(const Word &u, const Dictionnaire * dico=NULL) const;
// return probability to begin by u without log trick
double p_bar_directe(const Word &u, const Dictionnaire * dico=NULL) const;
// return the log probability to begin by u
double plog_bar(const Word &u, const Dictionnaire * dico=NULL) const;
// return the forward vector
RESULT logforward(PreciseSFunc &F, const Word &u) const;
RESULT logforwardprecalc(PreciseSFunc &F,
const Word &u, const PreciseSFunc &init) const;
RESULT forward(PreciseSFunc &F, const Word &u) const;
RESULT forwardprecalc(PreciseSFunc &F,
const Word &u, const PreciseSFunc &init) const;
// return the forward list vectors
RESULT logforward(list < PreciseSFunc > &F, const Word &u) const;
RESULT logforwardprecalc(list < PreciseSFunc > &F,
const Word &u, const PreciseSFunc &init) const;
RESULT logbackward(list < PreciseSFunc > &B, const Word &u) const;
RESULT logbackwardprecalc(list < PreciseSFunc > &B, // la liste des vecteurs
const Word &u, // le mot
const PreciseSFunc & term) const; // le vecteur terminal
// Apprentissage
RESULT BaumWelch(const Sample &S,
TransitionFunction &T,
SFunc &Iota,
SFunc &Tau,
int nb_tours,
bool verbose=false);
RESULT TransitionCount( const Sample &S,
TransitionFunction &T,
SFunc &Iota,
SFunc &Tau) const;
RESULT TransitionCount( const Word &u,
TransitionFunction &T,
SFunc &Iota,
SFunc &Tau,
const int nb_apparitions) const;
float count_nb_pass(const State x, const Sample &S) const;
public:
RESULT renormalise(void);
RESULT erase_bad_states(void);
private:
float val_outstate(const State q) const;
};
#endif

1284
spfa.cpp Normal file

File diff suppressed because it is too large Load Diff

13
test.H Normal file
View File

@ -0,0 +1,13 @@
/*
* test.h
* dees
*
* Created by Yann Esposito on 19/12/05.
* Copyright 2005 Yann Esposito. All rights reserved.
*
*/
// --- Une fonction de test (ne sert qu'au débogage) ---
void test_du_simplexe (void);
void test_PSe(void);
void test(void);

92
test.cpp Normal file
View File

@ -0,0 +1,92 @@
/*
* test.cpp
* dees
*
* Created by Yann Esposito on 19/12/05.
* Copyright 2005 __MyCompanyName__. All rights reserved.
*
*/
#include "main.H"
#include "test.H"
#include "include/lp_lib.h"
void test_PSe(void) {
MA A;
SFunc PSe;
SFunc::const_iterator q;
int res;
// A.becomeRandom(2,2);
// A.save("test/testPSe.ma");
A.load("test/testPSe.ma");
res = A.val_PSe(PSe);
cout << "res = " << res << endl;
for (q=PSe.begin() ; q != PSe.end() ; q++) {
cout << "P_" << q->first << "(\Se) = " << q-> second << endl;
}
}
void test_genere_mot_MA(void) {
MA A;
Word w;
int i;
A.load("test/testGenMot.ma");
for (i=0;i<1;i++){
cout << "i=" << i << " : ";
A.genere_mot(w);
cout << A.affiche(w);
cout << endl;
}
}
void test_simplex() {
Simplex simplex;
int i,j;
int nbinc, nbcont;
double input;
cout << "Entrez le nombre d'inconnues : ";
cin >> nbinc;
simplex.set_number_of_unknown_to(nbinc);
cout << "Entrez le nombres de contraintes : " ;
cin >> nbcont;
cout << "Entrez les contraintes (pour 3*X1 + 2*X2 = 4 écrire 3 2 4) : " << endl;
for (i = 1 ; i<= nbcont ; i++) {
for (j=1 ; j<= nbinc ; j++) {
cin >> input;
simplex.setparam(j,input);
}
cin >> input;
simplex.setval(input);
simplex.add_equality_constraint();
}
simplex.set_mode(realNotBounded);
simplex.set_minimize_epsilon_mode(-1);
map<int,float> sol;
float epsilon;
if (simplex.has_solution(sol,epsilon)) {
cout << "Solution : " << endl;
cout << "epsilon = " << epsilon << endl;
for (i = 1 ; i<= nbinc ; i++) {
cout << "X" << i << "=" << sol[i] << " ; ";
}
cout << endl;
}
else {
cout << "Pas de solution..." << endl;
}
}
void test(void) {
test_simplex();
}

0
toto Normal file
View File

365
ySimplex.cpp Normal file
View File

@ -0,0 +1,365 @@
// Algorithme dual du simplexe (méthode de Lemke) (fonction simplexe_dual).
// a : le tableau des coefficients du problème ;
// sol : un tableau renvoyant la solution optimale ;
// ineq1 : le nombre des inéquations en <= ;
// ineq2 : le nombre des inéquations en >= ;
// eq : le nombre des équations ;
// n : le nombre de variables.
// Elle calcule dans le tableau sol une solution optimale du programme linéaire
// (l'opposé de la valeur correspondante de la fonction économique est calculé dans a[0][0]).
// Les données doivent être fournies dans le tableau a de la façon suivante:
// * ligne 0 de a : la fonction économique
// L'élément 0 est égal à 0, les éléments 1 à n aux coefficients des variables dans la fonction
// * lignes 1 à ineq1 de a : les inéquations en <=
// L'élément 0 est égal au second membre,
// les éléments 1 à n aux coefficients des variables dans l'inéquation
// * lignes ineq1+1 à ineq1+ineq2 de a : les inéquations en >=
// L'élément 0 est égal au second membre,
// les éléments 1 à n aux coefficients des variables dans l'inéquation
// * lignes ineq1+ineq2+1 à ineq1+ineq2+eq de a : les équations
// L'élément 0 est égal au second membre,
// les éléments 1 à n aux coefficients des variables dans l'équation
#include "simplex.H"
int Simplex::ads_sortant(int m,int n,int phase)
{
int i,j,k,l;
double d,s,min;
l=0;
min=0.0;
k=0;
if(phase==1)
{
for(j=1;j<=n;j++)
{
if(hb[j]==n+m)
k=j;
}
}
if((phase==2)||(k!=0))
{
for(i=1;i<=m;i++)
{
d=a[i][k];
s=0.0;
if(d<0)
{
for (it=a[i].begin() ; it != a[i].end() ; it++)
s+=fabs(it->second);
d/=s;
if(d<min)
{
min=d;
l=i;
}
}
}
}
return(l);
}
int Simplex::ads_entrant(int n,int l)
{
int j,k;
double rap,min;
min=1e308;
k=0;
for(j=1;j<=n;j++)
{
if(a[l][j]<0)
{
rap=a[0][j]/a[l][j];
if(rap<min)
{
min=rap;
k=j;
}
}
}
return(k);
}
void Simplex::pivotage(int m,int n,int l,int k)
{
int i,j;
double pivot,coef;
pivot=a[l][k];
for(i=0;i<=m;i++)
if(i!=l)
{
coef=a[i][k]/pivot;
a[i][k]=-coef;
for(j=0;j<=n;j++)
if(j!=k)
a[i][j]=a[i][j]-coef*a[l][j];
}
coef=1/pivot;
a[l][k]=coef;
for(j=0;j<=n;j++)
if(j!=k)
a[l][j]=coef*a[l][j];
i=db[l];
db[l]=hb[k];
hb[k]=i;
}
int Simplex::simplexe_dual(int ineq1, int ineq2, int eq, int n)
{
try
{
int i,j,k,l,phase,m,m1;
double max;
m=ineq1+ineq2+eq;
for(i=ineq1+1;i<=ineq1+ineq2;i++)
for (it=a[i].begin() ; it != a[i].end() ; it++)
it->second = -(it->second);
for(i=1;i<=ineq1+ineq2;i++)
db[i]=n+i;
for(i=ineq1+ineq2+1;i<=m;i++)
db[i]=0;
for(j=1;j<=n;j++)
hb[j]=j;
if(eq!=0)
{
for(i=ineq1+ineq2+1;i<=m;i++)
{
l=i;
k=0;
for(j=1;j<=n;j++)
if(a[i][j]!=0)
k=j;
if(k==0)
{
if(a[i][0]!=0)
return(2);
}
else
{
pivotage(m,n,l,k);
hb[k]=hb[n];
for(j=0;j<=m;j++)
a[j][k]=a[j][n];
n-=1;
}
}
}
m1=m;
phase=2;
k=0;
max=0;
for(j=1;j<=n;j++)
if(a[0][j]>max)
{
max=a[0][j];
k=j;
}
if(k!=0)
phase=1;
l=1;
if(phase==1)
{
m1=m+1;
for(j=1;j<=n;j++)
if(a[0][j]>0)
a[m1][j]=1;
else
a[m1][j]=0;
a[m1][0]=0;
db[m1]=n+m+1;
pivotage(m1,n,m1,k);
}
while(phase<=2)
{
do
{
l=ads_sortant(m1,n,phase);
if(l!=0)
{
k=ads_entrant(n,l);
if(k==0)
{
return(1);
}
pivotage(m1,n,l,k);
}
}
while(l!=0);
if(phase==1)
{
k=0;
for(j=1;j<=n;j++)
if(hb[j]==n+1+m)
k=j;
if(k!=0)
{
if(fabs(a[0][k])>1e-15)
return(2);
else
{
for(i=1;i<=m1;i++)
if(a[i][k]!=0)
l=i;
pivotage(m1,n,l,k);
}
}
}
if(phase==1)
{
for(i=1;i<=m1;i++)
if(db[i]==n+m1)
l=i;
db[l]=db[m1];
for(j=0;j<=n;j++)
a[l][j]=a[m1][j];
}
phase+=1;
m1-=1;
}
for(i=1;i<=m+n;i++)
sol[i]=0;
for(i=1;i<=m;i++)
sol[db[i]]=a[i][0];
return (0);
}
catch (int erreur)
{
if (PFA_VERBOSE)
{
cerr << "ERREUR : Simplex::simplexe_dual" << endl;
switch (erreur)
{
default :
cerr << "Erreur n°" << erreur << endl;
}
}
return erreur;
}
}
int Simplex::affiche(int ineq1, int ineq2, int nbeq, int nbvar) {
int i, j;
cout << "--------------------------------" << endl;
cout << "Affichage du syst<73>me :" << endl;
cout << "--------------------------------" << endl;
char lettre = 'X';
cout << " minimize : ";
for (i=1 ; i<=nbvar ; i++) {
cout << a[0][i] << lettre++ << " ";
}
cout << "::" << endl;
for (i=1 ; i<=ineq1 ; i++){
lettre = 'X';
for (j=1 ; j<=nbvar ; j++) {
if (a[i][j]>0)
cout << "+";
cout << a[i][j] << lettre++ << " ";
}
cout << "<=" << a[i][0] << endl;
}
for (i=ineq1 + 1; i<= ineq1 + ineq2 ; i++) {
lettre = 'X';
for (j=1 ; j<=nbvar ; j++) {
if (a[i][j]>0)
cout << "+";
cout << a[i][j] << lettre++ << " ";
}
cout << ">=" << a[i][0] << endl;
}
for (i=ineq1 + ineq2 + 1 ; i<=ineq1 + ineq2 + nbeq ; i++) {
lettre = 'X';
for (j=1 ; j<=nbvar ; j++) {
if (a[i][j]>0)
cout << "+";
cout << a[i][j] << lettre++ << " ";
}
cout << "= " << a[i][0] << endl;
}
cout << "--------------------------------" << endl;
}
int Simplex::solve(int ineq1, int ineq2, int eq, int n, bool debug) {
try {
const int ntmp = n;
const int BORNEMAX = 1024;
int i,j,k;
int m=ineq1+ineq2+eq;
int res ;
// MODIFICATION POUR GERER DES VARIABLES NEGATIVES
for (i=0 ; i <= m ; i++) {
for (j=1 ; j<=n ; j++) {
a[i][j+n] = -a[i][j];
// cout << "a[" << i <<"][" << j << "]=" << a[i][j];
// cout << "a[" << i << "][" << j+n << "]=" << a[i][j+n];
}
// cout << endl;
}
n *= 2;
// FIN DE LA MODIFICATION
// MODIFICATION POUR EVITER UN BUG DE PRECISION ; on borne
// toutes les variables
k = ineq1 + ineq2 + 1;
for (i=0 ; i<eq ; i++) {
for (j=0 ; j<=n ; j++) {
a[k+i+n]=a[k+i];
}
}
for (i=0 ; i<n ; i++) {
for (j=1 ; j<=n ; j++) {
a[k+i][j]=0;
}
a[k+i][0]=-BORNEMAX;
a[k+i][i+1]=-1;
}
ineq2 = ineq2 + n;
// FIN DE LA MODIFICATION ANTIBUG DE PRECISION.
if (debug) {
affiche(ineq1,ineq2,eq,n);
}
res = simplexe_dual(ineq1,ineq2,eq,n);
if (res != 1) {
for (i=1 ; i<=ntmp ; i++)
sol[i] -= sol[i+ntmp];
// // --------- AFfICHAGE DEBUG SOLUTION -------
// char lettre = 'X';
// cout << "\nn=" << n << ", m=" << m << endl;
// cout << "\nSOLUTION : ";
// for (i=1 ; i<=n ; i++) {
// cout << lettre++ << "=" << sol[i]<< ", ";
// }
// cout << endl;
// // --------- FIN AFFICHAGE DEBUG SOLUTION ------
}
return (res);
}
catch (int erreur) {
if (PFA_VERBOSE)
{
cerr << "ERREUR : Simplex::solve" << endl;
switch (erreur)
{
default :
cerr << "Erreur n°" << erreur << endl;
}
}
return erreur;
}
}