commit 919d4a1006748d9ffcc67c6da0f59bbf215ece17 Author: Yann Esposito (Yogsototh) Date: Tue May 17 22:24:18 2011 +0200 Initial git init in the future I may add the SVN history diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..a4faf74 Binary files /dev/null and b/.DS_Store differ diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..90ec22b --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.svn diff --git a/apprend.sh b/apprend.sh new file mode 100755 index 0000000..ff45a1a --- /dev/null +++ b/apprend.sh @@ -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 diff --git a/dees b/dees new file mode 120000 index 0000000..92b3278 --- /dev/null +++ b/dees @@ -0,0 +1 @@ +build/Debug/dees \ No newline at end of file diff --git a/dees.xcodeproj/esposito.mode1 b/dees.xcodeproj/esposito.mode1 new file mode 100644 index 0000000..34b8a90 --- /dev/null +++ b/dees.xcodeproj/esposito.mode1 @@ -0,0 +1,1432 @@ + + + + + ActivePerspectiveName + Project + AllowedModules + + + BundleLoadPath + + MaxInstances + n + Module + PBXSmartGroupTreeModule + Name + Groups and Files Outline View + + + BundleLoadPath + + MaxInstances + n + Module + PBXNavigatorGroup + Name + Editor + + + BundleLoadPath + + MaxInstances + n + Module + XCTaskListModule + Name + Task List + + + BundleLoadPath + + MaxInstances + n + Module + XCDetailModule + Name + File and Smart Group Detail Viewer + + + BundleLoadPath + + MaxInstances + 1 + Module + PBXBuildResultsModule + Name + Detailed Build Results Viewer + + + BundleLoadPath + + MaxInstances + 1 + Module + PBXProjectFindModule + Name + Project Batch Find Tool + + + BundleLoadPath + + MaxInstances + n + Module + PBXRunSessionModule + Name + Run Log + + + BundleLoadPath + + MaxInstances + n + Module + PBXBookmarksModule + Name + Bookmarks Tool + + + BundleLoadPath + + MaxInstances + n + Module + PBXClassBrowserModule + Name + Class Browser + + + BundleLoadPath + + MaxInstances + n + Module + PBXCVSModule + Name + Source Code Control Tool + + + BundleLoadPath + + MaxInstances + n + Module + PBXDebugBreakpointsModule + Name + Debug Breakpoints Tool + + + BundleLoadPath + + MaxInstances + n + Module + XCDockableInspector + Name + Inspector + + + BundleLoadPath + + MaxInstances + n + Module + PBXOpenQuicklyModule + Name + Open Quickly Tool + + + BundleLoadPath + + MaxInstances + 1 + Module + PBXDebugSessionModule + Name + Debugger + + + BundleLoadPath + + MaxInstances + 1 + Module + PBXDebugCLIModule + Name + Debug Console + + + Description + DefaultDescriptionKey + DockingSystemVisible + + Extension + mode1 + FavBarConfig + + PBXProjectModuleGUID + F878A30809F3A37400225D95 + XCBarModuleItemNames + + XCBarModuleItems + + + FirstTimeWindowDisplayed + + Identifier + com.apple.perspectives.project.mode1 + MajorVersion + 31 + MinorVersion + 1 + Name + Default + Notifications + + OpenEditors + + PerspectiveWidths + + -1 + -1 + + Perspectives + + + ChosenToolbarItems + + active-target-popup + action + NSToolbarFlexibleSpaceItem + buildOrClean + build-and-runOrDebug + com.apple.ide.PBXToolbarStopButton + get-info + toggle-editor + NSToolbarFlexibleSpaceItem + com.apple.pbx.toolbar.searchfield + + ControllerClassBaseName + + IconName + WindowOfProjectWithEditor + Identifier + perspective.project + IsVertical + + Layout + + + BecomeActive + + ContentConfiguration + + PBXBottomSmartGroupGIDs + + 1C37FBAC04509CD000000102 + 1C37FAAC04509CD000000102 + 1C08E77C0454961000C914BD + 1C37FABC05509CD000000102 + 1C37FABC05539CD112110102 + E2644B35053B69B200211256 + 1C37FABC04509CD000100104 + 1CC0EA4004350EF90044410B + 1CC0EA4004350EF90041110B + + PBXProjectModuleGUID + 1CE0B1FE06471DED0097A5F4 + PBXProjectModuleLabel + Files + PBXProjectStructureProvided + yes + PBXSmartGroupTreeModuleColumnData + + PBXSmartGroupTreeModuleColumnWidthsKey + + 186 + + PBXSmartGroupTreeModuleColumnsKey_v4 + + MainColumn + + + PBXSmartGroupTreeModuleOutlineStateKey_v7 + + PBXSmartGroupTreeModuleOutlineStateExpansionKey + + 08FB7794FE84155DC02AAC07 + F878A31209F3A46500225D95 + F878A31109F3A45600225D95 + F878A31009F3A44A00225D95 + 08FB7795FE84155DC02AAC07 + 1C37FAAC04509CD000000102 + 1C37FABC05509CD000000102 + + PBXSmartGroupTreeModuleOutlineStateSelectionKey + + + 7 + 5 + 0 + + + PBXSmartGroupTreeModuleOutlineStateVisibleRectKey + {{0, 0}, {186, 602}} + + PBXTopSmartGroupGIDs + + XCIncludePerspectivesSwitch + + XCSharingToken + com.apple.Xcode.GFSharingToken + + GeometryConfiguration + + Frame + {{0, 0}, {203, 620}} + GroupTreeTableConfiguration + + MainColumn + 186 + + RubberWindowFrame + 0 85 987 661 0 0 1024 746 + + Module + PBXSmartGroupTreeModule + Proportion + 203pt + + + Dock + + + ContentConfiguration + + PBXProjectModuleGUID + 1CE0B20306471E060097A5F4 + PBXProjectModuleLabel + spfa.H + PBXSplitModuleInNavigatorKey + + Split0 + + PBXProjectModuleGUID + 1CE0B20406471E060097A5F4 + PBXProjectModuleLabel + spfa.H + _historyCapacity + 0 + bookmark + F844881B0C0B4B5000D2870A + history + + F860B0CA09F40B5F0027FF1E + F876431509F7F5E500BAAC93 + F8B74EFF09F9512000D55E52 + F8F48D780A243553009DE375 + F8F48D790A243553009DE375 + F8F48D7B0A243553009DE375 + F8F48D7C0A243553009DE375 + F8F48D7D0A243553009DE375 + F8F48D7F0A243553009DE375 + F8F48D800A243553009DE375 + F8F48D810A243553009DE375 + F8D16C060A2517DD00264622 + F8D93E540B8EE67900D2768C + F896E5800BFB0BC400C659C6 + F896E5810BFB0BC400C659C6 + F896E5820BFB0BC400C659C6 + F896E5830BFB0BC400C659C6 + F896E5840BFB0BC400C659C6 + F84488190C0B4B5000D2870A + F896E5850BFB0BC400C659C6 + + prevStack + + F860B02609F402D50027FF1E + F860B02709F402D50027FF1E + F860B03109F402D50027FF1E + F860B03609F402D50027FF1E + F860B03C09F402D50027FF1E + F860B0D109F40B5F0027FF1E + F860B0D309F40B5F0027FF1E + F860B0D409F40B5F0027FF1E + F860B0D509F40B5F0027FF1E + F860B0D609F40B5F0027FF1E + F860B0D809F40B5F0027FF1E + F80E92B009F4496F00850979 + F80E92B109F4496F00850979 + F80E92B309F4496F00850979 + F871D10509F4E5D7001A8E9E + F871D17609F4F4A6001A8E9E + F871D17709F4F4A6001A8E9E + F871D17F09F4F4A6001A8E9E + F8A1460C09F7E54200584BA4 + F896E5880BFB0BC400C659C6 + F844881A0C0B4B5000D2870A + + + SplitCount + 1 + + StatusBarVisibility + + + GeometryConfiguration + + Frame + {{0, 0}, {779, 423}} + RubberWindowFrame + 0 85 987 661 0 0 1024 746 + + Module + PBXNavigatorGroup + Proportion + 423pt + + + ContentConfiguration + + PBXProjectModuleGUID + 1CE0B20506471E060097A5F4 + PBXProjectModuleLabel + Detail + + GeometryConfiguration + + Frame + {{0, 428}, {779, 192}} + RubberWindowFrame + 0 85 987 661 0 0 1024 746 + + Module + XCDetailModule + Proportion + 192pt + + + Proportion + 779pt + + + Name + Project + ServiceClasses + + XCModuleDock + PBXSmartGroupTreeModule + XCModuleDock + PBXNavigatorGroup + XCDetailModule + + TableOfContents + + F84488170C0AF8E600D2870A + 1CE0B1FE06471DED0097A5F4 + F84488180C0AF8E600D2870A + 1CE0B20306471E060097A5F4 + 1CE0B20506471E060097A5F4 + + ToolbarConfiguration + xcode.toolbar.config.default + + + ControllerClassBaseName + + IconName + WindowOfProject + Identifier + perspective.morph + IsVertical + 0 + Layout + + + BecomeActive + 1 + ContentConfiguration + + PBXBottomSmartGroupGIDs + + 1C37FBAC04509CD000000102 + 1C37FAAC04509CD000000102 + 1C08E77C0454961000C914BD + 1C37FABC05509CD000000102 + 1C37FABC05539CD112110102 + E2644B35053B69B200211256 + 1C37FABC04509CD000100104 + 1CC0EA4004350EF90044410B + 1CC0EA4004350EF90041110B + + PBXProjectModuleGUID + 11E0B1FE06471DED0097A5F4 + PBXProjectModuleLabel + Files + PBXProjectStructureProvided + yes + PBXSmartGroupTreeModuleColumnData + + PBXSmartGroupTreeModuleColumnWidthsKey + + 186 + + PBXSmartGroupTreeModuleColumnsKey_v4 + + MainColumn + + + PBXSmartGroupTreeModuleOutlineStateKey_v7 + + PBXSmartGroupTreeModuleOutlineStateExpansionKey + + 29B97314FDCFA39411CA2CEA + 1C37FABC05509CD000000102 + + PBXSmartGroupTreeModuleOutlineStateSelectionKey + + + 0 + + + PBXSmartGroupTreeModuleOutlineStateVisibleRectKey + {{0, 0}, {186, 337}} + + PBXTopSmartGroupGIDs + + XCIncludePerspectivesSwitch + 1 + XCSharingToken + com.apple.Xcode.GFSharingToken + + GeometryConfiguration + + Frame + {{0, 0}, {203, 355}} + GroupTreeTableConfiguration + + MainColumn + 186 + + RubberWindowFrame + 373 269 690 397 0 0 1440 878 + + Module + PBXSmartGroupTreeModule + Proportion + 100% + + + Name + Morph + PreferredWidth + 300 + ServiceClasses + + XCModuleDock + PBXSmartGroupTreeModule + + TableOfContents + + 11E0B1FE06471DED0097A5F4 + + ToolbarConfiguration + xcode.toolbar.config.default.short + + + PerspectivesBarVisible + + ShelfIsVisible + + SourceDescription + file at '/System/Library/PrivateFrameworks/DevToolsInterface.framework/Versions/A/Resources/XCPerspectivesSpecificationMode1.xcperspec' + StatusbarIsVisible + + TimeStamp + 0.0 + ToolbarDisplayMode + 1 + ToolbarIsVisible + + ToolbarSizeMode + 1 + Type + Perspectives + UpdateMessage + The Default Workspace in this version of Xcode now includes support to hide and show the detail view (what has been referred to as the "Metro-Morph" feature). You must discard your current Default Workspace settings and update to the latest Default Workspace in order to gain this feature. Do you wish to update to the latest Workspace defaults for project '%@'? + WindowJustification + 5 + WindowOrderList + + /Users/esposito/Projets/dees/dees.xcodeproj + + WindowString + 0 85 987 661 0 0 1024 746 + WindowTools + + + FirstTimeWindowDisplayed + + Identifier + windowTool.build + IsVertical + + Layout + + + Dock + + + ContentConfiguration + + PBXProjectModuleGUID + 1CD0528F0623707200166675 + PBXProjectModuleLabel + + StatusBarVisibility + + + GeometryConfiguration + + Frame + {{0, 0}, {1024, 535}} + RubberWindowFrame + 0 60 1024 686 0 0 1024 746 + + Module + PBXNavigatorGroup + Proportion + 535pt + + + ContentConfiguration + + PBXProjectModuleGUID + XCMainBuildResultsModuleGUID + PBXProjectModuleLabel + Build + XCBuildResultsTrigger_Collapse + 1021 + XCBuildResultsTrigger_Open + 1011 + + GeometryConfiguration + + Frame + {{0, 540}, {1024, 105}} + RubberWindowFrame + 0 60 1024 686 0 0 1024 746 + + Module + PBXBuildResultsModule + Proportion + 105pt + + + Proportion + 645pt + + + Name + Build Results + ServiceClasses + + PBXBuildResultsModule + + StatusbarIsVisible + + TableOfContents + + F89BE30609F3A64D008C3386 + F8D16C0D0A2517DD00264622 + 1CD0528F0623707200166675 + XCMainBuildResultsModuleGUID + + ToolbarConfiguration + xcode.toolbar.config.build + WindowString + 0 60 1024 686 0 0 1024 746 + WindowToolGUID + F89BE30609F3A64D008C3386 + WindowToolIsVisible + + + + FirstTimeWindowDisplayed + + Identifier + windowTool.debugger + IsVertical + + Layout + + + Dock + + + ContentConfiguration + + Debugger + + HorizontalSplitView + + _collapsingFrameDimension + 0.0 + _indexOfCollapsedView + 0 + _percentageOfCollapsedView + 0.0 + isCollapsed + yes + sizes + + {{0, 0}, {383, 213}} + {{383, 0}, {498, 213}} + + + VerticalSplitView + + _collapsingFrameDimension + 0.0 + _indexOfCollapsedView + 0 + _percentageOfCollapsedView + 0.0 + isCollapsed + yes + sizes + + {{0, 0}, {881, 213}} + {{0, 213}, {881, 298}} + + + + LauncherConfigVersion + 8 + PBXProjectModuleGUID + 1C162984064C10D400B95A72 + PBXProjectModuleLabel + Debug - GLUTExamples (Underwater) + + GeometryConfiguration + + DebugConsoleDrawerSize + {100, 120} + DebugConsoleVisible + None + DebugConsoleWindowFrame + {{200, 200}, {500, 300}} + DebugSTDIOWindowFrame + {{200, 200}, {500, 300}} + Frame + {{0, 0}, {881, 511}} + RubberWindowFrame + 68 147 881 552 0 0 1024 746 + + Module + PBXDebugSessionModule + Proportion + 511pt + + + Proportion + 511pt + + + Name + Debugger + ServiceClasses + + PBXDebugSessionModule + + StatusbarIsVisible + + TableOfContents + + 1CD10A99069EF8BA00B06720 + F871D19009F4F510001A8E9E + 1C162984064C10D400B95A72 + F871D19109F4F510001A8E9E + F871D19209F4F510001A8E9E + F871D19309F4F510001A8E9E + F871D19409F4F510001A8E9E + F871D19509F4F510001A8E9E + F871D19609F4F510001A8E9E + + ToolbarConfiguration + xcode.toolbar.config.debug + WindowString + 68 147 881 552 0 0 1024 746 + WindowToolGUID + 1CD10A99069EF8BA00B06720 + WindowToolIsVisible + + + + Identifier + windowTool.find + Layout + + + Dock + + + Dock + + + ContentConfiguration + + PBXProjectModuleGUID + 1CDD528C0622207200134675 + PBXProjectModuleLabel + <No Editor> + PBXSplitModuleInNavigatorKey + + Split0 + + PBXProjectModuleGUID + 1CD0528D0623707200166675 + + SplitCount + 1 + + StatusBarVisibility + 1 + + GeometryConfiguration + + Frame + {{0, 0}, {781, 167}} + RubberWindowFrame + 62 385 781 470 0 0 1440 878 + + Module + PBXNavigatorGroup + Proportion + 781pt + + + Proportion + 50% + + + BecomeActive + 1 + ContentConfiguration + + PBXProjectModuleGUID + 1CD0528E0623707200166675 + PBXProjectModuleLabel + Project Find + + GeometryConfiguration + + Frame + {{8, 0}, {773, 254}} + RubberWindowFrame + 62 385 781 470 0 0 1440 878 + + Module + PBXProjectFindModule + Proportion + 50% + + + Proportion + 428pt + + + Name + Project Find + ServiceClasses + + PBXProjectFindModule + + StatusbarIsVisible + 1 + TableOfContents + + 1C530D57069F1CE1000CFCEE + 1C530D58069F1CE1000CFCEE + 1C530D59069F1CE1000CFCEE + 1CDD528C0622207200134675 + 1C530D5A069F1CE1000CFCEE + 1CE0B1FE06471DED0097A5F4 + 1CD0528E0623707200166675 + + WindowString + 62 385 781 470 0 0 1440 878 + WindowToolGUID + 1C530D57069F1CE1000CFCEE + WindowToolIsVisible + 0 + + + Identifier + MENUSEPARATOR + + + FirstTimeWindowDisplayed + + Identifier + windowTool.debuggerConsole + IsVertical + + Layout + + + Dock + + + BecomeActive + + ContentConfiguration + + PBXProjectModuleGUID + 1C78EAAC065D492600B07095 + PBXProjectModuleLabel + Debugger Console + + GeometryConfiguration + + Frame + {{0, 0}, {440, 358}} + RubberWindowFrame + 42 300 440 400 0 0 1024 746 + + Module + PBXDebugCLIModule + Proportion + 358pt + + + Proportion + 359pt + + + Name + Debugger Console + ServiceClasses + + PBXDebugCLIModule + + StatusbarIsVisible + + TableOfContents + + F871D19709F4F510001A8E9E + F871D19809F4F510001A8E9E + 1C78EAAC065D492600B07095 + + WindowString + 42 300 440 400 0 0 1024 746 + WindowToolGUID + F871D19709F4F510001A8E9E + WindowToolIsVisible + + + + FirstTimeWindowDisplayed + + Identifier + windowTool.run + IsVertical + + Layout + + + Dock + + + ContentConfiguration + + LauncherConfigVersion + 3 + PBXProjectModuleGUID + 1CD0528B0623707200166675 + PBXProjectModuleLabel + Run + Runner + + HorizontalSplitView + + _collapsingFrameDimension + 0.0 + _indexOfCollapsedView + 0 + _percentageOfCollapsedView + 0.0 + isCollapsed + yes + sizes + + {{0, 0}, {367, 168}} + {{0, 173}, {367, 270}} + + + VerticalSplitView + + _collapsingFrameDimension + 0.0 + _indexOfCollapsedView + 0 + _percentageOfCollapsedView + 0.0 + isCollapsed + yes + sizes + + {{0, 0}, {406, 443}} + {{411, 0}, {517, 443}} + + + + + GeometryConfiguration + + Frame + {{0, 0}, {459, 159}} + RubberWindowFrame + 89 476 459 200 0 0 1024 746 + + Module + PBXRunSessionModule + Proportion + 159pt + + + Proportion + 159pt + + + Name + Run Log + ServiceClasses + + PBXRunSessionModule + + StatusbarIsVisible + + TableOfContents + + 1C0AD2B3069F1EA900FABCE6 + F871D1A609F503B3001A8E9E + 1CD0528B0623707200166675 + F871D1A709F503B3001A8E9E + + ToolbarConfiguration + xcode.toolbar.config.run + WindowString + 89 476 459 200 0 0 1024 746 + WindowToolGUID + 1C0AD2B3069F1EA900FABCE6 + WindowToolIsVisible + + + + Identifier + windowTool.scm + Layout + + + Dock + + + ContentConfiguration + + PBXProjectModuleGUID + 1C78EAB2065D492600B07095 + PBXProjectModuleLabel + <No Editor> + PBXSplitModuleInNavigatorKey + + Split0 + + PBXProjectModuleGUID + 1C78EAB3065D492600B07095 + + SplitCount + 1 + + StatusBarVisibility + 1 + + GeometryConfiguration + + Frame + {{0, 0}, {452, 0}} + RubberWindowFrame + 743 379 452 308 0 0 1280 1002 + + Module + PBXNavigatorGroup + Proportion + 0pt + + + BecomeActive + 1 + ContentConfiguration + + PBXProjectModuleGUID + 1CD052920623707200166675 + PBXProjectModuleLabel + SCM + + GeometryConfiguration + + ConsoleFrame + {{0, 259}, {452, 0}} + Frame + {{0, 7}, {452, 259}} + RubberWindowFrame + 743 379 452 308 0 0 1280 1002 + TableConfiguration + + Status + 30 + FileName + 199 + Path + 197.09500122070312 + + TableFrame + {{0, 0}, {452, 250}} + + Module + PBXCVSModule + Proportion + 262pt + + + Proportion + 266pt + + + Name + SCM + ServiceClasses + + PBXCVSModule + + StatusbarIsVisible + 1 + TableOfContents + + 1C78EAB4065D492600B07095 + 1C78EAB5065D492600B07095 + 1C78EAB2065D492600B07095 + 1CD052920623707200166675 + + ToolbarConfiguration + xcode.toolbar.config.scm + WindowString + 743 379 452 308 0 0 1280 1002 + + + Identifier + windowTool.breakpoints + IsVertical + 0 + Layout + + + Dock + + + BecomeActive + 1 + ContentConfiguration + + PBXBottomSmartGroupGIDs + + 1C77FABC04509CD000000102 + + PBXProjectModuleGUID + 1CE0B1FE06471DED0097A5F4 + PBXProjectModuleLabel + Files + PBXProjectStructureProvided + no + PBXSmartGroupTreeModuleColumnData + + PBXSmartGroupTreeModuleColumnWidthsKey + + 168 + + PBXSmartGroupTreeModuleColumnsKey_v4 + + MainColumn + + + PBXSmartGroupTreeModuleOutlineStateKey_v7 + + PBXSmartGroupTreeModuleOutlineStateExpansionKey + + 1C77FABC04509CD000000102 + + PBXSmartGroupTreeModuleOutlineStateSelectionKey + + + 0 + + + PBXSmartGroupTreeModuleOutlineStateVisibleRectKey + {{0, 0}, {168, 350}} + + PBXTopSmartGroupGIDs + + XCIncludePerspectivesSwitch + 0 + + GeometryConfiguration + + Frame + {{0, 0}, {185, 368}} + GroupTreeTableConfiguration + + MainColumn + 168 + + RubberWindowFrame + 315 424 744 409 0 0 1440 878 + + Module + PBXSmartGroupTreeModule + Proportion + 185pt + + + ContentConfiguration + + PBXProjectModuleGUID + 1CA1AED706398EBD00589147 + PBXProjectModuleLabel + Detail + + GeometryConfiguration + + Frame + {{190, 0}, {554, 368}} + RubberWindowFrame + 315 424 744 409 0 0 1440 878 + + Module + XCDetailModule + Proportion + 554pt + + + Proportion + 368pt + + + MajorVersion + 2 + MinorVersion + 0 + Name + Breakpoints + ServiceClasses + + PBXSmartGroupTreeModule + XCDetailModule + + StatusbarIsVisible + 1 + TableOfContents + + 1CDDB66807F98D9800BB5817 + 1CDDB66907F98D9800BB5817 + 1CE0B1FE06471DED0097A5F4 + 1CA1AED706398EBD00589147 + + ToolbarConfiguration + xcode.toolbar.config.breakpoints + WindowString + 315 424 744 409 0 0 1440 878 + WindowToolGUID + 1CDDB66807F98D9800BB5817 + WindowToolIsVisible + 1 + + + FirstTimeWindowDisplayed + + Identifier + windowTool.debugAnimator + IsVertical + + Layout + + + Dock + + + ContentConfiguration + + PBXProjectModuleGUID + F871D19C09F4F52D001A8E9E + PBXProjectModuleLabel + + StatusBarVisibility + + + GeometryConfiguration + + Frame + {{0, 0}, {700, 459}} + RubberWindowFrame + 42 200 700 500 0 0 1024 746 + + Module + PBXNavigatorGroup + Proportion + 459pt + + + Proportion + 459pt + + + Name + Debug Visualizer + ServiceClasses + + PBXNavigatorGroup + + StatusbarIsVisible + + TableOfContents + + F871D19E09F4F52D001A8E9E + F871D19F09F4F52D001A8E9E + F871D19C09F4F52D001A8E9E + + ToolbarConfiguration + xcode.toolbar.config.debugAnimator + WindowString + 42 200 700 500 0 0 1024 746 + WindowToolGUID + F871D19E09F4F52D001A8E9E + WindowToolIsVisible + + + + Identifier + windowTool.bookmarks + Layout + + + Dock + + + Module + PBXBookmarksModule + Proportion + 100% + + + Proportion + 100% + + + Name + Bookmarks + ServiceClasses + + PBXBookmarksModule + + StatusbarIsVisible + 0 + WindowString + 538 42 401 187 0 0 1280 1002 + + + FirstTimeWindowDisplayed + + Identifier + windowTool.classBrowser + IsVertical + + Layout + + + Dock + + + ContentConfiguration + + OptionsSetName + Hierarchy, all classes + PBXProjectModuleGUID + 1CA6456E063B45B4001379D8 + PBXProjectModuleLabel + Class Browser - MA + + GeometryConfiguration + + ClassesFrame + {{0, 0}, {378, 96}} + ClassesTreeTableConfiguration + + PBXClassNameColumnIdentifier + 208 + PBXClassBookColumnIdentifier + 22 + + Frame + {{0, 0}, {630, 332}} + MembersFrame + {{0, 101}, {378, 231}} + MembersTreeTableConfiguration + + PBXMemberTypeIconColumnIdentifier + 22 + PBXMemberNameColumnIdentifier + 216 + PBXMemberTypeColumnIdentifier + 101 + PBXMemberBookColumnIdentifier + 22 + + RubberWindowFrame + 21 371 630 352 0 0 1024 746 + + Module + PBXClassBrowserModule + Proportion + 332pt + + + Proportion + 332pt + + + Name + Class Browser + ServiceClasses + + PBXClassBrowserModule + + StatusbarIsVisible + + TableOfContents + + 1C0AD2AF069F1E9B00FABCE6 + F8F48D6C0A2433FC009DE375 + 1CA6456E063B45B4001379D8 + + ToolbarConfiguration + xcode.toolbar.config.classbrowser + WindowString + 21 371 630 352 0 0 1024 746 + WindowToolGUID + 1C0AD2AF069F1E9B00FABCE6 + WindowToolIsVisible + + + + + diff --git a/dees.xcodeproj/esposito.pbxuser b/dees.xcodeproj/esposito.pbxuser new file mode 100644 index 0000000..c9b6237 --- /dev/null +++ b/dees.xcodeproj/esposito.pbxuser @@ -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 = "<>"; + }; + 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; + }; +} diff --git a/dees.xcodeproj/project.pbxproj b/dees.xcodeproj/project.pbxproj new file mode 100644 index 0000000..4fca345 --- /dev/null +++ b/dees.xcodeproj/project.pbxproj @@ -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 = ""; }; + 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 = ""; }; + F860AF3809F3D8430027FF1E /* simplex.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = simplex.cpp; sourceTree = ""; }; + F871D15409F4F14C001A8E9E /* pprfa_dees.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = pprfa_dees.cpp; sourceTree = ""; }; + F871D16009F4F3D6001A8E9E /* pprfa_bm.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = pprfa_bm.cpp; sourceTree = ""; }; + F878A31309F3A48B00225D95 /* test.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = test.cpp; sourceTree = ""; }; + F878A31409F3A48B00225D95 /* spfa.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = spfa.cpp; sourceTree = ""; }; + F878A31609F3A48B00225D95 /* sample.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = sample.cpp; sourceTree = ""; }; + F878A31709F3A48B00225D95 /* pprfa.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = pprfa.cpp; sourceTree = ""; }; + F878A31809F3A48B00225D95 /* pfa.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = pfa.cpp; sourceTree = ""; }; + F878A31909F3A48B00225D95 /* ma.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ma.cpp; sourceTree = ""; }; + F878A31A09F3A48B00225D95 /* interface.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = interface.cpp; sourceTree = ""; }; + F878A32309F3A4A100225D95 /* test.H */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = test.H; sourceTree = ""; }; + F878A32409F3A4A100225D95 /* spfa.H */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = spfa.H; sourceTree = ""; }; + F878A32509F3A4A100225D95 /* simplex.H */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = simplex.H; sourceTree = ""; }; + F878A32609F3A4A100225D95 /* sample.H */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = sample.H; sourceTree = ""; }; + F878A32709F3A4A100225D95 /* pprfa.H */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = pprfa.H; sourceTree = ""; }; + F878A32809F3A4A100225D95 /* pfa.H */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = pfa.H; sourceTree = ""; }; + F878A32909F3A4A100225D95 /* main.H */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = main.H; sourceTree = ""; }; + F878A32A09F3A4A100225D95 /* ma.H */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = ma.H; sourceTree = ""; }; + F878A32B09F3A4A100225D95 /* interface.H */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = interface.H; sourceTree = ""; }; + F878A32C09F3A4A100225D95 /* general.H */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = general.H; sourceTree = ""; }; + F878A33709F3A4B700225D95 /* liblpsolve55.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = liblpsolve55.a; path = lib/liblpsolve55.a; sourceTree = ""; }; + F878A33909F3A4D200225D95 /* lp_lib.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = lp_lib.h; path = include/lp_lib.h; sourceTree = ""; }; +/* 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 = ""; + }; + 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 = ""; + }; + 1AB674ADFE9D54B511CA2CBB /* Products */ = { + isa = PBXGroup; + children = ( + 8DD76F6C0486A84900D96B5E /* dees */, + ); + name = Products; + sourceTree = ""; + }; + C6859E8C029090F304C91782 /* Documentation */ = { + isa = PBXGroup; + children = ( + C6859E8B029090EE04C91782 /* dees.1 */, + ); + name = Documentation; + sourceTree = ""; + }; + 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 = ""; + }; + F878A31109F3A45600225D95 /* lib */ = { + isa = PBXGroup; + children = ( + F878A33709F3A4B700225D95 /* liblpsolve55.a */, + ); + name = lib; + sourceTree = ""; + }; + F878A31209F3A46500225D95 /* include */ = { + isa = PBXGroup; + children = ( + F878A33909F3A4D200225D95 /* lp_lib.h */, + ); + name = include; + sourceTree = ""; + }; +/* 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 */; +} diff --git a/general.H b/general.H new file mode 100644 index 0000000..c5c308d --- /dev/null +++ b/general.H @@ -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 +#include +#include +//#include +//#include +#include // pour cout << +#include // pour fic << +#include + +// ------------- 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 + +namespace hmext +{ +using ::hash_map; +} +; // inherit globals +#else + #include + #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 diff --git a/help/help.txt b/help/help.txt new file mode 100644 index 0000000..ca4576e --- /dev/null +++ b/help/help.txt @@ -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 diff --git a/include/declare.h b/include/declare.h new file mode 100644 index 0000000..fba1794 --- /dev/null +++ b/include/declare.h @@ -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 diff --git a/include/fortify.h b/include/fortify.h new file mode 100644 index 0000000..dd9b2db --- /dev/null +++ b/include/fortify.h @@ -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 + +#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__ */ diff --git a/include/ini.h b/include/ini.h new file mode 100644 index 0000000..bab76b5 --- /dev/null +++ b/include/ini.h @@ -0,0 +1,9 @@ +#include + +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); diff --git a/include/lp_Hash.h b/include/lp_Hash.h new file mode 100644 index 0000000..d93a741 --- /dev/null +++ b/include/lp_Hash.h @@ -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 */ + diff --git a/include/lp_MDO.h b/include/lp_MDO.h new file mode 100644 index 0000000..8475363 --- /dev/null +++ b/include/lp_MDO.h @@ -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 */ + diff --git a/include/lp_MPS.h b/include/lp_MPS.h new file mode 100644 index 0000000..218ed92 --- /dev/null +++ b/include/lp_MPS.h @@ -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 */ + diff --git a/include/lp_SOS.h b/include/lp_SOS.h new file mode 100644 index 0000000..27df12c --- /dev/null +++ b/include/lp_SOS.h @@ -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 */ diff --git a/include/lp_crash.h b/include/lp_crash.h new file mode 100644 index 0000000..9eb1760 --- /dev/null +++ b/include/lp_crash.h @@ -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 */ + diff --git a/include/lp_explicit.h b/include/lp_explicit.h new file mode 100644 index 0000000..e004b75 --- /dev/null +++ b/include/lp_explicit.h @@ -0,0 +1,1016 @@ +#include "lp_lib.h" + +/* entries for lp structure */ +add_column_func *_add_column; +add_columnex_func *_add_columnex; +add_constraint_func *_add_constraint; +add_constraintex_func *_add_constraintex; +add_lag_con_func *_add_lag_con; +add_SOS_func *_add_SOS; +column_in_lp_func *_column_in_lp; +copy_lp_func *_copy_lp; +default_basis_func *_default_basis; +del_column_func *_del_column; +del_constraint_func *_del_constraint; +delete_lp_func *_delete_lp; +dualize_lp_func *_dualize_lp; +free_lp_func *_free_lp; +get_anti_degen_func *_get_anti_degen; +get_basis_func *_get_basis; +get_basiscrash_func *_get_basiscrash; +get_bb_depthlimit_func *_get_bb_depthlimit; +get_bb_floorfirst_func *_get_bb_floorfirst; +get_bb_rule_func *_get_bb_rule; +get_bounds_tighter_func *_get_bounds_tighter; +get_break_at_value_func *_get_break_at_value; +get_col_name_func *_get_col_name; +get_columnex_func *_get_columnex; +get_constr_type_func *_get_constr_type; +get_constr_value_func *_get_constr_value; +get_constraints_func *_get_constraints; +get_dual_solution_func *_get_dual_solution; +get_epsb_func *_get_epsb; +get_epsd_func *_get_epsd; +get_epsel_func *_get_epsel; +get_epsint_func *_get_epsint; +get_epsperturb_func *_get_epsperturb; +get_epspivot_func *_get_epspivot; +get_improve_func *_get_improve; +get_infinite_func *_get_infinite; +get_lambda_func *_get_lambda; +get_lowbo_func *_get_lowbo; +get_lp_index_func *_get_lp_index; +get_lp_name_func *_get_lp_name; +get_Lrows_func *_get_Lrows; +get_mat_func *_get_mat; +get_mat_byindex_func *_get_mat_byindex; +get_max_level_func *_get_max_level; +get_maxpivot_func *_get_maxpivot; +get_mip_gap_func *_get_mip_gap; +get_multiprice_func *_get_multiprice; +get_nameindex_func *_get_nameindex; +get_Ncolumns_func *_get_Ncolumns; +get_negrange_func *_get_negrange; +get_nz_func *_get_nonzeros; +get_Norig_columns_func *_get_Norig_columns; +get_Norig_rows_func *_get_Norig_rows; +get_Nrows_func *_get_Nrows; +get_obj_bound_func *_get_obj_bound; +get_objective_func *_get_objective; +get_orig_index_func *_get_orig_index; +get_origcol_name_func *_get_origcol_name; +get_origrow_name_func *_get_origrow_name; +get_partialprice_func *_get_partialprice; +get_pivoting_func *_get_pivoting; +get_presolve_func *_get_presolve; +get_presolveloops_func *_get_presolveloops; +get_primal_solution_func *_get_primal_solution; +get_print_sol_func *_get_print_sol; +get_pseudocosts_func *_get_pseudocosts; +get_ptr_constraints_func *_get_ptr_constraints; +get_ptr_dual_solution_func *_get_ptr_dual_solution; +get_ptr_lambda_func *_get_ptr_lambda; +get_ptr_primal_solution_func *_get_ptr_primal_solution; +get_ptr_sensitivity_obj_func *_get_ptr_sensitivity_obj; +get_ptr_sensitivity_objex_func *_get_ptr_sensitivity_objex; +get_ptr_sensitivity_rhs_func *_get_ptr_sensitivity_rhs; +get_ptr_variables_func *_get_ptr_variables; +get_rh_func *_get_rh; +get_rh_range_func *_get_rh_range; +get_row_func *_get_row; +get_row_name_func *_get_row_name; +get_scalelimit_func *_get_scalelimit; +get_scaling_func *_get_scaling; +get_sensitivity_obj_func *_get_sensitivity_obj; +get_sensitivity_objex_func *_get_sensitivity_objex; +get_sensitivity_rhs_func *_get_sensitivity_rhs; +get_simplextype_func *_get_simplextype; +get_solutioncount_func *_get_solutioncount; +get_solutionlimit_func *_get_solutionlimit; +get_status_func *_get_status; +get_statustext_func *_get_statustext; +get_timeout_func *_get_timeout; +get_total_iter_func *_get_total_iter; +get_total_nodes_func *_get_total_nodes; +get_upbo_func *_get_upbo; +get_var_branch_func *_get_var_branch; +get_var_dualresult_func *_get_var_dualresult; +get_var_primalresult_func *_get_var_primalresult; +get_var_priority_func *_get_var_priority; +get_variables_func *_get_variables; +get_verbose_func *_get_verbose; +get_working_objective_func *_get_working_objective; +has_BFP_func *_has_BFP; +has_XLI_func *_has_XLI; +is_add_rowmode_func *_is_add_rowmode; +is_anti_degen_func *_is_anti_degen; +is_binary_func *_is_binary; +is_break_at_first_func *_is_break_at_first; +is_constr_type_func *_is_constr_type; +is_debug_func *_is_debug; +is_feasible_func *_is_feasible; +is_unbounded_func *_is_unbounded; +is_infinite_func *_is_infinite; +is_int_func *_is_int; +is_integerscaling_func *_is_integerscaling; +is_lag_trace_func *_is_lag_trace; +is_maxim_func *_is_maxim; +is_nativeBFP_func *_is_nativeBFP; +is_nativeXLI_func *_is_nativeXLI; +is_negative_func *_is_negative; +is_piv_mode_func *_is_piv_mode; +is_piv_rule_func *_is_piv_rule; +is_presolve_func *_is_presolve; +is_scalemode_func *_is_scalemode; +is_scaletype_func *_is_scaletype; +is_semicont_func *_is_semicont; +is_SOS_var_func *_is_SOS_var; +is_trace_func *_is_trace; +lp_solve_version_func *_lp_solve_version; +make_lp_func *_make_lp; +print_constraints_func *_print_constraints; +print_debugdump_func *_print_debugdump; +print_duals_func *_print_duals; +print_lp_func *_print_lp; +print_objective_func *_print_objective; +print_scales_func *_print_scales; +print_solution_func *_print_solution; +print_str_func *_print_str; +print_tableau_func *_print_tableau; +put_abortfunc_func *_put_abortfunc; +put_bb_nodefunc_func *_put_bb_nodefunc; +put_bb_branchfunc_func *_put_bb_branchfunc; +put_logfunc_func *_put_logfunc; +put_msgfunc_func *_put_msgfunc; +read_LPhandle_func *_read_LPhandle; +read_MPShandle_func *_read_MPShandle; +read_XLI_func *_read_XLI; +read_params_func *_read_params; +read_basis_func *_read_basis; +reset_basis_func *_reset_basis; +reset_params_func *_reset_params; +resize_lp_func *_resize_lp; +set_add_rowmode_func *_set_add_rowmode; +set_anti_degen_func *_set_anti_degen; +set_basisvar_func *_set_basisvar; +set_basis_func *_set_basis; +set_basiscrash_func *_set_basiscrash; +set_bb_depthlimit_func *_set_bb_depthlimit; +set_bb_floorfirst_func *_set_bb_floorfirst; +set_bb_rule_func *_set_bb_rule; +set_BFP_func *_set_BFP; +set_binary_func *_set_binary; +set_bounds_func *_set_bounds; +set_bounds_tighter_func *_set_bounds_tighter; +set_break_at_first_func *_set_break_at_first; +set_break_at_value_func *_set_break_at_value; +set_column_func *_set_column; +set_columnex_func *_set_columnex; +set_col_name_func *_set_col_name; +set_constr_type_func *_set_constr_type; +set_debug_func *_set_debug; +set_epsb_func *_set_epsb; +set_epsd_func *_set_epsd; +set_epsel_func *_set_epsel; +set_epsint_func *_set_epsint; +set_epslevel_func *_set_epslevel; +set_epsperturb_func *_set_epsperturb; +set_epspivot_func *_set_epspivot; +set_unbounded_func *_set_unbounded; +set_improve_func *_set_improve; +set_infinite_func *_set_infinite; +set_int_func *_set_int; +set_lag_trace_func *_set_lag_trace; +set_lowbo_func *_set_lowbo; +set_lp_name_func *_set_lp_name; +set_mat_func *_set_mat; +set_maxim_func *_set_maxim; +set_maxpivot_func *_set_maxpivot; +set_minim_func *_set_minim; +set_mip_gap_func *_set_mip_gap; +set_multiprice_func *_set_multiprice; +set_negrange_func *_set_negrange; +set_obj_bound_func *_set_obj_bound; +set_obj_fn_func *_set_obj_fn; +set_obj_fnex_func *_set_obj_fnex; +set_obj_func *_set_obj; +set_outputfile_func *_set_outputfile; +set_outputstream_func *_set_outputstream; +set_partialprice_func *_set_partialprice; +set_pivoting_func *_set_pivoting; +set_preferdual_func *_set_preferdual; +set_presolve_func *_set_presolve; +set_print_sol_func *_set_print_sol; +set_pseudocosts_func *_set_pseudocosts; +set_rh_func *_set_rh; +set_rh_range_func *_set_rh_range; +set_rh_vec_func *_set_rh_vec; +set_row_func *_set_row; +set_rowex_func *_set_rowex; +set_row_name_func *_set_row_name; +set_scalelimit_func *_set_scalelimit; +set_scaling_func *_set_scaling; +set_semicont_func *_set_semicont; +set_sense_func *_set_sense; +set_simplextype_func *_set_simplextype; +set_solutionlimit_func *_set_solutionlimit; +set_timeout_func *_set_timeout; +set_trace_func *_set_trace; +set_upbo_func *_set_upbo; +set_var_branch_func *_set_var_branch; +set_var_weights_func *_set_var_weights; +set_verbose_func *_set_verbose; +set_XLI_func *_set_XLI; +solve_func *_solve; +str_add_column_func *_str_add_column; +str_add_constraint_func *_str_add_constraint; +str_add_lag_con_func *_str_add_lag_con; +str_set_obj_fn_func *_str_set_obj_fn; +str_set_rh_vec_func *_str_set_rh_vec; +time_elapsed_func *_time_elapsed; +unscale_func *_unscale; +write_lp_func *_write_lp; +write_LP_func *_write_LP; +write_mps_func *_write_mps; +write_MPS_func *_write_MPS; +write_freemps_func *_write_freemps; +write_freeMPS_func *_write_freeMPS; +write_XLI_func *_write_XLI; +write_basis_func *_write_basis; +write_params_func *_write_params; + +#if defined LPSOLVEAPIFROMLPREC + +static int init_lpsolve(lprec *lp) +{ + _add_column = lp->add_column; + _add_columnex = lp->add_columnex; + _add_constraint = lp->add_constraint; + _add_constraintex = lp->add_constraintex; + _add_lag_con = lp->add_lag_con; + _add_SOS = lp->add_SOS; + _column_in_lp = lp->column_in_lp; + _copy_lp = lp->copy_lp; + _default_basis = lp->default_basis; + _del_column = lp->del_column; + _del_constraint = lp->del_constraint; + _delete_lp = lp->delete_lp; + _dualize_lp = lp->dualize_lp; + _free_lp = lp->free_lp; + _get_anti_degen = lp->get_anti_degen; + _get_basis = lp->get_basis; + _get_basiscrash = lp->get_basiscrash; + _get_bb_depthlimit = lp->get_bb_depthlimit; + _get_bb_floorfirst = lp->get_bb_floorfirst; + _get_bb_rule = lp->get_bb_rule; + _get_bounds_tighter = lp->get_bounds_tighter; + _get_break_at_value = lp->get_break_at_value; + _get_col_name = lp->get_col_name; + _get_columnex = lp->get_columnex; + _get_constr_type = lp->get_constr_type; + _get_constr_value = lp->get_constr_value; + _get_constraints = lp->get_constraints; + _get_dual_solution = lp->get_dual_solution; + _get_epsb = lp->get_epsb; + _get_epsd = lp->get_epsd; + _get_epsel = lp->get_epsel; + _get_epsint = lp->get_epsint; + _get_epsperturb = lp->get_epsperturb; + _get_epspivot = lp->get_epspivot; + _get_improve = lp->get_improve; + _get_infinite = lp->get_infinite; + _get_lambda = lp->get_lambda; + _get_lowbo = lp->get_lowbo; + _get_lp_index = lp->get_lp_index; + _get_lp_name = lp->get_lp_name; + _get_Lrows = lp->get_Lrows; + _get_mat = lp->get_mat; + _get_mat_byindex = lp->get_mat_byindex; + _get_max_level = lp->get_max_level; + _get_maxpivot = lp->get_maxpivot; + _get_mip_gap = lp->get_mip_gap; + _get_multiprice = lp->get_multiprice; + _get_nameindex = lp->get_nameindex; + _get_Ncolumns = lp->get_Ncolumns; + _get_negrange = lp->get_negrange; + _get_nonzeros = lp->get_nonzeros; + _get_Norig_columns = lp->get_Norig_columns; + _get_Norig_rows = lp->get_Norig_rows; + _get_Nrows = lp->get_Nrows; + _get_obj_bound = lp->get_obj_bound; + _get_objective = lp->get_objective; + _get_orig_index = lp->get_orig_index; + _get_origcol_name = lp->get_origcol_name; + _get_origrow_name = lp->get_origrow_name; + _get_partialprice = lp->get_partialprice; + _get_pivoting = lp->get_pivoting; + _get_presolve = lp->get_presolve; + _get_presolveloops = lp->get_presolveloops; + _get_primal_solution = lp->get_primal_solution; + _get_print_sol = lp->get_print_sol; + _get_pseudocosts = lp->get_pseudocosts; + _get_ptr_constraints = lp->get_ptr_constraints; + _get_ptr_dual_solution = lp->get_ptr_dual_solution; + _get_ptr_lambda = lp->get_ptr_lambda; + _get_ptr_primal_solution = lp->get_ptr_primal_solution; + _get_ptr_sensitivity_obj = lp->get_ptr_sensitivity_obj; + _get_ptr_sensitivity_objex = lp->get_ptr_sensitivity_objex; + _get_ptr_sensitivity_rhs = lp->get_ptr_sensitivity_rhs; + _get_ptr_variables = lp->get_ptr_variables; + _get_rh = lp->get_rh; + _get_rh_range = lp->get_rh_range; + _get_row = lp->get_row; + _get_row_name = lp->get_row_name; + _get_scalelimit = lp->get_scalelimit; + _get_scaling = lp->get_scaling; + _get_sensitivity_obj = lp->get_sensitivity_obj; + _get_sensitivity_objex = lp->get_sensitivity_objex; + _get_sensitivity_rhs = lp->get_sensitivity_rhs; + _get_simplextype = lp->get_simplextype; + _get_solutioncount = lp->get_solutioncount; + _get_solutionlimit = lp->get_solutionlimit; + _get_status = lp->get_status; + _get_statustext = lp->get_statustext; + _get_timeout = lp->get_timeout; + _get_total_iter = lp->get_total_iter; + _get_total_nodes = lp->get_total_nodes; + _get_upbo = lp->get_upbo; + _get_var_branch = lp->get_var_branch; + _get_var_dualresult = lp->get_var_dualresult; + _get_var_primalresult = lp->get_var_primalresult; + _get_var_priority = lp->get_var_priority; + _get_variables = lp->get_variables; + _get_verbose = lp->get_verbose; + _get_working_objective = lp->get_working_objective; + _has_BFP = lp->has_BFP; + _has_XLI = lp->has_XLI; + _is_add_rowmode = lp->is_add_rowmode; + _is_anti_degen = lp->is_anti_degen; + _is_binary = lp->is_binary; + _is_break_at_first = lp->is_break_at_first; + _is_constr_type = lp->is_constr_type; + _is_debug = lp->is_debug; + _is_feasible = lp->is_feasible; + _is_unbounded = lp->is_unbounded; + _is_infinite = lp->is_infinite; + _is_int = lp->is_int; + _is_integerscaling = lp->is_integerscaling; + _is_lag_trace = lp->is_lag_trace; + _is_maxim = lp->is_maxim; + _is_nativeBFP = lp->is_nativeBFP; + _is_nativeXLI = lp->is_nativeXLI; + _is_negative = lp->is_negative; + _is_piv_mode = lp->is_piv_mode; + _is_piv_rule = lp->is_piv_rule; + _is_presolve = lp->is_presolve; + _is_scalemode = lp->is_scalemode; + _is_scaletype = lp->is_scaletype; + _is_semicont = lp->is_semicont; + _is_SOS_var = lp->is_SOS_var; + _is_trace = lp->is_trace; + _lp_solve_version = lp->lp_solve_version; + _make_lp = lp->make_lp; + _print_constraints = lp->print_constraints; + _print_debugdump = lp->print_debugdump; + _print_duals = lp->print_duals; + _print_lp = lp->print_lp; + _print_objective = lp->print_objective; + _print_scales = lp->print_scales; + _print_solution = lp->print_solution; + _print_str = lp->print_str; + _print_tableau = lp->print_tableau; + _put_abortfunc = lp->put_abortfunc; + _put_bb_nodefunc = lp->put_bb_nodefunc; + _put_bb_branchfunc = lp->put_bb_branchfunc; + _put_logfunc = lp->put_logfunc; + _put_msgfunc = lp->put_msgfunc; + _read_LPhandle = lp->read_LPhandle; + _read_MPShandle = lp->read_MPShandle; + _read_XLI = lp->read_XLI; + _read_params = lp->read_params; + _read_basis = lp->read_basis; + _reset_basis = lp->reset_basis; + _reset_params = lp->reset_params; + _resize_lp = lp->resize_lp; + _set_add_rowmode = lp->set_add_rowmode; + _set_anti_degen = lp->set_anti_degen; + _set_basisvar = lp->set_basisvar; + _set_basis = lp->set_basis; + _set_basiscrash = lp->set_basiscrash; + _set_bb_depthlimit = lp->set_bb_depthlimit; + _set_bb_floorfirst = lp->set_bb_floorfirst; + _set_bb_rule = lp->set_bb_rule; + _set_BFP = lp->set_BFP; + _set_binary = lp->set_binary; + _set_bounds = lp->set_bounds; + _set_bounds_tighter = lp->set_bounds_tighter; + _set_break_at_first = lp->set_break_at_first; + _set_break_at_value = lp->set_break_at_value; + _set_column = lp->set_column; + _set_columnex = lp->set_columnex; + _set_col_name = lp->set_col_name; + _set_constr_type = lp->set_constr_type; + _set_debug = lp->set_debug; + _set_epsb = lp->set_epsb; + _set_epsd = lp->set_epsd; + _set_epsel = lp->set_epsel; + _set_epsint = lp->set_epsint; + _set_epslevel = lp->set_epslevel; + _set_epsperturb = lp->set_epsperturb; + _set_epspivot = lp->set_epspivot; + _set_unbounded = lp->set_unbounded; + _set_improve = lp->set_improve; + _set_infinite = lp->set_infinite; + _set_int = lp->set_int; + _set_lag_trace = lp->set_lag_trace; + _set_lowbo = lp->set_lowbo; + _set_lp_name = lp->set_lp_name; + _set_mat = lp->set_mat; + _set_maxim = lp->set_maxim; + _set_maxpivot = lp->set_maxpivot; + _set_minim = lp->set_minim; + _set_mip_gap = lp->set_mip_gap; + _set_multiprice = lp->set_multiprice; + _set_negrange = lp->set_negrange; + _set_obj_bound = lp->set_obj_bound; + _set_obj_fn = lp->set_obj_fn; + _set_obj_fnex = lp->set_obj_fnex; + _set_obj = lp->set_obj; + _set_outputfile = lp->set_outputfile; + _set_outputstream = lp->set_outputstream; + _set_partialprice = lp->set_partialprice; + _set_pivoting = lp->set_pivoting; + _set_preferdual = lp->set_preferdual; + _set_presolve = lp->set_presolve; + _set_print_sol = lp->set_print_sol; + _set_pseudocosts = lp->set_pseudocosts; + _set_rh = lp->set_rh; + _set_rh_range = lp->set_rh_range; + _set_rh_vec = lp->set_rh_vec; + _set_row = lp->set_row; + _set_rowex = lp->set_rowex; + _set_row_name = lp->set_row_name; + _set_scalelimit = lp->set_scalelimit; + _set_scaling = lp->set_scaling; + _set_semicont = lp->set_semicont; + _set_sense = lp->set_sense; + _set_simplextype = lp->set_simplextype; + _set_solutionlimit = lp->set_solutionlimit; + _set_timeout = lp->set_timeout; + _set_trace = lp->set_trace; + _set_upbo = lp->set_upbo; + _set_var_branch = lp->set_var_branch; + _set_var_weights = lp->set_var_weights; + _set_verbose = lp->set_verbose; + _set_XLI = lp->set_XLI; + _solve = lp->solve; + _str_add_column = lp->str_add_column; + _str_add_constraint = lp->str_add_constraint; + _str_add_lag_con = lp->str_add_lag_con; + _str_set_obj_fn = lp->str_set_obj_fn; + _str_set_rh_vec = lp->str_set_rh_vec; + _time_elapsed = lp->time_elapsed; + _unscale = lp->unscale; + _write_lp = lp->write_lp; + _write_LP = lp->write_LP; + _write_mps = lp->write_mps; + _write_MPS = lp->write_MPS; + _write_freemps = lp->write_freemps; + _write_freeMPS = lp->write_freeMPS; + _write_XLI = lp->write_XLI; + _write_basis = lp->write_basis; + _write_params = lp->write_params; + + return(TRUE); +} + +#elif defined LPSOLVEAPIFROMLIB + +#ifdef WIN32 +# include +#else +# include +#endif + +#if defined WIN32 +# define hlpsolve HINSTANCE +#else +# define hlpsolve void * +#endif + +static hlpsolve open_lpsolve_lib(char *filename) +{ + hlpsolve lpsolve; + +# if defined WIN32 + /* Get a handle to the Windows DLL module. */ + lpsolve = LoadLibrary("lpsolve55.dll"); +# else + lpsolve = dlopen("liblpsolve55.so", RTLD_LAZY);; +# endif + return(lpsolve); +} + +static int close_lpsolve_lib(hlpsolve lpsolve) +{ +#ifdef WIN32 + FreeLibrary(lpsolve); +#else + dlclose(lpsolve); +#endif + + return(TRUE); +} + +static int init_lpsolve(hlpsolve lpsolve) +{ +# if defined WIN32 +# define AddressOf GetProcAddress +# else +# define AddressOf dlsym +# endif + + /* assign API functions to lp structure */ + _add_column = (add_column_func *) AddressOf(lpsolve, "add_column"); + _add_columnex = (add_columnex_func *) AddressOf(lpsolve, "add_columnex"); + _add_constraint = (add_constraint_func *) AddressOf(lpsolve, "add_constraint"); + _add_constraintex = (add_constraintex_func *) AddressOf(lpsolve, "add_constraintex"); + _add_lag_con = (add_lag_con_func *) AddressOf(lpsolve, "add_lag_con"); + _add_SOS = (add_SOS_func *) AddressOf(lpsolve, "add_SOS"); + _column_in_lp = (column_in_lp_func *) AddressOf(lpsolve, "column_in_lp"); + _copy_lp = (copy_lp_func *) AddressOf(lpsolve, "copy_lp"); + _default_basis = (default_basis_func *) AddressOf(lpsolve, "default_basis"); + _del_column = (del_column_func *) AddressOf(lpsolve, "del_column"); + _del_constraint = (del_constraint_func *) AddressOf(lpsolve, "del_constraint"); + _delete_lp = (delete_lp_func *) AddressOf(lpsolve, "delete_lp"); + _dualize_lp = (dualize_lp_func *) AddressOf(lpsolve, "dualize_lp"); + _free_lp = (free_lp_func *) AddressOf(lpsolve, "free_lp"); + _get_anti_degen = (get_anti_degen_func *) AddressOf(lpsolve, "get_anti_degen"); + _get_basis = (get_basis_func *) AddressOf(lpsolve, "get_basis"); + _get_basiscrash = (get_basiscrash_func *) AddressOf(lpsolve, "get_basiscrash"); + _get_bb_depthlimit = (get_bb_depthlimit_func *) AddressOf(lpsolve, "get_bb_depthlimit"); + _get_bb_floorfirst = (get_bb_floorfirst_func *) AddressOf(lpsolve, "get_bb_floorfirst"); + _get_bb_rule = (get_bb_rule_func *) AddressOf(lpsolve, "get_bb_rule"); + _get_bounds_tighter = (get_bounds_tighter_func *) AddressOf(lpsolve, "get_bounds_tighter"); + _get_break_at_value = (get_break_at_value_func *) AddressOf(lpsolve, "get_break_at_value"); + _get_col_name = (get_col_name_func *) AddressOf(lpsolve, "get_col_name"); + _get_columnex = (get_columnex_func *) AddressOf(lpsolve, "get_columnex"); + _get_constr_type = (get_constr_type_func *) AddressOf(lpsolve, "get_constr_type"); + _get_constr_value = (get_constr_value_func *) AddressOf(lpsolve, "get_constr_value"); + _get_constraints = (get_constraints_func *) AddressOf(lpsolve, "get_constraints"); + _get_dual_solution = (get_dual_solution_func *) AddressOf(lpsolve, "get_dual_solution"); + _get_epsb = (get_epsb_func *) AddressOf(lpsolve, "get_epsb"); + _get_epsd = (get_epsd_func *) AddressOf(lpsolve, "get_epsd"); + _get_epsel = (get_epsel_func *) AddressOf(lpsolve, "get_epsel"); + _get_epsint = (get_epsint_func *) AddressOf(lpsolve, "get_epsint"); + _get_epsperturb = (get_epsperturb_func *) AddressOf(lpsolve, "get_epsperturb"); + _get_epspivot = (get_epspivot_func *) AddressOf(lpsolve, "get_epspivot"); + _get_improve = (get_improve_func *) AddressOf(lpsolve, "get_improve"); + _get_infinite = (get_infinite_func *) AddressOf(lpsolve, "get_infinite"); + _get_lambda = (get_lambda_func *) AddressOf(lpsolve, "get_lambda"); + _get_lowbo = (get_lowbo_func *) AddressOf(lpsolve, "get_lowbo"); + _get_lp_index = (get_lp_index_func *) AddressOf(lpsolve, "get_lp_index"); + _get_lp_name = (get_lp_name_func *) AddressOf(lpsolve, "get_lp_name"); + _get_Lrows = (get_Lrows_func *) AddressOf(lpsolve, "get_Lrows"); + _get_mat = (get_mat_func *) AddressOf(lpsolve, "get_mat"); + _get_mat_byindex = (get_mat_byindex_func *) AddressOf(lpsolve, "get_mat_byindex"); + _get_max_level = (get_max_level_func *) AddressOf(lpsolve, "get_max_level"); + _get_maxpivot = (get_maxpivot_func *) AddressOf(lpsolve, "get_maxpivot"); + _get_mip_gap = (get_mip_gap_func *) AddressOf(lpsolve, "get_mip_gap"); + _get_multiprice = (get_multiprice_func *) AddressOf(lpsolve, "get_multiprice"); + _get_nameindex = (get_nameindex_func *) AddressOf(lpsolve, "get_nameindex"); + _get_Ncolumns = (get_Ncolumns_func *) AddressOf(lpsolve, "get_Ncolumns"); + _get_negrange = (get_negrange_func *) AddressOf(lpsolve, "get_negrange"); + _get_nonzeros = (get_nz_func *) AddressOf(lpsolve, "get_nonzeros"); + _get_Norig_columns = (get_Norig_columns_func *) AddressOf(lpsolve, "get_Norig_columns"); + _get_Norig_rows = (get_Norig_rows_func *) AddressOf(lpsolve, "get_Norig_rows"); + _get_Nrows = (get_Nrows_func *) AddressOf(lpsolve, "get_Nrows"); + _get_obj_bound = (get_obj_bound_func *) AddressOf(lpsolve, "get_obj_bound"); + _get_objective = (get_objective_func *) AddressOf(lpsolve, "get_objective"); + _get_orig_index = (get_orig_index_func *) AddressOf(lpsolve, "get_orig_index"); + _get_origcol_name = (get_origcol_name_func *) AddressOf(lpsolve, "get_origcol_name"); + _get_origrow_name = (get_origrow_name_func *) AddressOf(lpsolve, "get_origrow_name"); + _get_partialprice = (get_partialprice_func *) AddressOf(lpsolve, "get_partialprice"); + _get_pivoting = (get_pivoting_func *) AddressOf(lpsolve, "get_pivoting"); + _get_presolve = (get_presolve_func *) AddressOf(lpsolve, "get_presolve"); + _get_presolveloops = (get_presolveloops_func *) AddressOf(lpsolve, "get_presolveloops"); + _get_primal_solution = (get_primal_solution_func *) AddressOf(lpsolve, "get_primal_solution"); + _get_print_sol = (get_print_sol_func *) AddressOf(lpsolve, "get_print_sol"); + _get_pseudocosts = (get_pseudocosts_func *) AddressOf(lpsolve, "get_pseudocosts"); + _get_ptr_constraints = (get_ptr_constraints_func *) AddressOf(lpsolve, "get_ptr_constraints"); + _get_ptr_dual_solution = (get_ptr_dual_solution_func *) AddressOf(lpsolve, "get_ptr_dual_solution"); + _get_ptr_lambda = (get_ptr_lambda_func *) AddressOf(lpsolve, "get_ptr_lambda"); + _get_ptr_primal_solution = (get_ptr_primal_solution_func *) AddressOf(lpsolve, "get_ptr_primal_solution"); + _get_ptr_sensitivity_obj = (get_ptr_sensitivity_obj_func *) AddressOf(lpsolve, "get_ptr_sensitivity_obj"); + _get_ptr_sensitivity_objex = (get_ptr_sensitivity_objex_func *) AddressOf(lpsolve, "get_ptr_sensitivity_objex"); + _get_ptr_sensitivity_rhs = (get_ptr_sensitivity_rhs_func *) AddressOf(lpsolve, "get_ptr_sensitivity_rhs"); + _get_ptr_variables = (get_ptr_variables_func *) AddressOf(lpsolve, "get_ptr_variables"); + _get_rh = (get_rh_func *) AddressOf(lpsolve, "get_rh"); + _get_rh_range = (get_rh_range_func *) AddressOf(lpsolve, "get_rh_range"); + _get_row = (get_row_func *) AddressOf(lpsolve, "get_row"); + _get_row_name = (get_row_name_func *) AddressOf(lpsolve, "get_row_name"); + _get_scalelimit = (get_scalelimit_func *) AddressOf(lpsolve, "get_scalelimit"); + _get_scaling = (get_scaling_func *) AddressOf(lpsolve, "get_scaling"); + _get_sensitivity_obj = (get_sensitivity_obj_func *) AddressOf(lpsolve, "get_sensitivity_obj"); + _get_sensitivity_objex = (get_sensitivity_objex_func *) AddressOf(lpsolve, "get_sensitivity_objex"); + _get_sensitivity_rhs = (get_sensitivity_rhs_func *) AddressOf(lpsolve, "get_sensitivity_rhs"); + _get_simplextype = (get_simplextype_func *) AddressOf(lpsolve, "get_simplextype"); + _get_solutioncount = (get_solutioncount_func *) AddressOf(lpsolve, "get_solutioncount"); + _get_solutionlimit = (get_solutionlimit_func *) AddressOf(lpsolve, "get_solutionlimit"); + _get_status = (get_status_func *) AddressOf(lpsolve, "get_status"); + _get_statustext = (get_statustext_func *) AddressOf(lpsolve, "get_statustext"); + _get_timeout = (get_timeout_func *) AddressOf(lpsolve, "get_timeout"); + _get_total_iter = (get_total_iter_func *) AddressOf(lpsolve, "get_total_iter"); + _get_total_nodes = (get_total_nodes_func *) AddressOf(lpsolve, "get_total_nodes"); + _get_upbo = (get_upbo_func *) AddressOf(lpsolve, "get_upbo"); + _get_var_branch = (get_var_branch_func *) AddressOf(lpsolve, "get_var_branch"); + _get_var_dualresult = (get_var_dualresult_func *) AddressOf(lpsolve, "get_var_dualresult"); + _get_var_primalresult = (get_var_primalresult_func *) AddressOf(lpsolve, "get_var_primalresult"); + _get_var_priority = (get_var_priority_func *) AddressOf(lpsolve, "get_var_priority"); + _get_variables = (get_variables_func *) AddressOf(lpsolve, "get_variables"); + _get_verbose = (get_verbose_func *) AddressOf(lpsolve, "get_verbose"); + _get_working_objective = (get_working_objective_func *) AddressOf(lpsolve, "get_working_objective"); + _has_BFP = (has_BFP_func *) AddressOf(lpsolve, "has_BFP"); + _has_XLI = (has_XLI_func *) AddressOf(lpsolve, "has_XLI"); + _is_add_rowmode = (is_add_rowmode_func *) AddressOf(lpsolve, "is_add_rowmode"); + _is_anti_degen = (is_anti_degen_func *) AddressOf(lpsolve, "is_anti_degen"); + _is_binary = (is_binary_func *) AddressOf(lpsolve, "is_binary"); + _is_break_at_first = (is_break_at_first_func *) AddressOf(lpsolve, "is_break_at_first"); + _is_constr_type = (is_constr_type_func *) AddressOf(lpsolve, "is_constr_type"); + _is_debug = (is_debug_func *) AddressOf(lpsolve, "is_debug"); + _is_feasible = (is_feasible_func *) AddressOf(lpsolve, "is_feasible"); + _is_unbounded = (is_unbounded_func *) AddressOf(lpsolve, "is_unbounded"); + _is_infinite = (is_infinite_func *) AddressOf(lpsolve, "is_infinite"); + _is_int = (is_int_func *) AddressOf(lpsolve, "is_int"); + _is_integerscaling = (is_integerscaling_func *) AddressOf(lpsolve, "is_integerscaling"); + _is_lag_trace = (is_lag_trace_func *) AddressOf(lpsolve, "is_lag_trace"); + _is_maxim = (is_maxim_func *) AddressOf(lpsolve, "is_maxim"); + _is_nativeBFP = (is_nativeBFP_func *) AddressOf(lpsolve, "is_nativeBFP"); + _is_nativeXLI = (is_nativeXLI_func *) AddressOf(lpsolve, "is_nativeXLI"); + _is_negative = (is_negative_func *) AddressOf(lpsolve, "is_negative"); + _is_piv_mode = (is_piv_mode_func *) AddressOf(lpsolve, "is_piv_mode"); + _is_piv_rule = (is_piv_rule_func *) AddressOf(lpsolve, "is_piv_rule"); + _is_presolve = (is_presolve_func *) AddressOf(lpsolve, "is_presolve"); + _is_scalemode = (is_scalemode_func *) AddressOf(lpsolve, "is_scalemode"); + _is_scaletype = (is_scaletype_func *) AddressOf(lpsolve, "is_scaletype"); + _is_semicont = (is_semicont_func *) AddressOf(lpsolve, "is_semicont"); + _is_SOS_var = (is_SOS_var_func *) AddressOf(lpsolve, "is_SOS_var"); + _is_trace = (is_trace_func *) AddressOf(lpsolve, "is_trace"); + _lp_solve_version = (lp_solve_version_func *) AddressOf(lpsolve, "lp_solve_version"); + _make_lp = (make_lp_func *) AddressOf(lpsolve, "make_lp"); + _print_constraints = (print_constraints_func *) AddressOf(lpsolve, "print_constraints"); + _print_debugdump = (print_debugdump_func *) AddressOf(lpsolve, "print_debugdump"); + _print_duals = (print_duals_func *) AddressOf(lpsolve, "print_duals"); + _print_lp = (print_lp_func *) AddressOf(lpsolve, "print_lp"); + _print_objective = (print_objective_func *) AddressOf(lpsolve, "print_objective"); + _print_scales = (print_scales_func *) AddressOf(lpsolve, "print_scales"); + _print_solution = (print_solution_func *) AddressOf(lpsolve, "print_solution"); + _print_str = (print_str_func *) AddressOf(lpsolve, "print_str"); + _print_tableau = (print_tableau_func *) AddressOf(lpsolve, "print_tableau"); + _put_abortfunc = (put_abortfunc_func *) AddressOf(lpsolve, "put_abortfunc"); + _put_bb_nodefunc = (put_bb_nodefunc_func *) AddressOf(lpsolve, "put_bb_nodefunc"); + _put_bb_branchfunc = (put_bb_branchfunc_func *) AddressOf(lpsolve, "put_bb_branchfunc"); + _put_logfunc = (put_logfunc_func *) AddressOf(lpsolve, "put_logfunc"); + _put_msgfunc = (put_msgfunc_func *) AddressOf(lpsolve, "put_msgfunc"); + _read_LPhandle = (read_LPhandle_func *) AddressOf(lpsolve, "read_LPhandle"); + _read_MPShandle = (read_MPShandle_func *) AddressOf(lpsolve, "read_MPShandle"); + _read_XLI = (read_XLI_func *) AddressOf(lpsolve, "read_XLI"); + _read_params = (read_params_func *) AddressOf(lpsolve, "read_params"); + _read_basis = (read_basis_func *) AddressOf(lpsolve, "read_basis"); + _reset_basis = (reset_basis_func *) AddressOf(lpsolve, "reset_basis"); + _reset_params = (reset_params_func *) AddressOf(lpsolve, "reset_params"); + _resize_lp = (resize_lp_func *) AddressOf(lpsolve, "resize_lp"); + _set_add_rowmode = (set_add_rowmode_func *) AddressOf(lpsolve, "set_add_rowmode"); + _set_anti_degen = (set_anti_degen_func *) AddressOf(lpsolve, "set_anti_degen"); + _set_basisvar = (set_basisvar_func *) AddressOf(lpsolve, "set_basisvar"); + _set_basis = (set_basis_func *) AddressOf(lpsolve, "set_basis"); + _set_basiscrash = (set_basiscrash_func *) AddressOf(lpsolve, "set_basiscrash"); + _set_bb_depthlimit = (set_bb_depthlimit_func *) AddressOf(lpsolve, "set_bb_depthlimit"); + _set_bb_floorfirst = (set_bb_floorfirst_func *) AddressOf(lpsolve, "set_bb_floorfirst"); + _set_bb_rule = (set_bb_rule_func *) AddressOf(lpsolve, "set_bb_rule"); + _set_BFP = (set_BFP_func *) AddressOf(lpsolve, "set_BFP"); + _set_binary = (set_binary_func *) AddressOf(lpsolve, "set_binary"); + _set_bounds = (set_bounds_func *) AddressOf(lpsolve, "set_bounds"); + _set_bounds_tighter = (set_bounds_tighter_func *) AddressOf(lpsolve, "set_bounds_tighter"); + _set_break_at_first = (set_break_at_first_func *) AddressOf(lpsolve, "set_break_at_first"); + _set_break_at_value = (set_break_at_value_func *) AddressOf(lpsolve, "set_break_at_value"); + _set_column = (set_column_func *) AddressOf(lpsolve, "set_column"); + _set_columnex = (set_columnex_func *) AddressOf(lpsolve, "set_columnex"); + _set_col_name = (set_col_name_func *) AddressOf(lpsolve, "set_col_name"); + _set_constr_type = (set_constr_type_func *) AddressOf(lpsolve, "set_constr_type"); + _set_debug = (set_debug_func *) AddressOf(lpsolve, "set_debug"); + _set_epsb = (set_epsb_func *) AddressOf(lpsolve, "set_epsb"); + _set_epsd = (set_epsd_func *) AddressOf(lpsolve, "set_epsd"); + _set_epsel = (set_epsel_func *) AddressOf(lpsolve, "set_epsel"); + _set_epsint = (set_epsint_func *) AddressOf(lpsolve, "set_epsint"); + _set_epslevel = (set_epslevel_func *) AddressOf(lpsolve, "set_epslevel"); + _set_epsperturb = (set_epsperturb_func *) AddressOf(lpsolve, "set_epsperturb"); + _set_epspivot = (set_epspivot_func *) AddressOf(lpsolve, "set_epspivot"); + _set_unbounded = (set_unbounded_func *) AddressOf(lpsolve, "set_unbounded"); + _set_improve = (set_improve_func *) AddressOf(lpsolve, "set_improve"); + _set_infinite = (set_infinite_func *) AddressOf(lpsolve, "set_infinite"); + _set_int = (set_int_func *) AddressOf(lpsolve, "set_int"); + _set_lag_trace = (set_lag_trace_func *) AddressOf(lpsolve, "set_lag_trace"); + _set_lowbo = (set_lowbo_func *) AddressOf(lpsolve, "set_lowbo"); + _set_lp_name = (set_lp_name_func *) AddressOf(lpsolve, "set_lp_name"); + _set_mat = (set_mat_func *) AddressOf(lpsolve, "set_mat"); + _set_maxim = (set_maxim_func *) AddressOf(lpsolve, "set_maxim"); + _set_maxpivot = (set_maxpivot_func *) AddressOf(lpsolve, "set_maxpivot"); + _set_minim = (set_minim_func *) AddressOf(lpsolve, "set_minim"); + _set_mip_gap = (set_mip_gap_func *) AddressOf(lpsolve, "set_mip_gap"); + _set_multiprice = (set_multiprice_func *) AddressOf(lpsolve, "set_multiprice"); + _set_negrange = (set_negrange_func *) AddressOf(lpsolve, "set_negrange"); + _set_obj_bound = (set_obj_bound_func *) AddressOf(lpsolve, "set_obj_bound"); + _set_obj_fn = (set_obj_fn_func *) AddressOf(lpsolve, "set_obj_fn"); + _set_obj_fnex = (set_obj_fnex_func *) AddressOf(lpsolve, "set_obj_fnex"); + _set_obj = (set_obj_func *) AddressOf(lpsolve, "set_obj"); + _set_outputfile = (set_outputfile_func *) AddressOf(lpsolve, "set_outputfile"); + _set_outputstream = (set_outputstream_func *) AddressOf(lpsolve, "set_outputstream"); + _set_partialprice = (set_partialprice_func *) AddressOf(lpsolve, "set_partialprice"); + _set_pivoting = (set_pivoting_func *) AddressOf(lpsolve, "set_pivoting"); + _set_preferdual = (set_preferdual_func *) AddressOf(lpsolve, "set_preferdual"); + _set_presolve = (set_presolve_func *) AddressOf(lpsolve, "set_presolve"); + _set_print_sol = (set_print_sol_func *) AddressOf(lpsolve, "set_print_sol"); + _set_pseudocosts = (set_pseudocosts_func *) AddressOf(lpsolve, "set_pseudocosts"); + _set_rh = (set_rh_func *) AddressOf(lpsolve, "set_rh"); + _set_rh_range = (set_rh_range_func *) AddressOf(lpsolve, "set_rh_range"); + _set_rh_vec = (set_rh_vec_func *) AddressOf(lpsolve, "set_rh_vec"); + _set_row = (set_row_func *) AddressOf(lpsolve, "set_row"); + _set_rowex = (set_rowex_func *) AddressOf(lpsolve, "set_rowex"); + _set_row_name = (set_row_name_func *) AddressOf(lpsolve, "set_row_name"); + _set_scalelimit = (set_scalelimit_func *) AddressOf(lpsolve, "set_scalelimit"); + _set_scaling = (set_scaling_func *) AddressOf(lpsolve, "set_scaling"); + _set_semicont = (set_semicont_func *) AddressOf(lpsolve, "set_semicont"); + _set_sense = (set_sense_func *) AddressOf(lpsolve, "set_sense"); + _set_simplextype = (set_simplextype_func *) AddressOf(lpsolve, "set_simplextype"); + _set_solutionlimit = (set_solutionlimit_func *) AddressOf(lpsolve, "set_solutionlimit"); + _set_timeout = (set_timeout_func *) AddressOf(lpsolve, "set_timeout"); + _set_trace = (set_trace_func *) AddressOf(lpsolve, "set_trace"); + _set_upbo = (set_upbo_func *) AddressOf(lpsolve, "set_upbo"); + _set_var_branch = (set_var_branch_func *) AddressOf(lpsolve, "set_var_branch"); + _set_var_weights = (set_var_weights_func *) AddressOf(lpsolve, "set_var_weights"); + _set_verbose = (set_verbose_func *) AddressOf(lpsolve, "set_verbose"); + _set_XLI = (set_XLI_func *) AddressOf(lpsolve, "set_XLI"); + _solve = (solve_func *) AddressOf(lpsolve, "solve"); + _str_add_column = (str_add_column_func *) AddressOf(lpsolve, "str_add_column"); + _str_add_constraint = (str_add_constraint_func *) AddressOf(lpsolve, "str_add_constraint"); + _str_add_lag_con = (str_add_lag_con_func *) AddressOf(lpsolve, "str_add_lag_con"); + _str_set_obj_fn = (str_set_obj_fn_func *) AddressOf(lpsolve, "str_set_obj_fn"); + _str_set_rh_vec = (str_set_rh_vec_func *) AddressOf(lpsolve, "str_set_rh_vec"); + _time_elapsed = (time_elapsed_func *) AddressOf(lpsolve, "time_elapsed"); + _unscale = (unscale_func *) AddressOf(lpsolve, "unscale"); + _write_lp = (write_lp_func *) AddressOf(lpsolve, "write_lp"); + _write_LP = (write_LP_func *) AddressOf(lpsolve, "write_LP"); + _write_mps = (write_mps_func *) AddressOf(lpsolve, "write_mps"); + _write_MPS = (write_MPS_func *) AddressOf(lpsolve, "write_MPS"); + _write_freemps = (write_freemps_func *) AddressOf(lpsolve, "write_freemps"); + _write_freeMPS = (write_freeMPS_func *) AddressOf(lpsolve, "write_freeMPS"); + _write_XLI = (write_XLI_func *) AddressOf(lpsolve, "write_XLI"); + _write_basis = (write_basis_func *) AddressOf(lpsolve, "write_basis"); + _write_params = (write_params_func *) AddressOf(lpsolve, "write_params"); + + return(TRUE); +# undef AddressOf +} + +#else +# error Either LPSOLVEAPIFROMLPREC or LPSOLVEAPIFROMLIB must be defined +#endif + +#define add_column _add_column +#define add_columnex _add_columnex +#define add_constraint _add_constraint +#define add_constraintex _add_constraintex +#define add_lag_con _add_lag_con +#define add_SOS _add_SOS +#define column_in_lp _column_in_lp +#define copy_lp _copy_lp +#define default_basis _default_basis +#define del_column _del_column +#define del_constraint _del_constraint +#define delete_lp _delete_lp +#define dualize_lp _dualize_lp +#define free_lp _free_lp +#define get_anti_degen _get_anti_degen +#define get_basis _get_basis +#define get_basiscrash _get_basiscrash +#define get_bb_depthlimit _get_bb_depthlimit +#define get_bb_floorfirst _get_bb_floorfirst +#define get_bb_rule _get_bb_rule +#define get_bounds_tighter _get_bounds_tighter +#define get_break_at_value _get_break_at_value +#define get_col_name _get_col_name +#define get_columnex _get_columnex +#define get_constr_type _get_constr_type +#define get_constr_value _get_constr_value +#define get_constraints _get_constraints +#define get_dual_solution _get_dual_solution +#define get_epsb _get_epsb +#define get_epsd _get_epsd +#define get_epsel _get_epsel +#define get_epsint _get_epsint +#define get_epsperturb _get_epsperturb +#define get_epspivot _get_epspivot +#define get_improve _get_improve +#define get_infinite _get_infinite +#define get_lambda _get_lambda +#define get_lowbo _get_lowbo +#define get_lp_index _get_lp_index +#define get_lp_name _get_lp_name +#define get_Lrows _get_Lrows +#define get_mat _get_mat +#define get_mat_byindex _get_mat_byindex +#define get_max_level _get_max_level +#define get_maxpivot _get_maxpivot +#define get_mip_gap _get_mip_gap +#define get_multiprice _get_multiprice +#define get_nameindex _get_nameindex +#define get_Ncolumns _get_Ncolumns +#define get_negrange _get_negrange +#define get_nonzeros _get_nonzeros +#define get_Norig_columns _get_Norig_columns +#define get_Norig_rows _get_Norig_rows +#define get_Nrows _get_Nrows +#define get_obj_bound _get_obj_bound +#define get_objective _get_objective +#define get_orig_index _get_orig_index +#define get_origcol_name _get_origcol_name +#define get_origrow_name _get_origrow_name +#define get_partialprice _get_partialprice +#define get_pivoting _get_pivoting +#define get_presolve _get_presolve +#define get_presolveloops _get_presolveloops +#define get_primal_solution _get_primal_solution +#define get_print_sol _get_print_sol +#define get_pseudocosts _get_pseudocosts +#define get_ptr_constraints _get_ptr_constraints +#define get_ptr_dual_solution _get_ptr_dual_solution +#define get_ptr_lambda _get_ptr_lambda +#define get_ptr_primal_solution _get_ptr_primal_solution +#define get_ptr_sensitivity_obj _get_ptr_sensitivity_obj +#define get_ptr_sensitivity_objex _get_ptr_sensitivity_objex +#define get_ptr_sensitivity_rhs _get_ptr_sensitivity_rhs +#define get_ptr_variables _get_ptr_variables +#define get_rh _get_rh +#define get_rh_range _get_rh_range +#define get_row _get_row +#define get_row_name _get_row_name +#define get_scalelimit _get_scalelimit +#define get_scaling _get_scaling +#define get_sensitivity_obj _get_sensitivity_obj +#define get_sensitivity_objex _get_sensitivity_objex +#define get_sensitivity_rhs _get_sensitivity_rhs +#define get_simplextype _get_simplextype +#define get_solutioncount _get_solutioncount +#define get_solutionlimit _get_solutionlimit +#define get_status _get_status +#define get_statustext _get_statustext +#define get_timeout _get_timeout +#define get_total_iter _get_total_iter +#define get_total_nodes _get_total_nodes +#define get_upbo _get_upbo +#define get_var_branch _get_var_branch +#define get_var_dualresult _get_var_dualresult +#define get_var_primalresult _get_var_primalresult +#define get_var_priority _get_var_priority +#define get_variables _get_variables +#define get_verbose _get_verbose +#define get_working_objective _get_working_objective +#define has_BFP _has_BFP +#define has_XLI _has_XLI +#define is_add_rowmode _is_add_rowmode +#define is_anti_degen _is_anti_degen +#define is_binary _is_binary +#define is_break_at_first _is_break_at_first +#define is_constr_type _is_constr_type +#define is_debug _is_debug +#define is_feasible _is_feasible +#define is_unbounded _is_unbounded +#define is_infinite _is_infinite +#define is_int _is_int +#define is_integerscaling _is_integerscaling +#define is_lag_trace _is_lag_trace +#define is_maxim _is_maxim +#define is_nativeBFP _is_nativeBFP +#define is_nativeXLI _is_nativeXLI +#define is_negative _is_negative +#define is_piv_mode _is_piv_mode +#define is_piv_rule _is_piv_rule +#define is_presolve _is_presolve +#define is_scalemode _is_scalemode +#define is_scaletype _is_scaletype +#define is_semicont _is_semicont +#define is_SOS_var _is_SOS_var +#define is_trace _is_trace +#define lp_solve_version _lp_solve_version +#define make_lp _make_lp +#define print_constraints _print_constraints +#define print_debugdump _print_debugdump +#define print_duals _print_duals +#define print_lp _print_lp +#define print_objective _print_objective +#define print_scales _print_scales +#define print_solution _print_solution +#define print_str _print_str +#define print_tableau _print_tableau +#define put_abortfunc _put_abortfunc +#define put_bb_nodefunc _put_bb_nodefunc +#define put_bb_branchfunc _put_bb_branchfunc +#define put_logfunc _put_logfunc +#define put_msgfunc _put_msgfunc +#define read_LPhandle _read_LPhandle +#define read_MPShandle _read_MPShandle +#define read_XLI _read_XLI +#define read_params _read_params +#define read_basis _read_basis +#define reset_basis _reset_basis +#define reset_params _reset_params +#define resize_lp _resize_lp +#define set_add_rowmode _set_add_rowmode +#define set_anti_degen _set_anti_degen +#define set_basisvar _set_basisvar +#define set_basis _set_basis +#define set_basiscrash _set_basiscrash +#define set_bb_depthlimit _set_bb_depthlimit +#define set_bb_floorfirst _set_bb_floorfirst +#define set_bb_rule _set_bb_rule +#define set_BFP _set_BFP +#define set_binary _set_binary +#define set_bounds _set_bounds +#define set_bounds_tighter _set_bounds_tighter +#define set_break_at_first _set_break_at_first +#define set_break_at_value _set_break_at_value +#define set_column _set_column +#define set_columnex _set_columnex +#define set_col_name _set_col_name +#define set_constr_type _set_constr_type +#define set_debug _set_debug +#define set_epsb _set_epsb +#define set_epsd _set_epsd +#define set_epsel _set_epsel +#define set_epsint _set_epsint +#define set_epslevel _set_epslevel +#define set_epsperturb _set_epsperturb +#define set_epspivot _set_epspivot +#define set_unbounded _set_unbounded +#define set_improve _set_improve +#define set_infinite _set_infinite +#define set_int _set_int +#define set_lag_trace _set_lag_trace +#define set_lowbo _set_lowbo +#define set_lp_name _set_lp_name +#define set_mat _set_mat +#define set_maxim _set_maxim +#define set_maxpivot _set_maxpivot +#define set_minim _set_minim +#define set_mip_gap _set_mip_gap +#define set_multiprice _set_multiprice +#define set_negrange _set_negrange +#define set_obj_bound _set_obj_bound +#define set_obj_fn _set_obj_fn +#define set_obj_fnex _set_obj_fnex +#define set_obj _set_obj +#define set_outputfile _set_outputfile +#define set_outputstream _set_outputstream +#define set_partialprice _set_partialprice +#define set_pivoting _set_pivoting +#define set_preferdual _set_preferdual +#define set_presolve _set_presolve +#define set_print_sol _set_print_sol +#define set_pseudocosts _set_pseudocosts +#define set_rh _set_rh +#define set_rh_range _set_rh_range +#define set_rh_vec _set_rh_vec +#define set_row _set_row +#define set_rowex _set_rowex +#define set_row_name _set_row_name +#define set_scalelimit _set_scalelimit +#define set_scaling _set_scaling +#define set_semicont _set_semicont +#define set_sense _set_sense +#define set_simplextype _set_simplextype +#define set_solutionlimit _set_solutionlimit +#define set_timeout _set_timeout +#define set_trace _set_trace +#define set_upbo _set_upbo +#define set_var_branch _set_var_branch +#define set_var_weights _set_var_weights +#define set_verbose _set_verbose +#define set_XLI _set_XLI +#define solve _solve +#define str_add_column _str_add_column +#define str_add_constraint _str_add_constraint +#define str_add_lag_con _str_add_lag_con +#define str_set_obj_fn _str_set_obj_fn +#define str_set_rh_vec _str_set_rh_vec +#define time_elapsed _time_elapsed +#define unscale _unscale +#define write_lp _write_lp +#define write_LP _write_LP +#define write_mps _write_mps +#define write_MPS _write_MPS +#define write_freemps _write_freemps +#define write_freeMPS _write_freeMPS +#define write_XLI _write_XLI +#define write_basis _write_basis +#define write_params _write_params diff --git a/include/lp_fortify.h b/include/lp_fortify.h new file mode 100644 index 0000000..2acb704 --- /dev/null +++ b/include/lp_fortify.h @@ -0,0 +1,5 @@ +#ifdef FORTIFY + +#include "fortify.h" + +#endif diff --git a/include/lp_lib.h b/include/lp_lib.h new file mode 100644 index 0000000..1add5af --- /dev/null +++ b/include/lp_lib.h @@ -0,0 +1,2266 @@ + +#ifndef HEADER_lp_lib +#define HEADER_lp_lib + +/* -------------------------------------------------------------------------- + + This is the main library header file for the lp_solve v5.0 release + + Starting at version 3.0, LP_Solve is released under the LGPL license. + For full information, see the enclosed file LGPL.txt. + + Original developer: Michel Berkelaar - michel@ics.ele.tue.nl + Most changes 1.5-2.0: Jeroen Dirks - jeroend@tor.numetrix.com + Changes 3.2-4.0: Kjell Eikland - kjell.eikland@broadpark.no + (Simplex code, SOS, SC, code optimization) + Peter Notebaert - lpsolve@peno.be + (Sensitivity analysis, documentation) + Changes 5.0+: Kjell Eikland - kjell.eikland@broadpark.no + (BFP, XLI, simplex, B&B, code modularization) + Peter Notebaert - lpsolve@peno.be + (Sensitivity analysis, New lp parser, LINDO (XLI) + parser, VB/.NET interface, documentation) + + Release notes: + + Version 4.0 enhances version 3.2 in terms of internal program/simplex + architecture, call level interfaces, data layout, features and contains + several bug fixes. There is now complete support for semi-continuous + variables and SOS constructions. In the process, a complete API + was added. The MPS parser has been amended to support this. + Sensitivity analysis and variouse bug fixes was provided by Peter + Notebaert in 4.0 sub-releases. Peter also wrote a complete + documentation of the API and contributed a VB interface, both of which + significantly enhanced the accessibility of lp_solve. + + Version 5.0 is a major rewrite and code cleanup. The main additions that + drove forward this cleanup were the modular inversion logic with optimal + column ordering, addition of primal phase 1 and dual phase 2 logic for + full flexibility in the selection of primal and dual simplex modes, + DEVEX and steepest edge pivot selection, along with dynamic cycling + detection and prevention. This cleanup made it possible to harmonize the + internal rounding principles, contributing to increased numerical stability. + + Version 5.1 rearranges the matrix storage model by enabling both legacy + element record-based storage and split vector storage. In addition the + lprec structure is optimized and additional routines are added, mainly for + sparse vector additions and enhanced XLI functionality. Support for XML- + based models was added on the basis of the LPFML schema via xli_LPFML. + + Version 5.2 removes the objective function from the constraint matrix, + adds a number of presolve options and speed them up. Degeneracy handling + is significantly improved. Support for XLI_ZIMPL was added. + Multiple and partial pricing has been enhanced and activated. + + -------------------------------------------------------------------------- */ +/* Define user program feature option switches */ +/* ------------------------------------------------------------------------- */ + +#if !defined _WINDOWS && !defined _WIN32 && !defined WIN32 +# define _isnan(x) FALSE +#endif + +/* Utility/system settings */ +/* ------------------------------------------------------------------------- */ +/*#define INTEGERTIME */ /* Set use of lower-resolution timer */ + + +/* New v5.0+ simplex/optimization features and settings */ +/* ------------------------------------------------------------------------- */ +/*#define NoRowScaleOF */ /* Optionally skip row-scaling of the OF */ +#define DoMatrixRounding /* Round A matrix elements to precision */ +#define DoBorderRounding /* Round RHS, bounds and ranges to precision */ +#define Phase1EliminateRedundant /* Remove rows of redundant artificials */ +#define FixViolatedOptimal +#define ImproveSolutionPrecision /* Round optimal solution values */ +/*#define IncreasePivotOnReducedAccuracy */ /* Increase epspivot on instability */ +/*#define FixInaccurateDualMinit */ /* Reinvert on inaccuracy in dual minits */ +/*#define EnforcePositiveTheta */ /* Ensure that the theta range is valid */ +#define ResetMinitOnReinvert +/*#define UsePrimalReducedCostUpdate */ /* Not tested */ +/*#define UseDualReducedCostUpdate */ /* Seems Ok, but slower than expected */ +/*#ifdef UseLegacyExtrad */ /* Use v3.2- style Extrad method */ +#define UseMilpExpandedRCF /* Non-ints in reduced cost bound tightening */ +/*#define UseMilpSlacksRCF */ /* Slacks in reduced cost bound tightening (degen + prone); requires !SlackInitMinusInf */ +#define LegacySlackDefinition /* Slack as the "value of the constraint" */ + + +/* Development features (change at own risk) */ +/* ------------------------------------------------------------------------- */ +/*#define MIPboundWithOF */ /* Enable to detect OF constraint for use during B&B */ +/*#define SlackInitMinusInf */ /* Slacks have 0 LB if this is not defined */ +#define FULLYBOUNDEDSIMPLEX FALSE /* WARNING: Activate at your own risk! */ + + +/* Specify use of the basic linear algebra subroutine library */ +/* ------------------------------------------------------------------------- */ +#define libBLAS 2 /* 0: No, 1: Internal, 2: External */ +#define libnameBLAS "myBLAS" + + +/* Active inverse logic (default is optimized original etaPFI) */ +/* ------------------------------------------------------------------------- */ +#if !defined LoadInverseLib +# define LoadInverseLib TRUE /* Enable alternate inverse libraries */ +#endif +/*#define ExcludeNativeInverse */ /* Disable INVERSE_ACTIVE inverse engine */ + +#define DEF_OBJINBASIS TRUE /* Additional rows inserted at the top (1 => OF) */ + +#define INVERSE_NONE -1 +#define INVERSE_LEGACY 0 +#define INVERSE_ETAPFI 1 +#define INVERSE_LUMOD 2 +#define INVERSE_LUSOL 3 +#define INVERSE_GLPKLU 4 + +#ifndef RoleIsExternalInvEngine /* Defined in inverse DLL drivers */ + #ifdef ExcludeNativeInverse + #define INVERSE_ACTIVE INVERSE_NONE /* Disable native engine */ + #else + #define INVERSE_ACTIVE INVERSE_LEGACY /* User or DLL-selected */ + #endif +#endif + + +/* Active external language interface logic (default is none) */ +/* ------------------------------------------------------------------------- */ +#if !defined LoadLanguageLib +# define LoadLanguageLib TRUE /* Enable alternate language libraries */ +#endif +#define ExcludeNativeLanguage /* Disable LANGUAGE_ACTIVE XLI */ + +#define LANGUAGE_NONE -1 +#define LANGUAGE_LEGACYLP 0 +#define LANGUAGE_CPLEXLP 1 +#define LANGUAGE_MPSX 2 +#define LANGUAGE_LPFML 3 +#define LANGUAGE_MATHPROG 4 +#define LANGUAGE_AMPL 5 +#define LANGUAGE_GAMS 6 +#define LANGUAGE_ZIMPL 7 +#define LANGUAGE_S 8 +#define LANGUAGE_R 9 +#define LANGUAGE_MATLAB 10 +#define LANGUAGE_OMATRIX 11 +#define LANGUAGE_SCILAB 12 +#define LANGUAGE_OCTAVE 13 +#define LANGUAGE_EMPS 14 + +#ifndef RoleIsExternalLanguageEngine /* Defined in XLI driver libraries */ + #ifdef ExcludeNativeLanguage + #define LANGUAGE_ACTIVE LANGUAGE_NONE /* Disable native engine */ + #else + #define LANGUAGE_ACTIVE LANGUAGE_CPLEXLP /* User or DLL-selected */ + #endif +#endif + + +/* Default parameters and tolerances */ +/* ------------------------------------------------------------------------- */ +#define OriginalPARAM 0 +#define ProductionPARAM 1 +#define ChvatalPARAM 2 +#define LoosePARAM 3 +#if 1 + #define ActivePARAM ProductionPARAM +#else + #define ActivePARAM LoosePARAM +#endif + + +/* Miscellaneous settings */ +/* ------------------------------------------------------------------------- */ +#ifndef Paranoia + #ifdef _DEBUG + #define Paranoia + #endif +#endif + + +/* Program version data */ +/* ------------------------------------------------------------------------- */ +#define MAJORVERSION 5 +#define MINORVERSION 5 +#define RELEASE 0 +#define BUILD 7 +#define BFPVERSION 12 /* Checked against bfp_compatible() */ +#define XLIVERSION 12 /* Checked against xli_compatible() */ +/* Note that both BFPVERSION and XLIVERSION typically have to be incremented + in the case that the lprec structure changes. */ + + +/* Include/header files */ +/* ------------------------------------------------------------------------- */ +#include +#include +#include +#include +#include + +#include "lp_types.h" +#include "lp_utils.h" + +#if (LoadInverseLib == TRUE) || (LoadLanguageLib == TRUE) + #ifdef WIN32 + #include + #else + #include + #endif +#endif + +#ifndef BFP_CALLMODEL + #ifdef WIN32 + #define BFP_CALLMODEL __stdcall /* "Standard" call model */ + #else + #define BFP_CALLMODEL + #endif +#endif +#ifndef XLI_CALLMODEL + #define XLI_CALLMODEL BFP_CALLMODEL +#endif + +#define REGISTER register /* Speed up certain operations */ + + +/* Definition of program constrants */ +/* ------------------------------------------------------------------------- */ +#define SIMPLEX_UNDEFINED 0 +#define SIMPLEX_Phase1_PRIMAL 1 +#define SIMPLEX_Phase1_DUAL 2 +#define SIMPLEX_Phase2_PRIMAL 4 +#define SIMPLEX_Phase2_DUAL 8 +#define SIMPLEX_DYNAMIC 16 +#define SIMPLEX_AUTODUALIZE 32 + +#define SIMPLEX_PRIMAL_PRIMAL (SIMPLEX_Phase1_PRIMAL + SIMPLEX_Phase2_PRIMAL) +#define SIMPLEX_DUAL_PRIMAL (SIMPLEX_Phase1_DUAL + SIMPLEX_Phase2_PRIMAL) +#define SIMPLEX_PRIMAL_DUAL (SIMPLEX_Phase1_PRIMAL + SIMPLEX_Phase2_DUAL) +#define SIMPLEX_DUAL_DUAL (SIMPLEX_Phase1_DUAL + SIMPLEX_Phase2_DUAL) +#define SIMPLEX_DEFAULT (SIMPLEX_DUAL_PRIMAL) + +/* Variable codes (internal) */ +#define ISREAL 0 +#define ISINTEGER 1 +#define ISSEMI 2 +#define ISSOS 4 +#define ISSOSTEMPINT 8 +#define ISGUB 16 + +/* Presolve defines */ +#define PRESOLVE_NONE 0 +#define PRESOLVE_ROWS 1 +#define PRESOLVE_COLS 2 +#define PRESOLVE_LINDEP 4 +#define PRESOLVE_AGGREGATE 8 /* Not implemented */ +#define PRESOLVE_SPARSER 16 /* Not implemented */ +#define PRESOLVE_SOS 32 +#define PRESOLVE_REDUCEMIP 64 +#define PRESOLVE_KNAPSACK 128 /* Implementation not tested completely */ +#define PRESOLVE_ELIMEQ2 256 +#define PRESOLVE_IMPLIEDFREE 512 +#define PRESOLVE_REDUCEGCD 1024 +#define PRESOLVE_PROBEFIX 2048 +#define PRESOLVE_PROBEREDUCE 4096 +#define PRESOLVE_ROWDOMINATE 8192 +#define PRESOLVE_COLDOMINATE 16384 /* Reduced functionality, should be expanded */ +#define PRESOLVE_MERGEROWS 32768 +#define PRESOLVE_IMPLIEDSLK 65536 +#define PRESOLVE_COLFIXDUAL 131072 +#define PRESOLVE_BOUNDS 262144 +#define PRESOLVE_LASTMASKMODE (PRESOLVE_DUALS - 1) +#define PRESOLVE_DUALS 524288 +#define PRESOLVE_SENSDUALS 1048576 + +/* Basis crash options */ +#define CRASH_NONE 0 +#define CRASH_NONBASICBOUNDS 1 +#define CRASH_MOSTFEASIBLE 2 +#define CRASH_LEASTDEGENERATE 3 + +/* Solution recomputation options (internal) */ +#define INITSOL_SHIFTZERO 0 +#define INITSOL_USEZERO 1 +#define INITSOL_ORIGINAL 2 + +/* Strategy codes to avoid or recover from degenerate pivots, + infeasibility or numeric errors via randomized bound relaxation */ +#define ANTIDEGEN_NONE 0 +#define ANTIDEGEN_FIXEDVARS 1 +#define ANTIDEGEN_COLUMNCHECK 2 +#define ANTIDEGEN_STALLING 4 +#define ANTIDEGEN_NUMFAILURE 8 +#define ANTIDEGEN_LOSTFEAS 16 +#define ANTIDEGEN_INFEASIBLE 32 +#define ANTIDEGEN_DYNAMIC 64 +#define ANTIDEGEN_DURINGBB 128 +#define ANTIDEGEN_RHSPERTURB 256 +#define ANTIDEGEN_BOUNDFLIP 512 +#define ANTIDEGEN_DEFAULT (ANTIDEGEN_FIXEDVARS | ANTIDEGEN_STALLING /* | ANTIDEGEN_INFEASIBLE */) + +/* REPORT defines */ +#define NEUTRAL 0 +#define CRITICAL 1 +#define SEVERE 2 +#define IMPORTANT 3 +#define NORMAL 4 +#define DETAILED 5 +#define FULL 6 + +/* MESSAGE defines */ +#define MSG_NONE 0 +#define MSG_PRESOLVE 1 +#define MSG_ITERATION 2 +#define MSG_INVERT 4 +#define MSG_LPFEASIBLE 8 +#define MSG_LPOPTIMAL 16 +#define MSG_LPEQUAL 32 +#define MSG_LPBETTER 64 +#define MSG_MILPFEASIBLE 128 +#define MSG_MILPEQUAL 256 +#define MSG_MILPBETTER 512 +#define MSG_MILPSTRATEGY 1024 +#define MSG_MILPOPTIMAL 2048 +#define MSG_PERFORMANCE 4096 +#define MSG_INITPSEUDOCOST 8192 + +/* MPS defines (internal) */ +#define MPSUNDEF -4 +#define MPSNAME -3 +#define MPSOBJSENSE -2 +#define MPSOBJNAME -1 +#define MPSROWS 0 +#define MPSCOLUMNS 1 +#define MPSRHS 2 +#define MPSBOUNDS 3 +#define MPSRANGES 4 +#define MPSSOS 5 + +#define MPSVARMASK "%-8s" +#define MPSVALUEMASK "%12g" + +/* Constraint type codes (internal) */ +#define ROWTYPE_EMPTY 0 +#define ROWTYPE_LE 1 +#define ROWTYPE_GE 2 +#define ROWTYPE_EQ 3 +#define ROWTYPE_CONSTRAINT ROWTYPE_EQ /* This is the mask for modes */ +#define ROWTYPE_OF 4 +#define ROWTYPE_INACTIVE 8 +#define ROWTYPE_RELAX 16 +#define ROWTYPE_GUB 32 +#define ROWTYPE_OFMAX (ROWTYPE_OF + ROWTYPE_GE) +#define ROWTYPE_OFMIN (ROWTYPE_OF + ROWTYPE_LE) +#define ROWTYPE_CHSIGN ROWTYPE_GE + +/* Public constraint codes */ +#define FR ROWTYPE_EMPTY +#define LE ROWTYPE_LE +#define GE ROWTYPE_GE +#define EQ ROWTYPE_EQ +#define OF ROWTYPE_OF + +/* MIP constraint classes */ +#define ROWCLASS_Unknown 0 /* Undefined/unknown */ +#define ROWCLASS_Objective 1 /* The objective function */ +#define ROWCLASS_GeneralREAL 2 /* General real-values constraint */ +#define ROWCLASS_GeneralMIP 3 /* General mixed integer/binary and real valued constraint */ +#define ROWCLASS_GeneralINT 4 /* General integer-only constraint */ +#define ROWCLASS_GeneralBIN 5 /* General binary-only constraint */ +#define ROWCLASS_KnapsackINT 6 /* Sum of positive integer times integer variables <= positive integer */ +#define ROWCLASS_KnapsackBIN 7 /* Sum of positive integer times binary variables <= positive integer */ +#define ROWCLASS_SetPacking 8 /* Sum of binary variables >= 1 */ +#define ROWCLASS_SetCover 9 /* Sum of binary variables <= 1 */ +#define ROWCLASS_GUB 10 /* Sum of binary variables = 1 */ +#define ROWCLASS_MAX ROWCLASS_GUB + +/* Column subsets (internal) */ +#define SCAN_USERVARS 1 +#define SCAN_SLACKVARS 2 +#define SCAN_ARTIFICIALVARS 4 +#define SCAN_PARTIALBLOCK 8 +#define USE_BASICVARS 16 +#define USE_NONBASICVARS 32 +#define SCAN_NORMALVARS (SCAN_USERVARS + SCAN_ARTIFICIALVARS) +#define SCAN_ALLVARS (SCAN_SLACKVARS + SCAN_USERVARS + SCAN_ARTIFICIALVARS) +#define USE_ALLVARS (USE_BASICVARS + USE_NONBASICVARS) +#define OMIT_FIXED 64 +#define OMIT_NONFIXED 128 + +/* Improvement defines */ +#define IMPROVE_NONE 0 +#define IMPROVE_SOLUTION 1 +#define IMPROVE_DUALFEAS 2 +#define IMPROVE_THETAGAP 4 +#define IMPROVE_BBSIMPLEX 8 +#define IMPROVE_DEFAULT (IMPROVE_DUALFEAS + IMPROVE_THETAGAP) +#define IMPROVE_INVERSE (IMPROVE_SOLUTION + IMPROVE_THETAGAP) + +/* Scaling types */ +#define SCALE_NONE 0 +#define SCALE_EXTREME 1 +#define SCALE_RANGE 2 +#define SCALE_MEAN 3 +#define SCALE_GEOMETRIC 4 +#define SCALE_FUTURE1 5 +#define SCALE_FUTURE2 6 +#define SCALE_CURTISREID 7 /* Override to Curtis-Reid "optimal" scaling */ + +/* Alternative scaling weights */ +#define SCALE_LINEAR 0 +#define SCALE_QUADRATIC 8 +#define SCALE_LOGARITHMIC 16 +#define SCALE_USERWEIGHT 31 +#define SCALE_MAXTYPE (SCALE_QUADRATIC-1) + +/* Scaling modes */ +#define SCALE_POWER2 32 /* As is or rounded to power of 2 */ +#define SCALE_EQUILIBRATE 64 /* Make sure that no scaled number is above 1 */ +#define SCALE_INTEGERS 128 /* Apply to integer columns/variables */ +#define SCALE_DYNUPDATE 256 /* Apply incrementally every solve() */ +#define SCALE_ROWSONLY 512 /* Override any scaling to only scale the rows */ +#define SCALE_COLSONLY 1024 /* Override any scaling to only scale the rows */ + +/* Standard defines for typical scaling models (no Lagrangeans) */ +#define SCALEMODEL_EQUILIBRATED (SCALE_LINEAR+SCALE_EXTREME+SCALE_INTEGERS) +#define SCALEMODEL_GEOMETRIC (SCALE_LINEAR+SCALE_GEOMETRIC+SCALE_INTEGERS) +#define SCALEMODEL_ARITHMETIC (SCALE_LINEAR+SCALE_MEAN+SCALE_INTEGERS) +#define SCALEMODEL_DYNAMIC (SCALEMODEL_GEOMETRIC+SCALE_EQUILIBRATE) +#define SCALEMODEL_CURTISREID (SCALE_CURTISREID+SCALE_INTEGERS+SCALE_POWER2) + +/* Iteration status and strategies (internal) */ +#define ITERATE_MAJORMAJOR 0 +#define ITERATE_MINORMAJOR 1 +#define ITERATE_MINORRETRY 2 + +/* Pricing methods */ +#define PRICER_FIRSTINDEX 0 +#define PRICER_DANTZIG 1 +#define PRICER_DEVEX 2 +#define PRICER_STEEPESTEDGE 3 +#define PRICER_LASTOPTION PRICER_STEEPESTEDGE + +/* Additional settings for pricers (internal) */ +#define PRICER_RANDFACT 0.1 +#define DEVEX_RESTARTLIMIT 1.0e+09 /* Reset the norms if any value exceeds this limit */ +#define DEVEX_MINVALUE 0.000 /* Minimum weight [0..1] for entering variable, consider 0.01 */ + +/* Pricing strategies */ +#define PRICE_PRIMALFALLBACK 4 /* In case of Steepest Edge, fall back to DEVEX in primal */ +#define PRICE_MULTIPLE 8 /* Enable multiple pricing (primal simplex) */ +#define PRICE_PARTIAL 16 /* Enable partial pricing */ +#define PRICE_ADAPTIVE 32 /* Temporarily use alternative strategy if cycling is detected */ +#define PRICE_HYBRID 64 /* NOT IMPLEMENTED */ +#define PRICE_RANDOMIZE 128 /* Adds a small randomization effect to the selected pricer */ +#define PRICE_AUTOPARTIAL 256 /* Detect and use data on the block structure of the model (primal) */ +#define PRICE_AUTOMULTIPLE 512 /* Automatically select multiple pricing (primal simplex) */ +#define PRICE_LOOPLEFT 1024 /* Scan entering/leaving columns left rather than right */ +#define PRICE_LOOPALTERNATE 2048 /* Scan entering/leaving columns alternatingly left/right */ +#define PRICE_HARRISTWOPASS 4096 /* Use Harris' primal pivot logic rather than the default */ +#define PRICE_FORCEFULL 8192 /* Non-user option to force full pricing */ +#define PRICE_TRUENORMINIT 16384 /* Use true norms for Devex and Steepest Edge initializations */ + +#define PRICE_STRATEGYMASK (PRICE_PRIMALFALLBACK + \ + PRICE_MULTIPLE + PRICE_PARTIAL + \ + PRICE_ADAPTIVE + PRICE_HYBRID + \ + PRICE_RANDOMIZE + PRICE_AUTOPARTIAL + PRICE_AUTOMULTIPLE + \ + PRICE_LOOPLEFT + PRICE_LOOPALTERNATE + \ + PRICE_HARRISTWOPASS + \ + PRICE_FORCEFULL + PRICE_TRUENORMINIT) + +/* B&B active variable codes (internal) */ +#define BB_REAL 0 +#define BB_INT 1 +#define BB_SC 2 +#define BB_SOS 3 +#define BB_GUB 4 + +/* B&B strategies */ +#define NODE_FIRSTSELECT 0 +#define NODE_GAPSELECT 1 +#define NODE_RANGESELECT 2 +#define NODE_FRACTIONSELECT 3 +#define NODE_PSEUDOCOSTSELECT 4 +#define NODE_PSEUDONONINTSELECT 5 /* Kjell Eikland #1 - Minimize B&B depth */ +#define NODE_PSEUDOFEASSELECT (NODE_PSEUDONONINTSELECT+NODE_WEIGHTREVERSEMODE) +#define NODE_PSEUDORATIOSELECT 6 /* Kjell Eikland #2 - Minimize a "cost/benefit" ratio */ +#define NODE_USERSELECT 7 +#define NODE_STRATEGYMASK (NODE_WEIGHTREVERSEMODE-1) /* Mask for B&B strategies */ +#define NODE_WEIGHTREVERSEMODE 8 +#define NODE_BRANCHREVERSEMODE 16 +#define NODE_GREEDYMODE 32 +#define NODE_PSEUDOCOSTMODE 64 +#define NODE_DEPTHFIRSTMODE 128 +#define NODE_RANDOMIZEMODE 256 +#define NODE_GUBMODE 512 +#define NODE_DYNAMICMODE 1024 +#define NODE_RESTARTMODE 2048 +#define NODE_BREADTHFIRSTMODE 4096 +#define NODE_AUTOORDER 8192 +#define NODE_RCOSTFIXING 16384 +#define NODE_STRONGINIT 32768 + +#define BRANCH_CEILING 0 +#define BRANCH_FLOOR 1 +#define BRANCH_AUTOMATIC 2 +#define BRANCH_DEFAULT 3 + +/* Action constants for simplex and B&B (internal) */ +#define ACTION_NONE 0 +#define ACTION_ACTIVE 1 +#define ACTION_REBASE 2 +#define ACTION_RECOMPUTE 4 +#define ACTION_REPRICE 8 +#define ACTION_REINVERT 16 +#define ACTION_TIMEDREINVERT 32 +#define ACTION_ITERATE 64 +#define ACTION_RESTART 255 + +/* Solver status values */ +#define UNKNOWNERROR -5 +#define DATAIGNORED -4 +#define NOBFP -3 +#define NOMEMORY -2 +#define NOTRUN -1 +#define OPTIMAL 0 +#define SUBOPTIMAL 1 +#define INFEASIBLE 2 +#define UNBOUNDED 3 +#define DEGENERATE 4 +#define NUMFAILURE 5 +#define USERABORT 6 +#define TIMEOUT 7 +#define RUNNING 8 +#define PRESOLVED 9 + +/* Branch & Bound and Lagrangean extra status values (internal) */ +#define PROCFAIL 10 +#define PROCBREAK 11 +#define FEASFOUND 12 +#define NOFEASFOUND 13 +#define FATHOMED 14 + +/* Status values internal to the solver (internal) */ +#define SWITCH_TO_PRIMAL 20 +#define SWITCH_TO_DUAL 21 +#define SINGULAR_BASIS 22 +#define LOSTFEAS 23 +#define MATRIXERROR 24 + +/* Objective testing options for "bb_better" (internal) */ +#define OF_RELAXED 0 +#define OF_INCUMBENT 1 +#define OF_WORKING 2 +#define OF_USERBREAK 3 +#define OF_HEURISTIC 4 +#define OF_DUALLIMIT 5 +#define OF_DELTA 8 /* Mode */ +#define OF_PROJECTED 16 /* Mode - future, not active */ + +#define OF_TEST_BT 1 +#define OF_TEST_BE 2 +#define OF_TEST_NE 3 +#define OF_TEST_WE 4 +#define OF_TEST_WT 5 +#define OF_TEST_RELGAP 8 /* Mode */ + + +/* Name list and sparse matrix storage parameters (internal) */ +#define MAT_START_SIZE 10000 +#define DELTACOLALLOC 100 +#define DELTAROWALLOC 100 +#define RESIZEFACTOR 4 /* Fractional increase in selected memory allocations */ + +/* Default solver parameters and tolerances (internal) */ +#define DEF_PARTIALBLOCKS 10 /* The default number of blocks for partial pricing */ +#define DEF_MAXRELAX 7 /* Maximum number of non-BB relaxations in MILP */ +#define DEF_MAXPIVOTRETRY 10 /* Maximum number of times to retry a div-0 situation */ +#define DEF_MAXSINGULARITIES 10 /* Maximum number of singularities in refactorization */ +#define MAX_MINITUPDATES 60 /* Maximum number of bound swaps between refactorizations + without recomputing the whole vector - contain errors */ +#define MIN_REFACTFREQUENCY 5 /* Refactorization frequency indicating an inherent + numerical instability of the basis */ +#define LAG_SINGULARLIMIT 5 /* Number of times the objective does not change + before it is assumed that the Lagrangean constraints + are non-binding, and therefore impossible to converge; + upper iteration limit is divided by this threshold */ +#define MIN_TIMEPIVOT 5.0e-02 /* Minimum time per pivot for reinversion optimization + purposes; use active monitoring only if a pivot + takes more than MINTIMEPIVOT seconds. 5.0e-2 is + roughly suitable for a 1GHz system. */ +#define MAX_STALLCOUNT 12 /* The absolute upper limit to the number of stalling or + cycling iterations before switching rule */ +#define MAX_RULESWITCH 5 /* The maximum number of times to try an alternate pricing rule + to recover from stalling; set negative for no limit. */ +#define DEF_TIMEDREFACT AUTOMATIC /* Default for timed refactorization in BFPs; + can be FALSE, TRUE or AUTOMATIC (dynamic) */ + +#define DEF_SCALINGLIMIT 5 /* The default maximum number of scaling iterations */ + +#define DEF_NEGRANGE -1.0e+06 /* Downward limit for expanded variable range before the + variable is split into positive and negative components */ +#define DEF_BB_LIMITLEVEL -50 /* Relative B&B limit to protect against very deep, + memory-consuming trees */ + +#define MAX_FRACSCALE 6 /* The maximum decimal scan range for simulated integers */ +#define RANDSCALE 100 /* Randomization scaling range */ +#define DOUBLEROUND 0.0e-02 /* Extra rounding scalar used in btran/ftran calculations; the + rationale for 0.0 is that prod_xA() uses rounding as well */ +#define DEF_EPSMACHINE 2.22e-16 /* Machine relative precision (doubles) */ +#define MIN_STABLEPIVOT 5.0 /* Minimum pivot magnitude assumed to be numerically stable */ + + +/* Precision macros */ +/* -------------------------------------------------------------------------------------- */ +#define PREC_REDUCEDCOST lp->epsvalue +#define PREC_IMPROVEGAP lp->epsdual +#define PREC_SUBSTFEASGAP lp->epsprimal +#if 1 + #define PREC_BASICSOLUTION lp->epsvalue /* Zero-rounding of RHS/basic solution vector */ +#else + #define PREC_BASICSOLUTION lp->epsmachine /* Zero-rounding of RHS/basic solution vector */ +#endif +#define LIMIT_ABS_REL 10.0 /* Limit for testing using relative metric */ + + +/* Parameters constants for short-cut setting of tolerances */ +/* -------------------------------------------------------------------------------------- */ +#define EPS_TIGHT 0 +#define EPS_MEDIUM 1 +#define EPS_LOOSE 2 +#define EPS_BAGGY 3 +#define EPS_DEFAULT EPS_TIGHT + + +#if ActivePARAM==ProductionPARAM /* PARAMETER SET FOR PRODUCTION */ +/* -------------------------------------------------------------------------------------- */ +#define DEF_INFINITE 1.0e+30 /* Limit for dynamic range */ +#define DEF_EPSVALUE 1.0e-12 /* High accuracy and feasibility preserving tolerance */ +#define DEF_EPSPRIMAL 1.0e-10 /* For rounding primal/RHS values to 0 */ +#define DEF_EPSDUAL 1.0e-09 /* For rounding reduced costs to 0 */ +#define DEF_EPSPIVOT 2.0e-07 /* Pivot reject threshold */ +#define DEF_PERTURB 1.0e-05 /* Perturbation scalar for degenerate problems; + must at least be RANDSCALE greater than EPSPRIMAL */ +#define DEF_EPSSOLUTION 1.0e-05 /* Margin of error for solution bounds */ +#define DEF_EPSINT 1.0e-07 /* Accuracy for considering a float value as integer */ + +#elif ActivePARAM==OriginalPARAM /* PARAMETER SET FOR LEGACY VERSIONS */ +/* -------------------------------------------------------------------------------------- */ +#define DEF_INFINITE 1.0e+24 /* Limit for dynamic range */ +#define DEF_EPSVALUE 1.0e-08 /* High accuracy and feasibility preserving tolerance */ +#define DEF_EPSPRIMAL 5.01e-07 /* For rounding primal/RHS values to 0, infeasibility */ +#define DEF_EPSDUAL 1.0e-06 /* For rounding reduced costs to 0 */ +#define DEF_EPSPIVOT 1.0e-04 /* Pivot reject threshold */ +#define DEF_PERTURB 1.0e-05 /* Perturbation scalar for degenerate problems; + must at least be RANDSCALE greater than EPSPRIMAL */ +#define DEF_EPSSOLUTION 1.0e-02 /* Margin of error for solution bounds */ +#define DEF_EPSINT 1.0e-03 /* Accuracy for considering a float value as integer */ + +#elif ActivePARAM==ChvatalPARAM /* PARAMETER SET EXAMPLES FROM Vacek Chvatal */ +/* -------------------------------------------------------------------------------------- */ +#define DEF_INFINITE 1.0e+30 /* Limit for dynamic range */ +#define DEF_EPSVALUE 1.0e-10 /* High accuracy and feasibility preserving tolerance */ +#define DEF_EPSPRIMAL 10e-07 /* For rounding primal/RHS values to 0 */ +#define DEF_EPSDUAL 10e-05 /* For rounding reduced costs to 0 */ +#define DEF_EPSPIVOT 10e-05 /* Pivot reject threshold */ +#define DEF_PERTURB 10e-03 /* Perturbation scalar for degenerate problems; + must at least be RANDSCALE greater than EPSPRIMAL */ +#define DEF_EPSSOLUTION 1.0e-05 /* Margin of error for solution bounds */ +#define DEF_EPSINT 5.0e-03 /* Accuracy for considering a float value as integer */ + +#elif ActivePARAM==LoosePARAM /* PARAMETER SET FOR LOOSE TOLERANCES */ +/* -------------------------------------------------------------------------------------- */ +#define DEF_INFINITE 1.0e+30 /* Limit for dynamic range */ +#define DEF_EPSVALUE 1.0e-10 /* High accuracy and feasibility preserving tolerance */ +#define DEF_EPSPRIMAL 5.01e-08 /* For rounding primal/RHS values to 0 */ +#define DEF_EPSDUAL 1.0e-07 /* For rounding reduced costs to 0 */ +#define DEF_EPSPIVOT 1.0e-05 /* Pivot reject threshold */ +#define DEF_PERTURB 1.0e-05 /* Perturbation scalar for degenerate problems; + must at least be RANDSCALE greater than EPSPRIMAL */ +#define DEF_EPSSOLUTION 1.0e-05 /* Margin of error for solution bounds */ +#define DEF_EPSINT 1.0e-04 /* Accuracy for considering a float value as integer */ + +#endif + + +#define DEF_MIP_GAP 1.0e-11 /* The default absolute and relative MIP gap */ +#define SCALEDINTFIXRANGE 1.6 /* Epsilon range multiplier < 2 for collapsing bounds to fix */ + +#define MIN_SCALAR 1.0e-10 /* Smallest allowed scaling adjustment */ +#define MAX_SCALAR 1.0e+10 /* Largest allowed scaling adjustment */ +#define DEF_SCALINGEPS 1.0e-02 /* Relative scaling convergence criterion for auto_scale */ + +#define DEF_LAGACCEPT 1.0e-03 /* Default Lagrangean convergence acceptance criterion */ +#define DEF_LAGCONTRACT 0.90 /* The contraction parameter for Lagrangean iterations */ +#define DEF_LAGMAXITERATIONS 100 /* The maximum number of Lagrangean iterations */ + +#define DEF_PSEUDOCOSTUPDATES 7 /* The default number of times pseudo-costs are recalculated; + experiments indicate that costs tend to stabilize */ +#define DEF_PSEUDOCOSTRESTART 0.15 /* The fraction of price updates required for B&B restart + when the mode is NODE_RESTARTMODE */ +#define DEF_MAXPRESOLVELOOPS 0 /* Upper limit to the number of loops during presolve, + <= 0 for no limit. */ + + +/* Hashing prototypes and function headers */ +/* ------------------------------------------------------------------------- */ +#include "lp_Hash.h" + + +/* Sparse matrix prototypes */ +/* ------------------------------------------------------------------------- */ +#include "lp_matrix.h" + + +/* Basis storage (mainly for B&B) */ +typedef struct _basisrec +{ + int level; + int *var_basic; + MYBOOL *is_basic; + MYBOOL *is_lower; + int pivots; + struct _basisrec *previous; +} basisrec; + +/* Presolve undo data storage */ +typedef struct _presolveundorec +{ + lprec *lp; + int orig_rows; + int orig_columns; + int orig_sum; + int *var_to_orig; /* sum_alloc+1 : Mapping of variables from solution to + best_solution to account for removed variables and + rows during presolve; a non-positive value indicates + that the constraint or variable was removed */ + int *orig_to_var; /* sum_alloc+1 : Mapping from original variable index to + current / working index number */ + REAL *fixed_rhs; /* rows_alloc+1 : Storage of values of presolved fixed colums */ + REAL *fixed_obj; /* columns_alloc+1: Storage of values of presolved fixed rows */ + DeltaVrec *deletedA; /* A matrix of eliminated data from matA */ + DeltaVrec *primalundo; /* Affine translation vectors for eliminated primal variables */ + DeltaVrec *dualundo; /* Affine translation vectors for eliminated dual variables */ + MYBOOL OFcolsdeleted; +} presolveundorec; + +/* Pseudo-cost arrays used during B&B */ +typedef struct _BBPSrec +{ + lprec *lp; + int pseodotype; + int updatelimit; + int updatesfinished; + REAL restartlimit; + MATitem *UPcost; + MATitem *LOcost; + struct _BBPSrec *secondary; +} BBPSrec; + +#include "lp_mipbb.h" + + +/* Partial pricing block data */ +typedef struct _partialrec { + lprec *lp; + int blockcount; /* ## The number of logical blocks or stages in the model */ + int blocknow; /* The currently active block */ + int *blockend; /* Array of column indeces giving the start of each block */ + int *blockpos; /* Array of column indeces giving the start scan position */ + MYBOOL isrow; +} partialrec; + + +/* Specially Ordered Sets (SOS) prototypes and settings */ +/* ------------------------------------------------------------------------- */ +/* SOS storage structure (LINEARSEARCH is typically in the 0-10 range) */ +#ifndef LINEARSEARCH +#define LINEARSEARCH 0 +#endif + +#include "lp_SOS.h" + + +/* Prototypes for user call-back functions */ +/* ------------------------------------------------------------------------- */ +typedef int (__WINAPI lphandle_intfunc)(lprec *lp, void *userhandle); +typedef void (__WINAPI lphandlestr_func)(lprec *lp, void *userhandle, char *buf); +typedef void (__WINAPI lphandleint_func)(lprec *lp, void *userhandle, int message); +typedef int (__WINAPI lphandleint_intfunc)(lprec *lp, void *userhandle, int message); + + +/* API typedef definitions */ +/* ------------------------------------------------------------------------- */ +typedef MYBOOL (__WINAPI add_column_func)(lprec *lp, REAL *column); +typedef MYBOOL (__WINAPI add_columnex_func)(lprec *lp, int count, REAL *column, int *rowno); +typedef MYBOOL (__WINAPI add_constraint_func)(lprec *lp, REAL *row, int constr_type, REAL rh); +typedef MYBOOL (__WINAPI add_constraintex_func)(lprec *lp, int count, REAL *row, int *colno, int constr_type, REAL rh); +typedef MYBOOL (__WINAPI add_lag_con_func)(lprec *lp, REAL *row, int con_type, REAL rhs); +typedef int (__WINAPI add_SOS_func)(lprec *lp, char *name, int sostype, int priority, int count, int *sosvars, REAL *weights); +typedef int (__WINAPI column_in_lp_func)(lprec *lp, REAL *column); +typedef lprec * (__WINAPI copy_lp_func)(lprec *lp); +typedef void (__WINAPI default_basis_func)(lprec *lp); +typedef MYBOOL (__WINAPI del_column_func)(lprec *lp, int colnr); +typedef MYBOOL (__WINAPI del_constraint_func)(lprec *lp, int rownr); +typedef void (__WINAPI delete_lp_func)(lprec *lp); +typedef MYBOOL (__WINAPI dualize_lp_func)(lprec *lp); +typedef void (__WINAPI free_lp_func)(lprec **plp); +typedef int (__WINAPI get_anti_degen_func)(lprec *lp); +typedef MYBOOL (__WINAPI get_basis_func)(lprec *lp, int *bascolumn, MYBOOL nonbasic); +typedef int (__WINAPI get_basiscrash_func)(lprec *lp); +typedef int (__WINAPI get_bb_depthlimit_func)(lprec *lp); +typedef int (__WINAPI get_bb_floorfirst_func)(lprec *lp); +typedef int (__WINAPI get_bb_rule_func)(lprec *lp); +typedef MYBOOL (__WINAPI get_bounds_tighter_func)(lprec *lp); +typedef REAL (__WINAPI get_break_at_value_func)(lprec *lp); +typedef char * (__WINAPI get_col_name_func)(lprec *lp, int colnr); +typedef MYBOOL (__WINAPI get_column_func)(lprec *lp, int colnr, REAL *column); +typedef int (__WINAPI get_columnex_func)(lprec *lp, int colnr, REAL *column, int *nzrow); +typedef int (__WINAPI get_constr_type_func)(lprec *lp, int rownr); +typedef REAL (__WINAPI get_constr_value_func)(lprec *lp, int rownr, int count, REAL *primsolution, int *nzindex); +typedef MYBOOL (__WINAPI get_constraints_func)(lprec *lp, REAL *constr); +typedef MYBOOL (__WINAPI get_dual_solution_func)(lprec *lp, REAL *rc); +typedef REAL (__WINAPI get_epsb_func)(lprec *lp); +typedef REAL (__WINAPI get_epsd_func)(lprec *lp); +typedef REAL (__WINAPI get_epsel_func)(lprec *lp); +typedef REAL (__WINAPI get_epsint_func)(lprec *lp); +typedef REAL (__WINAPI get_epsperturb_func)(lprec *lp); +typedef REAL (__WINAPI get_epspivot_func)(lprec *lp); +typedef int (__WINAPI get_improve_func)(lprec *lp); +typedef REAL (__WINAPI get_infinite_func)(lprec *lp); +typedef MYBOOL (__WINAPI get_lambda_func)(lprec *lp, REAL *lambda); +typedef REAL (__WINAPI get_lowbo_func)(lprec *lp, int colnr); +typedef int (__WINAPI get_lp_index_func)(lprec *lp, int orig_index); +typedef char * (__WINAPI get_lp_name_func)(lprec *lp); +typedef int (__WINAPI get_Lrows_func)(lprec *lp); +typedef REAL (__WINAPI get_mat_func)(lprec *lp, int rownr, int colnr); +typedef REAL (__WINAPI get_mat_byindex_func)(lprec *lp, int matindex, MYBOOL isrow, MYBOOL adjustsign); +typedef int (__WINAPI get_max_level_func)(lprec *lp); +typedef int (__WINAPI get_maxpivot_func)(lprec *lp); +typedef REAL (__WINAPI get_mip_gap_func)(lprec *lp, MYBOOL absolute); +typedef int (__WINAPI get_multiprice_func)(lprec *lp, MYBOOL getabssize); +typedef MYBOOL (__WINAPI is_use_names_func)(lprec *lp, MYBOOL isrow); +typedef void (__WINAPI set_use_names_func)(lprec *lp, MYBOOL isrow, MYBOOL use_names); +typedef int (__WINAPI get_nameindex_func)(lprec *lp, char *varname, MYBOOL isrow); +typedef int (__WINAPI get_Ncolumns_func)(lprec *lp); +typedef REAL (__WINAPI get_negrange_func)(lprec *lp); +typedef int (__WINAPI get_nz_func)(lprec *lp); +typedef int (__WINAPI get_Norig_columns_func)(lprec *lp); +typedef int (__WINAPI get_Norig_rows_func)(lprec *lp); +typedef int (__WINAPI get_Nrows_func)(lprec *lp); +typedef REAL (__WINAPI get_obj_bound_func)(lprec *lp); +typedef REAL (__WINAPI get_objective_func)(lprec *lp); +typedef int (__WINAPI get_orig_index_func)(lprec *lp, int lp_index); +typedef char * (__WINAPI get_origcol_name_func)(lprec *lp, int colnr); +typedef char * (__WINAPI get_origrow_name_func)(lprec *lp, int rownr); +typedef void (__WINAPI get_partialprice_func)(lprec *lp, int *blockcount, int *blockstart, MYBOOL isrow); +typedef int (__WINAPI get_pivoting_func)(lprec *lp); +typedef int (__WINAPI get_presolve_func)(lprec *lp); +typedef int (__WINAPI get_presolveloops_func)(lprec *lp); +typedef MYBOOL (__WINAPI get_primal_solution_func)(lprec *lp, REAL *pv); +typedef int (__WINAPI get_print_sol_func)(lprec *lp); +typedef MYBOOL (__WINAPI get_pseudocosts_func)(lprec *lp, REAL *clower, REAL *cupper, int *updatelimit); +typedef MYBOOL (__WINAPI get_ptr_constraints_func)(lprec *lp, REAL **constr); +typedef MYBOOL (__WINAPI get_ptr_dual_solution_func)(lprec *lp, REAL **rc); +typedef MYBOOL (__WINAPI get_ptr_lambda_func)(lprec *lp, REAL **lambda); +typedef MYBOOL (__WINAPI get_ptr_primal_solution_func)(lprec *lp, REAL **pv); +typedef MYBOOL (__WINAPI get_ptr_sensitivity_obj_func)(lprec *lp, REAL **objfrom, REAL **objtill); +typedef MYBOOL (__WINAPI get_ptr_sensitivity_objex_func)(lprec *lp, REAL **objfrom, REAL **objtill, REAL **objfromvalue, REAL **objtillvalue); +typedef MYBOOL (__WINAPI get_ptr_sensitivity_rhs_func)(lprec *lp, REAL **duals, REAL **dualsfrom, REAL **dualstill); +typedef MYBOOL (__WINAPI get_ptr_variables_func)(lprec *lp, REAL **var); +typedef REAL (__WINAPI get_rh_func)(lprec *lp, int rownr); +typedef REAL (__WINAPI get_rh_range_func)(lprec *lp, int rownr); +typedef int (__WINAPI get_rowex_func)(lprec *lp, int rownr, REAL *row, int *colno); +typedef MYBOOL (__WINAPI get_row_func)(lprec *lp, int rownr, REAL *row); +typedef char * (__WINAPI get_row_name_func)(lprec *lp, int rownr); +typedef REAL (__WINAPI get_scalelimit_func)(lprec *lp); +typedef int (__WINAPI get_scaling_func)(lprec *lp); +typedef MYBOOL (__WINAPI get_sensitivity_obj_func)(lprec *lp, REAL *objfrom, REAL *objtill); +typedef MYBOOL (__WINAPI get_sensitivity_objex_func)(lprec *lp, REAL *objfrom, REAL *objtill, REAL *objfromvalue, REAL *objtillvalue); +typedef MYBOOL (__WINAPI get_sensitivity_rhs_func)(lprec *lp, REAL *duals, REAL *dualsfrom, REAL *dualstill); +typedef int (__WINAPI get_simplextype_func)(lprec *lp); +typedef int (__WINAPI get_solutioncount_func)(lprec *lp); +typedef int (__WINAPI get_solutionlimit_func)(lprec *lp); +typedef int (__WINAPI get_status_func)(lprec *lp); +typedef char * (__WINAPI get_statustext_func)(lprec *lp, int statuscode); +typedef long (__WINAPI get_timeout_func)(lprec *lp); +typedef COUNTER (__WINAPI get_total_iter_func)(lprec *lp); +typedef COUNTER (__WINAPI get_total_nodes_func)(lprec *lp); +typedef REAL (__WINAPI get_upbo_func)(lprec *lp, int colnr); +typedef int (__WINAPI get_var_branch_func)(lprec *lp, int colnr); +typedef REAL (__WINAPI get_var_dualresult_func)(lprec *lp, int index); +typedef REAL (__WINAPI get_var_primalresult_func)(lprec *lp, int index); +typedef int (__WINAPI get_var_priority_func)(lprec *lp, int colnr); +typedef MYBOOL (__WINAPI get_variables_func)(lprec *lp, REAL *var); +typedef int (__WINAPI get_verbose_func)(lprec *lp); +typedef REAL (__WINAPI get_working_objective_func)(lprec *lp); +typedef MYBOOL (__WINAPI has_BFP_func)(lprec *lp); +typedef MYBOOL (__WINAPI has_XLI_func)(lprec *lp); +typedef MYBOOL (__WINAPI is_add_rowmode_func)(lprec *lp); +typedef MYBOOL (__WINAPI is_anti_degen_func)(lprec *lp, int testmask); +typedef MYBOOL (__WINAPI is_binary_func)(lprec *lp, int colnr); +typedef MYBOOL (__WINAPI is_break_at_first_func)(lprec *lp); +typedef MYBOOL (__WINAPI is_constr_type_func)(lprec *lp, int rownr, int mask); +typedef MYBOOL (__WINAPI is_debug_func)(lprec *lp); +typedef MYBOOL (__WINAPI is_feasible_func)(lprec *lp, REAL *values, REAL threshold); +typedef MYBOOL (__WINAPI is_unbounded_func)(lprec *lp, int colnr); +typedef MYBOOL (__WINAPI is_infinite_func)(lprec *lp, REAL value); +typedef MYBOOL (__WINAPI is_int_func)(lprec *lp, int column); +typedef MYBOOL (__WINAPI is_integerscaling_func)(lprec *lp); +typedef MYBOOL (__WINAPI is_lag_trace_func)(lprec *lp); +typedef MYBOOL (__WINAPI is_maxim_func)(lprec *lp); +typedef MYBOOL (__WINAPI is_nativeBFP_func)(lprec *lp); +typedef MYBOOL (__WINAPI is_nativeXLI_func)(lprec *lp); +typedef MYBOOL (__WINAPI is_negative_func)(lprec *lp, int colnr); +typedef MYBOOL (__WINAPI is_obj_in_basis_func)(lprec *lp); +typedef MYBOOL (__WINAPI is_piv_mode_func)(lprec *lp, int testmask); +typedef MYBOOL (__WINAPI is_piv_rule_func)(lprec *lp, int rule); +typedef MYBOOL (__WINAPI is_presolve_func)(lprec *lp, int testmask); +typedef MYBOOL (__WINAPI is_scalemode_func)(lprec *lp, int testmask); +typedef MYBOOL (__WINAPI is_scaletype_func)(lprec *lp, int scaletype); +typedef MYBOOL (__WINAPI is_semicont_func)(lprec *lp, int colnr); +typedef MYBOOL (__WINAPI is_SOS_var_func)(lprec *lp, int colnr); +typedef MYBOOL (__WINAPI is_trace_func)(lprec *lp); +typedef void (__WINAPI lp_solve_version_func)(int *majorversion, int *minorversion, int *release, int *build); +typedef lprec * (__WINAPI make_lp_func)(int rows, int columns); +typedef void (__WINAPI print_constraints_func)(lprec *lp, int columns); +typedef MYBOOL (__WINAPI print_debugdump_func)(lprec *lp, char *filename); +typedef void (__WINAPI print_duals_func)(lprec *lp); +typedef void (__WINAPI print_lp_func)(lprec *lp); +typedef void (__WINAPI print_objective_func)(lprec *lp); +typedef void (__WINAPI print_scales_func)(lprec *lp); +typedef void (__WINAPI print_solution_func)(lprec *lp, int columns); +typedef void (__WINAPI print_str_func)(lprec *lp, char *str); +typedef void (__WINAPI print_tableau_func)(lprec *lp); +typedef void (__WINAPI put_abortfunc_func)(lprec *lp, lphandle_intfunc newctrlc, void *ctrlchandle); +typedef void (__WINAPI put_bb_nodefunc_func)(lprec *lp, lphandleint_intfunc newnode, void *bbnodehandle); +typedef void (__WINAPI put_bb_branchfunc_func)(lprec *lp, lphandleint_intfunc newbranch, void *bbbranchhandle); +typedef void (__WINAPI put_logfunc_func)(lprec *lp, lphandlestr_func newlog, void *loghandle); +typedef void (__WINAPI put_msgfunc_func)(lprec *lp, lphandleint_func newmsg, void *msghandle, int mask); +typedef MYBOOL (__WINAPI read_LPhandle_func)(lprec **lp, FILE *filehandle, int verbose, char *lp_name); +typedef MYBOOL (__WINAPI read_MPShandle_func)(lprec **lp, FILE *filehandle, int typeMPS, int verbose); +typedef lprec * (__WINAPI read_XLI_func)(char *xliname, char *modelname, char *dataname, char *options, int verbose); +typedef MYBOOL (__WINAPI read_basis_func)(lprec *lp, char *filename, char *info); +typedef void (__WINAPI reset_basis_func)(lprec *lp); +typedef MYBOOL (__WINAPI read_params_func)(lprec *lp, char *filename, char *options); +typedef void (__WINAPI reset_params_func)(lprec *lp); +typedef MYBOOL (__WINAPI resize_lp_func)(lprec *lp, int rows, int columns); +typedef MYBOOL (__WINAPI set_add_rowmode_func)(lprec *lp, MYBOOL turnon); +typedef void (__WINAPI set_anti_degen_func)(lprec *lp, int anti_degen); +typedef int (__WINAPI set_basisvar_func)(lprec *lp, int basisPos, int enteringCol); +typedef MYBOOL (__WINAPI set_basis_func)(lprec *lp, int *bascolumn, MYBOOL nonbasic); +typedef void (__WINAPI set_basiscrash_func)(lprec *lp, int mode); +typedef void (__WINAPI set_bb_depthlimit_func)(lprec *lp, int bb_maxlevel); +typedef void (__WINAPI set_bb_floorfirst_func)(lprec *lp, int bb_floorfirst); +typedef void (__WINAPI set_bb_rule_func)(lprec *lp, int bb_rule); +typedef MYBOOL (__WINAPI set_BFP_func)(lprec *lp, char *filename); +typedef MYBOOL (__WINAPI set_binary_func)(lprec *lp, int colnr, MYBOOL must_be_bin); +typedef MYBOOL (__WINAPI set_bounds_func)(lprec *lp, int colnr, REAL lower, REAL upper); +typedef void (__WINAPI set_bounds_tighter_func)(lprec *lp, MYBOOL tighten); +typedef void (__WINAPI set_break_at_first_func)(lprec *lp, MYBOOL break_at_first); +typedef void (__WINAPI set_break_at_value_func)(lprec *lp, REAL break_at_value); +typedef MYBOOL (__WINAPI set_column_func)(lprec *lp, int colnr, REAL *column); +typedef MYBOOL (__WINAPI set_columnex_func)(lprec *lp, int colnr, int count, REAL *column, int *rowno); +typedef MYBOOL (__WINAPI set_col_name_func)(lprec *lp, int colnr, char *new_name); +typedef MYBOOL (__WINAPI set_constr_type_func)(lprec *lp, int rownr, int con_type); +typedef void (__WINAPI set_debug_func)(lprec *lp, MYBOOL debug); +typedef void (__WINAPI set_epsb_func)(lprec *lp, REAL epsb); +typedef void (__WINAPI set_epsd_func)(lprec *lp, REAL epsd); +typedef void (__WINAPI set_epsel_func)(lprec *lp, REAL epsel); +typedef void (__WINAPI set_epsint_func)(lprec *lp, REAL epsint); +typedef MYBOOL (__WINAPI set_epslevel_func)(lprec *lp, int epslevel); +typedef void (__WINAPI set_epsperturb_func)(lprec *lp, REAL epsperturb); +typedef void (__WINAPI set_epspivot_func)(lprec *lp, REAL epspivot); +typedef MYBOOL (__WINAPI set_unbounded_func)(lprec *lp, int colnr); +typedef void (__WINAPI set_improve_func)(lprec *lp, int improve); +typedef void (__WINAPI set_infinite_func)(lprec *lp, REAL infinite); +typedef MYBOOL (__WINAPI set_int_func)(lprec *lp, int colnr, MYBOOL must_be_int); +typedef void (__WINAPI set_lag_trace_func)(lprec *lp, MYBOOL lag_trace); +typedef MYBOOL (__WINAPI set_lowbo_func)(lprec *lp, int colnr, REAL value); +typedef MYBOOL (__WINAPI set_lp_name_func)(lprec *lp, char *lpname); +typedef MYBOOL (__WINAPI set_mat_func)(lprec *lp, int row, int column, REAL value); +typedef void (__WINAPI set_maxim_func)(lprec *lp); +typedef void (__WINAPI set_maxpivot_func)(lprec *lp, int max_num_inv); +typedef void (__WINAPI set_minim_func)(lprec *lp); +typedef void (__WINAPI set_mip_gap_func)(lprec *lp, MYBOOL absolute, REAL mip_gap); +typedef MYBOOL (__WINAPI set_multiprice_func)(lprec *lp, int multiblockdiv); +typedef void (__WINAPI set_negrange_func)(lprec *lp, REAL negrange); +typedef MYBOOL (__WINAPI set_obj_func)(lprec *lp, int colnr, REAL value); +typedef void (__WINAPI set_obj_bound_func)(lprec *lp, REAL obj_bound); +typedef MYBOOL (__WINAPI set_obj_fn_func)(lprec *lp, REAL *row); +typedef MYBOOL (__WINAPI set_obj_fnex_func)(lprec *lp, int count, REAL *row, int *colno); +typedef void (__WINAPI set_obj_in_basis_func)(lprec *lp, MYBOOL obj_in_basis); +typedef MYBOOL (__WINAPI set_outputfile_func)(lprec *lp, char *filename); +typedef void (__WINAPI set_outputstream_func)(lprec *lp, FILE *stream); +typedef MYBOOL (__WINAPI set_partialprice_func)(lprec *lp, int blockcount, int *blockstart, MYBOOL isrow); +typedef void (__WINAPI set_pivoting_func)(lprec *lp, int piv_rule); +typedef void (__WINAPI set_preferdual_func)(lprec *lp, MYBOOL dodual); +typedef void (__WINAPI set_presolve_func)(lprec *lp, int presolvemode, int maxloops); +typedef void (__WINAPI set_print_sol_func)(lprec *lp, int print_sol); +typedef MYBOOL (__WINAPI set_pseudocosts_func)(lprec *lp, REAL *clower, REAL *cupper, int *updatelimit); +typedef MYBOOL (__WINAPI set_rh_func)(lprec *lp, int rownr, REAL value); +typedef MYBOOL (__WINAPI set_rh_range_func)(lprec *lp, int rownr, REAL deltavalue); +typedef void (__WINAPI set_rh_vec_func)(lprec *lp, REAL *rh); +typedef MYBOOL (__WINAPI set_row_func)(lprec *lp, int rownr, REAL *row); +typedef MYBOOL (__WINAPI set_rowex_func)(lprec *lp, int rownr, int count, REAL *row, int *colno); +typedef MYBOOL (__WINAPI set_row_name_func)(lprec *lp, int rownr, char *new_name); +typedef void (__WINAPI set_scalelimit_func)(lprec *lp, REAL scalelimit); +typedef void (__WINAPI set_scaling_func)(lprec *lp, int scalemode); +typedef MYBOOL (__WINAPI set_semicont_func)(lprec *lp, int colnr, MYBOOL must_be_sc); +typedef void (__WINAPI set_sense_func)(lprec *lp, MYBOOL maximize); +typedef void (__WINAPI set_simplextype_func)(lprec *lp, int simplextype); +typedef void (__WINAPI set_solutionlimit_func)(lprec *lp, int limit); +typedef void (__WINAPI set_timeout_func)(lprec *lp, long sectimeout); +typedef void (__WINAPI set_trace_func)(lprec *lp, MYBOOL trace); +typedef MYBOOL (__WINAPI set_upbo_func)(lprec *lp, int colnr, REAL value); +typedef MYBOOL (__WINAPI set_var_branch_func)(lprec *lp, int colnr, int branch_mode); +typedef MYBOOL (__WINAPI set_var_weights_func)(lprec *lp, REAL *weights); +typedef void (__WINAPI set_verbose_func)(lprec *lp, int verbose); +typedef MYBOOL (__WINAPI set_XLI_func)(lprec *lp, char *filename); +typedef int (__WINAPI solve_func)(lprec *lp); +typedef MYBOOL (__WINAPI str_add_column_func)(lprec *lp, char *col_string); +typedef MYBOOL (__WINAPI str_add_constraint_func)(lprec *lp, char *row_string ,int constr_type, REAL rh); +typedef MYBOOL (__WINAPI str_add_lag_con_func)(lprec *lp, char *row_string, int con_type, REAL rhs); +typedef MYBOOL (__WINAPI str_set_obj_fn_func)(lprec *lp, char *row_string); +typedef MYBOOL (__WINAPI str_set_rh_vec_func)(lprec *lp, char *rh_string); +typedef REAL (__WINAPI time_elapsed_func)(lprec *lp); +typedef void (__WINAPI unscale_func)(lprec *lp); +typedef MYBOOL (__WINAPI write_lp_func)(lprec *lp, char *filename); +typedef MYBOOL (__WINAPI write_LP_func)(lprec *lp, FILE *output); +typedef MYBOOL (__WINAPI write_mps_func)(lprec *lp, char *filename); +typedef MYBOOL (__WINAPI write_MPS_func)(lprec *lp, FILE *output); +typedef MYBOOL (__WINAPI write_freemps_func)(lprec *lp, char *filename); +typedef MYBOOL (__WINAPI write_freeMPS_func)(lprec *lp, FILE *output); +typedef MYBOOL (__WINAPI write_XLI_func)(lprec *lp, char *filename, char *options, MYBOOL results); +typedef MYBOOL (__WINAPI write_basis_func)(lprec *lp, char *filename); +typedef MYBOOL (__WINAPI write_params_func)(lprec *lp, char *filename, char *options); + + +/* Prototypes for callbacks from basis inverse/factorization libraries */ +/* ------------------------------------------------------------------------- */ +typedef MYBOOL (__WINAPI userabortfunc)(lprec *lp, int level); +typedef void (__VACALL reportfunc)(lprec *lp, int level, char *format, ...); +typedef char * (__VACALL explainfunc)(lprec *lp, char *format, ...); +typedef int (__WINAPI getvectorfunc)(lprec *lp, int varin, REAL *pcol, int *nzlist, int *maxabs); +typedef int (__WINAPI getpackedfunc)(lprec *lp, int j, int rn[], double bj[]); +typedef REAL (__WINAPI get_OF_activefunc)(lprec *lp, int varnr, REAL mult); +typedef int (__WINAPI getMDOfunc)(lprec *lp, MYBOOL *usedpos, int *colorder, int *size, MYBOOL symmetric); +typedef MYBOOL (__WINAPI invertfunc)(lprec *lp, MYBOOL shiftbounds, MYBOOL final); +typedef void (__WINAPI set_actionfunc)(int *actionvar, int actionmask); +typedef MYBOOL (__WINAPI is_actionfunc)(int actionvar, int testmask); +typedef void (__WINAPI clear_actionfunc)(int *actionvar, int actionmask); + + +/* Prototypes for basis inverse/factorization libraries */ +/* ------------------------------------------------------------------------- */ +typedef char *(BFP_CALLMODEL BFPchar)(void); +typedef void (BFP_CALLMODEL BFP_lp)(lprec *lp); +typedef void (BFP_CALLMODEL BFP_lpint)(lprec *lp, int newsize); +typedef int (BFP_CALLMODEL BFPint_lp)(lprec *lp); +typedef int (BFP_CALLMODEL BFPint_lpint)(lprec *lp, int kind); +typedef REAL (BFP_CALLMODEL BFPreal_lp)(lprec *lp); +typedef REAL *(BFP_CALLMODEL BFPrealp_lp)(lprec *lp); +typedef void (BFP_CALLMODEL BFP_lpbool)(lprec *lp, MYBOOL maximum); +typedef int (BFP_CALLMODEL BFPint_lpbool)(lprec *lp, MYBOOL maximum); +typedef int (BFP_CALLMODEL BFPint_lpintintboolbool)(lprec *lp, int uservars, int Bsize, MYBOOL *usedpos, MYBOOL final); +typedef void (BFP_CALLMODEL BFP_lprealint)(lprec *lp, REAL *pcol, int *nzidx); +typedef void (BFP_CALLMODEL BFP_lprealintrealint)(lprec *lp, REAL *prow, int *pnzidx, REAL *drow, int *dnzidx); +typedef MYBOOL (BFP_CALLMODEL BFPbool_lp)(lprec *lp); +typedef MYBOOL (BFP_CALLMODEL BFPbool_lpbool)(lprec *lp, MYBOOL changesign); +typedef MYBOOL (BFP_CALLMODEL BFPbool_lpint)(lprec *lp, int size); +typedef MYBOOL (BFP_CALLMODEL BFPbool_lpintintchar)(lprec *lp, int size, int deltasize, char *options); +typedef MYBOOL (BFP_CALLMODEL BFPbool_lpintintint)(lprec *lp, int size, int deltasize, int sizeofvar); +typedef LREAL (BFP_CALLMODEL BFPlreal_lpintintreal)(lprec *lp, int row_nr, int col_nr, REAL *pcol); +typedef REAL (BFP_CALLMODEL BFPreal_lplrealreal)(lprec *lp, LREAL theta, REAL *pcol); + +typedef int (BFP_CALLMODEL getcolumnex_func)(lprec *lp, int colnr, REAL *nzvalues, int *nzrows, int *mapin); +typedef int (BFP_CALLMODEL BFPint_lpintrealcbintint)(lprec *lp, int items, getcolumnex_func cb, int *maprow, int*mapcol); + +/* Prototypes for external language libraries */ +/* ------------------------------------------------------------------------- */ +typedef char *(XLI_CALLMODEL XLIchar)(void); +typedef MYBOOL (XLI_CALLMODEL XLIbool_lpintintint)(lprec* lp, int size, int deltasize, int sizevar); +typedef MYBOOL (XLI_CALLMODEL XLIbool_lpcharcharcharint)(lprec *lp, char *modelname, char *dataname, char *options, int verbose); +typedef MYBOOL (XLI_CALLMODEL XLIbool_lpcharcharbool)(lprec *lp, char *filename, char *options, MYBOOL results); + + +/* Main lp_solve prototypes and function definitions */ +/* ------------------------------------------------------------------------- */ +struct _lprec +{ + /* Full list of exported functions made available in a quasi object-oriented fashion */ + add_column_func *add_column; + add_columnex_func *add_columnex; + add_constraint_func *add_constraint; + add_constraintex_func *add_constraintex; + add_lag_con_func *add_lag_con; + add_SOS_func *add_SOS; + column_in_lp_func *column_in_lp; + copy_lp_func *copy_lp; + default_basis_func *default_basis; + del_column_func *del_column; + del_constraint_func *del_constraint; + delete_lp_func *delete_lp; + dualize_lp_func *dualize_lp; + free_lp_func *free_lp; + get_anti_degen_func *get_anti_degen; + get_basis_func *get_basis; + get_basiscrash_func *get_basiscrash; + get_bb_depthlimit_func *get_bb_depthlimit; + get_bb_floorfirst_func *get_bb_floorfirst; + get_bb_rule_func *get_bb_rule; + get_bounds_tighter_func *get_bounds_tighter; + get_break_at_value_func *get_break_at_value; + get_col_name_func *get_col_name; + get_columnex_func *get_columnex; + get_constr_type_func *get_constr_type; + get_constr_value_func *get_constr_value; + get_constraints_func *get_constraints; + get_dual_solution_func *get_dual_solution; + get_epsb_func *get_epsb; + get_epsd_func *get_epsd; + get_epsel_func *get_epsel; + get_epsint_func *get_epsint; + get_epsperturb_func *get_epsperturb; + get_epspivot_func *get_epspivot; + get_improve_func *get_improve; + get_infinite_func *get_infinite; + get_lambda_func *get_lambda; + get_lowbo_func *get_lowbo; + get_lp_index_func *get_lp_index; + get_lp_name_func *get_lp_name; + get_Lrows_func *get_Lrows; + get_mat_func *get_mat; + get_mat_byindex_func *get_mat_byindex; + get_max_level_func *get_max_level; + get_maxpivot_func *get_maxpivot; + get_mip_gap_func *get_mip_gap; + get_multiprice_func *get_multiprice; + get_nameindex_func *get_nameindex; + get_Ncolumns_func *get_Ncolumns; + get_negrange_func *get_negrange; + get_nz_func *get_nonzeros; + get_Norig_columns_func *get_Norig_columns; + get_Norig_rows_func *get_Norig_rows; + get_Nrows_func *get_Nrows; + get_obj_bound_func *get_obj_bound; + get_objective_func *get_objective; + get_orig_index_func *get_orig_index; + get_origcol_name_func *get_origcol_name; + get_origrow_name_func *get_origrow_name; + get_partialprice_func *get_partialprice; + get_pivoting_func *get_pivoting; + get_presolve_func *get_presolve; + get_presolveloops_func *get_presolveloops; + get_primal_solution_func *get_primal_solution; + get_print_sol_func *get_print_sol; + get_pseudocosts_func *get_pseudocosts; + get_ptr_constraints_func *get_ptr_constraints; + get_ptr_dual_solution_func *get_ptr_dual_solution; + get_ptr_lambda_func *get_ptr_lambda; + get_ptr_primal_solution_func *get_ptr_primal_solution; + get_ptr_sensitivity_obj_func *get_ptr_sensitivity_obj; + get_ptr_sensitivity_objex_func *get_ptr_sensitivity_objex; + get_ptr_sensitivity_rhs_func *get_ptr_sensitivity_rhs; + get_ptr_variables_func *get_ptr_variables; + get_rh_func *get_rh; + get_rh_range_func *get_rh_range; + get_row_func *get_row; + get_rowex_func *get_rowex; + get_row_name_func *get_row_name; + get_scalelimit_func *get_scalelimit; + get_scaling_func *get_scaling; + get_sensitivity_obj_func *get_sensitivity_obj; + get_sensitivity_objex_func *get_sensitivity_objex; + get_sensitivity_rhs_func *get_sensitivity_rhs; + get_simplextype_func *get_simplextype; + get_solutioncount_func *get_solutioncount; + get_solutionlimit_func *get_solutionlimit; + get_status_func *get_status; + get_statustext_func *get_statustext; + get_timeout_func *get_timeout; + get_total_iter_func *get_total_iter; + get_total_nodes_func *get_total_nodes; + get_upbo_func *get_upbo; + get_var_branch_func *get_var_branch; + get_var_dualresult_func *get_var_dualresult; + get_var_primalresult_func *get_var_primalresult; + get_var_priority_func *get_var_priority; + get_variables_func *get_variables; + get_verbose_func *get_verbose; + get_working_objective_func *get_working_objective; + has_BFP_func *has_BFP; + has_XLI_func *has_XLI; + is_add_rowmode_func *is_add_rowmode; + is_anti_degen_func *is_anti_degen; + is_binary_func *is_binary; + is_break_at_first_func *is_break_at_first; + is_constr_type_func *is_constr_type; + is_debug_func *is_debug; + is_feasible_func *is_feasible; + is_infinite_func *is_infinite; + is_int_func *is_int; + is_integerscaling_func *is_integerscaling; + is_lag_trace_func *is_lag_trace; + is_maxim_func *is_maxim; + is_nativeBFP_func *is_nativeBFP; + is_nativeXLI_func *is_nativeXLI; + is_negative_func *is_negative; + is_obj_in_basis_func *is_obj_in_basis; + is_piv_mode_func *is_piv_mode; + is_piv_rule_func *is_piv_rule; + is_presolve_func *is_presolve; + is_scalemode_func *is_scalemode; + is_scaletype_func *is_scaletype; + is_semicont_func *is_semicont; + is_SOS_var_func *is_SOS_var; + is_trace_func *is_trace; + is_unbounded_func *is_unbounded; + is_use_names_func *is_use_names; + lp_solve_version_func *lp_solve_version; + make_lp_func *make_lp; + print_constraints_func *print_constraints; + print_debugdump_func *print_debugdump; + print_duals_func *print_duals; + print_lp_func *print_lp; + print_objective_func *print_objective; + print_scales_func *print_scales; + print_solution_func *print_solution; + print_str_func *print_str; + print_tableau_func *print_tableau; + put_abortfunc_func *put_abortfunc; + put_bb_nodefunc_func *put_bb_nodefunc; + put_bb_branchfunc_func *put_bb_branchfunc; + put_logfunc_func *put_logfunc; + put_msgfunc_func *put_msgfunc; + read_LPhandle_func *read_LPhandle; + read_MPShandle_func *read_MPShandle; + read_XLI_func *read_XLI; + read_params_func *read_params; + read_basis_func *read_basis; + reset_basis_func *reset_basis; + reset_params_func *reset_params; + resize_lp_func *resize_lp; + set_add_rowmode_func *set_add_rowmode; + set_anti_degen_func *set_anti_degen; + set_basisvar_func *set_basisvar; + set_basis_func *set_basis; + set_basiscrash_func *set_basiscrash; + set_bb_depthlimit_func *set_bb_depthlimit; + set_bb_floorfirst_func *set_bb_floorfirst; + set_bb_rule_func *set_bb_rule; + set_BFP_func *set_BFP; + set_binary_func *set_binary; + set_bounds_func *set_bounds; + set_bounds_tighter_func *set_bounds_tighter; + set_break_at_first_func *set_break_at_first; + set_break_at_value_func *set_break_at_value; + set_column_func *set_column; + set_columnex_func *set_columnex; + set_col_name_func *set_col_name; + set_constr_type_func *set_constr_type; + set_debug_func *set_debug; + set_epsb_func *set_epsb; + set_epsd_func *set_epsd; + set_epsel_func *set_epsel; + set_epsint_func *set_epsint; + set_epslevel_func *set_epslevel; + set_epsperturb_func *set_epsperturb; + set_epspivot_func *set_epspivot; + set_unbounded_func *set_unbounded; + set_improve_func *set_improve; + set_infinite_func *set_infinite; + set_int_func *set_int; + set_lag_trace_func *set_lag_trace; + set_lowbo_func *set_lowbo; + set_lp_name_func *set_lp_name; + set_mat_func *set_mat; + set_maxim_func *set_maxim; + set_maxpivot_func *set_maxpivot; + set_minim_func *set_minim; + set_mip_gap_func *set_mip_gap; + set_multiprice_func *set_multiprice; + set_negrange_func *set_negrange; + set_obj_bound_func *set_obj_bound; + set_obj_fn_func *set_obj_fn; + set_obj_fnex_func *set_obj_fnex; + set_obj_func *set_obj; + set_obj_in_basis_func *set_obj_in_basis; + set_outputfile_func *set_outputfile; + set_outputstream_func *set_outputstream; + set_partialprice_func *set_partialprice; + set_pivoting_func *set_pivoting; + set_preferdual_func *set_preferdual; + set_presolve_func *set_presolve; + set_print_sol_func *set_print_sol; + set_pseudocosts_func *set_pseudocosts; + set_rh_func *set_rh; + set_rh_range_func *set_rh_range; + set_rh_vec_func *set_rh_vec; + set_row_func *set_row; + set_rowex_func *set_rowex; + set_row_name_func *set_row_name; + set_scalelimit_func *set_scalelimit; + set_scaling_func *set_scaling; + set_semicont_func *set_semicont; + set_sense_func *set_sense; + set_simplextype_func *set_simplextype; + set_solutionlimit_func *set_solutionlimit; + set_timeout_func *set_timeout; + set_trace_func *set_trace; + set_upbo_func *set_upbo; + set_use_names_func *set_use_names; + set_var_branch_func *set_var_branch; + set_var_weights_func *set_var_weights; + set_verbose_func *set_verbose; + set_XLI_func *set_XLI; + solve_func *solve; + str_add_column_func *str_add_column; + str_add_constraint_func *str_add_constraint; + str_add_lag_con_func *str_add_lag_con; + str_set_obj_fn_func *str_set_obj_fn; + str_set_rh_vec_func *str_set_rh_vec; + time_elapsed_func *time_elapsed; + unscale_func *unscale; + write_lp_func *write_lp; + write_LP_func *write_LP; + write_mps_func *write_mps; + write_MPS_func *write_MPS; + write_freemps_func *write_freemps; + write_freeMPS_func *write_freeMPS; + write_XLI_func *write_XLI; + write_basis_func *write_basis; + write_params_func *write_params; + + /* Spacer */ + int *alignmentspacer; + + /* Problem description */ + char *lp_name; /* The name of the model */ + + /* Problem sizes */ + int sum; /* The total number of variables, including slacks */ + int rows; + int columns; + int equalities; /* No of non-Lagrangean equality constraints in the problem */ + int boundedvars; /* Count of bounded variables */ + int INTfuture1; + + /* Memory allocation sizes */ + int sum_alloc; /* The allocated memory for row+column-sized data */ + int rows_alloc; /* The allocated memory for row-sized data */ + int columns_alloc; /* The allocated memory for column-sized data */ + + /* Model status and solver result variables */ + MYBOOL source_is_file; /* The base model was read from a file */ + MYBOOL model_is_pure; /* The model has been built entirely from row and column additions */ + MYBOOL model_is_valid; /* Has this lp pased the 'test' */ + MYBOOL tighten_on_set; /* Specify if bounds will be tightened or overriden at bound setting */ + MYBOOL names_used; /* Flag to indicate if names for rows and columns are used */ + MYBOOL use_row_names; /* Flag to indicate if names for rows are used */ + MYBOOL use_col_names; /* Flag to indicate if names for columns are used */ + + MYBOOL lag_trace; /* Print information on Lagrange progression */ + MYBOOL spx_trace; /* Print information on simplex progression */ + MYBOOL bb_trace; /* TRUE to print extra debug information */ + MYBOOL streamowned; /* TRUE if the handle should be closed at delete_lp() */ + MYBOOL obj_in_basis; /* TRUE if the objective function is in the basis matrix */ + + int spx_status; /* Simplex solver feasibility/mode code */ + int lag_status; /* Extra status variable for lag_solve */ + int solutioncount; /* number of equal-valued solutions found (up to solutionlimit) */ + int solutionlimit; /* upper number of equal-valued solutions kept track of */ + + REAL real_solution; /* Optimal non-MIP solution base */ + REAL *solution; /* sum_alloc+1 : Solution array of the next to optimal LP, + Index 0 : Objective function value, + Indeces 1..rows : Slack variable values, + Indeced rows+1..sum : Variable values */ + REAL *best_solution; /* sum_alloc+1 : Solution array of optimal 'Integer' LP, + structured as the solution array above */ + REAL *full_solution; /* sum_alloc+1 : Final solution array expanded for deleted variables */ + REAL *edgeVector; /* Array of reduced cost scaling norms (DEVEX and Steepest Edge) */ + + REAL *drow; /* sum+1: Reduced costs of the last simplex */ + int *nzdrow; /* sum+1: Indeces of non-zero reduced costs of the last simplex */ + REAL *duals; /* rows_alloc+1 : The dual variables of the last LP */ + REAL *full_duals; /* sum_alloc+1: Final duals array expanded for deleted variables */ + REAL *dualsfrom; /* sum_alloc+1 :The sensitivity on dual variables/reduced costs + of the last LP */ + REAL *dualstill; /* sum_alloc+1 :The sensitivity on dual variables/reduced costs + of the last LP */ + REAL *objfrom; /* columns_alloc+1 :The sensitivity on objective function + of the last LP */ + REAL *objtill; /* columns_alloc+1 :The sensitivity on objective function + of the last LP */ + REAL *objfromvalue; /* columns_alloc+1 :The value of the variables when objective value + is at its from value of the last LP */ + REAL *orig_obj; /* Unused pointer - Placeholder for OF not part of B */ + REAL *obj; /* Special vector used to temporarily change the OF vector */ + + COUNTER current_iter; /* Number of iterations in the current/last simplex */ + COUNTER total_iter; /* Number of iterations over all B&B steps */ + COUNTER current_bswap; /* Number of bound swaps in the current/last simplex */ + COUNTER total_bswap; /* Number of bount swaps over all B&B steps */ + int solvecount; /* The number of solve() performed in this model */ + int max_pivots; /* Number of pivots between refactorizations of the basis */ + + /* Various execution parameters */ + int simplex_strategy; /* Set desired combination of primal and dual simplex algorithms */ + int simplex_mode; /* Specifies the current simplex mode during solve; see simplex_strategy */ + int verbose; /* Set amount of run-time messages and results */ + int print_sol; /* TRUE to print optimal solution; AUTOMATIC skips zeros */ + FILE *outstream; /* Output stream, initialized to STDOUT */ + + /* Main Branch and Bound settings */ + MYBOOL *bb_varbranch; /* Determines branching strategy at the individual variable level; + the setting here overrides the bb_floorfirst setting */ + int piv_strategy; /* Strategy for selecting row and column entering/leaving */ + int _piv_rule_; /* Internal working rule-part of piv_strategy above */ + int bb_rule; /* Rule for selecting B&B variables */ + MYBOOL bb_floorfirst; /* Set BRANCH_FLOOR for B&B to set variables to floor bound first; + conversely with BRANCH_CEILING, the ceiling value is set first */ + MYBOOL bb_breakfirst; /* TRUE to stop at first feasible solution */ + MYBOOL _piv_left_; /* Internal variable indicating active pricing loop order */ + MYBOOL BOOLfuture1; + + REAL scalelimit; /* Relative convergence criterion for iterated scaling */ + int scalemode; /* OR-ed codes for data scaling */ + int improve; /* Set to non-zero for iterative improvement */ + int anti_degen; /* Anti-degen strategy (or none) TRUE to avoid cycling */ + int do_presolve; /* PRESOLVE_ parameters for LP presolving */ + int presolveloops; /* Maximum number of presolve loops */ + + int perturb_count; /* The number of bound relaxation retries performed */ + + /* Row and column names storage variables */ + hashelem **row_name; /* rows_alloc+1 */ + hashelem **col_name; /* columns_alloc+1 */ + hashtable *rowname_hashtab; /* hash table to store row names */ + hashtable *colname_hashtab; /* hash table to store column names */ + + /* Optionally specify continuous rows/column blocks for partial pricing */ + partialrec *rowblocks; + partialrec *colblocks; + + /* Row and column type codes */ + MYBOOL *var_type; /* sum_alloc+1 : TRUE if variable must be integer */ + + /* Data for multiple pricing */ + multirec *multivars; + int multiblockdiv; /* The divisor used to set or augment pricing block */ + + /* Variable (column) parameters */ + int fixedvars; /* The current number of basic fixed variables in the model */ + int int_vars; /* Number of variables required to be integer */ + + int sc_vars; /* Number of semi-continuous variables */ + REAL *sc_lobound; /* sum_columns+1 : TRUE if variable is semi-continuous; + value replaced by conventional lower bound during solve */ + int *var_is_free; /* columns+1: Index of twin variable if variable is free */ + int *var_priority; /* columns: Priority-mapping of variables */ + + SOSgroup *GUB; /* Pointer to record containing GUBs */ + + int sos_vars; /* Number of variables in the sos_priority list */ + int sos_ints; /* Number of integers in SOS'es above */ + SOSgroup *SOS; /* Pointer to record containing all SOS'es */ + int *sos_priority; /* Priority-sorted list of variables (no duplicates) */ + + /* Optionally specify list of active rows/columns used in multiple pricing */ + REAL *bsolveVal; /* rows+1: bsolved solution vector for reduced costs */ + int *bsolveIdx; /* rows+1: Non-zero indeces of bsolveVal */ + + /* RHS storage */ + REAL *orig_rhs; /* rows_alloc+1 : The RHS after scaling and sign + changing, but before 'Bound transformation' */ + LREAL *rhs; /* rows_alloc+1 : The RHS of the current simplex tableau */ + + /* Row (constraint) parameters */ + int *row_type; /* rows_alloc+1 : Row/constraint type coding */ + + /* Optionally specify data for dual long-step */ + multirec *longsteps; + + /* Original and working row and variable bounds */ + REAL *orig_upbo; /* sum_alloc+1 : Bound before transformations */ + REAL *upbo; /* " " : Upper bound after transformation and B&B work */ + REAL *orig_lowbo; /* " " */ + REAL *lowbo; /* " " : Lower bound after transformation and B&B work */ + + /* User data and basis factorization matrices (ETA or LU, product form) */ + MATrec *matA; + INVrec *invB; + + /* Basis and bounds */ + BBrec *bb_bounds; /* The linked list of B&B bounds */ + BBrec *rootbounds; /* The bounds at the lowest B&B level */ + basisrec *bb_basis; /* The linked list of B&B bases */ + basisrec *rootbasis; + OBJmonrec *monitor; /* Objective monitoring record for stalling/degeneracy handling */ + + /* Scaling parameters */ + REAL *scalars; /* sum_alloc+1:0..Rows the scaling of the rows, + Rows+1..Sum the scaling of the columns */ + MYBOOL scaling_used; /* TRUE if scaling is used */ + MYBOOL columns_scaled; /* TRUE if the columns are scaled too */ + MYBOOL varmap_locked; /* Determines whether the var_to_orig and orig_to_var are fixed */ + + /* Variable state information */ + MYBOOL basis_valid; /* TRUE is the basis is still valid */ + int crashmode; /* Basis crashing mode (or none) */ + int *var_basic; /* rows_alloc+1: The list of columns in the basis */ + REAL *val_nonbasic; /* Array to store current values of non-basic variables */ + MYBOOL *is_basic; /* sum_alloc+1: TRUE if the column is in the basis */ + MYBOOL *is_lower; /* " " : TRUE if the variable is at its + lower bound (or in the basis), FALSE otherwise */ + + /* Simplex basis indicators */ + int *rejectpivot; /* List of unacceptable pivot choices due to division-by-zero */ + BBPSrec *bb_PseudoCost; /* Data structure for costing of node branchings */ + int bb_PseudoUpdates; /* Maximum number of updates for pseudo-costs */ + int bb_strongbranches; /* The number of strong B&B branches performed */ + int is_strongbranch; /* Are we currently in a strong branch mode? */ + int bb_improvements; /* The number of discrete B&B objective improvement steps */ + + /* Solver working variables */ + REAL rhsmax; /* The maximum |value| of the rhs vector at any iteration */ + REAL suminfeas; /* The working sum of primal and dual infeasibilities */ + REAL bigM; /* Original objective weighting in primal phase 1 */ + REAL P1extraVal; /* Phase 1 OF/RHS offset for feasibility */ + int P1extraDim; /* Phase 1 additional columns/rows for feasibility */ + int spx_action; /* ACTION_ variables for the simplex routine */ + MYBOOL spx_perturbed; /* The variable bounds were relaxed/perturbed into this simplex */ + MYBOOL bb_break; /* Solver working variable; signals break of the B&B */ + MYBOOL wasPreprocessed; /* The solve preprocessing was performed */ + MYBOOL wasPresolved; /* The solve presolver was invoked */ + int INTfuture2; + + /* Lagragean solver storage and parameters */ + MATrec *matL; + REAL *lag_rhs; /* Array of Lagrangean rhs vector */ + int *lag_con_type; /* Array of GT, LT or EQ */ + REAL *lambda; /* Lambda values (Lagrangean multipliers) */ + REAL lag_bound; /* The Lagrangian lower OF bound */ + REAL lag_accept; /* The Lagrangian convergence criterion */ + + /* Solver thresholds */ + REAL infinite; /* Limit for dynamic range */ + REAL negrange; /* Limit for negative variable range */ + REAL epsmachine; /* Default machine accuracy */ + REAL epsvalue; /* Input data precision / rounding of data values to 0 */ + REAL epsprimal; /* For rounding RHS values to 0/infeasibility */ + REAL epsdual; /* For rounding reduced costs to zero */ + REAL epspivot; /* Pivot reject tolerance */ + REAL epsperturb; /* Perturbation scalar */ + REAL epssolution; /* The solution tolerance for final validation */ + + /* Branch & Bound working parameters */ + int bb_status; /* Indicator that the last solvelp() gave an improved B&B solution */ + int bb_level; /* Solver B&B working variable (recursion depth) */ + int bb_maxlevel; /* The deepest B&B level of the last solution */ + int bb_limitlevel; /* The maximum B&B level allowed */ + COUNTER bb_totalnodes; /* Total number of nodes processed in B&B */ + int bb_solutionlevel; /* The B&B level of the last / best solution */ + int bb_cutpoolsize; /* Size of the B&B cut pool */ + int bb_cutpoolused; /* Currently used cut pool */ + int bb_constraintOF; /* General purpose B&B parameter (typically for testing) */ + int *bb_cuttype; /* The type of the currently used cuts */ + int *bb_varactive; /* The B&B state of the variable; 0 means inactive */ + DeltaVrec *bb_upperchange; /* Changes to upper bounds during the B&B phase */ + DeltaVrec *bb_lowerchange; /* Changes to lower bounds during the B&B phase */ + + REAL bb_deltaOF; /* Minimum OF step value; computed at beginning of solve() */ + + REAL bb_breakOF; /* User-settable value for the objective function deemed + to be sufficiently good in an integer problem */ + REAL bb_limitOF; /* "Dual" bound / limit to final optimal MIP solution */ + REAL bb_heuristicOF; /* Set initial "at least better than" guess for objective function + (can significantly speed up B&B iterations) */ + REAL bb_parentOF; /* The OF value of the previous BB simplex */ + REAL bb_workOF; /* The unadjusted OF value for the current best solution */ + + /* Internal work arrays allocated as required */ + presolveundorec *presolve_undo; + workarraysrec *workarrays; + + /* MIP parameters */ + REAL epsint; /* Margin of error in determining if a float value is integer */ + REAL mip_absgap; /* Absolute MIP gap */ + REAL mip_relgap; /* Relative MIP gap */ + + /* Time/timer variables and extended status text */ + double timecreate; + double timestart; + double timeheuristic; + double timepresolved; + double timeend; + long sectimeout; + + /* Extended status message text set via explain() */ + char *ex_status; + + /* Refactorization engine interface routines (for dynamic DLL/SO BFPs) */ +#if LoadInverseLib == TRUE + #ifdef WIN32 + HINSTANCE hBFP; + #else + void *hBFP; + #endif +#endif + BFPchar *bfp_name; + BFPbool_lpintintint *bfp_compatible; + BFPbool_lpintintchar *bfp_init; + BFP_lp *bfp_free; + BFPbool_lpint *bfp_resize; + BFPint_lp *bfp_memallocated; + BFPbool_lp *bfp_restart; + BFPbool_lp *bfp_mustrefactorize; + BFPint_lp *bfp_preparefactorization; + BFPint_lpintintboolbool *bfp_factorize; + BFP_lp *bfp_finishfactorization; + BFP_lp *bfp_updaterefactstats; + BFPlreal_lpintintreal *bfp_prepareupdate; + BFPreal_lplrealreal *bfp_pivotRHS; + BFPbool_lpbool *bfp_finishupdate; + BFP_lprealint *bfp_ftran_prepare; + BFP_lprealint *bfp_ftran_normal; + BFP_lprealint *bfp_btran_normal; + BFP_lprealintrealint *bfp_btran_double; + BFPint_lp *bfp_status; + BFPint_lpbool *bfp_nonzeros; + BFPbool_lp *bfp_implicitslack; + BFPint_lp *bfp_indexbase; + BFPint_lp *bfp_rowoffset; + BFPint_lp *bfp_pivotmax; + BFPbool_lpint *bfp_pivotalloc; + BFPint_lp *bfp_colcount; + BFPbool_lp *bfp_canresetbasis; + BFPreal_lp *bfp_efficiency; + BFPrealp_lp *bfp_pivotvector; + BFPint_lp *bfp_pivotcount; + BFPint_lpint *bfp_refactcount; + BFPbool_lp *bfp_isSetI; + BFPint_lpintrealcbintint *bfp_findredundant; + + /* External language interface routines (for dynamic DLL/SO XLIs) */ +#if LoadLanguageLib == TRUE + #ifdef WIN32 + HINSTANCE hXLI; + #else + void *hXLI; + #endif +#endif + XLIchar *xli_name; + XLIbool_lpintintint *xli_compatible; + XLIbool_lpcharcharcharint *xli_readmodel; + XLIbool_lpcharcharbool *xli_writemodel; + + /* Miscellaneous internal functions made available externally */ + userabortfunc *userabort; + reportfunc *report; + explainfunc *explain; + getvectorfunc *get_lpcolumn; + getpackedfunc *get_basiscolumn; + get_OF_activefunc *get_OF_active; + getMDOfunc *getMDO; + invertfunc *invert; + set_actionfunc *set_action; + is_actionfunc *is_action; + clear_actionfunc *clear_action; + + /* User program interface callbacks */ + lphandle_intfunc *ctrlc; + void *ctrlchandle; /* User-specified "owner process ID" */ + lphandlestr_func *writelog; + void *loghandle; /* User-specified "owner process ID" */ + lphandlestr_func *debuginfo; + lphandleint_func *usermessage; + int msgmask; + void *msghandle; /* User-specified "owner process ID" */ + lphandleint_intfunc *bb_usenode; + void *bb_nodehandle; /* User-specified "owner process ID" */ + lphandleint_intfunc *bb_usebranch; + void *bb_branchhandle; /* User-specified "owner process ID" */ + +}; + + +#ifdef __cplusplus +__EXTERN_C { +#endif + + +/* User and system function interfaces */ +/* ------------------------------------------------------------------------- */ + +void __EXPORT_TYPE __WINAPI lp_solve_version(int *majorversion, int *minorversion, int *release, int *build); + +lprec __EXPORT_TYPE * __WINAPI make_lp(int rows, int columns); +MYBOOL __EXPORT_TYPE __WINAPI resize_lp(lprec *lp, int rows, int columns); +int __EXPORT_TYPE __WINAPI get_status(lprec *lp); +char __EXPORT_TYPE * __WINAPI get_statustext(lprec *lp, int statuscode); +MYBOOL __EXPORT_TYPE __WINAPI is_obj_in_basis(lprec *lp); +void __EXPORT_TYPE __WINAPI set_obj_in_basis(lprec *lp, MYBOOL obj_in_basis); +/* Create and initialise a lprec structure defaults */ + +lprec __EXPORT_TYPE * __WINAPI copy_lp(lprec *lp); +MYBOOL __EXPORT_TYPE __WINAPI dualize_lp(lprec *lp); +STATIC MYBOOL memopt_lp(lprec *lp, int rowextra, int colextra, int nzextra); +/* Copy or dualize the lp */ + +void __EXPORT_TYPE __WINAPI delete_lp(lprec *lp); +void __EXPORT_TYPE __WINAPI free_lp(lprec **plp); +/* Remove problem from memory */ + +MYBOOL __EXPORT_TYPE __WINAPI set_lp_name(lprec *lp, char *lpname); +char __EXPORT_TYPE * __WINAPI get_lp_name(lprec *lp); +/* Set and get the problem name */ + +MYBOOL __EXPORT_TYPE __WINAPI has_BFP(lprec *lp); +MYBOOL __EXPORT_TYPE __WINAPI is_nativeBFP(lprec *lp); +MYBOOL __EXPORT_TYPE __WINAPI set_BFP(lprec *lp, char *filename); +/* Set basis factorization engine */ + +lprec __EXPORT_TYPE * __WINAPI read_XLI(char *xliname, char *modelname, char *dataname, char *options, int verbose); +MYBOOL __EXPORT_TYPE __WINAPI write_XLI(lprec *lp, char *filename, char *options, MYBOOL results); +MYBOOL __EXPORT_TYPE __WINAPI has_XLI(lprec *lp); +MYBOOL __EXPORT_TYPE __WINAPI is_nativeXLI(lprec *lp); +MYBOOL __EXPORT_TYPE __WINAPI set_XLI(lprec *lp, char *filename); +/* Set external language interface */ + +MYBOOL __EXPORT_TYPE __WINAPI set_obj(lprec *lp, int colnr, REAL value); +MYBOOL __EXPORT_TYPE __WINAPI set_obj_fn(lprec *lp, REAL *row); +MYBOOL __EXPORT_TYPE __WINAPI set_obj_fnex(lprec *lp, int count, REAL *row, int *colno); +/* set the objective function (Row 0) of the matrix */ +MYBOOL __EXPORT_TYPE __WINAPI str_set_obj_fn(lprec *lp, char *row_string); +/* The same, but with string input */ +void __EXPORT_TYPE __WINAPI set_sense(lprec *lp, MYBOOL maximize); +void __EXPORT_TYPE __WINAPI set_maxim(lprec *lp); +void __EXPORT_TYPE __WINAPI set_minim(lprec *lp); +MYBOOL __EXPORT_TYPE __WINAPI is_maxim(lprec *lp); +/* Set optimization direction for the objective function */ + +MYBOOL __EXPORT_TYPE __WINAPI add_constraint(lprec *lp, REAL *row, int constr_type, REAL rh); +MYBOOL __EXPORT_TYPE __WINAPI add_constraintex(lprec *lp, int count, REAL *row, int *colno, int constr_type, REAL rh); +MYBOOL __EXPORT_TYPE __WINAPI set_add_rowmode(lprec *lp, MYBOOL turnon); +MYBOOL __EXPORT_TYPE __WINAPI is_add_rowmode(lprec *lp); +/* Add a constraint to the problem, row is the constraint row, rh is the right hand side, + constr_type is the type of constraint (LE (<=), GE(>=), EQ(=)) */ +MYBOOL __EXPORT_TYPE __WINAPI str_add_constraint(lprec *lp, char *row_string, int constr_type, REAL rh); +/* The same, but with string input */ + +MYBOOL __EXPORT_TYPE __WINAPI set_row(lprec *lp, int rownr, REAL *row); +MYBOOL __EXPORT_TYPE __WINAPI set_rowex(lprec *lp, int rownr, int count, REAL *row, int *colno); +MYBOOL __EXPORT_TYPE __WINAPI get_row(lprec *lp, int rownr, REAL *row); +int __EXPORT_TYPE __WINAPI get_rowex(lprec *lp, int rownr, REAL *row, int *colno); +/* Fill row with the row row_nr from the problem */ + +MYBOOL __EXPORT_TYPE __WINAPI del_constraint(lprec *lp, int rownr); +STATIC MYBOOL del_constraintex(lprec *lp, LLrec *rowmap); +/* Remove constrain nr del_row from the problem */ + +MYBOOL __EXPORT_TYPE __WINAPI add_lag_con(lprec *lp, REAL *row, int con_type, REAL rhs); +/* add a Lagrangian constraint of form Row' x contype Rhs */ +MYBOOL __EXPORT_TYPE __WINAPI str_add_lag_con(lprec *lp, char *row_string, int con_type, REAL rhs); +/* The same, but with string input */ +void __EXPORT_TYPE __WINAPI set_lag_trace(lprec *lp, MYBOOL lag_trace); +MYBOOL __EXPORT_TYPE __WINAPI is_lag_trace(lprec *lp); +/* Set debugging/tracing mode of the Lagrangean solver */ + +MYBOOL __EXPORT_TYPE __WINAPI set_constr_type(lprec *lp, int rownr, int con_type); +int __EXPORT_TYPE __WINAPI get_constr_type(lprec *lp, int rownr); +REAL __EXPORT_TYPE __WINAPI get_constr_value(lprec *lp, int rownr, int count, REAL *primsolution, int *nzindex); +MYBOOL __EXPORT_TYPE __WINAPI is_constr_type(lprec *lp, int rownr, int mask); +STATIC char *get_str_constr_type(lprec *lp, int con_type); +STATIC int get_constr_class(lprec *lp, int rownr); +STATIC char *get_str_constr_class(lprec *lp, int con_class); +/* Set the type of constraint in row Row (LE, GE, EQ) */ + +MYBOOL __EXPORT_TYPE __WINAPI set_rh(lprec *lp, int rownr, REAL value); +REAL __EXPORT_TYPE __WINAPI get_rh(lprec *lp, int rownr); +/* Set and get the right hand side of a constraint row */ +MYBOOL __EXPORT_TYPE __WINAPI set_rh_range(lprec *lp, int rownr, REAL deltavalue); +REAL __EXPORT_TYPE __WINAPI get_rh_range(lprec *lp, int rownr); +/* Set the RHS range; i.e. the lower and upper bounds of a constraint row */ +void __EXPORT_TYPE __WINAPI set_rh_vec(lprec *lp, REAL *rh); +/* Set the right hand side vector */ +MYBOOL __EXPORT_TYPE __WINAPI str_set_rh_vec(lprec *lp, char *rh_string); +/* The same, but with string input */ + +MYBOOL __EXPORT_TYPE __WINAPI add_column(lprec *lp, REAL *column); +MYBOOL __EXPORT_TYPE __WINAPI add_columnex(lprec *lp, int count, REAL *column, int *rowno); +MYBOOL __EXPORT_TYPE __WINAPI str_add_column(lprec *lp, char *col_string); +/* Add a column to the problem */ + +MYBOOL __EXPORT_TYPE __WINAPI set_column(lprec *lp, int colnr, REAL *column); +MYBOOL __EXPORT_TYPE __WINAPI set_columnex(lprec *lp, int colnr, int count, REAL *column, int *rowno); +/* Overwrite existing column data */ + +int __EXPORT_TYPE __WINAPI column_in_lp(lprec *lp, REAL *column); +/* Returns the column index if column is already present in lp, otherwise 0. + (Does not look at bounds and types, only looks at matrix values */ + +int __EXPORT_TYPE __WINAPI get_columnex(lprec *lp, int colnr, REAL *column, int *nzrow); +MYBOOL __EXPORT_TYPE __WINAPI get_column(lprec *lp, int colnr, REAL *column); +/* Fill column with the column col_nr from the problem */ + +MYBOOL __EXPORT_TYPE __WINAPI del_column(lprec *lp, int colnr); +STATIC MYBOOL del_columnex(lprec *lp, LLrec *colmap); +/* Delete a column */ + +MYBOOL __EXPORT_TYPE __WINAPI set_mat(lprec *lp, int rownr, int colnr, REAL value); +/* Fill in element (Row,Column) of the matrix + Row in [0..Rows] and Column in [1..Columns] */ +REAL __EXPORT_TYPE __WINAPI get_mat(lprec *lp, int rownr, int colnr); +REAL __EXPORT_TYPE __WINAPI get_mat_byindex(lprec *lp, int matindex, MYBOOL isrow, MYBOOL adjustsign); +int __EXPORT_TYPE __WINAPI get_nonzeros(lprec *lp); +/* get a single element from the matrix */ /* Name changed from "mat_elm" by KE */ + +void __EXPORT_TYPE __WINAPI set_bounds_tighter(lprec *lp, MYBOOL tighten); +MYBOOL get_bounds(lprec *lp, int column, REAL *lower, REAL *upper); +MYBOOL __EXPORT_TYPE __WINAPI get_bounds_tighter(lprec *lp); +MYBOOL __EXPORT_TYPE __WINAPI set_upbo(lprec *lp, int colnr, REAL value); +REAL __EXPORT_TYPE __WINAPI get_upbo(lprec *lp, int colnr); +MYBOOL __EXPORT_TYPE __WINAPI set_lowbo(lprec *lp, int colnr, REAL value); +REAL __EXPORT_TYPE __WINAPI get_lowbo(lprec *lp, int colnr); +MYBOOL __EXPORT_TYPE __WINAPI set_bounds(lprec *lp, int colnr, REAL lower, REAL upper); +MYBOOL __EXPORT_TYPE __WINAPI set_unbounded(lprec *lp, int colnr); +MYBOOL __EXPORT_TYPE __WINAPI is_unbounded(lprec *lp, int colnr); +/* Set the upper and lower bounds of a variable */ + +MYBOOL __EXPORT_TYPE __WINAPI set_int(lprec *lp, int colnr, MYBOOL must_be_int); +MYBOOL __EXPORT_TYPE __WINAPI is_int(lprec *lp, int colnr); +MYBOOL __EXPORT_TYPE __WINAPI set_binary(lprec *lp, int colnr, MYBOOL must_be_bin); +MYBOOL __EXPORT_TYPE __WINAPI is_binary(lprec *lp, int colnr); +MYBOOL __EXPORT_TYPE __WINAPI set_semicont(lprec *lp, int colnr, MYBOOL must_be_sc); +MYBOOL __EXPORT_TYPE __WINAPI is_semicont(lprec *lp, int colnr); +MYBOOL __EXPORT_TYPE __WINAPI is_negative(lprec *lp, int colnr); +MYBOOL __EXPORT_TYPE __WINAPI set_var_weights(lprec *lp, REAL *weights); +int __EXPORT_TYPE __WINAPI get_var_priority(lprec *lp, int colnr); +/* Set the type of variable */ + +MYBOOL __EXPORT_TYPE __WINAPI set_pseudocosts(lprec *lp, REAL *clower, REAL *cupper, int *updatelimit); +MYBOOL __EXPORT_TYPE __WINAPI get_pseudocosts(lprec *lp, REAL *clower, REAL *cupper, int *updatelimit); +/* Set initial values for, or get computed pseudocost vectors; + note that setting of pseudocosts can only happen in response to a + call-back function optionally requesting this */ + +int __EXPORT_TYPE __WINAPI add_SOS(lprec *lp, char *name, int sostype, int priority, int count, int *sosvars, REAL *weights); +MYBOOL __EXPORT_TYPE __WINAPI is_SOS_var(lprec *lp, int colnr); +/* Add SOS constraints */ + +MYBOOL __EXPORT_TYPE __WINAPI set_row_name(lprec *lp, int rownr, char *new_name); +char __EXPORT_TYPE * __WINAPI get_row_name(lprec *lp, int rownr); +char __EXPORT_TYPE * __WINAPI get_origrow_name(lprec *lp, int rownr); +/* Set/Get the name of a constraint row */ /* Get added by KE */ + +MYBOOL __EXPORT_TYPE __WINAPI set_col_name(lprec *lp, int colnr, char *new_name); +char __EXPORT_TYPE * __WINAPI get_col_name(lprec *lp, int colnr); +char __EXPORT_TYPE * __WINAPI get_origcol_name(lprec *lp, int colnr); +/* Set/Get the name of a variable column */ /* Get added by KE */ + +void __EXPORT_TYPE __WINAPI unscale(lprec *lp); +/* Undo previous scaling of the problem */ + +void __EXPORT_TYPE __WINAPI set_preferdual(lprec *lp, MYBOOL dodual); +void __EXPORT_TYPE __WINAPI set_simplextype(lprec *lp, int simplextype); +int __EXPORT_TYPE __WINAPI get_simplextype(lprec *lp); +/* Set/Get if lp_solve should prefer the dual simplex over the primal -- added by KE */ + +void __EXPORT_TYPE __WINAPI default_basis(lprec *lp); +void __EXPORT_TYPE __WINAPI set_basiscrash(lprec *lp, int mode); +int __EXPORT_TYPE __WINAPI get_basiscrash(lprec *lp); +int __EXPORT_TYPE __WINAPI set_basisvar(lprec *lp, int basisPos, int enteringCol); +MYBOOL __EXPORT_TYPE __WINAPI set_basis(lprec *lp, int *bascolumn, MYBOOL nonbasic); +MYBOOL __EXPORT_TYPE __WINAPI get_basis(lprec *lp, int *bascolumn, MYBOOL nonbasic); +void __EXPORT_TYPE __WINAPI reset_basis(lprec *lp); +/* Set/Get basis for a re-solved system */ /* Added by KE */ + +MYBOOL __EXPORT_TYPE __WINAPI is_feasible(lprec *lp, REAL *values, REAL threshold); +/* returns TRUE if the vector in values is a feasible solution to the lp */ + +int __EXPORT_TYPE __WINAPI solve(lprec *lp); +/* Solve the problem */ + +REAL __EXPORT_TYPE __WINAPI time_elapsed(lprec *lp); +/* Return the number of seconds since start of solution process */ + +void __EXPORT_TYPE __WINAPI put_bb_nodefunc(lprec *lp, lphandleint_intfunc newnode, void *bbnodehandle); +void __EXPORT_TYPE __WINAPI put_bb_branchfunc(lprec *lp, lphandleint_intfunc newbranch, void *bbbranchhandle); +/* Allow the user to override B&B node and branching decisions */ + +void __EXPORT_TYPE __WINAPI put_abortfunc(lprec *lp, lphandle_intfunc newctrlc, void *ctrlchandle); +/* Allow the user to define an interruption callback function */ + +void __EXPORT_TYPE __WINAPI put_logfunc(lprec *lp, lphandlestr_func newlog, void *loghandle); +/* Allow the user to define a logging function */ + +void __EXPORT_TYPE __WINAPI put_msgfunc(lprec *lp, lphandleint_func newmsg, void *msghandle, int mask); +/* Allow the user to define an event-driven message/reporting */ + +MYBOOL __EXPORT_TYPE __WINAPI get_primal_solution(lprec *lp, REAL *pv); +MYBOOL __EXPORT_TYPE __WINAPI get_ptr_primal_solution(lprec *lp, REAL **pv); +MYBOOL __EXPORT_TYPE __WINAPI get_dual_solution(lprec *lp, REAL *rc); +MYBOOL __EXPORT_TYPE __WINAPI get_ptr_dual_solution(lprec *lp, REAL **rc); +MYBOOL __EXPORT_TYPE __WINAPI get_lambda(lprec *lp, REAL *lambda); +MYBOOL __EXPORT_TYPE __WINAPI get_ptr_lambda(lprec *lp, REAL **lambda); +/* Get the primal, dual/reduced costs and Lambda vectors */ + +/* Read an MPS file */ +lprec __EXPORT_TYPE * __WINAPI read_MPS(char *filename, int verbose); +lprec __EXPORT_TYPE * __WINAPI read_mps(FILE *filename, int verbose); +lprec __EXPORT_TYPE * __WINAPI read_freeMPS(char *filename, int verbose); +lprec __EXPORT_TYPE * __WINAPI read_freemps(FILE *filename, int verbose); + +/* Write a MPS file to output */ +MYBOOL __EXPORT_TYPE __WINAPI write_mps(lprec *lp, char *filename); +MYBOOL __EXPORT_TYPE __WINAPI write_MPS(lprec *lp, FILE *output); +MYBOOL __EXPORT_TYPE __WINAPI write_freemps(lprec *lp, char *filename); +MYBOOL __EXPORT_TYPE __WINAPI write_freeMPS(lprec *lp, FILE *output); + +MYBOOL __EXPORT_TYPE __WINAPI write_lp(lprec *lp, char *filename); +MYBOOL __EXPORT_TYPE __WINAPI write_LP(lprec *lp, FILE *output); + /* Write a LP file to output */ + +MYBOOL __WINAPI LP_readhandle(lprec **lp, FILE *filename, int verbose, char *lp_name); +lprec __EXPORT_TYPE * __WINAPI read_lp(FILE *filename, int verbose, char *lp_name); +lprec __EXPORT_TYPE * __WINAPI read_LP(char *filename, int verbose, char *lp_name); +/* Old-style lp format file parser */ + +MYBOOL __EXPORT_TYPE __WINAPI write_basis(lprec *lp, char *filename); +MYBOOL __EXPORT_TYPE __WINAPI read_basis(lprec *lp, char *filename, char *info); +/* Read and write basis from/to file in CPLEX BAS format */ + +MYBOOL __EXPORT_TYPE __WINAPI write_params(lprec *lp, char *filename, char *options); +MYBOOL __EXPORT_TYPE __WINAPI read_params(lprec *lp, char *filename, char *options); +void __EXPORT_TYPE __WINAPI reset_params(lprec *lp); +/* Read and write parameter file */ + +void __EXPORT_TYPE __WINAPI print_lp(lprec *lp); +void __EXPORT_TYPE __WINAPI print_tableau(lprec *lp); +/* Print the current problem, only useful in very small (test) problems */ + +void __EXPORT_TYPE __WINAPI print_objective(lprec *lp); +void __EXPORT_TYPE __WINAPI print_solution(lprec *lp, int columns); +void __EXPORT_TYPE __WINAPI print_constraints(lprec *lp, int columns); +/* Print the solution to stdout */ + +void __EXPORT_TYPE __WINAPI print_duals(lprec *lp); +/* Print the dual variables of the solution */ + +void __EXPORT_TYPE __WINAPI print_scales(lprec *lp); +/* If scaling is used, print the scaling factors */ + +void __EXPORT_TYPE __WINAPI print_str(lprec *lp, char *str); + +void __EXPORT_TYPE __WINAPI set_outputstream(lprec *lp, FILE *stream); +MYBOOL __EXPORT_TYPE __WINAPI set_outputfile(lprec *lp, char *filename); + +void __EXPORT_TYPE __WINAPI set_verbose(lprec *lp, int verbose); +int __EXPORT_TYPE __WINAPI get_verbose(lprec *lp); + +void __EXPORT_TYPE __WINAPI set_timeout(lprec *lp, long sectimeout); +long __EXPORT_TYPE __WINAPI get_timeout(lprec *lp); + +void __EXPORT_TYPE __WINAPI set_print_sol(lprec *lp, int print_sol); +int __EXPORT_TYPE __WINAPI get_print_sol(lprec *lp); + +void __EXPORT_TYPE __WINAPI set_debug(lprec *lp, MYBOOL debug); +MYBOOL __EXPORT_TYPE __WINAPI is_debug(lprec *lp); + +void __EXPORT_TYPE __WINAPI set_trace(lprec *lp, MYBOOL trace); +MYBOOL __EXPORT_TYPE __WINAPI is_trace(lprec *lp); + +MYBOOL __EXPORT_TYPE __WINAPI print_debugdump(lprec *lp, char *filename); + +void __EXPORT_TYPE __WINAPI set_anti_degen(lprec *lp, int anti_degen); +int __EXPORT_TYPE __WINAPI get_anti_degen(lprec *lp); +MYBOOL __EXPORT_TYPE __WINAPI is_anti_degen(lprec *lp, int testmask); + +void __EXPORT_TYPE __WINAPI set_presolve(lprec *lp, int presolvemode, int maxloops); +int __EXPORT_TYPE __WINAPI get_presolve(lprec *lp); +int __EXPORT_TYPE __WINAPI get_presolveloops(lprec *lp); +MYBOOL __EXPORT_TYPE __WINAPI is_presolve(lprec *lp, int testmask); + +int __EXPORT_TYPE __WINAPI get_orig_index(lprec *lp, int lp_index); +int __EXPORT_TYPE __WINAPI get_lp_index(lprec *lp, int orig_index); + +void __EXPORT_TYPE __WINAPI set_maxpivot(lprec *lp, int max_num_inv); +int __EXPORT_TYPE __WINAPI get_maxpivot(lprec *lp); + +void __EXPORT_TYPE __WINAPI set_obj_bound(lprec *lp, REAL obj_bound); +REAL __EXPORT_TYPE __WINAPI get_obj_bound(lprec *lp); + +void __EXPORT_TYPE __WINAPI set_mip_gap(lprec *lp, MYBOOL absolute, REAL mip_gap); +REAL __EXPORT_TYPE __WINAPI get_mip_gap(lprec *lp, MYBOOL absolute); + +void __EXPORT_TYPE __WINAPI set_bb_rule(lprec *lp, int bb_rule); +int __EXPORT_TYPE __WINAPI get_bb_rule(lprec *lp); + +MYBOOL __EXPORT_TYPE __WINAPI set_var_branch(lprec *lp, int colnr, int branch_mode); +int __EXPORT_TYPE __WINAPI get_var_branch(lprec *lp, int colnr); + +MYBOOL __EXPORT_TYPE __WINAPI is_infinite(lprec *lp, REAL value); +void __EXPORT_TYPE __WINAPI set_infinite(lprec *lp, REAL infinite); +REAL __EXPORT_TYPE __WINAPI get_infinite(lprec *lp); + +void __EXPORT_TYPE __WINAPI set_epsint(lprec *lp, REAL epsint); +REAL __EXPORT_TYPE __WINAPI get_epsint(lprec *lp); + +void __EXPORT_TYPE __WINAPI set_epsb(lprec *lp, REAL epsb); +REAL __EXPORT_TYPE __WINAPI get_epsb(lprec *lp); + +void __EXPORT_TYPE __WINAPI set_epsd(lprec *lp, REAL epsd); +REAL __EXPORT_TYPE __WINAPI get_epsd(lprec *lp); + +void __EXPORT_TYPE __WINAPI set_epsel(lprec *lp, REAL epsel); +REAL __EXPORT_TYPE __WINAPI get_epsel(lprec *lp); + +MYBOOL __EXPORT_TYPE __WINAPI set_epslevel(lprec *lp, int epslevel); + +void __EXPORT_TYPE __WINAPI set_scaling(lprec *lp, int scalemode); +int __EXPORT_TYPE __WINAPI get_scaling(lprec *lp); +MYBOOL __EXPORT_TYPE __WINAPI is_scalemode(lprec *lp, int testmask); +MYBOOL __EXPORT_TYPE __WINAPI is_scaletype(lprec *lp, int scaletype); +MYBOOL __EXPORT_TYPE __WINAPI is_integerscaling(lprec *lp); +void __EXPORT_TYPE __WINAPI set_scalelimit(lprec *lp, REAL scalelimit); +REAL __EXPORT_TYPE __WINAPI get_scalelimit(lprec *lp); + +void __EXPORT_TYPE __WINAPI set_improve(lprec *lp, int improve); +int __EXPORT_TYPE __WINAPI get_improve(lprec *lp); + +void __EXPORT_TYPE __WINAPI set_pivoting(lprec *lp, int piv_rule); +int __EXPORT_TYPE __WINAPI get_pivoting(lprec *lp); +MYBOOL __EXPORT_TYPE __WINAPI set_partialprice(lprec *lp, int blockcount, int *blockstart, MYBOOL isrow); +void __EXPORT_TYPE __WINAPI get_partialprice(lprec *lp, int *blockcount, int *blockstart, MYBOOL isrow); + +MYBOOL __EXPORT_TYPE __WINAPI set_multiprice(lprec *lp, int multiblockdiv); +int __EXPORT_TYPE __WINAPI get_multiprice(lprec *lp, MYBOOL getabssize); + +MYBOOL __WINAPI is_use_names(lprec *lp, MYBOOL isrow); +void __WINAPI set_use_names(lprec *lp, MYBOOL isrow, MYBOOL use_names); + +int __EXPORT_TYPE __WINAPI get_nameindex(lprec *lp, char *varname, MYBOOL isrow); + +MYBOOL __EXPORT_TYPE __WINAPI is_piv_mode(lprec *lp, int testmask); +MYBOOL __EXPORT_TYPE __WINAPI is_piv_rule(lprec *lp, int rule); + +void __EXPORT_TYPE __WINAPI set_break_at_first(lprec *lp, MYBOOL break_at_first); +MYBOOL __EXPORT_TYPE __WINAPI is_break_at_first(lprec *lp); + +void __EXPORT_TYPE __WINAPI set_bb_floorfirst(lprec *lp, int bb_floorfirst); +int __EXPORT_TYPE __WINAPI get_bb_floorfirst(lprec *lp); + +void __EXPORT_TYPE __WINAPI set_bb_depthlimit(lprec *lp, int bb_maxlevel); +int __EXPORT_TYPE __WINAPI get_bb_depthlimit(lprec *lp); + +void __EXPORT_TYPE __WINAPI set_break_at_value(lprec *lp, REAL break_at_value); +REAL __EXPORT_TYPE __WINAPI get_break_at_value(lprec *lp); + +void __EXPORT_TYPE __WINAPI set_negrange(lprec *lp, REAL negrange); +REAL __EXPORT_TYPE __WINAPI get_negrange(lprec *lp); + +void __EXPORT_TYPE __WINAPI set_epsperturb(lprec *lp, REAL epsperturb); +REAL __EXPORT_TYPE __WINAPI get_epsperturb(lprec *lp); + +void __EXPORT_TYPE __WINAPI set_epspivot(lprec *lp, REAL epspivot); +REAL __EXPORT_TYPE __WINAPI get_epspivot(lprec *lp); + +int __EXPORT_TYPE __WINAPI get_max_level(lprec *lp); +COUNTER __EXPORT_TYPE __WINAPI get_total_nodes(lprec *lp); +COUNTER __EXPORT_TYPE __WINAPI get_total_iter(lprec *lp); + +REAL __EXPORT_TYPE __WINAPI get_objective(lprec *lp); +REAL __EXPORT_TYPE __WINAPI get_working_objective(lprec *lp); + +REAL __EXPORT_TYPE __WINAPI get_var_primalresult(lprec *lp, int index); +REAL __EXPORT_TYPE __WINAPI get_var_dualresult(lprec *lp, int index); + +MYBOOL __EXPORT_TYPE __WINAPI get_variables(lprec *lp, REAL *var); +MYBOOL __EXPORT_TYPE __WINAPI get_ptr_variables(lprec *lp, REAL **var); + +MYBOOL __EXPORT_TYPE __WINAPI get_constraints(lprec *lp, REAL *constr); +MYBOOL __EXPORT_TYPE __WINAPI get_ptr_constraints(lprec *lp, REAL **constr); + +MYBOOL __EXPORT_TYPE __WINAPI get_sensitivity_rhs(lprec *lp, REAL *duals, REAL *dualsfrom, REAL *dualstill); +MYBOOL __EXPORT_TYPE __WINAPI get_ptr_sensitivity_rhs(lprec *lp, REAL **duals, REAL **dualsfrom, REAL **dualstill); + +MYBOOL __EXPORT_TYPE __WINAPI get_sensitivity_obj(lprec *lp, REAL *objfrom, REAL *objtill); +MYBOOL __EXPORT_TYPE __WINAPI get_sensitivity_objex(lprec *lp, REAL *objfrom, REAL *objtill, REAL *objfromvalue, REAL *objtillvalue); +MYBOOL __EXPORT_TYPE __WINAPI get_ptr_sensitivity_obj(lprec *lp, REAL **objfrom, REAL **objtill); +MYBOOL __EXPORT_TYPE __WINAPI get_ptr_sensitivity_objex(lprec *lp, REAL **objfrom, REAL **objtill, REAL **objfromvalue, REAL **objtillvalue); + +void __EXPORT_TYPE __WINAPI set_solutionlimit(lprec *lp, int limit); +int __EXPORT_TYPE __WINAPI get_solutionlimit(lprec *lp); +int __EXPORT_TYPE __WINAPI get_solutioncount(lprec *lp); + +int __EXPORT_TYPE __WINAPI get_Norig_rows(lprec *lp); +int __EXPORT_TYPE __WINAPI get_Nrows(lprec *lp); +int __EXPORT_TYPE __WINAPI get_Lrows(lprec *lp); + +int __EXPORT_TYPE __WINAPI get_Norig_columns(lprec *lp); +int __EXPORT_TYPE __WINAPI get_Ncolumns(lprec *lp); + + +#ifdef __cplusplus +} +#endif + + +/* Forward definitions of functions used internaly by the lp toolkit */ +MYBOOL set_callbacks(lprec *lp); +STATIC int yieldformessages(lprec *lp); +MYBOOL __WINAPI userabort(lprec *lp, int message); +/*char * __VACALL explain(lprec *lp, char *format, ...); +void __VACALL report(lprec *lp, int level, char *format, ...);*/ + +/* Memory management routines */ +STATIC MYBOOL append_rows(lprec *lp, int deltarows); +STATIC MYBOOL append_columns(lprec *lp, int deltacolumns); +STATIC void inc_rows(lprec *lp, int delta); +STATIC void inc_columns(lprec *lp, int delta); +STATIC MYBOOL init_rowcol_names(lprec *lp); +STATIC MYBOOL inc_row_space(lprec *lp, int deltarows); +STATIC MYBOOL inc_col_space(lprec *lp, int deltacols); +STATIC MYBOOL shift_rowcoldata(lprec *lp, int base, int delta, LLrec *usedmap, MYBOOL isrow); +STATIC MYBOOL shift_basis(lprec *lp, int base, int delta, LLrec *usedmap, MYBOOL isrow); +STATIC MYBOOL shift_rowdata(lprec *lp, int base, int delta, LLrec *usedmap); +STATIC MYBOOL shift_coldata(lprec *lp, int base, int delta, LLrec *usedmap); + +/* INLINE */ MYBOOL is_chsign(lprec *lp, int rownr); + +STATIC MYBOOL inc_lag_space(lprec *lp, int deltarows, MYBOOL ignoreMAT); +lprec *make_lag(lprec *server); + +REAL get_rh_upper(lprec *lp, int rownr); +REAL get_rh_lower(lprec *lp, int rownr); +MYBOOL set_rh_upper(lprec *lp, int rownr, REAL value); +MYBOOL set_rh_lower(lprec *lp, int rownr, REAL value); +STATIC int bin_count(lprec *lp, MYBOOL working); +STATIC int MIP_count(lprec *lp); +STATIC int SOS_count(lprec *lp); +STATIC int GUB_count(lprec *lp); +STATIC int identify_GUB(lprec *lp, MYBOOL mark); +STATIC int prepare_GUB(lprec *lp); + +STATIC MYBOOL refactRecent(lprec *lp); +STATIC MYBOOL check_if_less(lprec *lp, REAL x, REAL y, int variable); +STATIC MYBOOL feasiblePhase1(lprec *lp, REAL epsvalue); +STATIC void free_duals(lprec *lp); +STATIC void initialize_solution(lprec *lp, MYBOOL shiftbounds); +STATIC void recompute_solution(lprec *lp, MYBOOL shiftbounds); +STATIC int verify_solution(lprec *lp, MYBOOL reinvert, char *info); +STATIC int check_solution(lprec *lp, int lastcolumn, REAL *solution, + REAL *upbo, REAL *lowbo, REAL tolerance); +/* INLINE */ MYBOOL is_fixedvar(lprec *lp, int variable); +/* INLINE */ MYBOOL is_splitvar(lprec *lp, int colnr); + +void __WINAPI set_action(int *actionvar, int actionmask); +void __WINAPI clear_action(int *actionvar, int actionmask); +MYBOOL __WINAPI is_action(int actionvar, int testmask); + +INLINE MYBOOL is_bb_rule(lprec *lp, int bb_rule); +/* INLINE */ MYBOOL is_bb_mode(lprec *lp, int bb_mask); +/* INLINE */ int get_piv_rule(lprec *lp); +STATIC char *get_str_piv_rule(int rule); +STATIC MYBOOL __WINAPI set_var_priority(lprec *lp); +STATIC int find_sc_bbvar(lprec *lp, int *count); +STATIC int find_sos_bbvar(lprec *lp, int *count, MYBOOL intsos); +STATIC int find_int_bbvar(lprec *lp, int *count, BBrec *BB, MYBOOL *isfeasible); + +/* Solution-related functions */ +STATIC REAL compute_dualslacks(lprec *lp, int target, REAL **dvalues, int **nzdvalues, MYBOOL dosum); +STATIC MYBOOL solution_is_int(lprec *lp, int index, MYBOOL checkfixed); +STATIC MYBOOL bb_better(lprec *lp, int target, int mode); +STATIC void construct_solution(lprec *lp, REAL *target); +STATIC void transfer_solution_var(lprec *lp, int uservar); +STATIC MYBOOL construct_duals(lprec *lp); +STATIC MYBOOL construct_sensitivity_duals(lprec *lp); +STATIC MYBOOL construct_sensitivity_obj(lprec *lp); + +STATIC int add_GUB(lprec *lp, char *name, int priority, int count, int *sosvars); +STATIC basisrec *push_basis(lprec *lp, int *basisvar, MYBOOL *isbasic, MYBOOL *islower); +STATIC MYBOOL compare_basis(lprec *lp); +STATIC MYBOOL restore_basis(lprec *lp); +STATIC MYBOOL pop_basis(lprec *lp, MYBOOL restore); +STATIC MYBOOL is_BasisReady(lprec *lp); +STATIC MYBOOL is_slackbasis(lprec *lp); +STATIC MYBOOL verify_basis(lprec *lp); +STATIC int unload_basis(lprec *lp, MYBOOL restorelast); + +STATIC int perturb_bounds(lprec *lp, BBrec *perturbed, MYBOOL doRows, MYBOOL doCols, MYBOOL includeFIXED); +STATIC MYBOOL validate_bounds(lprec *lp, REAL *upbo, REAL *lowbo); +STATIC MYBOOL impose_bounds(lprec *lp, REAL * upbo, REAL *lowbo); +STATIC int unload_BB(lprec *lp); + +STATIC REAL feasibilityOffset(lprec *lp, MYBOOL isdual); +STATIC MYBOOL isP1extra(lprec *lp); +STATIC REAL get_refactfrequency(lprec *lp, MYBOOL final); +STATIC int findBasicFixedvar(lprec *lp, int afternr, MYBOOL slacksonly); +STATIC MYBOOL isBasisVarFeasible(lprec *lp, REAL tol, int basis_row); +STATIC MYBOOL isPrimalFeasible(lprec *lp, REAL tol, int infeasibles[], REAL *feasibilitygap); +STATIC MYBOOL isDualFeasible(lprec *lp, REAL tol, int *boundflips, int infeasibles[], REAL *feasibilitygap); + +/* Main simplex driver routines */ +STATIC int preprocess(lprec *lp); +STATIC void postprocess(lprec *lp); +STATIC MYBOOL performiteration(lprec *lp, int rownr, int varin, LREAL theta, MYBOOL primal, MYBOOL allowminit, REAL *prow, int *nzprow, REAL *pcol, int *nzpcol, int *boundswaps); +STATIC void transfer_solution_var(lprec *lp, int uservar); +STATIC void transfer_solution(lprec *lp, MYBOOL dofinal); + +/* Scaling utilities */ +STATIC REAL scaled_floor(lprec *lp, int colnr, REAL value, REAL epsscale); +STATIC REAL scaled_ceil(lprec *lp, int colnr, REAL value, REAL epsscale); + +/* Variable mapping utility routines */ +STATIC void varmap_lock(lprec *lp); +STATIC void varmap_clear(lprec *lp); +STATIC MYBOOL varmap_canunlock(lprec *lp); +STATIC void varmap_addconstraint(lprec *lp); +STATIC void varmap_addcolumn(lprec *lp); +STATIC void varmap_delete(lprec *lp, int base, int delta, LLrec *varmap); +STATIC void varmap_compact(lprec *lp, int prev_rows, int prev_cols); +STATIC MYBOOL varmap_validate(lprec *lp, int varno); +STATIC MYBOOL del_varnameex(lprec *lp, hashelem **namelist, hashtable *ht, int varnr, LLrec *varmap); + +/* Pseudo-cost routines (internal) */ +STATIC BBPSrec *init_pseudocost(lprec *lp, int pseudotype); +STATIC void free_pseudocost(lprec *lp); +STATIC REAL get_pseudorange(BBPSrec *pc, int mipvar, int varcode); +STATIC void update_pseudocost(BBPSrec *pc, int mipvar, int varcode, MYBOOL capupper, REAL varsol); +STATIC REAL get_pseudobranchcost(BBPSrec *pc, int mipvar, MYBOOL dofloor); +STATIC REAL get_pseudonodecost(BBPSrec *pc, int mipvar, int vartype, REAL varsol); + +/* Matrix access and equation solving routines */ +STATIC void set_OF_override(lprec *lp, REAL *ofVector); +STATIC void set_OF_p1extra(lprec *lp, REAL p1extra); +STATIC void unset_OF_p1extra(lprec *lp); +MYBOOL modifyOF1(lprec *lp, int index, REAL *ofValue, REAL mult); +REAL __WINAPI get_OF_active(lprec *lp, int varnr, REAL mult); +STATIC MYBOOL is_OF_nz(lprec *lp, int colnr); + +STATIC int get_basisOF(lprec *lp, int coltarget[], REAL crow[], int colno[]); +int __WINAPI get_basiscolumn(lprec *lp, int j, int rn[], double bj[]); +int __WINAPI obtain_column(lprec *lp, int varin, REAL *pcol, int *nzlist, int *maxabs); +STATIC int compute_theta(lprec *lp, int rownr, LREAL *theta, int isupbound, REAL HarrisScalar, MYBOOL primal); + +/* Pivot utility routines */ +STATIC int findBasisPos(lprec *lp, int notint, int *var_basic); +STATIC MYBOOL check_degeneracy(lprec *lp, REAL *pcol, int *degencount); + +typedef int (__WINAPI read_modeldata_func)(void *userhandle, char *buf, int max_size); +typedef int (__WINAPI write_modeldata_func)(void *userhandle, char *buf); +MYBOOL __WINAPI MPS_readex(lprec **newlp, void *userhandle, read_modeldata_func read_modeldata, int typeMPS, int verbose); +#if defined develop +lprec __EXPORT_TYPE * __WINAPI read_lpex(void *userhandle, read_modeldata_func read_modeldata, int verbose, char *lp_name); +MYBOOL __EXPORT_TYPE __WINAPI write_lpex(lprec *lp, void *userhandle, write_modeldata_func write_modeldata); + +lprec __EXPORT_TYPE * __WINAPI read_mpsex(void *userhandle, read_modeldata_func read_modeldata, int verbose); +lprec __EXPORT_TYPE * __WINAPI read_freempsex(void *userhandle, read_modeldata_func read_modeldata, int verbose); + +MYBOOL MPS_writefileex(lprec *lp, int typeMPS, void *userhandle, write_modeldata_func write_modeldata); +#endif + +#endif /* HEADER_lp_lib */ diff --git a/include/lp_matrix.h b/include/lp_matrix.h new file mode 100644 index 0000000..a1cf9b6 --- /dev/null +++ b/include/lp_matrix.h @@ -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 */ + diff --git a/include/lp_mipbb.h b/include/lp_mipbb.h new file mode 100644 index 0000000..db1947c --- /dev/null +++ b/include/lp_mipbb.h @@ -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 */ + diff --git a/include/lp_presolve.h b/include/lp_presolve.h new file mode 100644 index 0000000..f59406b --- /dev/null +++ b/include/lp_presolve.h @@ -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 */ diff --git a/include/lp_price.h b/include/lp_price.h new file mode 100644 index 0000000..9e8d8bc --- /dev/null +++ b/include/lp_price.h @@ -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 */ + diff --git a/include/lp_pricePSE.h b/include/lp_pricePSE.h new file mode 100644 index 0000000..1c8c2f8 --- /dev/null +++ b/include/lp_pricePSE.h @@ -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 */ + diff --git a/include/lp_report.h b/include/lp_report.h new file mode 100644 index 0000000..a8567fe --- /dev/null +++ b/include/lp_report.h @@ -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 */ + diff --git a/include/lp_rlp.h b/include/lp_rlp.h new file mode 100644 index 0000000..b9cffb2 --- /dev/null +++ b/include/lp_rlp.h @@ -0,0 +1,1901 @@ +/* A lexical scanner generated by flex */ + +/* Scanner skeleton version: + * $Header: /home/daffy/u0/vern/flex/RCS/flex.skl,v 2.91 96/09/10 16:58:48 vern Exp $ + */ + +#define FLEX_SCANNER +#define YY_FLEX_MAJOR_VERSION 2 +#define YY_FLEX_MINOR_VERSION 5 + +#include + + +/* cfront 1.2 defines "c_plusplus" instead of "__cplusplus" */ +#ifdef c_plusplus +#ifndef __cplusplus +#define __cplusplus +#endif +#endif + + +#ifdef __cplusplus + +#include +#include + +/* Use prototypes in function declarations. */ +#define YY_USE_PROTOS + +/* The "const" storage-class-modifier is valid. */ +#define YY_USE_CONST + +#else /* ! __cplusplus */ + +#if __STDC__ + +#define YY_USE_PROTOS +#define YY_USE_CONST + +#endif /* __STDC__ */ +#endif /* ! __cplusplus */ + +#ifdef __TURBOC__ + #pragma warn -rch + #pragma warn -use +#include +#include +#define YY_USE_CONST +#define YY_USE_PROTOS +#endif + +#ifdef YY_USE_CONST +#define lp_yyconst const +#else +#define lp_yyconst +#endif + + +#ifdef YY_USE_PROTOS +#define YY_PROTO(proto) proto +#else +#define YY_PROTO(proto) () +#endif + +/* Returned upon end-of-file. */ +#define YY_NULL 0 + +/* Promotes a possibly negative, possibly signed char to an unsigned + * integer for use as an array index. If the signed char is negative, + * we want to instead treat it as an 8-bit unsigned char, hence the + * double cast. + */ +#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) + +/* Enter a start condition. This macro really ought to take a parameter, + * but we do it the disgusting crufty way forced on us by the ()-less + * definition of BEGIN. + */ +#define BEGIN lp_yy_start = 1 + 2 * + +/* Translate the current start state into a value that can be later handed + * to BEGIN to return to the state. The YYSTATE alias is for lex + * compatibility. + */ +#define YY_START ((lp_yy_start - 1) / 2) +#define YYSTATE YY_START + +/* Action number for EOF rule of a given start state. */ +#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) + +/* Special action meaning "start processing a new file". */ +#define YY_NEW_FILE lp_yyrestart( lp_yyin ) + +#define YY_END_OF_BUFFER_CHAR 0 + +/* Size of default input buffer. */ +#define YY_BUF_SIZE 16384 + +typedef struct lp_yy_buffer_state *YY_BUFFER_STATE; + +extern int lp_yyleng; +extern FILE *lp_yyin, *lp_yyout; + +#define EOB_ACT_CONTINUE_SCAN 0 +#define EOB_ACT_END_OF_FILE 1 +#define EOB_ACT_LAST_MATCH 2 + +/* The funky do-while in the following #define is used to turn the definition + * int a single C statement (which needs a semi-colon terminator). This + * avoids problems with code like: + * + * if ( condition_holds ) + * lp_yyless( 5 ); + * else + * do_something_else(); + * + * Prior to using the do-while the compiler would get upset at the + * "else" because it interpreted the "if" statement as being all + * done when it reached the ';' after the lp_yyless() call. + */ + +/* Return all but the first 'n' matched characters back to the input stream. */ + +#define lp_yyless(n) \ + do \ + { \ + /* Undo effects of setting up lp_yytext. */ \ + *lp_yy_cp = lp_yy_hold_char; \ + YY_RESTORE_YY_MORE_OFFSET \ + lp_yy_c_buf_p = lp_yy_cp = lp_yy_bp + n - YY_MORE_ADJ; \ + YY_DO_BEFORE_ACTION; /* set up lp_yytext again */ \ + } \ + while ( 0 ) + +#define unput(c) lp_yyunput( c, lp_yytext_ptr ) + +/* The following is because we cannot portably get our hands on size_t + * (without autoconf's help, which isn't available because we want + * flex-generated scanners to compile on their own). + */ +typedef unsigned int lp_yy_size_t; + + +struct lp_yy_buffer_state + { + FILE *lp_yy_input_file; + + char *lp_yy_ch_buf; /* input buffer */ + char *lp_yy_buf_pos; /* current position in input buffer */ + + /* Size of input buffer in bytes, not including room for EOB + * characters. + */ + lp_yy_size_t lp_yy_buf_size; + + /* Number of characters read into lp_yy_ch_buf, not including EOB + * characters. + */ + int lp_yy_n_chars; + + /* Whether we "own" the buffer - i.e., we know we created it, + * and can realloc() it to grow it, and should free() it to + * delete it. + */ + int lp_yy_is_our_buffer; + + /* Whether this is an "interactive" input source; if so, and + * if we're using stdio for input, then we want to use getc() + * instead of fread(), to make sure we stop fetching input after + * each newline. + */ + int lp_yy_is_interactive; + + /* Whether we're considered to be at the beginning of a line. + * If so, '^' rules will be active on the next match, otherwise + * not. + */ + int lp_yy_at_bol; + + /* Whether to try to fill the input buffer when we reach the + * end of it. + */ + int lp_yy_fill_buffer; + + int lp_yy_buffer_status; +#define YY_BUFFER_NEW 0 +#define YY_BUFFER_NORMAL 1 + /* When an EOF's been seen but there's still some text to process + * then we mark the buffer as YY_EOF_PENDING, to indicate that we + * shouldn't try reading from the input source any more. We might + * still have a bunch of tokens to match, though, because of + * possible backing-up. + * + * When we actually see the EOF, we change the status to "new" + * (via lp_yyrestart()), so that the user can continue scanning by + * just pointing lp_yyin at a new input file. + */ +#define YY_BUFFER_EOF_PENDING 2 + }; + +static YY_BUFFER_STATE lp_yy_current_buffer = 0; + +/* We provide macros for accessing buffer states in case in the + * future we want to put the buffer states in a more general + * "scanner state". + */ +#define YY_CURRENT_BUFFER lp_yy_current_buffer + + +/* lp_yy_hold_char holds the character lost when lp_yytext is formed. */ +static char lp_yy_hold_char; + +static int lp_yy_n_chars; /* number of characters read into lp_yy_ch_buf */ + + +int lp_yyleng; + +/* Points to current character in buffer. */ +static char *lp_yy_c_buf_p = (char *) 0; +static int lp_yy_init = 1; /* whether we need to initialize */ +static int lp_yy_start = 0; /* start state number */ + +/* Flag which is used to allow lp_yywrap()'s to do buffer switches + * instead of setting up a fresh lp_yyin. A bit of a hack ... + */ +static int lp_yy_did_buffer_switch_on_eof; + +void lp_yyrestart YY_PROTO(( FILE *input_file )); + +void lp_yy_switch_to_buffer YY_PROTO(( YY_BUFFER_STATE new_buffer )); +void lp_yy_load_buffer_state YY_PROTO(( void )); +YY_BUFFER_STATE lp_yy_create_buffer YY_PROTO(( FILE *file, int size )); +void lp_yy_delete_buffer YY_PROTO(( YY_BUFFER_STATE b )); +void lp_yy_init_buffer YY_PROTO(( YY_BUFFER_STATE b, FILE *file )); +void lp_yy_flush_buffer YY_PROTO(( YY_BUFFER_STATE b )); +#define YY_FLUSH_BUFFER lp_yy_flush_buffer( lp_yy_current_buffer ) + +YY_BUFFER_STATE lp_yy_scan_buffer YY_PROTO(( char *base, lp_yy_size_t size )); +YY_BUFFER_STATE lp_yy_scan_string YY_PROTO(( lp_yyconst char *lp_yy_str )); +YY_BUFFER_STATE lp_yy_scan_bytes YY_PROTO(( lp_yyconst char *bytes, int len )); + +static void *lp_yy_flex_alloc YY_PROTO(( lp_yy_size_t )); +static void *lp_yy_flex_realloc YY_PROTO(( void *, lp_yy_size_t )); +static void lp_yy_flex_free YY_PROTO(( void * )); + +#define lp_yy_new_buffer lp_yy_create_buffer + +#define lp_yy_set_interactive(is_interactive) \ + { \ + if ( ! lp_yy_current_buffer ) \ + lp_yy_current_buffer = lp_yy_create_buffer( lp_yyin, YY_BUF_SIZE ); \ + lp_yy_current_buffer->lp_yy_is_interactive = is_interactive; \ + } + +#define lp_yy_set_bol(at_bol) \ + { \ + if ( ! lp_yy_current_buffer ) \ + lp_yy_current_buffer = lp_yy_create_buffer( lp_yyin, YY_BUF_SIZE ); \ + lp_yy_current_buffer->lp_yy_at_bol = at_bol; \ + } + +#define YY_AT_BOL() (lp_yy_current_buffer->lp_yy_at_bol) + + +#define YY_USES_REJECT +typedef unsigned char YY_CHAR; +FILE *lp_yyin = (FILE *) 0, *lp_yyout = (FILE *) 0; +typedef int lp_yy_state_type; +#define YY_FLEX_LEX_COMPAT +extern int lp_yylineno; +int lp_yylineno = 1; +extern char lp_yytext[]; + + +static lp_yy_state_type lp_yy_get_previous_state YY_PROTO(( void )); +static lp_yy_state_type lp_yy_try_NUL_trans YY_PROTO(( lp_yy_state_type current_state )); +static int lp_yy_get_next_buffer YY_PROTO(( void )); +static void lp_yy_fatal_error YY_PROTO(( lp_yyconst char msg[] )); + +/* Done after the current pattern has been matched and before the + * corresponding action - sets up lp_yytext. + */ +#define YY_DO_BEFORE_ACTION \ + lp_yytext_ptr = lp_yy_bp; \ + lp_yyleng = (int) (lp_yy_cp - lp_yy_bp); \ + lp_yy_hold_char = *lp_yy_cp; \ + *lp_yy_cp = '\0'; \ + if ( lp_yyleng + lp_yy_more_offset >= YYLMAX ) \ + YY_FATAL_ERROR( "token too large, exceeds YYLMAX" ); \ + lp_yy_flex_strncpy( &lp_yytext[lp_yy_more_offset], lp_yytext_ptr, lp_yyleng + 1 ); \ + lp_yyleng += lp_yy_more_offset; \ + lp_yy_prev_more_offset = lp_yy_more_offset; \ + lp_yy_more_offset = 0; \ + lp_yy_c_buf_p = lp_yy_cp; + +#define YY_NUM_RULES 30 +#define YY_END_OF_BUFFER 31 +static lp_yyconst short int lp_yy_acclist[149] = + { 0, + 26, 26, 31, 29, 30, 10, 17, 29, 30, 10, + 17, 30, 25, 29, 30, 17, 29, 30, 11, 29, + 30, 29, 30, 29, 30, 14, 15, 29, 30, 24, + 29, 30, 28, 29, 30, 26, 29, 30, 26, 29, + 30, 27, 29, 30, 23, 29, 30, 23, 29, 30, + 10, 17, 29, 30, 23, 29, 30, 23, 29, 30, + 3, 30, 4, 30, 3, 5, 30, 3, 30, 9, + 30, 7, 30, 8, 9, 30, 10, 17, 17, 17, + 15, 1, 6, 15, 14, 15, 26, 27, 23, 22, + 23, 23, 10, 17, 23, 23, 23, 2, 15, 15, + + 21, 23, 23, 18, 23, 19, 23, 23, 23, 20, + 23,16400, 23, 13, 22, 23, 12, 22, 23, 18, + 19, 20, 23, 19, 23, 20, 23, 20, 23, 8208, + 8208, 13, 23, 12, 23, 20, 23, 23, 23, 23, + 23, 23, 18, 23, 23, 23, 18,16400 + } ; + +static lp_yyconst short int lp_yy_accept[126] = + { 0, + 1, 2, 3, 3, 3, 3, 3, 4, 6, 10, + 13, 16, 19, 22, 24, 26, 30, 33, 36, 39, + 42, 45, 48, 51, 55, 58, 61, 63, 65, 68, + 70, 72, 74, 77, 79, 80, 81, 81, 82, 83, + 84, 85, 87, 87, 88, 89, 90, 91, 91, 92, + 93, 95, 95, 95, 96, 97, 98, 99, 99, 100, + 100, 101, 102, 102, 103, 104, 104, 104, 104, 106, + 108, 109, 110, 112, 113, 114, 114, 116, 117, 117, + 119, 120, 121, 122, 123, 124, 126, 128, 130, 131, + 132, 132, 133, 134, 135, 136, 136, 137, 138, 138, + + 138, 139, 140, 140, 141, 141, 141, 142, 143, 143, + 145, 145, 145, 146, 147, 148, 148, 149, 149, 149, + 149, 149, 149, 149, 149 + } ; + +static lp_yyconst int lp_yy_ec[256] = + { 0, + 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, + 1, 1, 4, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 2, 1, 1, 5, 6, 5, 5, 5, 1, + 1, 7, 8, 9, 10, 11, 12, 13, 14, 14, + 13, 13, 13, 13, 13, 13, 13, 15, 16, 17, + 18, 19, 1, 5, 20, 21, 22, 21, 23, 24, + 25, 21, 26, 21, 21, 21, 27, 28, 29, 21, + 21, 30, 31, 32, 33, 21, 21, 34, 35, 36, + 5, 1, 5, 5, 5, 1, 20, 21, 22, 21, + + 23, 24, 25, 21, 26, 21, 21, 21, 27, 28, + 29, 21, 21, 30, 31, 32, 33, 21, 21, 34, + 35, 36, 5, 1, 5, 5, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1 + } ; + +static lp_yyconst int lp_yy_meta[37] = + { 0, + 1, 2, 2, 2, 3, 4, 5, 2, 5, 2, + 4, 4, 4, 4, 6, 5, 6, 5, 5, 3, + 3, 3, 3, 3, 3, 7, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3 + } ; + +static lp_yyconst short int lp_yy_base[131] = + { 0, + 0, 35, 35, 37, 42, 44, 288, 297, 47, 50, + 297, 257, 297, 49, 52, 54, 297, 297, 261, 297, + 260, 54, 55, 80, 59, 63, 297, 297, 297, 265, + 297, 297, 297, 91, 250, 94, 231, 94, 297, 297, + 96, 101, 108, 297, 297, 74, 243, 0, 108, 111, + 0, 229, 50, 88, 114, 117, 297, 232, 124, 130, + 136, 297, 236, 138, 143, 222, 231, 221, 139, 118, + 142, 146, 156, 163, 236, 41, 235, 157, 98, 234, + 161, 225, 297, 233, 165, 176, 164, 180, 196, 297, + 217, 297, 170, 297, 186, 218, 228, 187, 219, 214, + + 191, 194, 216, 198, 205, 200, 201, 206, 175, 202, + 164, 191, 218, 229, 297, 151, 234, 149, 124, 118, + 101, 94, 54, 297, 260, 267, 273, 278, 283, 289 + } ; + +static lp_yyconst short int lp_yy_def[131] = + { 0, + 124, 1, 125, 125, 126, 126, 124, 124, 124, 124, + 124, 127, 124, 124, 124, 124, 124, 124, 124, 124, + 124, 128, 128, 124, 128, 128, 124, 124, 124, 124, + 124, 124, 124, 124, 127, 124, 124, 124, 124, 124, + 124, 124, 124, 124, 124, 128, 124, 129, 128, 128, + 24, 124, 124, 128, 128, 128, 124, 124, 124, 124, + 124, 124, 129, 128, 128, 124, 124, 124, 128, 128, + 128, 128, 128, 130, 124, 124, 124, 128, 124, 124, + 128, 124, 124, 124, 128, 128, 128, 128, 124, 124, + 124, 124, 128, 124, 128, 124, 124, 128, 124, 124, + + 128, 128, 124, 128, 124, 124, 128, 128, 124, 128, + 124, 124, 128, 128, 124, 124, 130, 124, 124, 124, + 124, 124, 124, 0, 124, 124, 124, 124, 124, 124 + } ; + +static lp_yyconst short int lp_yy_nxt[334] = + { 0, + 8, 9, 10, 9, 8, 8, 11, 12, 13, 12, + 14, 15, 16, 16, 17, 18, 19, 20, 21, 22, + 22, 22, 22, 22, 22, 22, 23, 22, 22, 22, + 22, 22, 22, 22, 22, 22, 24, 28, 29, 28, + 29, 30, 76, 30, 32, 33, 32, 33, 34, 34, + 34, 34, 34, 34, 35, 92, 35, 35, 39, 35, + 25, 38, 38, 40, 41, 26, 42, 42, 47, 47, + 48, 48, 67, 47, 49, 48, 43, 47, 68, 48, + 50, 51, 34, 34, 83, 55, 54, 35, 47, 35, + 48, 56, 34, 34, 34, 36, 36, 36, 35, 79, + + 35, 36, 47, 36, 48, 52, 38, 38, 59, 59, + 53, 41, 94, 42, 42, 60, 43, 60, 43, 69, + 61, 61, 47, 43, 48, 47, 123, 48, 47, 122, + 48, 47, 47, 48, 48, 70, 59, 59, 65, 76, + 71, 64, 61, 61, 79, 72, 43, 73, 61, 61, + 121, 120, 77, 47, 48, 48, 47, 80, 48, 48, + 47, 85, 48, 78, 89, 89, 89, 86, 81, 88, + 47, 47, 48, 48, 119, 47, 87, 48, 47, 47, + 48, 48, 118, 93, 47, 99, 48, 95, 91, 98, + 47, 116, 48, 88, 47, 101, 48, 89, 89, 89, + + 47, 47, 48, 48, 115, 47, 70, 48, 47, 104, + 48, 102, 47, 117, 48, 47, 47, 48, 48, 76, + 47, 107, 48, 113, 108, 117, 107, 110, 114, 108, + 79, 112, 77, 111, 48, 89, 89, 89, 109, 106, + 105, 97, 103, 80, 100, 48, 97, 96, 62, 62, + 47, 84, 83, 82, 75, 74, 66, 62, 58, 124, + 27, 27, 27, 27, 27, 27, 27, 31, 31, 31, + 31, 31, 31, 31, 36, 37, 57, 45, 44, 36, + 46, 46, 37, 46, 46, 63, 63, 124, 124, 63, + 90, 124, 90, 90, 90, 90, 7, 124, 124, 124, + + 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, + 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, + 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, + 124, 124, 124 + } ; + +static lp_yyconst short int lp_yy_chk[334] = + { 0, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 2, 3, 3, 4, + 4, 3, 76, 4, 5, 5, 6, 6, 9, 9, + 9, 10, 10, 10, 9, 76, 9, 10, 15, 10, + 2, 14, 14, 15, 16, 2, 16, 16, 22, 23, + 22, 23, 53, 25, 23, 25, 16, 26, 53, 26, + 23, 24, 24, 24, 123, 26, 25, 24, 46, 24, + 46, 26, 34, 34, 34, 36, 36, 36, 34, 79, + + 34, 36, 54, 36, 54, 24, 38, 38, 41, 41, + 24, 42, 79, 42, 42, 43, 38, 43, 41, 54, + 43, 43, 49, 42, 49, 50, 122, 50, 55, 121, + 55, 56, 70, 56, 70, 55, 59, 59, 50, 64, + 55, 49, 60, 60, 65, 55, 59, 56, 61, 61, + 120, 119, 64, 69, 64, 69, 71, 65, 71, 65, + 72, 69, 72, 64, 74, 74, 74, 71, 65, 73, + 73, 78, 73, 78, 118, 81, 72, 81, 87, 85, + 87, 85, 116, 78, 93, 86, 93, 81, 74, 85, + 86, 111, 86, 88, 88, 93, 88, 89, 89, 89, + + 95, 98, 95, 98, 109, 101, 86, 101, 102, 98, + 102, 95, 104, 112, 104, 107, 110, 107, 110, 113, + 108, 101, 108, 107, 102, 112, 101, 104, 108, 102, + 114, 106, 113, 105, 113, 117, 117, 117, 103, 100, + 99, 97, 96, 114, 91, 114, 84, 82, 80, 77, + 75, 68, 67, 66, 63, 58, 52, 47, 37, 117, + 125, 125, 125, 125, 125, 125, 125, 126, 126, 126, + 126, 126, 126, 126, 127, 35, 30, 21, 19, 127, + 128, 128, 12, 128, 128, 129, 129, 7, 0, 129, + 130, 0, 130, 130, 130, 130, 124, 124, 124, 124, + + 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, + 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, + 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, + 124, 124, 124 + } ; + +static lp_yy_state_type lp_yy_state_buf[YY_BUF_SIZE + 2], *lp_yy_state_ptr; +static char *lp_yy_full_match; +static int lp_yy_lp; +static int lp_yy_looking_for_trail_begin = 0; +static int lp_yy_full_lp; +static int *lp_yy_full_state; +#define YY_TRAILING_MASK 0x2000 +#define YY_TRAILING_HEAD_MASK 0x4000 +#define REJECT \ +{ \ +*lp_yy_cp = lp_yy_hold_char; /* undo effects of setting up lp_yytext */ \ +lp_yy_cp = lp_yy_full_match; /* restore poss. backed-over text */ \ +lp_yy_lp = lp_yy_full_lp; /* restore orig. accepting pos. */ \ +lp_yy_state_ptr = lp_yy_full_state; /* restore orig. state */ \ +lp_yy_current_state = *lp_yy_state_ptr; /* restore curr. state */ \ +++lp_yy_lp; \ +goto find_rule; \ +} +static int lp_yy_more_offset = 0; +static int lp_yy_prev_more_offset = 0; +#define lp_yymore() (lp_yy_more_offset = lp_yy_flex_strlen( lp_yytext )) +#define YY_NEED_STRLEN +#define YY_MORE_ADJ 0 +#define YY_RESTORE_YY_MORE_OFFSET \ + { \ + lp_yy_more_offset = lp_yy_prev_more_offset; \ + lp_yyleng -= lp_yy_more_offset; \ + } +#ifndef YYLMAX +#define YYLMAX 8192 +#endif + +char lp_yytext[YYLMAX]; +char *lp_yytext_ptr; +#define INITIAL 0 +#define COMMENT 1 + +#define LINECOMMENT 2 + + +/* Macros after this point can all be overridden by user definitions in + * section 1. + */ + +#ifndef YY_SKIP_YYWRAP +#ifdef __cplusplus +extern "C" int lp_yywrap YY_PROTO(( void )); +#else +extern int lp_yywrap YY_PROTO(( void )); +#endif +#endif + +#ifndef YY_NO_UNPUT +static void lp_yyunput YY_PROTO(( int c, char *buf_ptr )); +#endif + +#ifndef lp_yytext_ptr +static void lp_yy_flex_strncpy YY_PROTO(( char *, lp_yyconst char *, int )); +#endif + +#ifdef YY_NEED_STRLEN +static int lp_yy_flex_strlen YY_PROTO(( lp_yyconst char * )); +#endif + +#ifndef YY_NO_INPUT +#ifdef __cplusplus +static int lp_yyinput YY_PROTO(( void )); +#else +static int input YY_PROTO(( void )); +#endif +#endif + +#if YY_STACK_USED +static int lp_yy_start_stack_ptr = 0; +static int lp_yy_start_stack_depth = 0; +static int *lp_yy_start_stack = 0; +#ifndef YY_NO_PUSH_STATE +static void lp_yy_push_state YY_PROTO(( int new_state )); +#endif +#ifndef YY_NO_POP_STATE +static void lp_yy_pop_state YY_PROTO(( void )); +#endif +#ifndef YY_NO_TOP_STATE +static int lp_yy_top_state YY_PROTO(( void )); +#endif + +#else +#define YY_NO_PUSH_STATE 1 +#define YY_NO_POP_STATE 1 +#define YY_NO_TOP_STATE 1 +#endif + +#ifdef YY_MALLOC_DECL +YY_MALLOC_DECL +#else +#if __STDC__ +#ifndef __cplusplus +#include +#endif +#else +/* Just try to get by without declaring the routines. This will fail + * miserably on non-ANSI systems for which sizeof(size_t) != sizeof(int) + * or sizeof(void*) != sizeof(int). + */ +#endif +#endif + +/* Amount of stuff to slurp up with each read. */ +#ifndef YY_READ_BUF_SIZE +#define YY_READ_BUF_SIZE 8192 +#endif + +/* Copy whatever the last rule matched to the standard output. */ + +#ifndef ECHO +/* This used to be an fputs(), but since the string might contain NUL's, + * we now use fwrite(). + */ +#define ECHO (void) fwrite( lp_yytext, lp_yyleng, 1, lp_yyout ) +#endif + +/* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, + * is returned in "result". + */ +#ifndef YY_INPUT +#define YY_INPUT(buf,result,max_size) \ + if ( lp_yy_current_buffer->lp_yy_is_interactive ) \ + { \ + int c = '*', n; \ + for ( n = 0; n < max_size && \ + (c = getc( lp_yyin )) != EOF && c != '\n'; ++n ) \ + buf[n] = (char) c; \ + if ( c == '\n' ) \ + buf[n++] = (char) c; \ + if ( c == EOF && ferror( lp_yyin ) ) \ + YY_FATAL_ERROR( "input in flex scanner failed" ); \ + result = n; \ + } \ + else if ( ((result = fread( buf, 1, max_size, lp_yyin )) == 0) \ + && ferror( lp_yyin ) ) \ + YY_FATAL_ERROR( "input in flex scanner failed" ); +#endif + +/* No semi-colon after return; correct usage is to write "lp_yyterminate();" - + * we don't want an extra ';' after the "return" because that will cause + * some compilers to complain about unreachable statements. + */ +#ifndef lp_yyterminate +#define lp_yyterminate() return YY_NULL +#endif + +/* Number of entries by which start-condition stack grows. */ +#ifndef YY_START_STACK_INCR +#define YY_START_STACK_INCR 25 +#endif + +/* Report a fatal error. */ +#ifndef YY_FATAL_ERROR +#define YY_FATAL_ERROR(msg) lp_yy_fatal_error( msg ) +#endif + +/* Default declaration of generated scanner - a define so the user can + * easily add parameters. + */ +#ifndef YY_DECL +#define YY_DECL int lp_yylex YY_PROTO(( void )) +#endif + +/* Code executed at the beginning of each rule, after lp_yytext and lp_yyleng + * have been set up. + */ +#ifndef YY_USER_ACTION +#define YY_USER_ACTION +#endif + +/* Code executed at the end of each rule. */ +#ifndef YY_BREAK +#define YY_BREAK break; +#endif + +#define YY_RULE_SETUP \ + if ( lp_yyleng > 0 ) \ + lp_yy_current_buffer->lp_yy_at_bol = \ + (lp_yytext[lp_yyleng - 1] == '\n'); \ + YY_USER_ACTION + +YY_DECL + { + register lp_yy_state_type lp_yy_current_state; + register char *lp_yy_cp, *lp_yy_bp; + register int lp_yy_act; + + + + if ( lp_yy_init ) + { + lp_yy_init = 0; + +#ifdef YY_USER_INIT + YY_USER_INIT; +#endif + + if ( ! lp_yy_start ) + lp_yy_start = 1; /* first start state */ + + if ( ! lp_yyin ) + lp_yyin = stdin; + + if ( ! lp_yyout ) + lp_yyout = stdout; + + if ( ! lp_yy_current_buffer ) + lp_yy_current_buffer = + lp_yy_create_buffer( lp_yyin, YY_BUF_SIZE ); + + lp_yy_load_buffer_state(); + } + + while ( 1 ) /* loops until end-of-file is reached */ + { + lp_yy_cp = lp_yy_c_buf_p; + + /* Support of lp_yytext. */ + *lp_yy_cp = lp_yy_hold_char; + + /* lp_yy_bp points to the position in lp_yy_ch_buf of the start of + * the current run. + */ + lp_yy_bp = lp_yy_cp; + + lp_yy_current_state = lp_yy_start; + lp_yy_current_state += YY_AT_BOL(); + lp_yy_state_ptr = lp_yy_state_buf; + *lp_yy_state_ptr++ = lp_yy_current_state; +lp_yy_match: + do + { + register YY_CHAR lp_yy_c = lp_yy_ec[YY_SC_TO_UI(*lp_yy_cp)]; + while ( lp_yy_chk[lp_yy_base[lp_yy_current_state] + lp_yy_c] != lp_yy_current_state ) + { + lp_yy_current_state = (int) lp_yy_def[lp_yy_current_state]; + if ( lp_yy_current_state >= 125 ) + lp_yy_c = lp_yy_meta[(unsigned int) lp_yy_c]; + } + lp_yy_current_state = lp_yy_nxt[lp_yy_base[lp_yy_current_state] + (unsigned int) lp_yy_c]; + *lp_yy_state_ptr++ = lp_yy_current_state; + ++lp_yy_cp; + } + while ( lp_yy_base[lp_yy_current_state] != 297 ); + +lp_yy_find_action: + lp_yy_current_state = *--lp_yy_state_ptr; + lp_yy_lp = lp_yy_accept[lp_yy_current_state]; +find_rule: /* we branch to this label when backing up */ + for ( ; ; ) /* until we find what rule we matched */ + { + if ( lp_yy_lp && lp_yy_lp < lp_yy_accept[lp_yy_current_state + 1] ) + { + lp_yy_act = lp_yy_acclist[lp_yy_lp]; + if ( lp_yy_act & YY_TRAILING_HEAD_MASK || + lp_yy_looking_for_trail_begin ) + { + if ( lp_yy_act == lp_yy_looking_for_trail_begin ) + { + lp_yy_looking_for_trail_begin = 0; + lp_yy_act &= ~YY_TRAILING_HEAD_MASK; + break; + } + } + else if ( lp_yy_act & YY_TRAILING_MASK ) + { + lp_yy_looking_for_trail_begin = lp_yy_act & ~YY_TRAILING_MASK; + lp_yy_looking_for_trail_begin |= YY_TRAILING_HEAD_MASK; + lp_yy_full_match = lp_yy_cp; + lp_yy_full_state = lp_yy_state_ptr; + lp_yy_full_lp = lp_yy_lp; + } + else + { + lp_yy_full_match = lp_yy_cp; + lp_yy_full_state = lp_yy_state_ptr; + lp_yy_full_lp = lp_yy_lp; + break; + } + ++lp_yy_lp; + goto find_rule; + } + --lp_yy_cp; + lp_yy_current_state = *--lp_yy_state_ptr; + lp_yy_lp = lp_yy_accept[lp_yy_current_state]; + } + + YY_DO_BEFORE_ACTION; + + if ( lp_yy_act != YY_END_OF_BUFFER ) + { + int lp_yyl; + for ( lp_yyl = 0; lp_yyl < lp_yyleng; ++lp_yyl ) + if ( lp_yytext[lp_yyl] == '\n' ) + ++lp_yylineno; + } + +do_action: /* This label is used only to access EOF actions. */ + + + switch ( lp_yy_act ) + { /* beginning of action switch */ +case 1: +YY_RULE_SETUP +{ + BEGIN COMMENT; +} /* begin skip comment */ + YY_BREAK +case 2: +YY_RULE_SETUP +{ + BEGIN INITIAL; +} /* end skip comment */ + YY_BREAK +case 3: +YY_RULE_SETUP +{ +} + YY_BREAK +case 4: +YY_RULE_SETUP +{ +} + YY_BREAK +case 5: +YY_RULE_SETUP +{ +} + YY_BREAK +case 6: +YY_RULE_SETUP +{ + BEGIN LINECOMMENT; +} /* begin skip LINECOMMENT */ + YY_BREAK +case 7: +YY_RULE_SETUP +{ + BEGIN INITIAL; +} /* end skip LINECOMMENT */ + YY_BREAK +case 8: +YY_RULE_SETUP +{ + BEGIN INITIAL; +} /* end skip LINECOMMENT */ + YY_BREAK +case 9: +YY_RULE_SETUP +{ +} + YY_BREAK +case 10: +YY_RULE_SETUP +{ +} + YY_BREAK +case 11: +YY_RULE_SETUP +{ + return(COMMA); +} + YY_BREAK +case 12: +YY_RULE_SETUP +{ + return(MINIMISE); +} + YY_BREAK +case 13: +YY_RULE_SETUP +{ + return(MAXIMISE); +} + YY_BREAK +case 14: +YY_RULE_SETUP +{ + f = atof((char *)lp_yytext); + return(INTCONS); +} /* f contains the last float */ + YY_BREAK +case 15: +YY_RULE_SETUP +{ + f = atof((char *)lp_yytext); + return(CONS); +} /* f contains the last float */ + YY_BREAK +case 16: +YY_RULE_SETUP +{ + char *ptr; + + f = DEF_INFINITE; + Sign = 0; + ptr = (char *)lp_yytext; + while (isspace(*ptr)) ptr++; + if(*ptr == '-') + Sign = 1; + return(INF); +} /* f contains the last float */ + YY_BREAK +case 17: +YY_RULE_SETUP +{ + Sign = 0; + for(x = 0; x < lp_yyleng; x++) + if(lp_yytext[x] == '-' || lp_yytext[x] == '+') + Sign = (Sign == (lp_yytext[x] == '+')); + return (SIGN); + /* Sign is TRUE if the sign-string + represents a '-'. Otherwise Sign + is FALSE */ +} + YY_BREAK +case 18: +YY_RULE_SETUP +{ + if((!Within_int_decl) && (!Within_sec_decl) && (!Within_sos_decl)) { + Within_int_decl = TRUE; + Within_sos_decl1 = FALSE; + } + return(SEC_INT); +} + YY_BREAK +case 19: +YY_RULE_SETUP +{ + if((!Within_int_decl) && (!Within_sec_decl) && (!Within_sos_decl)) { + Within_sec_decl = TRUE; + Within_sos_decl1 = FALSE; + } + return(SEC_SEC); +} + YY_BREAK +case 20: +YY_RULE_SETUP +{ + if(!Within_sos_decl) + SOStype0 = (short)atoi(((char *)lp_yytext) + 3); + if((!Within_int_decl) && (!Within_sec_decl) && (!Within_sos_decl)) + Within_sos_decl = TRUE; + return(SEC_SOS); +} + YY_BREAK +case 21: +YY_RULE_SETUP +{ + FREE(Last_var); + Last_var = strdup((char *)lp_yytext); + Last_var[strlen(Last_var) - 2] = 0; + return(SOSDESCR); +} + YY_BREAK +case 22: +YY_RULE_SETUP +{ + FREE(Last_var); + Last_var = strdup((char *)lp_yytext); + Last_var[strlen(Last_var) - 1] = 0; + return(VARIABLECOLON); +} + YY_BREAK +case 23: +YY_RULE_SETUP +{ + FREE(Last_var); + Last_var = strdup((char *)lp_yytext); + return(VAR); +} + YY_BREAK +case 24: +YY_RULE_SETUP +{ + return (COLON); +} + YY_BREAK +case 25: +YY_RULE_SETUP +{ + return(AR_M_OP); +} + YY_BREAK +case 26: +YY_RULE_SETUP +{ + return(RE_OPLE); +} + YY_BREAK +case 27: +YY_RULE_SETUP +{ + return(RE_OPGE); +} + YY_BREAK +case 28: +YY_RULE_SETUP +{ + Within_int_decl = Within_sec_decl = Within_sos_decl = FALSE; + check_int_sec_sos_decl(Within_int_decl, Within_sec_decl, Within_sos_decl); + return(END_C); +} + YY_BREAK +case 29: +YY_RULE_SETUP +{ + report(NULL, CRITICAL, "LEX ERROR : %s lineno %d\n", lp_yytext, lp_yylineno); + return(UNDEFINED); +} + YY_BREAK +case 30: +YY_RULE_SETUP +ECHO; + YY_BREAK + case YY_STATE_EOF(INITIAL): + case YY_STATE_EOF(COMMENT): + case YY_STATE_EOF(LINECOMMENT): + lp_yyterminate(); + + case YY_END_OF_BUFFER: + { + /* Amount of text matched not including the EOB char. */ + int lp_yy_amount_of_matched_text = (int) (lp_yy_cp - lp_yytext_ptr) - 1; + + /* Undo the effects of YY_DO_BEFORE_ACTION. */ + *lp_yy_cp = lp_yy_hold_char; + YY_RESTORE_YY_MORE_OFFSET + + if ( lp_yy_current_buffer->lp_yy_buffer_status == YY_BUFFER_NEW ) + { + /* We're scanning a new file or input source. It's + * possible that this happened because the user + * just pointed lp_yyin at a new source and called + * lp_yylex(). If so, then we have to assure + * consistency between lp_yy_current_buffer and our + * globals. Here is the right place to do so, because + * this is the first action (other than possibly a + * back-up) that will match for the new input source. + */ + lp_yy_n_chars = lp_yy_current_buffer->lp_yy_n_chars; + lp_yy_current_buffer->lp_yy_input_file = lp_yyin; + lp_yy_current_buffer->lp_yy_buffer_status = YY_BUFFER_NORMAL; + } + + /* Note that here we test for lp_yy_c_buf_p "<=" to the position + * of the first EOB in the buffer, since lp_yy_c_buf_p will + * already have been incremented past the NUL character + * (since all states make transitions on EOB to the + * end-of-buffer state). Contrast this with the test + * in input(). + */ + if ( lp_yy_c_buf_p <= &lp_yy_current_buffer->lp_yy_ch_buf[lp_yy_n_chars] ) + { /* This was really a NUL. */ + lp_yy_state_type lp_yy_next_state; + + lp_yy_c_buf_p = lp_yytext_ptr + lp_yy_amount_of_matched_text; + + lp_yy_current_state = lp_yy_get_previous_state(); + + /* Okay, we're now positioned to make the NUL + * transition. We couldn't have + * lp_yy_get_previous_state() go ahead and do it + * for us because it doesn't know how to deal + * with the possibility of jamming (and we don't + * want to build jamming into it because then it + * will run more slowly). + */ + + lp_yy_next_state = lp_yy_try_NUL_trans( lp_yy_current_state ); + + lp_yy_bp = lp_yytext_ptr + YY_MORE_ADJ; + + if ( lp_yy_next_state ) + { + /* Consume the NUL. */ + lp_yy_cp = ++lp_yy_c_buf_p; + lp_yy_current_state = lp_yy_next_state; + goto lp_yy_match; + } + + else + { + lp_yy_cp = lp_yy_c_buf_p; + goto lp_yy_find_action; + } + } + + else switch ( lp_yy_get_next_buffer() ) + { + case EOB_ACT_END_OF_FILE: + { + lp_yy_did_buffer_switch_on_eof = 0; + + if ( lp_yywrap() ) + { + /* Note: because we've taken care in + * lp_yy_get_next_buffer() to have set up + * lp_yytext, we can now set up + * lp_yy_c_buf_p so that if some total + * hoser (like flex itself) wants to + * call the scanner after we return the + * YY_NULL, it'll still work - another + * YY_NULL will get returned. + */ + lp_yy_c_buf_p = lp_yytext_ptr + YY_MORE_ADJ; + + lp_yy_act = YY_STATE_EOF(YY_START); + goto do_action; + } + + else + { + if ( ! lp_yy_did_buffer_switch_on_eof ) + YY_NEW_FILE; + } + break; + } + + case EOB_ACT_CONTINUE_SCAN: + lp_yy_c_buf_p = + lp_yytext_ptr + lp_yy_amount_of_matched_text; + + lp_yy_current_state = lp_yy_get_previous_state(); + + lp_yy_cp = lp_yy_c_buf_p; + lp_yy_bp = lp_yytext_ptr + YY_MORE_ADJ; + goto lp_yy_match; + + case EOB_ACT_LAST_MATCH: + lp_yy_c_buf_p = + &lp_yy_current_buffer->lp_yy_ch_buf[lp_yy_n_chars]; + + lp_yy_current_state = lp_yy_get_previous_state(); + + lp_yy_cp = lp_yy_c_buf_p; + lp_yy_bp = lp_yytext_ptr + YY_MORE_ADJ; + goto lp_yy_find_action; + } + break; + } + + default: + YY_FATAL_ERROR( + "fatal flex scanner internal error--no action found" ); + } /* end of action switch */ + } /* end of scanning one token */ + } /* end of lp_yylex */ + + +/* lp_yy_get_next_buffer - try to read in a new buffer + * + * Returns a code representing an action: + * EOB_ACT_LAST_MATCH - + * EOB_ACT_CONTINUE_SCAN - continue scanning from current position + * EOB_ACT_END_OF_FILE - end of file + */ + +static int lp_yy_get_next_buffer() + { + register char *dest = lp_yy_current_buffer->lp_yy_ch_buf; + register char *source = lp_yytext_ptr; + register int number_to_move, i; + int ret_val; + + if ( lp_yy_c_buf_p > &lp_yy_current_buffer->lp_yy_ch_buf[lp_yy_n_chars + 1] ) + YY_FATAL_ERROR( + "fatal flex scanner internal error--end of buffer missed" ); + + if ( lp_yy_current_buffer->lp_yy_fill_buffer == 0 ) + { /* Don't try to fill the buffer, so this is an EOF. */ + if ( lp_yy_c_buf_p - lp_yytext_ptr - YY_MORE_ADJ == 1 ) + { + /* We matched a single character, the EOB, so + * treat this as a final EOF. + */ + return EOB_ACT_END_OF_FILE; + } + + else + { + /* We matched some text prior to the EOB, first + * process it. + */ + return EOB_ACT_LAST_MATCH; + } + } + + /* Try to read more data. */ + + /* First move last chars to start of buffer. */ + number_to_move = (int) (lp_yy_c_buf_p - lp_yytext_ptr) - 1; + + for ( i = 0; i < number_to_move; ++i ) + *(dest++) = *(source++); + + if ( lp_yy_current_buffer->lp_yy_buffer_status == YY_BUFFER_EOF_PENDING ) + /* don't do the read, it's not guaranteed to return an EOF, + * just force an EOF + */ + lp_yy_current_buffer->lp_yy_n_chars = lp_yy_n_chars = 0; + + else + { + int num_to_read = + lp_yy_current_buffer->lp_yy_buf_size - number_to_move - 1; + + while ( num_to_read <= 0 ) + { /* Not enough room in the buffer - grow it. */ +#ifdef YY_USES_REJECT + YY_FATAL_ERROR( +"input buffer overflow, can't enlarge buffer because scanner uses REJECT" ); +#else + + /* just a shorter name for the current buffer */ + YY_BUFFER_STATE b = lp_yy_current_buffer; + + int lp_yy_c_buf_p_offset = + (int) (lp_yy_c_buf_p - b->lp_yy_ch_buf); + + if ( b->lp_yy_is_our_buffer ) + { + int new_size = b->lp_yy_buf_size * 2; + + if ( new_size <= 0 ) + b->lp_yy_buf_size += b->lp_yy_buf_size / 8; + else + b->lp_yy_buf_size *= 2; + + b->lp_yy_ch_buf = (char *) + /* Include room in for 2 EOB chars. */ + lp_yy_flex_realloc( (void *) b->lp_yy_ch_buf, + b->lp_yy_buf_size + 2 ); + } + else + /* Can't grow it, we don't own it. */ + b->lp_yy_ch_buf = 0; + + if ( ! b->lp_yy_ch_buf ) + YY_FATAL_ERROR( + "fatal error - scanner input buffer overflow" ); + + lp_yy_c_buf_p = &b->lp_yy_ch_buf[lp_yy_c_buf_p_offset]; + + num_to_read = lp_yy_current_buffer->lp_yy_buf_size - + number_to_move - 1; +#endif + } + + if ( num_to_read > YY_READ_BUF_SIZE ) + num_to_read = YY_READ_BUF_SIZE; + + /* Read in more data. */ + YY_INPUT( (&lp_yy_current_buffer->lp_yy_ch_buf[number_to_move]), + lp_yy_n_chars, num_to_read ); + + lp_yy_current_buffer->lp_yy_n_chars = lp_yy_n_chars; + } + + if ( lp_yy_n_chars == 0 ) + { + if ( number_to_move == YY_MORE_ADJ ) + { + ret_val = EOB_ACT_END_OF_FILE; + lp_yyrestart( lp_yyin ); + } + + else + { + ret_val = EOB_ACT_LAST_MATCH; + lp_yy_current_buffer->lp_yy_buffer_status = + YY_BUFFER_EOF_PENDING; + } + } + + else + ret_val = EOB_ACT_CONTINUE_SCAN; + + lp_yy_n_chars += number_to_move; + lp_yy_current_buffer->lp_yy_ch_buf[lp_yy_n_chars] = YY_END_OF_BUFFER_CHAR; + lp_yy_current_buffer->lp_yy_ch_buf[lp_yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR; + + lp_yytext_ptr = &lp_yy_current_buffer->lp_yy_ch_buf[0]; + + return ret_val; + } + + +/* lp_yy_get_previous_state - get the state just before the EOB char was reached */ + +static lp_yy_state_type lp_yy_get_previous_state() + { + register lp_yy_state_type lp_yy_current_state; + register char *lp_yy_cp; + + lp_yy_current_state = lp_yy_start; + lp_yy_current_state += YY_AT_BOL(); + lp_yy_state_ptr = lp_yy_state_buf; + *lp_yy_state_ptr++ = lp_yy_current_state; + + for ( lp_yy_cp = lp_yytext_ptr + YY_MORE_ADJ; lp_yy_cp < lp_yy_c_buf_p; ++lp_yy_cp ) + { + register YY_CHAR lp_yy_c = (*lp_yy_cp ? lp_yy_ec[YY_SC_TO_UI(*lp_yy_cp)] : 1); + while ( lp_yy_chk[lp_yy_base[lp_yy_current_state] + lp_yy_c] != lp_yy_current_state ) + { + lp_yy_current_state = (int) lp_yy_def[lp_yy_current_state]; + if ( lp_yy_current_state >= 125 ) + lp_yy_c = lp_yy_meta[(unsigned int) lp_yy_c]; + } + lp_yy_current_state = lp_yy_nxt[lp_yy_base[lp_yy_current_state] + (unsigned int) lp_yy_c]; + *lp_yy_state_ptr++ = lp_yy_current_state; + } + + return lp_yy_current_state; + } + + +/* lp_yy_try_NUL_trans - try to make a transition on the NUL character + * + * synopsis + * next_state = lp_yy_try_NUL_trans( current_state ); + */ + +#ifdef YY_USE_PROTOS +static lp_yy_state_type lp_yy_try_NUL_trans( lp_yy_state_type lp_yy_current_state ) +#else +static lp_yy_state_type lp_yy_try_NUL_trans( lp_yy_current_state ) +lp_yy_state_type lp_yy_current_state; +#endif + { + register int lp_yy_is_jam; + + register YY_CHAR lp_yy_c = 1; + while ( lp_yy_chk[lp_yy_base[lp_yy_current_state] + lp_yy_c] != lp_yy_current_state ) + { + lp_yy_current_state = (int) lp_yy_def[lp_yy_current_state]; + if ( lp_yy_current_state >= 125 ) + lp_yy_c = lp_yy_meta[(unsigned int) lp_yy_c]; + } + lp_yy_current_state = lp_yy_nxt[lp_yy_base[lp_yy_current_state] + (unsigned int) lp_yy_c]; + lp_yy_is_jam = (lp_yy_current_state == 124); + if ( ! lp_yy_is_jam ) + *lp_yy_state_ptr++ = lp_yy_current_state; + + return lp_yy_is_jam ? 0 : lp_yy_current_state; + } + + +#ifndef YY_NO_UNPUT +#ifdef YY_USE_PROTOS +static void lp_yyunput( int c, register char *lp_yy_bp ) +#else +static void lp_yyunput( c, lp_yy_bp ) +int c; +register char *lp_yy_bp; +#endif + { + register char *lp_yy_cp = lp_yy_c_buf_p; + + /* undo effects of setting up lp_yytext */ + *lp_yy_cp = lp_yy_hold_char; + + if ( lp_yy_cp < lp_yy_current_buffer->lp_yy_ch_buf + 2 ) + { /* need to shift things up to make room */ + /* +2 for EOB chars. */ + register int number_to_move = lp_yy_n_chars + 2; + register char *dest = &lp_yy_current_buffer->lp_yy_ch_buf[ + lp_yy_current_buffer->lp_yy_buf_size + 2]; + register char *source = + &lp_yy_current_buffer->lp_yy_ch_buf[number_to_move]; + + while ( source > lp_yy_current_buffer->lp_yy_ch_buf ) + *--dest = *--source; + + lp_yy_cp += (int) (dest - source); + lp_yy_bp += (int) (dest - source); + lp_yy_current_buffer->lp_yy_n_chars = + lp_yy_n_chars = lp_yy_current_buffer->lp_yy_buf_size; + + if ( lp_yy_cp < lp_yy_current_buffer->lp_yy_ch_buf + 2 ) + YY_FATAL_ERROR( "flex scanner push-back overflow" ); + } + + *--lp_yy_cp = (char) c; + + if ( c == '\n' ) + --lp_yylineno; + + lp_yytext_ptr = lp_yy_bp; + lp_yy_hold_char = *lp_yy_cp; + lp_yy_c_buf_p = lp_yy_cp; + } +#endif /* ifndef YY_NO_UNPUT */ + + +#ifdef __cplusplus +static int lp_yyinput() +#else +static int input() +#endif + { + int c; + + *lp_yy_c_buf_p = lp_yy_hold_char; + + if ( *lp_yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) + { + /* lp_yy_c_buf_p now points to the character we want to return. + * If this occurs *before* the EOB characters, then it's a + * valid NUL; if not, then we've hit the end of the buffer. + */ + if ( lp_yy_c_buf_p < &lp_yy_current_buffer->lp_yy_ch_buf[lp_yy_n_chars] ) + /* This was really a NUL. */ + *lp_yy_c_buf_p = '\0'; + + else + { /* need more input */ + int offset = lp_yy_c_buf_p - lp_yytext_ptr; + ++lp_yy_c_buf_p; + + switch ( lp_yy_get_next_buffer() ) + { + case EOB_ACT_LAST_MATCH: + /* This happens because lp_yy_g_n_b() + * sees that we've accumulated a + * token and flags that we need to + * try matching the token before + * proceeding. But for input(), + * there's no matching to consider. + * So convert the EOB_ACT_LAST_MATCH + * to EOB_ACT_END_OF_FILE. + */ + + /* Reset buffer status. */ + lp_yyrestart( lp_yyin ); + + /* fall through */ + + case EOB_ACT_END_OF_FILE: + { + if ( lp_yywrap() ) + return EOF; + + if ( ! lp_yy_did_buffer_switch_on_eof ) + YY_NEW_FILE; +#ifdef __cplusplus + return lp_yyinput(); +#else + return input(); +#endif + } + + case EOB_ACT_CONTINUE_SCAN: + lp_yy_c_buf_p = lp_yytext_ptr + offset; + break; + } + } + } + + c = *(unsigned char *) lp_yy_c_buf_p; /* cast for 8-bit char's */ + *lp_yy_c_buf_p = '\0'; /* preserve lp_yytext */ + lp_yy_hold_char = *++lp_yy_c_buf_p; + + lp_yy_current_buffer->lp_yy_at_bol = (c == '\n'); + if ( lp_yy_current_buffer->lp_yy_at_bol ) + ++lp_yylineno; + + return c; + } + + +#ifdef YY_USE_PROTOS +void lp_yyrestart( FILE *input_file ) +#else +void lp_yyrestart( input_file ) +FILE *input_file; +#endif + { + if ( ! lp_yy_current_buffer ) + lp_yy_current_buffer = lp_yy_create_buffer( lp_yyin, YY_BUF_SIZE ); + + lp_yy_init_buffer( lp_yy_current_buffer, input_file ); + lp_yy_load_buffer_state(); + } + + +#ifdef YY_USE_PROTOS +void lp_yy_switch_to_buffer( YY_BUFFER_STATE new_buffer ) +#else +void lp_yy_switch_to_buffer( new_buffer ) +YY_BUFFER_STATE new_buffer; +#endif + { + if ( lp_yy_current_buffer == new_buffer ) + return; + + if ( lp_yy_current_buffer ) + { + /* Flush out information for old buffer. */ + *lp_yy_c_buf_p = lp_yy_hold_char; + lp_yy_current_buffer->lp_yy_buf_pos = lp_yy_c_buf_p; + lp_yy_current_buffer->lp_yy_n_chars = lp_yy_n_chars; + } + + lp_yy_current_buffer = new_buffer; + lp_yy_load_buffer_state(); + + /* We don't actually know whether we did this switch during + * EOF (lp_yywrap()) processing, but the only time this flag + * is looked at is after lp_yywrap() is called, so it's safe + * to go ahead and always set it. + */ + lp_yy_did_buffer_switch_on_eof = 1; + } + + +#ifdef YY_USE_PROTOS +void lp_yy_load_buffer_state( void ) +#else +void lp_yy_load_buffer_state() +#endif + { + lp_yy_n_chars = lp_yy_current_buffer->lp_yy_n_chars; + lp_yytext_ptr = lp_yy_c_buf_p = lp_yy_current_buffer->lp_yy_buf_pos; + lp_yyin = lp_yy_current_buffer->lp_yy_input_file; + lp_yy_hold_char = *lp_yy_c_buf_p; + } + + +#ifdef YY_USE_PROTOS +YY_BUFFER_STATE lp_yy_create_buffer( FILE *file, int size ) +#else +YY_BUFFER_STATE lp_yy_create_buffer( file, size ) +FILE *file; +int size; +#endif + { + YY_BUFFER_STATE b; + + b = (YY_BUFFER_STATE) lp_yy_flex_alloc( sizeof( struct lp_yy_buffer_state ) ); + if ( ! b ) + YY_FATAL_ERROR( "out of dynamic memory in lp_yy_create_buffer()" ); + + b->lp_yy_buf_size = size; + + /* lp_yy_ch_buf has to be 2 characters longer than the size given because + * we need to put in 2 end-of-buffer characters. + */ + b->lp_yy_ch_buf = (char *) lp_yy_flex_alloc( b->lp_yy_buf_size + 2 ); + if ( ! b->lp_yy_ch_buf ) + YY_FATAL_ERROR( "out of dynamic memory in lp_yy_create_buffer()" ); + + b->lp_yy_is_our_buffer = 1; + + lp_yy_init_buffer( b, file ); + + return b; + } + + +#ifdef YY_USE_PROTOS +void lp_yy_delete_buffer( YY_BUFFER_STATE b ) +#else +void lp_yy_delete_buffer( b ) +YY_BUFFER_STATE b; +#endif + { + if ( ! b ) + return; + + if ( b == lp_yy_current_buffer ) + lp_yy_current_buffer = (YY_BUFFER_STATE) 0; + + if ( b->lp_yy_is_our_buffer ) + lp_yy_flex_free( (void *) b->lp_yy_ch_buf ); + + lp_yy_flex_free( (void *) b ); + } + + +#ifndef YY_ALWAYS_INTERACTIVE +#ifndef YY_NEVER_INTERACTIVE +extern int isatty YY_PROTO(( int )); +#endif +#endif + +#ifdef YY_USE_PROTOS +void lp_yy_init_buffer( YY_BUFFER_STATE b, FILE *file ) +#else +void lp_yy_init_buffer( b, file ) +YY_BUFFER_STATE b; +FILE *file; +#endif + + + { + lp_yy_flush_buffer( b ); + + b->lp_yy_input_file = file; + b->lp_yy_fill_buffer = 1; + +#if YY_ALWAYS_INTERACTIVE + b->lp_yy_is_interactive = 1; +#else +#if YY_NEVER_INTERACTIVE + b->lp_yy_is_interactive = 0; +#else + b->lp_yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0; +#endif +#endif + } + + +#ifdef YY_USE_PROTOS +void lp_yy_flush_buffer( YY_BUFFER_STATE b ) +#else +void lp_yy_flush_buffer( b ) +YY_BUFFER_STATE b; +#endif + + { + if ( ! b ) + return; + + b->lp_yy_n_chars = 0; + + /* We always need two end-of-buffer characters. The first causes + * a transition to the end-of-buffer state. The second causes + * a jam in that state. + */ + b->lp_yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; + b->lp_yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; + + b->lp_yy_buf_pos = &b->lp_yy_ch_buf[0]; + + b->lp_yy_at_bol = 1; + b->lp_yy_buffer_status = YY_BUFFER_NEW; + + if ( b == lp_yy_current_buffer ) + lp_yy_load_buffer_state(); + } + + +#ifndef YY_NO_SCAN_BUFFER +#ifdef YY_USE_PROTOS +YY_BUFFER_STATE lp_yy_scan_buffer( char *base, lp_yy_size_t size ) +#else +YY_BUFFER_STATE lp_yy_scan_buffer( base, size ) +char *base; +lp_yy_size_t size; +#endif + { + YY_BUFFER_STATE b; + + if ( size < 2 || + base[size-2] != YY_END_OF_BUFFER_CHAR || + base[size-1] != YY_END_OF_BUFFER_CHAR ) + /* They forgot to leave room for the EOB's. */ + return 0; + + b = (YY_BUFFER_STATE) lp_yy_flex_alloc( sizeof( struct lp_yy_buffer_state ) ); + if ( ! b ) + YY_FATAL_ERROR( "out of dynamic memory in lp_yy_scan_buffer()" ); + + b->lp_yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ + b->lp_yy_buf_pos = b->lp_yy_ch_buf = base; + b->lp_yy_is_our_buffer = 0; + b->lp_yy_input_file = 0; + b->lp_yy_n_chars = b->lp_yy_buf_size; + b->lp_yy_is_interactive = 0; + b->lp_yy_at_bol = 1; + b->lp_yy_fill_buffer = 0; + b->lp_yy_buffer_status = YY_BUFFER_NEW; + + lp_yy_switch_to_buffer( b ); + + return b; + } +#endif + + +#ifndef YY_NO_SCAN_STRING +#ifdef YY_USE_PROTOS +YY_BUFFER_STATE lp_yy_scan_string( lp_yyconst char *lp_yy_str ) +#else +YY_BUFFER_STATE lp_yy_scan_string( lp_yy_str ) +lp_yyconst char *lp_yy_str; +#endif + { + int len; + for ( len = 0; lp_yy_str[len]; ++len ) + ; + + return lp_yy_scan_bytes( lp_yy_str, len ); + } +#endif + + +#ifndef YY_NO_SCAN_BYTES +#ifdef YY_USE_PROTOS +YY_BUFFER_STATE lp_yy_scan_bytes( lp_yyconst char *bytes, int len ) +#else +YY_BUFFER_STATE lp_yy_scan_bytes( bytes, len ) +lp_yyconst char *bytes; +int len; +#endif + { + YY_BUFFER_STATE b; + char *buf; + lp_yy_size_t n; + int i; + + /* Get memory for full buffer, including space for trailing EOB's. */ + n = len + 2; + buf = (char *) lp_yy_flex_alloc( n ); + if ( ! buf ) + YY_FATAL_ERROR( "out of dynamic memory in lp_yy_scan_bytes()" ); + + for ( i = 0; i < len; ++i ) + buf[i] = bytes[i]; + + buf[len] = buf[len+1] = YY_END_OF_BUFFER_CHAR; + + b = lp_yy_scan_buffer( buf, n ); + if ( ! b ) + YY_FATAL_ERROR( "bad buffer in lp_yy_scan_bytes()" ); + + /* It's okay to grow etc. this buffer, and we should throw it + * away when we're done. + */ + b->lp_yy_is_our_buffer = 1; + + return b; + } +#endif + + +#ifndef YY_NO_PUSH_STATE +#ifdef YY_USE_PROTOS +static void lp_yy_push_state( int new_state ) +#else +static void lp_yy_push_state( new_state ) +int new_state; +#endif + { + if ( lp_yy_start_stack_ptr >= lp_yy_start_stack_depth ) + { + lp_yy_size_t new_size; + + lp_yy_start_stack_depth += YY_START_STACK_INCR; + new_size = lp_yy_start_stack_depth * sizeof( int ); + + if ( ! lp_yy_start_stack ) + lp_yy_start_stack = (int *) lp_yy_flex_alloc( new_size ); + + else + lp_yy_start_stack = (int *) lp_yy_flex_realloc( + (void *) lp_yy_start_stack, new_size ); + + if ( ! lp_yy_start_stack ) + YY_FATAL_ERROR( + "out of memory expanding start-condition stack" ); + } + + lp_yy_start_stack[lp_yy_start_stack_ptr++] = YY_START; + + BEGIN(new_state); + } +#endif + + +#ifndef YY_NO_POP_STATE +static void lp_yy_pop_state() + { + if ( --lp_yy_start_stack_ptr < 0 ) + YY_FATAL_ERROR( "start-condition stack underflow" ); + + BEGIN(lp_yy_start_stack[lp_yy_start_stack_ptr]); + } +#endif + + +#ifndef YY_NO_TOP_STATE +static int lp_yy_top_state() + { + return lp_yy_start_stack[lp_yy_start_stack_ptr - 1]; + } +#endif + +#ifndef YY_EXIT_FAILURE +#define YY_EXIT_FAILURE 2 +#endif + +#ifdef YY_USE_PROTOS +static void lp_yy_fatal_error( lp_yyconst char msg[] ) +#else +static void lp_yy_fatal_error( msg ) +char msg[]; +#endif + { + (void) fprintf( stderr, "%s\n", msg ); + exit( YY_EXIT_FAILURE ); + } + + + +/* Redefine lp_yyless() so it works in section 3 code. */ + +#undef lp_yyless +#define lp_yyless(n) \ + do \ + { \ + /* Undo effects of setting up lp_yytext. */ \ + lp_yytext[lp_yyleng] = lp_yy_hold_char; \ + lp_yy_c_buf_p = lp_yytext + n; \ + lp_yy_hold_char = *lp_yy_c_buf_p; \ + *lp_yy_c_buf_p = '\0'; \ + lp_yyleng = n; \ + } \ + while ( 0 ) + + +/* Internal utility routines. */ + +#ifndef lp_yytext_ptr +#ifdef YY_USE_PROTOS +static void lp_yy_flex_strncpy( char *s1, lp_yyconst char *s2, int n ) +#else +static void lp_yy_flex_strncpy( s1, s2, n ) +char *s1; +lp_yyconst char *s2; +int n; +#endif + { + register int i; + for ( i = 0; i < n; ++i ) + s1[i] = s2[i]; + } +#endif + +#ifdef YY_NEED_STRLEN +#ifdef YY_USE_PROTOS +static int lp_yy_flex_strlen( lp_yyconst char *s ) +#else +static int lp_yy_flex_strlen( s ) +lp_yyconst char *s; +#endif + { + register int n; + for ( n = 0; s[n]; ++n ) + ; + + return n; + } +#endif + + +#ifdef YY_USE_PROTOS +static void *lp_yy_flex_alloc( lp_yy_size_t size ) +#else +static void *lp_yy_flex_alloc( size ) +lp_yy_size_t size; +#endif + { + return (void *) malloc( size ); + } + +#ifdef YY_USE_PROTOS +static void *lp_yy_flex_realloc( void *ptr, lp_yy_size_t size ) +#else +static void *lp_yy_flex_realloc( ptr, size ) +void *ptr; +lp_yy_size_t size; +#endif + { + /* The cast to (char *) in the following accommodates both + * implementations that use char* generic pointers, and those + * that use void* generic pointers. It works with the latter + * because both ANSI C and C++ allow castless assignment from + * any pointer type to void*, and deal with argument conversions + * as though doing an assignment. + */ + return (void *) realloc( (char *) ptr, size ); + } + +#ifdef YY_USE_PROTOS +static void lp_yy_flex_free( void *ptr ) +#else +static void lp_yy_flex_free( ptr ) +void *ptr; +#endif + { + free( ptr ); + } + +#if YY_MAIN +int main() + { + lp_yylex(); + return 0; + } +#endif + diff --git a/include/lp_scale.h b/include/lp_scale.h new file mode 100644 index 0000000..2aa8cc6 --- /dev/null +++ b/include/lp_scale.h @@ -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 */ + diff --git a/include/lp_simplex.h b/include/lp_simplex.h new file mode 100644 index 0000000..d973f72 --- /dev/null +++ b/include/lp_simplex.h @@ -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 */ + diff --git a/include/lp_solveDLL.h b/include/lp_solveDLL.h new file mode 100644 index 0000000..ebf98af --- /dev/null +++ b/include/lp_solveDLL.h @@ -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 + +// 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_) diff --git a/include/lp_types.h b/include/lp_types.h new file mode 100644 index 0000000..dd42a44 --- /dev/null +++ b/include/lp_types.h @@ -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 */ diff --git a/include/lp_utils.h b/include/lp_utils.h new file mode 100644 index 0000000..b9af81f --- /dev/null +++ b/include/lp_utils.h @@ -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 + diff --git a/include/lp_wlp.h b/include/lp_wlp.h new file mode 100644 index 0000000..010858b --- /dev/null +++ b/include/lp_wlp.h @@ -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 */ + diff --git a/include/lpkit.h b/include/lpkit.h new file mode 100644 index 0000000..87913a4 --- /dev/null +++ b/include/lpkit.h @@ -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) diff --git a/include/lpsolve.h b/include/lpsolve.h new file mode 100644 index 0000000..ebf98af --- /dev/null +++ b/include/lpsolve.h @@ -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 + +// 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_) diff --git a/include/ufortify.h b/include/ufortify.h new file mode 100644 index 0000000..a495e92 --- /dev/null +++ b/include/ufortify.h @@ -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 diff --git a/include/yacc_read.h b/include/yacc_read.h new file mode 100644 index 0000000..0fa53f4 --- /dev/null +++ b/include/yacc_read.h @@ -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 diff --git a/interface.H b/interface.H new file mode 100644 index 0000000..b93f2aa --- /dev/null +++ b/interface.H @@ -0,0 +1,5 @@ +#ifndef _INTERFACE_H +#define INTERFACE_H +#include "main.H" +void Y(); +#endif diff --git a/interface.cpp b/interface.cpp new file mode 100644 index 0000000..0df2021 --- /dev/null +++ b/interface.cpp @@ -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]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 F, B; + A.logforward(F,w); + A.logbackward(B,w); + + list::const_iterator f; + list::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; + } +} diff --git a/lib/liblpsolve55.a b/lib/liblpsolve55.a new file mode 100644 index 0000000..9821eaa Binary files /dev/null and b/lib/liblpsolve55.a differ diff --git a/lib/liblpsolve55.dylib b/lib/liblpsolve55.dylib new file mode 100755 index 0000000..1e4b968 Binary files /dev/null and b/lib/liblpsolve55.dylib differ diff --git a/lib/linux_liblpsolve55.a b/lib/linux_liblpsolve55.a new file mode 100644 index 0000000..ca78fe5 Binary files /dev/null and b/lib/linux_liblpsolve55.a differ diff --git a/ma.H b/ma.H new file mode 100644 index 0000000..f031814 --- /dev/null +++ b/ma.H @@ -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 + +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 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 diff --git a/ma.cpp b/ma.cpp new file mode 100644 index 0000000..ce68748 --- /dev/null +++ b/ma.cpp @@ -0,0 +1,2562 @@ +/*************************************************************************** + ma.C + ------------------- + begin : Tue Jul 16 2002 + copyright : (C) 2002 by Yann Esposito + email : esposito@cmi.univ-mrs.fr +***************************************************************************/ + +/* + Pour les notes, voir le fichier "ffa.h". + See "ffa.h" file to view notes. +*/ + +#include "ma.H" +#include +#include +#include +#include +#include "simplex.H" + +RESULT MA::save_dot (const string Filename, int precision, bool noms_etats, + bool multiple_trans) const +{ + return save_dot (Filename.c_str (), precision, noms_etats, multiple_trans); +} + + +/// ------- MÈthodes internes --------- +float +MA::random (float min, float max) const +{ + if (PFA_SAFE) + { + assert (min <= max); + } + return ((((float) rand () + 1) / INT_MAX) * (max - min)) + + min; +} + +/// --------------------- Constructeurs et Destructeurs ---------------------- +// Constructeur par dÈfaut +MA::MA (int nb_lettres, int nb_etats) +{ + // Initialisation de l'alphabet + int i; + for (i = 0; i < nb_lettres; ++i) + { + Sigma.insert ('a' + i); + } + + // Initialisation de l'ensemble d'Ètats + for (i = 0; i < nb_etats; ++i) + Q.insert (i); + + // Initialisation de iota + StateSet::iterator q; + for (q = Q.begin (); q != Q.end (); ++q) + iota[*q] = 0; + if (nb_etats != 0) + iota[*(Q.begin ())] = 1; + + // Initialisation de tau + for (q = Q.begin (); q != Q.end (); ++q) + tau[*q] = 1; + + // Initialisation de phi + // On laise phi complËtement vide, l'automate n'a pas d'arÃte ‡ l'initialisation. +} + +// Destructeur par dÈfaut +MA::~MA () +{} + + +/// -------------------------- Affichage ---------------------------------- + +// Fonction d'affichage d'automate +string MA::message (void) const +{ + string + mesg; // La variable qui va contenir le message a afficher. + char + flottant[3 * (sizeof (float)) + 1]; // un tableau suffisamment grand pour Ècrire un flottant en dÈcimal. + mesg = "--- AFFICHAGE de " + name + " ---\n"; + + if (PFA_VERBOSE) + { + // Affichage du dictionnaire + for (Dictionnaire::const_iterator d = alph.begin (); + d != alph.end (); ++d) + { + mesg += "alph["; + mesg += d->first; + mesg += "]=" + d->second + " ; "; + } + mesg += "\n"; + } + + // Affichage de l'alphabet + Alphabet::const_iterator l; + mesg += "Sigma = {"; + if (Sigma.empty ()) + { + mesg += "}\n"; + } + else + { + for (l = Sigma.begin (); l != Sigma.end ();) + { + if (alph.find (*l) == alph.end ()) + { + mesg += *l; + } + else + { + mesg += (alph.find (*l))->second; + } + + if (++l != Sigma.end ()) + { + mesg += ", "; + } + else + { + mesg += "}\n"; + } + } + } + + // Affichage des Ètats + StateSet::const_iterator e; + mesg += "Q = {"; + e = Q.begin (); + if (e == Q.end ()) + { + mesg += "}\n"; + } + while (e != Q.end ()) + { + sprintf (flottant, "%d", *e); + mesg += flottant; + e++; + if (e != Q.end ()) + { + mesg += ", "; + } + else + { + mesg += "}\n"; + } + } + + // Affichage de iota + SFunc::const_iterator s; + stringstream convert; + string nombre; + mesg += "iota : "; + for (s = iota.begin (); s != iota.end (); ++s) + { + mesg += "("; + sprintf (flottant, "%d", s->first); + mesg += flottant; + mesg += ", "; + //convert << s->second; + //convert >> nombre; + //mesg += nombre; + sprintf (flottant, "%f", s->second); + mesg += flottant; + mesg += ") "; + } + mesg += "\n"; + + // Affichage de tau + mesg += "tau : "; + int i=0; + for (s = tau.begin (); s != tau.end (); ++s) + { + mesg += "("; + sprintf (flottant, "%d", s->first); + mesg += flottant; + mesg += ", "; + sprintf (flottant, "%f", s->second); + mesg += flottant; + mesg += ") "; + if (i++%5 == 0) { + mesg += "\n"; + } + } + mesg += "\n"; + + // Affichage de phi + mesg += "phi : "; + if (phi.empty ()) + mesg += "vide"; + else + { + LettreSFunc::const_iterator a; + Graph::const_iterator q; + 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++) + { + mesg += "("; + sprintf (flottant, "%d", + q->first); + mesg += flottant; + mesg += ","; + + // on Ècrit la bonne lettre + if (alph.find (a->first) == + alph.end ()) + mesg += a->first; + else + mesg += alph.find (a->first)->second; + + mesg += ","; + sprintf (flottant, "%d", s->first); + mesg += flottant; + mesg += ") = "; + sprintf (flottant, "%f", s->second); + mesg += flottant; + mesg += " ; "; + } + } + mesg+="\n"; + } + } + mesg += "\n"; + + return mesg; +} + +// Chargement d'un fichier dot pour l'affichage de graphe +RESULT +MA::save_dot (const char *Filename, + const int precision, + const bool noms_etats, + const bool multiples_trans) const +{ + try + { + if (Filename == NULL) + { + throw 0; + } + + ofstream fp (Filename); + if (fp == NULL) + { + throw 1; + } + fp.precision (precision); //fp.flags(ios::scientific); + + if (!name.empty ()) + fp << "digraph \"" << name << "\" {" << endl; + else + fp << "digraph G {" << endl; + + // On met le graphe en mode horizontal (Left to Right) + fp << "graph [rankdir=LR]" << endl; + + Graph::const_iterator q; + StateSet::const_iterator e; + LettreSFunc::const_iterator a, b; + SFunc::const_iterator s, r; + StateSet W; + Dictionnaire::const_iterator tl; + + for (e = Q.begin (); e != Q.end (); ++e) + { + // On crÈe la flÃche d'initialisation si il y a lieu + if ((iota.find (*e) != iota.end ()) && (iota.find (*e)->second != 0)) + { + fp << "iota" << *e << "[shape=plaintext, label = "; + fp << (iota.find (*e))-> + second << " psfrag = \"$"; + fp << (iota.find (*e))-> + second << "$\", height=.15]" << + endl; + fp << "iota" << *e << " -> " << *e << + "[minlen=1]" << endl; + } + + // on cree l'etat avec ses attributs + fp << *e; + fp << " [ label = \""; + if (noms_etats) + { + fp << *e << "\\n"; + } + // if ((iota.find(*e) != iota.end()) && + // (iota.find(*e)->second != 0)) { + //fp << "i=" << (iota.find(*e))->second << "\\n"; + // + if ((tau.find (*e) != tau.end ()) + && (tau.find (*e)->second != 0)) + { + fp << (tau.find (*e))->second; + fp << "\",peripheries=2"; + } + else + { + fp << "\""; + } + fp << "]" << endl; + + // on ecrit ses successeurs + q = phi.find (*e); + if (q != phi.end ()) + { + if (multiples_trans) + { + for (a = q->second.begin ();a != q->second.end (); a++) + { + for (s =(a->second).begin ();s !=(a->second).end ();s++) + { + if (s->second !=0) + fp << "\t" << q->first; + fp << " -> " << s->first; + fp << "[label=\""; + tl = alph.find(a->first); + if (tl == alph.end()) { + throw 3; + } + fp << tl->second; + fp << "," << s->second; + fp << "\"]" << endl; + } + } + } + else + { + // le W sert a ne pas s'occuper plusieurs fois de l'etat d'arrive + W.clear(); + for (a = q->second.begin (); a != q->second.end (); a++) + { + for (s =(a->second).begin ();s !=(a->second).end ();s++) + { + if (s->second !=0) + { + if (W.find(s->first)==W.end()) + { + W.insert (s->first); + fp << "\t" << q->first << " -> " << s->first; + fp << "[label=\""; + tl=alph.find(a->first); + if (tl == alph.end()) + throw 3; + fp << tl->second << "," << s->second; + for (b = a; ++b != q->second.end ();) + { + r = b->second.find (s->first); + if (r != b->second.end ()) + { + fp << "\\n"; + tl = alph.find (b->first); + if (tl == alph.end()) + throw 3; + fp << tl->second << "," << r->second; + } + } + fp << "\"]" << endl; + } + } + } + } + } + } + } + + fp << "}" << endl; + return VAL (0); + } + catch (int erreur) + { + if (PFA_VERBOSE) + { + cerr << "ERREUR MA::save_dot" << endl; + switch (erreur) + { + case 0: + cerr << "\tFilename == NULL !!!" << endl; + break; + case 1: + cerr << "\tErreur d'ouverture du fichier " << Filename << endl; + break; + case 3: + cerr << "\tErreur du dictionnaire toutes les lettres ne sont pas definies" << endl; + default: + cerr << "Erreur n∞" << erreur << endl; + break; + } + } + return ERR (erreur); + } +} + +// Fonction d'affichage d'automate sur la sortie standart +RESULT MA::affiche (void) const +{ + cout << message (); + return VAL (0); +} + +/// --------------------- Entree sortie su fichier ------------------------------ + +RESULT MA::save (ofstream &fp, const FormatSauvegarde c_format) const +{ + try + { + // les itÈrateur pour la structure + Graph::const_iterator q; + LettreSFunc::const_iterator a; + SFunc::const_iterator s; + StateSet::const_iterator e; + Dictionnaire::const_iterator l; + + // la precision de sortie est maximale + fp.precision (20); + // first case format ffa or mdi + switch (c_format) + { + case paffa: + // calculation of the number of edges + // Entete writing + fp << "% MA file generated" << "\n"; + fp << "name \t" << name << "\n"; + + fp << "alph\n"; + for (l=alph.begin() ; l != alph.end() ; ++l) { + fp << l->first << " \t" << l->second << "\n"; + } + fp << ".\n"; + + fp << "iota\n"; + for (s=iota.begin() ;s != iota.end() ; ++s) { + fp << s->first << " \t" << s->second << "\n"; + } + fp << ".\n"; + + fp << "tau\n"; + for (s=tau.begin() ; s != tau.end() ;++s) { + fp << s->first << " \t" << s->second << "\n"; + } + fp << ".\n"; + + fp << "phi\n"; + 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) { + fp << q->first << " \t"; + fp << a->first << " \t"; + fp << s->first << " \t"; + fp << s->second << "\n"; + } + } + } + fp << ".\n"; + + return 0; + break; + + case paalergia: + // =========== Format alergia !!! format avec perte d'information !!! ==== + // =========== il faut travailler avec des PDFAs !!!!!!!!!! ============== + if (phi.find (0) == phi.end ()) + throw - 3; + + 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) + { + fp << q->first << " "; + fp << alph.find (a->first)->second; + fp << " " << s->first; + fp << " " << s->second << endl; + } + } + } + return 0; + break; + default: + throw - 4; + } + } + catch (int e) + { + if (PFA_VERBOSE) + { + cerr << "ERROR in MA::Save !!!!" << endl; + cerr << " \t"; + switch (e) + { + case -3: + cerr << "There is no initial state" << + endl; + case -4: + cerr << "unrecognized format : " << + c_format << endl; + default: + cerr << "Erreur non prise en compte !" << + endl; + } + } + return e; + } + catch (...) + { + if (PFA_VERBOSE) + { + cerr << "ERROR in MA::Save !!!" << endl; + cerr << "Unexpected error *!#@???" << endl; + } + return ERR (0); + } +} + +// Sauvegarde le MA dans Filename +RESULT +MA::save (const char *Filename, const FormatSauvegarde c_format) const +{ + try { + // On ouvre le fichier + if (Filename == NULL) + throw -1; + ofstream fp (Filename); + if (!fp.good ()) + throw -2; + + return MA::save(fp, c_format); + } + catch (int e) { + if (PFA_VERBOSE) + { + cerr << "ERROR in MA::Save !!!!" << endl; + cerr << " \t"; + switch (e) + { + case -1: + cerr << "Filename == NULL !!!" << endl; + case -2: + cerr << "I can't open the file" << + Filename << endl; + default: + cerr << "Erreur non prise en compte !" << + endl; + } + } + return e; + } +} + +// erase cleanly all transitions with parameter between minval and maxval +RESULT MA::erase_transitions (const double maxval, const double minval) +{ + Graph::iterator q, qtmp; + LettreSFunc::iterator a, atmp; + SFunc::iterator s, stmp; + + // erase for iota + for (s=iota.begin() ; s != iota.end() ; ) { + if ((s->second >= minval) && (s->second <= maxval)) { + stmp = s; + ++stmp; + iota.erase (s); + s = stmp; + } + else { + ++s; + } + } + + // erase for tau + for (s=tau.begin() ; s != tau.end() ; ) { + if ((s->second >= minval)&& (s->second <= maxval)) { + stmp = s; + ++stmp; + tau.erase (s); + s = stmp; + } + else { + ++s; + } + } + + // erase for transitions + for (q = phi.begin (); q != phi.end ();) { + for (a = q->second.begin (); a != q->second.end ();) { + for (s = a->second.begin (); s != a->second.end ();) { + if ((s->second >= minval) && (s->second <= maxval)) { + stmp = s; + ++stmp; + a->second.erase (s); + s = stmp; + } + else { + ++s; + } + } + if (a->second.empty ()) { + atmp = a; + ++atmp; + q->second.erase (a); + a = atmp; + } + else { + ++a; + } + } + if (q->second.empty ()) { + qtmp = q; + ++qtmp; + phi.erase (q); + q = qtmp; + } + else { + ++q; + } + } + + return 0; +} + + +// erase cleanly the transition phi(qbeg,l,qend) +RESULT MA::eraseTransition(const State qbeg, const Lettre l, const State qend) { + Graph::iterator q; + LettreSFunc::iterator a; + SFunc::iterator s; + + q = phi.find(qbeg); + if (q != phi.end ()) + { + a = q->second.find(l); + if (a != q->second.end ()) + { + s = a->second.find(qend); + if (s != a->second.end ()) + { + a->second.erase (s); + } + + if (a->second.empty ()) + { + q->second.erase (a); + } + } + if (q->second.empty ()) + { + phi.erase (q); + } + } + return VAL(0); +} + + +// emmonde l'automate +RESULT MA::emmonde(void) { + // --- Explication de l'algorithme ------ + // On fait un parcour en profondeur en notant tous les Ètats atteint en partant + // des sources (les Ètats initiaux) + // Puis on inverse le graphe et on refait un parcours en profondeur en partant + // des Ètats terminaux. + // Les Ètat atteignables par les Ètats initiaux et qui ne sont pas atteint + // par les Ètats terminaux du graphe inverse sont des Ètats ‡ supprimer. + // --- Fin de l'explication de l'algorithme --- + + // d'abord le parcours inverse + // 1 - On crÈe le graphe inverse + Graph Inv; // The inverse graph + Graph::iterator q; // some state + LettreSFunc::iterator a; // some letter + SFunc::iterator s, r; + StateSet Qir; // set of states from which we can reach a terminal state + StateSet Q2; // set of reachable states + StateSet W; // set for algorithm + StateSet BadStates; // set of bad states + State etat_cour; // current state + + // On inverse le graphe Inv(r,a,q) = phi (q,a,r) + 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) + { + Inv[s->first][a->first][q->first] = s->second; + } + } + } + + // Pour chaque Ètat terminal, on regarde l'ensemble des Ètats que + // l'on atteint + for (r = tau.begin (); r != tau.end (); ++r) + { + W.insert (r->first); + Qir.insert (r->first); + } + + while (!W.empty ()) + { + etat_cour = *(W.begin ()); + W.erase (W.begin ()); + q = Inv.find (etat_cour); + if (q != Inv.end ()) + { + for (a = q->second.begin (); a != q->second.end (); ++a) + { + for (s = a->second.begin (); s != a->second.end (); ++s) + { + if (Qir.find (s->first) == Qir.end ()) + { + Qir.insert (s->first); + W.insert (s->first); + } + } + } + } + } + // Qir contient tous les Ètats atteignables dans le graphe inverse + + // Pour chaque Ètat initial on regarde si on tombe bien dans + // l'ensemble des Ètats qui atteignent un Ètat terminal. + W.clear() ; // inutile mais au cas o˘ + for (r = iota.begin (); r != iota.end (); ++r) + { + W.insert (r->first); + Q2.insert (r->first); + } + + 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 (Q2.find (s->first) == Q2.end ()) + { + Q2.insert (s->first); + W.insert (s->first); + } + + if (Qir.find (s->first) == Qir.end ()) + { + BadStates.insert (s->first); + } + + } + } + } + } + // Q2 contient l'ensemble des Ètats atteignables + // BadStates contient l'ensemble des Ètats accessibles ‡ partir + // desquels on ne peut atteindre un Ètat non terminal + + // Suppressions de tous les Ètats de BadStates + StateSet::iterator bs; + for (bs = BadStates.begin (); bs != BadStates.end (); ++bs) + { + erase (*bs); + } + + // suppression des Ètats non accessibles + BadStates=Q; + for (bs = BadStates.begin() ; bs != BadStates.end() ; ++bs) + { + if (Q2.find(*bs) == Q2.end()) + { + erase(*bs); + } + } + return VAL(0); +} + + +// Charge le MA de Filename +RESULT MA::load (const char *Filename) +{ + try + { + // on modifie le ffa donc on perd l'attribution du ffa + if (Filename == NULL) + throw - 1; + ifstream fp (Filename); + if (fp == NULL) + throw - 2; + fp.precision (30); + string buf; + char tmp[64]; + char c; + bool finfichier; + State q, r, s; + Lettre a; + Dictionnaire::iterator l; + float proba; + + vide (); // on vide le MA + fp >> buf; + if (buf == "%Alergia") + { // ================= cas format alergia ============= + while (fp.good ()) + { // jusqu'‡ la fin du fichier + fp >> q; // on lit l'Ètat de dÈpart + addState (q); + fp >> buf; // on lit la lettre de la transition + a = addLettre (buf); + fp >> r; // on lit l'Ètat d'arrivÈ + addState (r); + fp >> proba; // on lit la probabilitÈ de la transition + addTransition (q, a, r, proba); + } + + // L'Ètat 0 est le seul Ètat initial + iota[0] = 1; + + // On met ‡ jour tau + StateSet::const_iterator iq; + Graph::const_iterator ie; + LettreSFunc::const_iterator ia; + SFunc::const_iterator ir; + + for (iq = Q.begin (); iq != Q.end (); ++iq) + { + proba = 0; // we use proba to make the sum + ie = phi.find (*iq); + if (ie != phi.end ()) + { + for (ia = ie->second.begin (); + ia != ie->second.end (); ++ia) + { + for (ir = ia->second.begin (); + ir != ia->second.end (); + ++ir) + { + proba += ir->second; + } + } + } + tau[*iq] = 1 - proba; + } + } + else if (buf == "%MDI") + { // ========================== cas format MDI ================== + float f1, f2; + int numstates; + char cbuf[20]; + while (fp.good()) { + if (*(buf.begin()) == '%') { // =========================== commentaire ===================== + finfichier = ((fp >> c) == NULL); + while ((!finfichier) && (c != '\n')) + { + finfichier = ((fp.get (c)) == NULL); + } + finfichier = ((fp >> buf) == NULL); + } + else if (buf == "Name") { + getline(fp,name); + fp >> buf; + } + else if (buf == "NumStates") { + fp >> numstates; + for (int i=0 ; i< numstates ; ++i) { + addState(i); + } + fp >> buf; + } + else if (buf == "NumEdges") { + fp >> buf; + fp >> buf; + } + else if (buf == "State") { + fp >> q; // on lit l'etat courant + fp.getline(cbuf,20,'='); + buf = cbuf; + if (buf == " initial") { + fp >> iota[q]; + fp.getline(cbuf,20,'='); + buf = cbuf; + } + if (buf == " final") { + fp >> f1; + fp.get(c); + fp >> f2; + tau[q]=f1/f2; + } + else { + cerr << "PARSE ERROR final : q=" << q << endl; + } + fp >> buf; // on recupere le %Ci=0.xxxxxxx + fp >> buf; // on recupere le numero de l'etat + // on commence a lire les transition sortantes + while ((buf != "State") && (fp.good())) { + fp >> s; // on lit l'etat d'arrive + fp >> buf; // on lit la lettre + // on efface les guillemets + buf.erase(buf.begin()); + buf.erase(--buf.end()); + fp.getline(cbuf,20,'='); + fp >> f1; + fp.get(c); + fp >> f2; + if (buf.empty()) { + tau[q]+=f1/f2; + } + else { + a=addLettre(buf); + addTransition(q,a,s,f1/f2); + //phi[q][a][s]=f1/f2; + } + fp >> buf; // on lit le %Ci=0.xxxxxxx + fp >> buf; + } + } + } + } + else if (buf == "%OLDMA") + { // ================= cas format ffa interne ============= + while (fp.good ()) + { // Tand que l'on est pas ‡ la fin du fichier + if (*(buf.begin()) == '%') + { // =========================== commentaire ===================== + finfichier = ((fp >> c) == NULL); + while ((!finfichier) && (c != '\n')) + { + finfichier = + ((fp.get (c)) == + NULL); + } + finfichier = ((fp >> buf) == NULL); + } + // ============================== State ======================== + else if (buf == "State") + { + // --------------- Lecture de la ligne initiale ---------------- + fp >> q; // on lit l'Ètat de dÈpart + Q.insert (q); // on ajoute l'etat q + sprintf (tmp, "%d", q); + finfichier = ((fp >> buf) == NULL); // on lit la suite + while ((buf != "State") + && (buf != tmp) + && (!finfichier)) + { + if (buf == "c") + { + fp >> buf; // on lit le = + fp >> buf; // on lit le chiffre mais on en fait rien + } + else if (buf == "i") + { // on lit la probabilitÈ d'Ãtre initial + fp >> buf; // on lit le = + fp >> proba; // on lit la probabilitÈ + if (proba != 0) + iota[q] = + proba; + } + else if (buf == "f") + { // on lit la probabilitÈ d'Ãtre terminal + fp >> buf; // on lit le = + fp >> proba; // on lit la probabilitÈ + if (proba != 1) + tau[q] = 1 - + proba; + } + finfichier = ((fp >> buf) == NULL); // on lit la suite + } + // ---------------- Lecture des transitions sortantes ---------------- + r = q; + while ((buf != "State") + && (!finfichier)) + { + if (PFA_VERBOSE) + { + if (buf != tmp) + { + cerr << "load WARNING !" << endl; + cerr << "La premiËre lettre d'une colone ne correspond pas ‡ l'Ètat" << endl; + } + } + fp >> s; // on lit l'Ètat d'arrivÈ + fp >> buf; // on lit la lettre + + a = addLettre(buf); + //~ // on cherche la lettre correspondante + //~ for (l = alph.begin (); + //~ (l != alph.end ()) + //~ && (l->second != buf); + //~ l++) + //~ ; + //~ if (l == alph.end ()) + //~ { // si on ne retrouve pas la lettre + //~ a = addLettre (); // on ajoute une lettre + //~ alph[a] = buf; // ‡ laquelle on fait correspondre la bonne chaine de caractËre + //~ } + //~ else // sinon + //~ a = l->first; // on attribu la lettre en cours. + + fp >> buf; // on lit 'p' + fp >> buf; // on lit '=' + fp >> proba; // on lit la proba de l'arÃte + + phi[q][a][s] = proba; // on insËre l'arÃte + finfichier = ((fp >> buf) == NULL); // on lit la lettre suivante. + } + } + else + { // Autres cas, on ne fait rien d'autre qu'avancer + fp >> buf; + } + } + { // ================= cas format ffa interne ============= + while (fp.good ()) + { // Tand que l'on est pas ‡ la fin du fichier + if (*(buf.begin()) == '%') + { // =========================== commentaire ===================== + finfichier = ((fp >> c) == NULL); + while ((!finfichier) && (c != '\n')) + { + finfichier = + ((fp.get (c)) == + NULL); + } + finfichier = ((fp >> buf) == NULL); + } + // ============================== State ======================== + else if (buf == "State") + { + // --------------- Lecture de la ligne initiale ---------------- + fp >> q; // on lit l'Ètat de dÈpart + Q.insert (q); // on ajoute l'etat q + sprintf (tmp, "%d", q); + finfichier = ((fp >> buf) == NULL); // on lit la suite + while ((buf != "State") + && (buf != tmp) + && (!finfichier)) + { + if (buf == "c") + { + fp >> buf; // on lit le = + fp >> buf; // on lit le chiffre mais on en fait rien + } + else if (buf == "i") + { // on lit la probabilitÈ d'Ãtre initial + fp >> buf; // on lit le = + fp >> proba; // on lit la probabilitÈ + if (proba != 0) + iota[q] = + proba; + } + else if (buf == "f") + { // on lit la probabilitÈ d'Ãtre terminal + fp >> buf; // on lit le = + fp >> proba; // on lit la probabilitÈ + if (proba != 1) + tau[q] = 1 - + proba; + } + finfichier = ((fp >> buf) == NULL); // on lit la suite + } + // ---------------- Lecture des transitions sortantes ---------------- + r = q; + while ((buf != "State") + && (!finfichier)) + { + if (PFA_VERBOSE) + { + if (buf != tmp) + { + cerr << "load WARNING !" << endl; + cerr << "La premiËre lettre d'une colone ne correspond pas ‡ l'Ètat" << endl; + } + } + fp >> s; // on lit l'Ètat d'arrivÈ + fp >> buf; // on lit la lettre + + a = addLettre(buf); + //~ // on cherche la lettre correspondante + //~ for (l = alph.begin (); + //~ (l != alph.end ()) + //~ && (l->second != buf); + //~ l++) + //~ ; + //~ if (l == alph.end ()) + //~ { // si on ne retrouve pas la lettre + //~ a = addLettre (); // on ajoute une lettre + //~ alph[a] = buf; // ‡ laquelle on fait correspondre la bonne chaine de caractËre + //~ } + //~ else // sinon + //~ a = l->first; // on attribu la lettre en cours. + + fp >> buf; // on lit 'p' + fp >> buf; // on lit '=' + fp >> proba; // on lit la proba de l'arÃte + + phi[q][a][s] = proba; // on insËre l'arÃte + finfichier = ((fp >> buf) == NULL); // on lit la lettre suivante. + } + } + else + { // Autres cas, on ne fait rien d'autre qu'avancer + fp >> buf; + } + } + + } + return 0; + } + + + + else { + stringstream str; + Lettre a; + TrueLettre b; + while (fp.good ()) + { // Tand que l'on est pas ‡ la fin du fichier + if (*(buf.begin()) == '%') + { // =========================== commentaire ===================== + fp.get(c); + while ((fp.good()) && (c != '\n')) { + fp.get (c); + } + fp >> buf; + } + else if (buf == "name") { + fp.get(c); + name+=c; + while ((fp.good()) && (c != '\n')) { + fp.get (c); + name+=c; + } + fp >> buf; + } + else if (buf == "alph") + { // dictionnaire + fp >> buf; + while ((buf != ".") && (fp.good())) { + if (*(buf.begin()) == '%') + { // --- commentaire --- + fp.get(c); + while ((fp.good()) && (c != '\n')) { + fp.get (c); + } + fp >> buf; + } + str << buf; + str >> a; + fp >> b; + Sigma.insert(a); + alph[a]=b; + fp >> buf; + } + fp >> buf; + } + else if (buf == "iota") + { // iota + fp >> buf; + while ((buf != ".") && (fp.good())) { + + if (*(buf.begin()) == '%') + { // --- commentaire --- + fp.get(c); + while ((fp.good()) && (c != '\n')) { + fp.get (c); + } + fp >> buf; + } + + q=atoi(buf.c_str()); + fp >> proba; + Q.insert(q); + iota[q]=proba; + fp >> buf; + } + fp >> buf; + } + else if (buf == "tau") + { // iota + fp >> buf; + while ((buf != ".") && (fp.good())) { + + if (*(buf.begin()) == '%') + { // --- commentaire --- + fp.get(c); + while ((fp.good()) && (c != '\n')) { + fp.get (c); + } + fp >> buf; + } + + q=atoi(buf.c_str()); + fp >> proba; + Q.insert(q); + tau[q]=proba; + fp >> buf; + } + fp >> buf; + } + else if (buf == "phi") { + fp >> buf; + while ((buf != ".") && (fp.good())) { + + if (*(buf.begin()) == '%') + { // --- commentaire --- + fp.get(c); + while ((fp.good()) && (c != '\n')) { + fp.get (c); + } + fp >> buf; + } + + q=atoi(buf.c_str()); + fp >> a; + fp >> s; + fp >> proba; + + if (alph.find(a) == alph.end()) { + cerr << "!!! Lettre : " << a << endl; + throw -3; + } + + Q.insert(q); + Q.insert(s); + phi[q][a][s]=proba; + + fp >> buf; + } + fp >> buf; + } + else + { // Autres cas, on ne fait rien d'autre qu'avancer + fp >> buf; + } + } + } + return VAL(0); + } + catch (int erreur) + { + if (PFA_VERBOSE) + { + cerr << "MA::load" << endl; + switch (erreur) + { + case -1: + cerr << "ERROR in MA::Save !!!!" << endl; + cerr << " \tFilename == NULL !!!" << endl; + break; + case -2: + cerr << "Erreur lors de l'ouverture du fichier : " << Filename << endl; + break; + case -3: + cerr << "Erreur alph n'est pas bien defini, des lettres manques !" << endl; + default: + cerr << "Erreur inconnue ?" << endl; + } + } + return erreur; + } + catch (...) + { + if (PFA_VERBOSE) + { + cout << "MA::load(" << Filename << ")" << endl; + cout << "Erreur inexplicable ?" << endl; + } + return ERR (0); + } +} + + +/// ----------------------- Modifieurs ------------------------------- + +// Fonction qui ajoute une transition +RESULT MA::addTransition (const Transition & t, const float val) +{ + if (PFA_SAFE) + { + assert (Q.find (t.qdep) != Q.end ()); + assert (Sigma.find (t.a) != Sigma.end ()); + assert (Q.find (t.qarr) != Q.end ()); + } + + if (val != 0) + { + phi[t.qdep][t.a][t.qarr] = val; + } + else { + Graph::const_iterator q; + q = phi.find(t.qdep); + if ( q != phi.end()) { + LettreSFunc::const_iterator a = q->second.find(t.a); + if (a != q->second.end()) { + SFunc::const_iterator s = a->second.find(t.qarr); + if (s != a->second.end()) { + phi[t.qdep][t.a][t.qarr] = val; + } + } + } + } + + if (PFA_SAFE) + { + assert (coherent ()); + } + return VAL (0); +} + + +// Ajout une lettre par defaut ‡ l'alphabet +Lettre MA::addLettre (void) +{ + Lettre + a; + if (!Sigma.empty ()) + { + a = *(--(Sigma.end ())) + 1; + } + else + { + a = 'a'; + } + + Sigma.insert (a); + alph[a] = a; + return a; +} + +// Ajout de la lettre buf +Lettre MA::addLettre (const TrueLettre & buf) +{ + // search whether buf is a new letter + Lettre a; + Dictionnaire::iterator l; + for (l = alph.begin (); (l != alph.end ()) && (l->second != buf); ++l) + ; + if (l == alph.end ()) + { // if buf is new then + a = addLettre (); // we add the letter + alph[a] = buf; // and we associate it with buf + } + else { + a = l->first; + } + return a; +} + + +// Ajoute un Ètat +State MA::addNewState (const float init, const float term) +{ + State q; + if (!Q.empty ()) + { + q = *(--Q.end()) + 1; + while (Q.find(q) != Q.end()) + ++q; + } + else + { + q = 1; + } + addState(q,init,term); + return q; +} + + +// Ajoute l'Ètat q s'il n'existe pas +State MA::addState (const State q, const float init, const float term) +{ + if (Q.find (q) == Q.end ()) + { + Q.insert (q); + } + if (init != 0) + iota[q]=init; + if (term != 0) + tau[q]=term; + return q; + if (PFA_SAFE) + assert(coherent()); +} + + +// Ajout d'une transition +RESULT MA::addTransition (const State qdep, const Lettre a, const State qarr, const float val) +{ + if (PFA_SAFE) + { + assert (Q.find (qdep) != Q.end ()); + assert (Sigma.find (a) != Sigma.end ()); + assert (Q.find (qarr) != Q.end ()); + } + if (val != 0) + { + phi[qdep][a][qarr] = val; + } + + if (PFA_SAFE) + { + assert (coherent ()); + } + return VAL (0); +} + +// Cree un MA aleatoire +RESULT MA::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) +{ + float init, term; + int i; + StateSet::const_iterator q, s; + Alphabet::const_iterator a; + + // on vide le MA + vide (); + // on initialise la variable aleatoire + if (num_graphe != 0) + srand (num_graphe); + + // on ajoute les états + for (i = 0; i < nb_etats; i++) + { + if (random () < prob_init) + init = random (min_trans, max_trans); + else + init = 0; + + if (random () < prob_term) + term = random (min_trans, max_trans); + else + term = 0; + + addNewState (init, term); + } + + // on ajoute les lettres + for (i = 0; i < nb_lettres; i++) + { + addLettre (); + } + + // on cree les transitions avec des distributions uniformes + for (q = Q.begin (); q != Q.end (); q++) + { // pour tous les Ètats + for (a = Sigma.begin (); a != Sigma.end (); a++) + { + for (s = Q.begin (); s != Q.end (); s++) + { + if (random () < densite) + { // si on tire un nombre inferieur ‡ la densitÈ, on cree une arete + phi[*q][*a][*s] = + random (min_trans, max_trans); + } + } + } + } + return VAL (0); +} + +// Cree un MA aleatoire +RESULT MA::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) +{ + int i; + StateSet::const_iterator q, s; + Alphabet::const_iterator a; + + // on vide le MA + vide (); + // on initialise la variable aleatoire + if (num_graphe != 0) + srand (num_graphe); + + // on ajoute les Ètats + for (i = 0; i < nb_etats; ++i) + { + addState(i,0,0); + } + + // on ajoute les lettres + for (i = 0; i < nb_lettres; i++) + { + addLettre (); + } + + for (i=0 ; i< nb_init ; ++i) + { + iota[rand()%nb_etats]=random(min_trans,max_trans); + } + + for (i=0 ; i max_tau) { + cerr << "MA::renormalize_state : "; + cerr << "min_tau > max_tau" << endl; + throw ERR_INPUT; + } + if (min > max) { + cerr << "MA::renormalize_state : "; + cerr << "min > max" << endl; + throw ERR_INPUT; + } + + Graph::iterator r; + LettreSFunc::iterator a; + SFunc::iterator s; + float sum, x; + bool taumodif=true; + sum=tau[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++) { + sum+=s->second; + } + } + } + bool good=false; + StateSet BadStates; + while ( !good ) { + good=true; + x=normalization/sum; + if (tau[q]*x > max_tau) { + tau[q]=max_tau; + if (taumodif) { + taumodif=false; + good=false; + } + } else if (tau[q]*x < min_tau) { + tau[q]=min_tau; + if (taumodif) { + taumodif=false; + good=false; + } + } else { + tau[q]=x*tau[q]; + } + sum=tau[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 (x*s->second > max) { + s->second = max; + if (BadStates.find(s->first) == BadStates.end()) { + BadStates.insert(s->first); + good=false; + } + } + else if (x*s->second < min) { + s->second=min; + if (BadStates.find(s->first) == BadStates.end()) { + BadStates.insert(s->first); + good=false; + } + } + else { + s->second=x*s->second; + } + } + } + } + } + return VAL(0); +} + +// 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 +RESULT MA::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) +{ + + int i; + StateSet::const_iterator q, s; + SFunc::iterator r; + Alphabet::const_iterator a; + + const int ERR_INPUT=-1023; + if (min_iota > max_iota) { + cerr << "min_iota > max_iota !!!" << endl; + throw ERR_INPUT; + } + if (min_trans > max_trans) { + cerr << "min_trans > max_trans !!!" << endl; + throw ERR_INPUT; + } + if (min_tau > max_tau) { + cerr << "min_tau > max_tau !!!" << endl; + throw ERR_INPUT; + } + + // on vide le MA + vide (); + // on initialise la variable aleatoire + if (num_graphe != 0) + srand (num_graphe); + + // on ajoute les Ètats + for (i = 0; i < nb_etats; i++) + { + addState(i,0,0); + } + + // on ajoute les lettres + for (i = 0; i < nb_lettres; i++) { + addLettre (); + } + + /// --- iota --- + i=0; + for (i=0 ; isecond; + } + float x; + bool good=false; + StateSet BadStates; + while ( !good ) { + x=normalization/sum; + good=true; + for (r=iota.begin() ; r != iota.end() ; r++) { + if (x * r->second > max_iota) { + sum+=r->second=max_iota; + if (BadStates.find(r->first) == BadStates.end()) { + BadStates.insert(r->first); + good=false; + } + } + else if (x * r->second < min_iota) { + sum+=r->second=min_iota; + if (BadStates.find(r->first) == BadStates.end()) { + BadStates.insert(r->first); + good=false; + } + } + else { + sum+=r->second = x*r->second; + } + } + } + } + + /// --- Tau + Transitions --- + i=0; + for (i=0 ; isecond>0?q->second:-q->second; + } + sum = 1/sum; + for (q=V.begin() ; q != V.end() ; q++) { + q->second *= sum; + if (q->second == 0) { + V.erase(q); + } + } + // // Affichage de debogage + // cout << "\tMA::normaliseVecteur\n"; + // for (q=V.begin() ; q != V.end() ; q++) { + // cout << "\tV[" << q->first << "]=" << q->second << endl; + // } + // cout << "\t---\n"; +} + + +// genere un mot en fonction du modèle. En particulier, il faut récupérer +// la valeur des P_q(\Se) pour tous les états q. +// Description de l'algorithme : +// Soit r un langage rationnel, on construit P_r de la façon suivante ; +// Neg(u)=\sum_{x \in \Sigma}r(ux\Se)<0?r(ux\Se):0 + r(u)<0?r(u):0 +// P_r(ux\Se) = r(ux\Se)/Neg(u) si r(a\Se)>0 et 0 sinon +// P_r(\eps) = r(\eps)/Neg(u) + +RESULT MA::genere_mot(Word &w, const bool safe){ + // Dans un premier temps, on rÈcupËre les valeurs des + // P_q(\Se) + SFunc PSe; // contiendra la valeur des P_q(\Se) + + if (val_PSe(PSe) != VAL(0)) { + if ( safe ) { + return ERR(0); + } + } + + // on a w donnÈ, on calcule P(w), P(wx\Se) pour tout x et on conserve + // les w^-1P(\eps) et w^-1P(x\Se) positifs + w=""; // le mot courant initialisÈ ‡ epsilon + Lettre c; // la lettre courante + bool termine=false; + double Negw, Posw; + Alphabet::const_iterator x; + SFunc V, Vtmp; + SFunc::const_iterator q; + LettreSFunc::const_iterator a; + SFunc::const_iterator s; + Graph::const_iterator r; + map px; // va contenir px[0] = P(w), px[1] = P(wx_1\Se), ... , px[n] = P(wx_n\Se) + map::const_iterator l; + bool lettreTrouve; + double val; + double sum; + + V = iota; + + while (!termine) { + // normaliser le vecteur V, fait en sorte de mettre + // la somme de ses valeurs ‡ 1 et supprimes les entrÈes + // nulles (qui sont inutiles) + normaliseVecteur(V); + Negw=0; Posw=0; + // calcul de w^-1P(\eps) + px[0] = 0; + for (q = V.begin() ; q != V.end() ; q++) { + px[0]+= q->second * val_tau(q->first); + } + // on met ‡ jour Neg(w) et Pos(w) + if (px[0] < 0) + Negw += px[0]; + else + Posw += px[0]; + + // // AFFICHAGE DEBUG + // cout << "px[.]:" << endl; + // for (l=px.begin() ; l != px.end() ; l++) { + // cout << "px["; + // cout << l->first==0?'0':l->first; + // cout << "]="; + // cout << l->second << endl; + // } + // cout << "Negw=" << Negw << ", Posw=" << Posw << endl; + // cout << " -- px[.]" << endl; + // // END AFFICHAGE DEBUG + + // initialisation de px + for (x=Sigma.begin() ; x != Sigma.end() ; x++) + px[*x]=0; + // calcul de w^-1P(x\Se) + for (q = V.begin() ; q != V.end() ; q++) { + r=phi.find(q->first); + if (r != phi.end()) { + for (a=r->second.begin() ; a != r->second.end() ; a++) { + for (s=a->second.begin() ; s != a->second.end() ; s++) { + // // AFFICHAGE DEBUG + // cout << "\t\t**********" << endl; + // cout << "q->first=" << q->first << endl; + // cout << "q->second=" << q->second << endl; + // cout << "r->first=" << r->first << endl; + // cout << "a->first=" << a->first << endl; + // cout << "s->first=" << s->first << endl; + // cout << "s->second=" << s->second << endl; + // cout << "PSe[s->first]=" << PSe[s->first] << endl; + // cout << "\t\t**********" << endl; + // // FIN AFFICHAGE DEBUG + px[a->first] += q->second * s->second * PSe[s->first]; + } + } + } + } + for (x=Sigma.begin() ; x != Sigma.end() ; x++) { + // mise ‡ jour de Neg(w) et Pos(w) + if (px[*x] < 0) + Negw += px[*x]; + else + Posw += px[*x]; + } + + // // AFFICHAGE DEBUG + // cout << "px[.]: " << endl; + // for (l=px.begin() ; l != px.end() ; l++) { + // cout << "px["; + // cout << l->first==0?'0':l->first ; + // cout << "]="; + // cout << l->second ; + // cout << endl; + // } + // cout << "Negw=" << Negw << ", Posw=" << Posw << endl; + // cout << " -- px[.]" << endl; + // // END AFFICHAGE DEBUG + + // on a fini de calculer les valeurs possibles. On choisit seulement + // parmis les valeurs positives + if (Posw == 0) { + cerr << "ERREUR !!! MA::genere_mot" << endl; + cerr << "prefixe = "; + cerr << affiche(w) << endl; + cerr << "Impossible d'utiliser cette methode avec ce prefixe dans ce MA" << endl; + cerr << "Pos(\\epsilon)=0 !!!" << endl; + throw ERR(21); + } + val = random(0,Posw); + sum = 0; + lettreTrouve=false; + for (l=px.begin() ; l != px.end() && !lettreTrouve ; l++) { + // // AFFICHAGE DE DEBUG + // cout << "\tval=" << val; + // cout << ", sum=" << sum; + // cout << ", Posw=" << Posw; + // cout << ", Negw=" << Negw; + // cout << "\tpx["; + // cout << l->first==0?'0':l->first; + // cout << "]="; + // cout << l->second << endl; + // // AFFICHAGE DE DEBUG + if (l->second > 0) { + sum+= l->second; + if (sum >= val) { + if (l->first != 0) { + c = l->first; + w += c; + // // AFFICHAGE DEBUG + // cout << "c="; + // cout << c; + // cout << ", w=" ; + // cout << affiche(w); + // cout << endl; + // // AFFICHAGE DEBUG + } + else { + termine=true; + // // AFFICHAGE DEBUG + // cout << "termine" << endl ; + // // AFFICHAGE DEBUG + } + lettreTrouve=true; + } + } + } + + if (!termine) { + Vtmp.clear(); + // Mise ‡ jour du vecteur d'initialisation + for (q=V.begin() ; q != V.end() ; q++) { + r=phi.find(q->first); + if (r != phi.end()) { + a = r->second.find(c); + if (a != r->second.end()) { + for (s=a->second.begin() ; s != a->second.end() ; s++) { + Vtmp[s->first] += q->second * s->second; + } + } + } + } + V = Vtmp; + } + } + return VAL(0); +} + +// genere un Èchantillon de mots +RESULT MA::genere_echantillon ( int taille, + Sample & S, + const int num_echantillon) +{ + 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); +} + +// genere un Èchantillon de mots : l'echantillon reste identique si lot est identique +RESULT MA::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); +} + + +// Calcule les valeurs de P_q(\S_e) pour +// tous les Ètats q +RESULT MA::val_PSe(SFunc &PSe) const { + Simplex simplex; + StateSet::const_iterator q,r; + Alphabet::const_iterator a; + int j; + float tmp; + + simplex.set_number_of_unknown_to(Q.size()); + + for (q=Q.begin() ; q != Q.end() ; q++) { + simplex.setval(-val_tau(*q)); + for (r=Q.begin(), j=1 ; r != Q.end() ; r++, j++) { + if (*r == *q) { + tmp=-1; + } + else { + tmp=0; + } + for (a=Sigma.begin() ; a != Sigma.end() ; a++) { + tmp += val_phi(*q,*a,*r); + } + simplex.setparam(j,tmp); + } + simplex.add_equality_constraint(); + } + + simplex.set_mode(realNotBounded); // on utilise des réels pouvant êtres négatifs + + float epsilon; + if (! simplex.has_solution(PSe,epsilon) ) { + PSe.clear(); + simplex.affiche(); + cerr << "ERREUR INEXPLICABLE !!!!\n"; + cerr << "Le système d'équation doit être mal posé !\n"; + throw ERR(0); + } else { + return VAL(0); + } +} + +/// --------------------- Testeurs ------------------------------ + +// Teste la cohÈrence de la structure de donnÈe. +bool MA::coherent (void) const +{ + bool + res = true; + // on cherche une transition contenant un Ètat n'appartenant pas + // ‡ l'ensemble des Ètats. + Graph::const_iterator q; + LettreSFunc::const_iterator a; + SFunc::const_iterator s; + 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 ( (Q.find(q->first) == Q.end ()) + || (Q.find (s->first) == Q.end ())) + { + res = false; + if (PFA_VERBOSE) + { + cerr << "Erreur de coherence (phi) : ("; + cerr << q->first << "," << a->first << ","; + cerr << s->first << ") = " << s->second << " !!! " << endl; + } + } + } + } + } + return res; +} + +// Teste si le MA est coherent et est un SPFA. valeur de iota, tau et phi dans [0,1] +bool MA::isSPFA (void) const +{ + + if (!coherent ()) + { // si le ffa n'est pas coherent + return false; + } + // si le ffa est coherent + // Test de iota + SFunc::const_iterator s; + float sum = 0; + // cerr.precision(30); + for (s = iota.begin (); s != iota.end (); ++s) + { + if ((s->second < 0) || (s->second > 1)) + { + //~ cerr << "iota " << s->first << "<0 ou >1 !!! : " << s->second << endl; + return false; + } + sum += s->second; + } + if (!simeqone (sum)) + { + return false; + } + //cerr << "iota OK" << endl; + + // Test de tau + for (s = tau.begin (); s != tau.end (); ++s) + { + if ((s->second < 0) || (s->second > 1)) + { + //~ cerr << "tau " << s->first << "<0 ou >1 : " << s->second << endl; + return false; + } + } + + // Test of phi and + // of the property : \forall q \in Q and \forall a \in \Sigma + // tau(q) + \sum_{s\in Q} phi(q,a,s)=1 + Graph::const_iterator q; + LettreSFunc::const_iterator a; + for (q = phi.begin (); q != phi.end (); ++q) + { + sum = val_tau (q->first); + for (a = q->second.begin (); a != q->second.end (); ++a) + { + for (s = a->second.begin (); s != a->second.end (); ++s) + { + if ((s->second < 0) || (s->second > 1)) + { + //~ cerr << "phi(" << q->first << ","; + //~ cerr << a->first << ","; + //~ cerr << s->first << ")="; + //~ cerr << s->second << " FALSE !!!" << endl; + return false; + } + //cerr << "phi(" << q->first << "," << a->first << "," << s->first << ")=" << s->second << endl; + //cerr << "sum = " << sum << endl; + sum += s->second; + } + } + if (!simeqone (sum)) + { + //cerr << "phi(" << q->first << ",*,*)=" << sum << " FALSE !!!" << endl; + return false; + } + } + // on a passÈ toutes les Èpreuves + return true; +} + +// Fonction qui rend le MA vide (pas d'Ètats pas de lettre) +void +MA::vide () +{ + name.clear (); + Q.clear (); + Sigma.clear (); + iota.clear (); + tau.clear (); + phi.clear (); + alph.clear (); +} + +// renvoi vrai si le MA est un PFA +bool MA::isPFA () const +{ + if (!isSPFA ()) + return false; + + // --- Explication de l'algorithme ------ + // On fait un parcour en profondeur en notant tous les Ètats atteint en partant + // des sources (les Ètats initiaux) + // Puis on inverse le graphe et on refait un parcours en profondeur en partant + // des Ètats terminaux. + // Si l'ensemble des Ètats atteint par les Ètats terminaux dans le graphe + // inverse contient l'ensemble des Ètats atteint en partant des Ètats initiaux + // alors le SPFA considÈrÈ est un PFA. + // --- Fin de l'explication de l'algorithme --- + + // d'abord le parcours inverse + // 1 - On crÈe le graphe inverse + Graph + Inv; + Graph::const_iterator q; + LettreSFunc::const_iterator a; + SFunc::const_iterator s, r; + StateSet + Qir, + Q2, + W; + State + etat_cour; + + // On inverse le graphe Inv(r,a,q) = phi (q,a,r) + + 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++) + { + Inv[s->first][a->first][q->first] = s->second; + } + } + } + + // Pour chaque Ètat terminal, on regarde l'ensemble des Ètats que + // l'on atteint + for (r = tau.begin (); r != tau.end (); r++) + { + W.insert (r->first); + Qir.insert (r->first); + } + + while (!W.empty ()) + { + etat_cour = *(W.begin ()); + W.erase (W.begin ()); + q = Inv.find (etat_cour); + if (q != Inv.end ()) + { + for (a = (q->second).begin (); + a != (q->second).end (); a++) + { + for (s = (a->second).begin (); + s != (a->second).end (); s++) + { + if (Qir.find (s->first) == Qir.end ()) + { + Qir.insert (s->first); + W.insert (s->first); + } + } + } + } + } + + // Pour chaque Ètat initial on regarde si on tombe bien dans + // l'ensemble des Ètats qui atteignent un Ètat terminal. + for (r = iota.begin (); r != iota.end (); ++r) + { + W.insert (r->first); + Q2.insert (r->first); + } + + 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 (Q2.find (a->first) == Q2.end ()) + { + Q2.insert (a->first); + W.insert (a->first); + } + if (Qir.find (s->first) == Qir.end ()) + { + return false; + } + } + } + } + } + return true; +} + + +string MA::affiche (const Word & w) const +{ + Word::const_iterator a; + string res; + Dictionnaire::const_iterator x; + for (a = w.begin() ; a != w.end () ; ++a) + { + x=alph.find(*a); + if (x == alph.end()) { + res = "Dictionnaire ERROR "; + res += *a; + return res; + } + res += x->second; + res += ' '; + } + return res; +} + +void MA::next (Word & w) const +{ + Word::reverse_iterator ll; // last letter + Word::iterator z; + Lettre a; + Lettre first = *Sigma.begin (); + int i; + int level = w.size (); + bool end = false; + while ((w.size () > 0) && (!end)) + { + ll = w.rbegin (); + a = *ll; + ++a; + if (Sigma.find (a) != Sigma.end ()) + { + ++(*ll); + end = true; + } + else + { + z=w.end(); + --z; + w.erase(z); // w.pop_back (); + } + } + if (!end) + ++level; + for (i = w.size (); i < level; ++i) + { + w += first; // w.push_back (first); + } + +} + + +// erase the state badstate and all transitions from and to it +RESULT MA::erase (State badstate) +{ + Graph::iterator q, qtmp; + LettreSFunc::iterator a, atmp; + SFunc::iterator s, stmp; + StateSet::iterator r; + + // Suppression dans l'ensemble d'Ètats + r=Q.find (badstate); + if ( r == Q.end () ) + { + cerr << "MA::erase (State badstate) : demande de suppression d'un etat inexistant" << endl; + exit (-1); + } + Q.erase (r); + // Suppression dans iota + s = iota.find(badstate); + if (s != iota.end ()) + iota.erase (s); + // Suppression dans tau + s = tau.find(badstate); + if (s != tau.end ()) + tau.erase (s); + // Suppression dans phi + if (phi.find (badstate) != phi.end ()) + phi.erase (phi.find (badstate)); + + for (q = phi.begin (); q != phi.end ();) + { + for (a = q->second.begin (); a != q->second.end ();) + { + for (s = a->second.begin (); s != a->second.end ();) + { + if (s->first == badstate) + { + stmp = s; + ++stmp; + a->second.erase (s); + s = stmp; + } + else + ++s; + } + if (a->second.empty ()) + { + atmp = a; + ++atmp; + q->second.erase (a); + a = atmp; + } + else + ++a; + } + if (q->second.empty ()) + { + qtmp = q; + ++qtmp; + phi.erase (q); + q = qtmp; + } + else + ++q; + } + + return VAL (0); +} + +StateSet MA::delta (const State q, const Word &w) const +{ + StateSet R; + R.insert(q); + return delta(R,w); +} + +StateSet MA::delta (const StateSet &R, const Word &w) const +{ + StateSet V; // le vecteur correspondant aux Ètats atteints + StateSet X; // un vecteur temporaire + StateSet::iterator xi; + Graph::const_iterator q; + LettreSFunc::const_iterator b; + SFunc::const_iterator r; + Word::const_iterator a; + + //~ cout << endl; + V=R; + for (a=w.begin() ;a != w.end() ; a++) + { + X.clear(); + for (xi=V.begin() ; xi != V.end() ; ++xi) + { + q=phi.find(*xi); + if (q != phi.end()) + { + b=q->second.find(*a); + if (b != q->second.end()) + { + for (r = b->second.begin() ; r != b->second.end() ; ++r) + { + X.insert(r->first); + } + } + } + } + V=X; + } + return V; +} + + +void MA::allTransitions(TransitionFunction &T) const { + T.clear(); + Graph::const_iterator q; + LettreSFunc::const_iterator a; + SFunc::const_iterator r; + Transition t; + 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; + for (r=a->second.begin() ; r != a->second.end() ; ++r) { + t.qarr=r->first; + T[t]=0; + } + } + } +} + +void MA::allStates(SFunc &S) const { + StateSet::const_iterator q; + S.clear(); + for (q=Q.begin() ; q!=Q.end() ;++q) { + S[*q]=0; + } +} + +// Become the MA with maximum number of transitions +RESULT MA::becomeComplete (const int nb_etats, const int nb_lettres) { + clear(); + float valinit = 1/ float(nb_etats); + float val = 1/float(nb_etats + 1); + int i; + + for (i=0 ; i + +// 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 diff --git a/main.cpp b/main.cpp new file mode 100644 index 0000000..ca1f36e --- /dev/null +++ b/main.cpp @@ -0,0 +1,1324 @@ +/*************************************************************************** + main.C - description + ------------------- + begin : mer oct 9 19:14:09 CEST 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. * + * * + ***************************************************************************/ + +using namespace std; +#include "interface.H" +#include "test.H" +#include "main.H" + +// #define MAXFLOAT 3.40282347e+38F + +/// ########################################################################## /// +// --- Les variables globales d'entrées qui parametre l'expérimentation + +// Les fichier + +string temporary_directory= "/tmp/dees/"; // le répertoire temporaire + +string ficffaA = temporary_directory + "A"; // Fichier du ffa A +string ficffaB = temporary_directory + "B"; // Fichier du ffa B +string ficdotA = temporary_directory + "A.dot"; // Le fichier dot associé à A +string ficdotB = temporary_directory + "B.dot"; // Le fichier dot associé à B +string ficech = temporary_directory + "A.ech"; // Le fichier échantillon généré par A +string ficechpre = temporary_directory + "A.ecp"; // Le fichier échantillon préfixe généré par A +string ficpsA = temporary_directory + "A.ps"; // La fichier de visualisation de A +string ficpsB = temporary_directory + "B.ps"; // Le fichier de visualisation de B + +// Les Èchantillons +Sample S; // main sample +Sample Stest; // test sample +int num_ech = 0; // Le numero de l'Èchantillon +int num_ech_test = 1; // Le numbero de l'Èchantillon test +int taille_ech = 1000; // La taille de l'Èchantillon +int taille_ech_test = 1000; // La taille de l'Èchantillon test + +// Le PFA alÈatoire +int numPFA = 0; // Le numero du PFA gÈnÈrÈ +int nb_etats = 5; // Le nombre d'Ètats du PFA gÈnÈrÈ +int nb_lettres = 2; // Le nombre de lettres du PFA gÈnÈrÈ + +// Les prÈcisions +double precision = 0.5; // la prÈcision (0 -> prefix tree, 1 -> single state) +double precpow = -1; // La prÈcision en mode exponentiel +double epsprime = 0; // La valeur de suppression des transitions (0 delete nothing, 1 delete all) +unsigned int seuil = 0; // le seuil en dessous duquel un prefixe n'est plus pris en compte dans l'apprentissage +double seuilbm = .0001 ; // Le seuil pour le test de convergence de BM +unsigned int maxmots = INT_MAX; // le nombre maximal de mots à ajouter à l'ensemble de test à chaque étapes + +// L'affichage +string nom_A = "A"; // le nom du PFA A +string nom_B = "B"; // le nom du PFA B +bool affiche_A = true; // affiche l'automate source ou non +bool affiche_B = true; // affiche l'automate destination +bool verbose = false; // mode verbose pour le test +bool affiche_etats = false; // affiche les Ètats dans le .dot +int viewprec=3; // precision des parametres a l'affichage +bool viewstates=false; // on met le numero des etats +bool viewmultipletransitions=false; // vrai pour ne plus regrouper les transitions +bool interactive=false; // interactive mode + +// L'apprentissage +T_ModeReturn moderet = end; // Le mode de retour des arÃtes (end ou begin) +T_ModeEpsilon modeeps = variable; // Le mode d'apprentissage avec epsilon fixe ou variable (epsfixed ou variable) +float test_proportion = 0.2; // la proportion de l'echantillon attribuee au test +int nb_tours = 100; // Le nombre d'itÈrations pour Baum Welch +int nb_essais = 10; // le nombre d'essais pour le best learning +int max_states = INT_MAX; // le nombre maximal d'etats pour DEES +bool stepssave = false; // vrai si on veut enregistrer toutes les étapes de l'apprentissage. + +// L'exportation de fichier +string format = "ffa"; + +// les distances +bool smooth = false; + +string cmd; +PPRFA A; +PPRFA B; + +stringstream convert; // variable qui permet de convertir les stream en entiers ou flottants + +/// ########################################################################## /// + + +// affiche un mot +string +affiche (const Word & w, const Dictionnaire & alph) +{ + Word::const_iterator a; + string res; + for (a = w.begin (); a != w.end (); ++a) + { + res += alph.find (*a)->second; + res += ' '; + } + return res; +} + + +void show(MA A) { + string dotfile; + string pdffile; + stringstream trad; + trad << temporary_directory << "pfa"<< int(time(NULL)); + trad >> pdffile; + dotfile=pdffile; + pdffile += ".pdf"; + dotfile += ".dot"; + A.save_dot(dotfile, viewprec, viewstates, viewmultipletransitions); + string cmd; + cmd += "dot -Tepdf "; + cmd += dotfile; + cmd += ">"; + cmd += pdffile; + system(cmd.c_str()); + show_ps(pdffile); +} + + + +// La procÈdure qui initialise le random +int +randomize (void) +{ + // mise a jour du random + unsigned int i = 0; + char c; + ifstream dev_rnd ("/dev/urandom"); + if (dev_rnd != NULL) + { + for (int k = 0; k < 4; k++) + { + dev_rnd.get (c); + i = i << 8 | c; + } + srand (i); + return i; + } + else + { + srand (num_ech); + return num_ech; + } +} + +int +affiche_utilisation (void) +{ + string fichelp = "./help/"; + fichelp += "help.txt"; + ifstream fh (fichelp.c_str ()); + if (fh == NULL) + { + cout << "DEES : "; + cout << "WARNING: " << fichelp << " not found." << endl; + } + else + { + cout << fh.rdbuf (); + fh.close (); + cout << endl; + } + return 0; +} + +int +affiche_options (void) +{ + string fichelp = "/Users/esposito/dees/help/"; + fichelp += "/help_options.txt"; + ifstream fh (fichelp.c_str ()); + if (fh == NULL) + { + cout << "DEES : "; + cout << "WARNING: " << fichelp << " not found." << endl; + } + else + { + cout << fh.rdbuf (); + fh.close (); + cout << endl; + } + return 0; +} + + +RESULT +export_to_pdf (const MA & A, + const string & fic_pdf, + const string & fic_tmp, + const int precision, + const bool noms_etats, + const bool multiples_trans) +{ + A.save_dot (fic_tmp, precision, noms_etats, multiples_trans); // On l'enregistre dans un fichier dot + // on Ècrit la commande + string cmd; + cmd = "dot -Tepdf "; + cmd += fic_tmp; + cmd += " > "; + cmd += fic_pdf; + + // on execute la transformation + system (cmd.c_str ()); + return 0; +} + +void +show_ps (string & fic_pdf) +{ + string cmd; + cmd += "open "; + cmd += fic_pdf; + cmd += "&"; + system (cmd.c_str ()); +} + + +// Affiche toutes les distances entre A et B +void +affiche_distance (PFA & A, const PFA & B, const int taille_ech_test, + const string & flag) +{ + double pA, pB; + A.genere_echantillon (taille_ech_test, S, num_ech_test); + cerr << "Test_Sample_size\t"; + cerr << "precision\t"; + cerr << "perplex A\t"; + cerr << "perplex B\t"; + cerr << "KL div\t"; + cerr << "d_2\t"; + cerr << "L_1\t"; + cerr << "d_2(nlog)\t"; + cerr << "L_1(nlog)\t"; + cout << taille_ech_test << "\t"; + cout << precision << "\t"; + cout << (pA = A.perplexite (S)) << "\t"; + cout << (pB = B.perplexite (S)) << "\t"; + cout << pB - pA << "\t"; + cout << A.d_2 (B, S) << "\t"; + cout << A.L_1 (B, S) << "\t"; + cout << A.d_2nlog (B, S) << "\t"; + cout << A.L_1nlog (B, S) << "\t"; + cout << flag << endl; +} + +void +affiche_distance (PFA & A, const PFA & B, const int taille_ech, + const char *flag) +{ + string s_flag = flag; + affiche_distance (A, B, taille_ech, s_flag); +} + +void +affiche_classe (PFA & A) +{ + if (!A.coherent ()) + { + cout << "uncoherent MA" << endl; + } + else if (!A.isSPFA ()) + { + cout << "MA" << endl; + } + else if (!A.isPFA ()) + { + cout << "SPFA" << endl; + } + else if (!A.isPRFA ()) + { + cout << "PFA" << endl; + } + else if (!A.isPDFA ()) + { + cout << "PRFA" << endl; + } + else + { + cout << "PDFA" << endl; + } +} + + +// Crossed validation learning +// Apprentissage avec validation croisÈe + +void Alergia(PFA &A, float prec, string ficsample, bool verbose) { + stringstream AL; + string ficsampletmp=temporary_directory + "tmpsample.alergia"; + Sample S; + S.load(ficsample); + S.save(ficsampletmp, alergia); + AL << "alergia"; + AL << " -a " << prec; + AL << " -o " << ficffaA; + AL << " -f " << ficsampletmp; + if (verbose) { + cout << ":: " << AL.str() << endl; + } + system(AL.str().c_str()); + + stringstream MOD; + string fictmp=temporary_directory + "alergia.tmp"; + MOD << "echo %Alergia > " << fictmp; + MOD << " && cat " << ficffaA << " >> " << fictmp; + if (verbose) { + cout << "transformation de l'automate avec :\n"; + cout << MOD.str() << endl; + } + system(MOD.str().c_str()); // on ajoute %Alergia au dÈbut du fichier + + if (verbose) { + cout << "on charge le fichier : " << fictmp << endl; + } + + A.load(fictmp); +} + +void MDI(PFA &A, float prec, string ficsample, bool verbose) { + string ficsampletmp=temporary_directory + "tmpsample.mdi"; + Sample S; + S.load(ficsample); + S.save(ficsampletmp, mdi); + stringstream MDI; + MDI << "mdi"; + MDI << " -b"; + if (verbose) { + MDI << " -v"; + } + MDI << " -c " << prec / double(taille_ech); + MDI << " -o " << ficffaA; + MDI << " -i " << ficsampletmp; + if (verbose) { + cout << ":: " << MDI.str() << endl; + } + system(MDI.str().c_str()); + + stringstream MOD; + string fictmp=temporary_directory + "mdi.tmp"; + MOD << "echo %MDI > " << fictmp; + MOD << " && cat " << ficffaA << " >> " << fictmp; + + if (verbose) { + cout << "transformation de l'automate avec :\n"; + cout << MOD.str() << endl; + } + system(MOD.str().c_str()); // on ajoute %MDI au dÈbut du fichier + + if (verbose) { + cout << "on charge le fichier : " << fictmp << endl; + } + + A.load(fictmp); +} + +// --- La procedure pour debbugger --- +float fonction (float val, float moy, float ecart) +{ + float constante = 1/(ecart * sqrt(2 * 3.1415)); + return constante * exp(- ((val - moy)*(val - moy)) / ecart); +} + +void BaumWelch(PFA A, Sample S, int nb_turns, string output) { + TransitionFunction T; + SFunc Iota, Tau; + double val, oldval; + A.allTransitions(T); + A.allStates(Iota); + A.allStates(Tau); + oldval=A.Likelihood(S); + for (int i=0 ; i < nb_turns ; i++) { + A.BaumWelch(S,T,Iota,Tau,3,true); + val=A.Likelihood(S); + //if (abs(val-oldval)<.1) { + // break; + //} + oldval=val; + if (verbose) { + cout << "Likelihood: " << A.Likelihood(S) << "\n"; + } + } + cout << endl; + + A.erase_bad_states(); + A.save(output); +} + + +// génère un PA complet + +RESULT generate_complete_random_pfa(int argc, char **argv, int i) { + + if (argc < i + 2) { + cerr << "dees --grp nbstates nbletters file" << endl; + cerr << "generate a complete random automaton with 'nbstates' states\n"; + cerr << "'nbletters' letters and save it in file\n"; + cerr << "usefull option:\n"; + cerr << "--numPFA : the number of the ma by default random number is choosen.\n"; + return -1; + } + + int nbstates=atoi(argv[i++]); + int nbletters=atoi(argv[i++]); + string output=argv[i++]; + + int num_graphe=0; //cout << "num graphe: "; cin >> num_graphe; + float min_trans=0.01; //cout << "min_trans: "; cin >> min_trans; + float max_trans=1; //cout << "max_trans: "; cin >> max_trans; + float prob_init=1; //cout << "prob_init: "; cin >> prob_init; + float prob_trans=1; //cout << "prob_trans: "; cin >> prob_trans; + float prob_term=1; //cout << "prob_term: "; cin >> prob_term; + + if (verbose) { + cout << "num graphe: " << num_graphe << endl; + cout << "prob_trans: " << prob_trans << endl; + cout << "prob_init: " << prob_init << endl; + cout << "prob_term: " << prob_term << endl; + cout << "min_trans: " << min_trans << endl; + cout << "max_trans: " << max_trans << endl; + } + + A.becomeRandom (nbstates, nbletters, numPFA, prob_trans, prob_init, prob_term, min_trans, max_trans); + + return A.save (output); +} + +RESULT generate_random_pfa(int argc, char **argv, int i) { + if (argc < i+3) { + cerr << "dees --random nbstates nbletters file\n"; + cerr << "generate a random automaton of class 'class' with 'nbstates' states\n"; + cerr << "'nbletters' letters and save it in file\n"; + cerr << "usefull option:\n"; + cerr << "--numPFA : the number of the ma by default random number is choosen.\n"; + cerr << "--interactive : ask you to enter values\n"; + return -1; + } + int nbstates=atoi(argv[i++]); + int nbletters=atoi(argv[i++]); + string output=argv[i++]; + + int num_graphe=0; + int max_nb_succ=nbstates; + int max_nb_init=nbstates; + int max_nb_term=nbstates; + float min_trans=0; + float max_trans=1; + float min_iota=0; + float max_iota=1; + float min_tau=0; + float max_tau=1; + float normalization=1; + float prob_init=.3; + float prob_trans=.3; + float prob_term=.3; + + if (interactive) { + cout << "num graphe (0=random): "; cin >> num_graphe; + cout << "max_nb_succ (width of the graph): "; cin >> max_nb_succ; + cout << "max_nb_init: "; cin >> max_nb_init; + cout << "max_nb_term: "; cin >> max_nb_term; + cout << "min_trans (minimal value of a transition): "; cin >> min_trans; + cout << "max_trans (maximal value of a transition): "; cin >> max_trans; + cout << "min_iota (minimal initial value): "; cin >> min_iota; + cout << "max_iota (maximal initial value): "; cin >> max_iota; + cout << "min_tau (minimal terminaison value): "; cin >> min_tau; + cout << "max_tau (maximal terminaison value): "; cin >> max_tau; + cout << "normalization (value of normalisation mostly 1): "; cin >> normalization; + cout << "prob_init (probability for a state to be initial: "; cin >> prob_init; + cout << "prob_trans (probability for a terminaison to araise): "; cin >> prob_trans; + cout << "prob_term (probability for a state to be terminal): "; cin >> prob_term; + } + + A.becomeRandomControl (nbstates, nbletters, num_graphe, max_nb_succ, max_nb_init, max_nb_term, min_trans, max_trans, min_iota, max_iota, min_tau, max_tau, normalization, prob_init, prob_trans, prob_term); + + return A.save(output); +} + +RESULT show_sample_forward(int argc, char**argv, int i) { + if (argc < i+2) { + cerr << "usage : --forward PFA sample\n"; + cerr << "return a list of couple word and its probability for the PFA\n"; + throw 2; + } + A.load(argv[i++]); + S.load(argv[i++]); + if (A.dictionnaire() != S.dictionnaire()) { + cerr << "Alphabets of the PFA and of the sample differ !" << endl; + Dictionnaire D; + Dictionnaire::const_iterator x; + cerr << "dictionnaire of the PFA\n"; + D=A.dictionnaire(); + for (x=D.begin() ; x != D.end() ; x++) { + cout << x->first << ":" << x->second << "\n"; + } + + cerr << "dictionnaire of the Sample\n"; + D=S.dictionnaire(); + for (x=D.begin() ; x != D.end() ; x++) { + cout << x->first << ":" << x->second << "\n"; + } + throw 2; + } + Sample::const_iterator w; + double somme=0 ; + double logsomme = 0; + double val ; + for (w=S.begin() ; w != S.end() ; w++) { + cout << A.affiche(w->first) << " : "; + cout.flush(); + val = A.p_bar(w->first); + somme += val; + cout << val ; + val = A.plog_bar(w->first); + logsomme += val; + cout << ", log forward : " << val; + cout << ", exp(log forward) :" << exp(val); + cout << ", pBarDirect : " << A.p_bar_directe(w->first); + cout << endl; + } + cout << "sum = " << somme << ", somme de exp(log(forward)) : " << logsomme << endl; + return VAL(0); +} + + +RESULT show_sample_proba(int argc, char **argv, int i){ + if (argc < i+2) { + cerr << "usage : --proba PFA sample\n"; + cerr << "return a list of couple word and its probability for the PFA\n"; + throw 2; + } + A.load(argv[i++]); + S.load(argv[i++]); + if (A.dictionnaire() != S.dictionnaire()) { + cerr << "Alphabets of the PFA and of the sample differ !" << endl; + Dictionnaire D; + Dictionnaire::const_iterator x; + cerr << "dictionnaire of the PFA\n"; + D=A.dictionnaire(); + for (x=D.begin() ; x != D.end() ; x++) { + cout << x->first << ":" << x->second << "\n"; + } + + cerr << "dictionnaire of the Sample\n"; + D=S.dictionnaire(); + for (x=D.begin() ; x != D.end() ; x++) { + cout << x->first << ":" << x->second << "\n"; + } + throw 2; + } + Sample::const_iterator w; + double somme=0 ; + double logsomme = 0; + double val ; + for (w=S.begin() ; w != S.end() ; w++) { + cout << A.affiche(w->first) << " : "; + cout.flush(); + val = A.p_directe(w->first); + somme += val; + cout << val ; + val = A.plog(w->first); + logsomme += val; + cout << ", log p : " << val; + cout << ", exp(log p) :" << exp(val); + cout << endl; + } + cout << "sum = " << somme << ", somme de exp(log(p)) : " << logsomme << endl; + return VAL(0); +} + +void affiche_PSe(void) { + SFunc PSe; + SFunc::const_iterator q; + int res; + + 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; + } +} + + +/// ############################################################################# /// +/// ### INIT COMMAND LINE + MAIN #### /// +/// ############################################################################# /// + +// initialisation des arguments (ligne de commande) +int +initialise_arguments (int argc, char *argv[]) +{ + string arg; + int i = 1; + while ((i < argc) && (argv[i][0] == '-')) + { // pour chaque argument commenÃant par - + arg = argv[i]; + if ((arg == "-h") || (arg == "--help")) + { // affiche l'aide + throw 1; + } + // options muettes + else if ( + (arg == "--export") || // exporte vers des formats d'automates differents + (arg == "--convert") || // convertit des echantillons + (arg == "--dist") || // affiche la distance entre deux ffa + (arg == "--class") || // affiche la classe d'un pfa + (arg == "--sample") || // genere un Èchantillon + (arg == "--grp") || // genere un automate probabiliste + (arg == "--gcrp") || // genere un automate probabiliste complet + (arg == "--mdi") || // algorithme mdi + (arg == "--alergia") || // algorithme alergia + (arg == "--bm") || // algorithme Baum Welch + (arg == "--affiche") || // affiche un automate sur la sortie standard + (arg == "-H") || // affiche l'aide Ètendue (options) + (arg == "-Y" || arg == "-I") || // envoie la fonction Y (mode interactif) + (arg == "--test") || // fait un test ‡ partir de l'automate + (arg == "--random") || // generate a random automaton + (arg == "--proba") || // show probabilities of words of a sample + (arg == "--forward") || // show forward values of words of a sample + (arg == "--deletetransitions") || // delete transitions of some value + ((arg == "-P") || (arg == "--showps")) || // affichage postscript + (arg == "--PSe") // Affichage des valeurs de P(\Se) pour chaque état + + ) + { + } + else if ( + (arg == "--dees") || // algorithme dees (cible PRFA) + (arg == "--deesha") || // algorithme deesha (cible MA) + (arg == "--deesdet") ) // algorithme basé sur dees mais se limitant aux solution déterministes + { + precision=1; + } else if (arg == "--deesbm") // algorithme dees Baum Welch + { + precision=2; + } + else if ((arg == "--DEBUG") + || (arg == "-d") || (arg == "--debug")) + { + // PFA_DEBUG=true; + } + else if (arg == "--interactive") + { + interactive=true; + ++i; + } + else if (arg == "--format") + { + format = argv[++i]; + } + else if ((arg == "--VERBOSE") || (arg == "-v") || (arg == "--verbose")) + { + verbose = true; + // PFA_VERBOSE=true; + } + else if ((arg == "--MUTE") || (arg == "-m") || (arg == "--mute")) + { + // PFA_VERBOSE=false; + verbose = false; + } + else if ((arg == "--SAFE") || (arg == "--safe")) + { + // PFA_SAFE=true; + } + else if ((arg == "--UNSAFE") || (arg == "--unsafe")) + { + // PFA_SAFE=false; + } + else if ((arg == "--taille_ech") || (arg == "-te")) + { + convert << argv[++i]; + convert >> taille_ech; + } + else if (arg == "--maxmots") { + convert << argv[++i]; + convert >> maxmots; + } + else if (arg == "--num_ech") + { + num_ech = atoi (argv[++i]); + } + else if (arg == "--num_ech_test") + { + num_ech_test = atoi (argv[++i]); + } + else if ((arg == "--ficffaA") || (arg == "-i")) + { + ficffaA = argv[++i]; + } + else if (arg == "--ficffaB") + { + ficffaB = argv[++i]; + } + else if (arg == "-o") + { + ficffaA = ficech = ficffaB = ficdotB = ficpsB = argv[++i]; + } + else if (arg == "--moderet") + { + arg = argv[++i]; + if (arg == "begin") + moderet = begin; + else + moderet = end; + } + else if (arg == "--modeeps") + { + arg = argv[++i]; + if (arg == "fixed") + modeeps = epsfixed; + else if (arg == "variable") + modeeps = variable; + else + cerr << "option for --modeeps can be 'fixed' or 'variable', here it is '" << arg << endl; + } + else if (arg == "--ficdotA") + { + ficdotA = argv[++i]; + } + else if (arg == "--ficdotB") + { + ficdotB = argv[++i]; + } + else if (arg == "--ficech") + { + ficech = argv[++i]; + } + else if (arg == "--ficechpre") + { + ficechpre = argv[++i]; + } + else if ((arg == "--precision") || (arg == "-p")) + { + precision = atof (argv[++i]); + } + else if (arg == "--epsprime") + { + epsprime = atof (argv[++i]); + } + else if (arg == "--seuil") + { + seuil = atoi (argv[++i]); + } + else if (arg == "--numPFA") + { + numPFA = atoi (argv[++i]); + } + else if (arg == "--seuilbm") + { + seuilbm = atof (argv[++i]); + } + else if (arg == "--nb_tours") + { + nb_tours = atoi (argv[++i]); + } + else if (arg == "--ficps") + { + ficpsA = argv[++i]; + } + else if (arg == "--ficpsB") + { + ficpsB = argv[++i]; + } + else if (arg == "--stepssave") + { + stepssave=true ; + } + else if (arg == "--nb_etats") + { + nb_etats = atoi (argv[++i]); + } + else if (arg == "--nb_essais") { + nb_essais = atoi (argv[++i]); + } + else if (arg == "--max_states") { + max_states = atoi (argv[++i]); + } + else if (arg == "--nb_lettres") + { + nb_lettres = atoi (argv[++i]); + } + else if (arg == "--precpow") + { + precpow = atof (argv[++i]); + } + else if (arg == "--affiche_A") + { + affiche_A = true; + } + else if (arg == "--affiche_B") + { + affiche_B = true; + } + else if (arg == "--blind") + { + affiche_A = affiche_B = false; + } + else if ((arg == "--taille_ech_test") || (arg == "-tt")) + { + taille_ech_test = atoi (argv[++i]); + } + else if (arg == "--name") + { + nom_A = argv[++i]; + } + else if (arg == "--nom_B") + { + nom_B = argv[++i]; + } + else if (arg == "--test_proportion") + { + test_proportion = atof (argv[++i]); + } + else if (arg == "--smooth") { + smooth=true; + } + else if (arg == "--rand") { + srand( atoi(argv[++i]) ); + } + else if (arg == "--viewprec") { + viewprec=atoi(argv[++i]); + } + else if (arg == "--viewstates") { + viewstates=true; + } + else if (arg == "--viewmultipletransitions") { + viewmultipletransitions=true; + } + else + { + cerr << "unknow option : " << arg << endl; + } + i++; + } + return i; +} + +// La procedure principale +int +main (int argc, char *argv[]) +{ + int i = 0; + string commande; + commande = "mkdir " + temporary_directory + ">/dev/null 2>&1"; + system(commande.c_str()); + try + { + if (argc < 2) + throw 1; + randomize (); + i = initialise_arguments (argc, argv); + + string arg; + arg = argv[1]; + if (arg == "-h" || arg == "--help") + { // ---------- help --------------- + throw 1; + } + else if (arg == "-H") + { // ----------------- HELP with options ------- + affiche_utilisation (); + affiche_options (); + cout << "Report bugs or suggestions to Yann Esposito ." << endl; + } + else if ((arg == "-Y") || (arg == "-I")) + { // -------------- interactive mode ------------- + Y (); + } + else if (arg == "--test") + { + test(); + } + else if (arg == "--PSe") + { + ficffaA = argv[i]; + if (!OK(A.load(ficffaA))) { + throw string ("Erreur d'ouverture du fichier ") + ficffaA; + } + affiche_PSe(); + } + else if (arg == "--export") + { // ---------------- exportation---------------- + if (argc < i + 3) { + cerr << "export command export some automaton file to another format" << endl; + cerr << "available format are dot, pdf and ffa." << endl; + cerr << "usage: dees --export [OPTIONS] format input output" << endl; + throw 2; + } + format = argv[i]; + ficffaA = argv[i+1]; + ficffaB = argv[i + 2]; + if (!OK(A.load (ficffaA))) { + throw string ("Erreur d'ouverture du fichier ") + ficffaA; + } + A.name = nom_A; + if (format == "dot") + { // exportation to dot format + A.save_dot (ficffaB); + } + else if (format == "pdf") + { // exportation to ps format + export_to_pdf (A, ficffaB, temporary_directory + "tmp.dot"); + } + else if (format == "ffa") + { // exportation ffa + A.save (ficffaB); + } + else + { + cerr << "export command export some automaton file to another format" << endl; + cerr << "available format are dot, ps and ffa." << endl; + cerr << "usage: dees --export [OPTIONS] format input output" << endl; + throw 4; + } + } + else if (arg == "--affiche") + { // ------------------------ affichage ------------------- + if (argc < i + 1) { + cerr << "--affiche command show the automaton on standart output" << endl; + cerr << "usage: dees --affiche [OPTIONS] automaton" << endl; + throw 2; + } + A.load (argv[i]); + A.affiche (); + } + else if ((arg == "--showps") || (arg == "-P")) + { // --- affichage du postscript ------ + if (argc < i + 1) { + cerr << "showps or -P command show the automaton in gv" << endl; + cerr << "you must have dot (part of Graphviz project) and a script named open" << endl; + cerr << "which is a pdf viewer installed" << endl; + cerr << "usage: dees <--showps or -P> [OPTIONS] automaton" << endl; + cerr << "usefull option: --name name" << endl; + throw 2; // pas assez d'arguments + } + A.load (argv[i]); + A.name = nom_A; + show(A); + } + else if (arg == "--dist") + { // ----------------------- calcul des distances ------------ + if (argc < i + 2) { + cerr << "dist command show some distances between two automata." << endl; + cerr << "usage: dees --dist [OPTIONS] automaton_A automaton_B" << endl; + cerr << "usefull option: --taille_ech_test size" << endl; + cerr << " --smooth or --no_smooth" << endl; + throw 2; + } + A.load (argv[i]); + B.load (argv[i + 1]); + if (smooth == true) { + B.lisse (); + } + affiche_distance (A, B, taille_ech_test, ""); + } + else if (arg == "--deletetransitions") { + if (argc < i + 3) { + cerr << "dees --deletetransitions input_pfa output_pfa min max\n"; + cerr << "delete transitions of the input_pfa which values are between min and max\n"; + cerr << "renormalise and save it in output_pfa file.\n"; + return -1; + } + PFA A; + string input=argv[i++]; + string output=argv[i++]; + double min=atof(argv[i++]); + double max=atof(argv[i++]); + A.load(input); + if (max < min) { + double tmp = max; + max=min; + min=tmp; + cerr << "Warning max < min !" << endl; + } + A.erase_transitions(max,min); + A.rend_PFA(); + A.save(output); + } + else if (arg == "--sample") + { // --------------------- generation d'un echantillon --- + if (argc < i + 3) { + cerr << "sample command generate a sample from an automaton." << endl; + cerr << "usage: dees --sample [OPTIONS] automaton size sample" << endl; + cerr << "usefull options:" << endl; + cerr << "--format " << endl; + cerr << "--num_ech num_sample" << endl; + throw 2; + } + ficffaA = argv[i]; + taille_ech = atoi (argv[i + 1]); + ficech = argv[i + 2]; + A.load (ficffaA); + A.genere_echantillon (taille_ech, S, num_ech); + if (format == "ffa") + S.save (ficech, ffa); + else if (format == "alergia") + S.save (ficech, alergia); + else if (format == "mdi") + S.save (ficech, mdi); + else + throw 4; + } + else if (arg == "--mdi") { + if (argc > i) + { + ficech = argv[i]; + } + else + { + throw 1; + } + if (verbose) + cout << "loading " << ficech << "..." << endl; + + MDI(A,precision,ficech,verbose); + + if (verbose) + cout << "saving A in " << ficffaA << endl; + A.save (ficffaA); + // affichage de l'automate + if (affiche_A) + { + show(A); + } + } + else if (arg == "--alergia") { + if (argc <= i) + throw 1; + + ficech = argv[i]; + if (verbose) + cout << "loading " << ficech << "..." << endl; + + Alergia(A,precision,ficech,verbose); + + if (verbose) + cout << "saving A in " << ficffaA << endl; + + A.save (ficffaA); + // affichage de l'automate + if (affiche_A) + { + show(A); + } + } + else if (arg == "--deesdet") + { + + if (argc > i) + { + ficech = argv[i]; + } + else + { + cerr << "--dees command learn an automaton using dees." << endl; + cerr << "usage: dees --dees [OPTIONS] sample" << endl; + cerr << "usefull options:" << endl; + cerr << "-p or --precision float\tthe precision parameter" << endl; + cerr << "--epsprime float\tnumber under which a transition is deleted" << endl; + cerr << "-v or --verbose" << endl; + cerr << "--moderet [begin or end]" << endl; + cerr << "--max_states number" << endl; + cerr << "--seuil seuil" << endl; + cerr << "--stepssave\tsave steps of the algorithm" << endl; + throw 2; + } + if (verbose) + cout << "loading " << ficech << "..." << endl; + if (!OK (S.load (ficech.c_str ()))) + { + cerr << "impossible d'ouvrir " << ficech << endl; + throw 5; + } + + epsprime = precision*pow(double(S.size()),-0.25)/5; + epsprime = min(sqrt(precision),0.1); + + A.DEES (determinist, S, precision, epsprime, verbose, moderet, modeeps, max_states, seuil,10,0,true,stepssave); + if (verbose) + cout << "saving A in " << ficffaA << endl; + A.save (ficffaA); + // affichage de l'automate + if (affiche_A) + { + show(A); + } + } + else if (arg == "--dees") + { + + if (argc > i) + { + ficech = argv[i]; + } + else + { + cerr << "--dees command learn an automaton using dees." << endl; + cerr << "usage: dees --dees [OPTIONS] sample" << endl; + cerr << "usefull options:" << endl; + cerr << "-p or --precision float\tthe precision parameter" << endl; + cerr << "--epsprime float\tnumber under which a transition is deleted" << endl; + cerr << "-v or --verbose" << endl; + cerr << "--moderet [begin or end]" << endl; + cerr << "--max_states number" << endl; + cerr << "--seuil seuil" << endl; + cerr << "--stepssave\tsave steps of the algorithm" << endl; + throw 2; + } + if (verbose) + cout << "loading " << ficech << "..." << endl; + if (!OK (S.load (ficech.c_str ()))) + { + cerr << "impossible d'ouvrir " << ficech << endl; + throw 5; + } + + epsprime = precision*pow(double(S.size()),-0.25)/5; + epsprime = min(sqrt(precision),0.1); + + A.DEES (positive, S, precision, epsprime, verbose, moderet, modeeps, max_states, seuil,10,0,true,stepssave); + if (verbose) + cout << "saving A in " << ficffaA << endl; + A.save (ficffaA); + // affichage de l'automate + if (affiche_A) + { + show(A); + } + } + else if (arg == "--deesbm") { + // --- DEES version Baum Welch --- + if (argc > i) + { + ficech = argv[i]; + } + else + { + cerr << "--deesbm command learn an automaton using deesbm." << endl; + cerr << "usage: dees --deesbm [OPTIONS] sample" << endl; + cerr << "usefull options:" << endl; + cerr << "-p or --precision number" << endl; + cerr << "-v or --verbose" << endl; + cerr << "--max_states number\tmaximal number of states" << endl; + cerr << "--seuil number\tminimal number of suffix do use residual" << endl; + cerr << "--nb_tours number\tmax number of turns for Baum Welch" << endl; + cerr << "--seuilbm double\tprecision under which Baum Welch is considered to found the Max Likelihood Model" << endl; + cerr << "-o or --ficffaA file\ttarget file" << endl; + throw 2; + } + if (verbose) + cout << "loading " << ficech << "..." << endl; + if (!OK (S.load (ficech.c_str ()))) + { + cerr << "impossible d'ouvrir " << ficech << + endl; + throw 5; + } + + epsprime = precision*pow(double(S.size()),-0.25)/5; + + A.DEESBM (S, precision, epsprime, verbose, max_states, seuil, seuilbm, nb_tours); + if (verbose) + cout << "saving A in " << ficffaA << endl; + // A.emmonde(); + A.save (ficffaA); + // affichage de l'automate + if (affiche_A) + { + show(A); + } + } + else if (arg == "--deesha") + { + + if (argc > i) + { + ficech = argv[i]; + } + else + { + throw 1; + } + if (verbose) + cout << "loading " << ficech << "..." << endl; + if (!OK (S.load (ficech.c_str ()))) + { + cerr << "impossible d'ouvrir " << ficech << + endl; + throw 5; + } + + // epsprime = precision/(2*sqrt(sqrt(n))) + // epsprime est donc un o(precision) + epsprime = precision*pow(double(S.size()),-0.25)/5; + + A.DEES (nonconstrained, S, precision, epsprime, verbose, moderet,modeeps, max_states, seuil, maxmots); + if (verbose) + cout << "saving A in " << ficffaA << endl; + // A.emmonde(); + A.save (ficffaA); + // affichage de l'automate + if (affiche_A) + { + show(A); + } + } + else if ((arg == "--generate_complete_random_pfa") || (arg == "--gcrp")) + { // --- generation d'un pfa aléatoire complet --- + generate_complete_random_pfa(argc, argv, i); + } + else if ((arg == "--generate_random_pfa") || (arg == "--grp")) + { + generate_random_pfa(argc, argv, i); + } + else if (arg == "--proba") { // show values of words for an MA + show_sample_proba(argc, argv, i); + } + else if (arg == "--forward") { // show prefix values of words for an MA + show_sample_forward(argc, argv, i); + } + else if (arg == "--class") + { // --- show the class of the automaton + if (argc < 3) + throw 2; + A.load (argv[2]); + affiche_classe (A); + } + else if (arg == "--bm") { // Baum Welch Algorithm + if (argc < i+4) { + cerr << "dees --bm pfa sample number_of_turns output_pfa\n"; + cerr << "work baum welch using the pfa for initialisation (structure + parameters)\n"; + cerr << "remember Baum Welch never change a 0 valued parameter\n"; + return -1; + } + string pfa=argv[i++]; + string sample=argv[i++]; + int nb_turns=atoi(argv[i++]); + string output=argv[i++]; + + A.load(pfa); + S.load(sample); + BaumWelch(A,S,nb_turns,output); + } + else if (arg == "--convert") { + if (argc < i+3) { + cerr << "dees --convert format sample output\n"; + cerr << "Change the format of the sample to output.\n"; + cerr << "format could be dees for internal, alergia or mdi\n"; + return -1; + } + string format=argv[++i]; + string input=argv[++i]; + string output=argv[++i]; + S.load(input); + if (format == "alergia") { + S.save(output, alergia); + } + else if (format == "mdi") { + S.save(output, mdi); + } + else { + S.save(output); + } + } + else + { // ---------- choix non traitÈ ------------- + throw 1; + } + return EXIT_SUCCESS; + } + catch (int err) + { + switch (err) + { + case 1: + affiche_utilisation (); + cout << "Report bugs or suggestions to Yann Esposito ." << endl; + break; + case 2: + cerr << "\nNo enougth arguments" << endl; + break; + case 3: + cerr << "Input error, I cannot read the file." << + argv[i] << endl; + break; + case 4: + cerr << format << "is an unknown format." << endl; + break; + case 5: + cerr << "I/O Error !!!" << endl; + break; + default: + cerr << "unknown error occured !" << endl; + } + + if (err != 1) + { + cerr << "use -h, --help or -H option to display help" << endl; + } + } + catch (string erreur) { + cerr << erreur << endl; + } + catch (...) + { + cerr << "Unknown error !!!" << endl; + affiche_utilisation (); + return -1; + } +} \ No newline at end of file diff --git a/oldsimplex.H b/oldsimplex.H new file mode 100644 index 0000000..b00385f --- /dev/null +++ b/oldsimplex.H @@ -0,0 +1,31 @@ +#include "general.H" +#include // pour fabs + +// ------- La classe ---------- +class Simplex +{ +public: + //hash_map > a; // La matrice des contraintes + //hash_map sol; // Le tableau des solutions + //hash_map db; // Un tableau + //hash_map hb; // un autre tableau + + map > a; // La matrice des contraintes + map sol; // Le tableau des solutions + map db; // Un tableau + map hb; // un autre tableau + map::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); +}; diff --git a/pfa.H b/pfa.H new file mode 100644 index 0000000..b0519cc --- /dev/null +++ b/pfa.H @@ -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 diff --git a/pfa.cpp b/pfa.cpp new file mode 100644 index 0000000..23f081f --- /dev/null +++ b/pfa.cpp @@ -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 +#include + +// 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; +} diff --git a/pprfa.H b/pprfa.H new file mode 100644 index 0000000..723f9f7 --- /dev/null +++ b/pprfa.H @@ -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 + &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 + &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 &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 diff --git a/pprfa.cpp b/pprfa.cpp new file mode 100644 index 0000000..7c186e5 --- /dev/null +++ b/pprfa.cpp @@ -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); +} + + diff --git a/pprfa_bm.cpp b/pprfa_bm.cpp new file mode 100644 index 0000000..d65ca97 --- /dev/null +++ b/pprfa_bm.cpp @@ -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 &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 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]<> 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 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; + // ---- + +} + diff --git a/pprfa_dees.cpp b/pprfa_dees.cpp new file mode 100644 index 0000000..871b0ce --- /dev/null +++ b/pprfa_dees.cpp @@ -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 &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::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::const_iterator wy; + map::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 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::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); + } + */ +} \ No newline at end of file diff --git a/sample.H b/sample.H new file mode 100644 index 0000000..55eb8e8 --- /dev/null +++ b/sample.H @@ -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 +// ----------------------- 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 infeq; + return infeq(u,v); + } + } +}; + +// Type echantillon qui suit l'ordre naturel sur les mots +typedef map 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 diff --git a/sample.cpp b/sample.cpp new file mode 100644 index 0000000..04d790b --- /dev/null +++ b/sample.cpp @@ -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 + +// 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 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 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; + } +} diff --git a/simplex.H b/simplex.H new file mode 100644 index 0000000..106def3 --- /dev/null +++ b/simplex.H @@ -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 constraints, double val); + int add_absolute_constraint_with_parameters(const map constraints, double val); + + // return the solution int the map solution + bool has_solution(map &solution, float &epsilon); + // renvoie 0 si + int set_minimize_epsilon_mode (double epsilon = -1); + +}; + diff --git a/simplex.cpp b/simplex.cpp new file mode 100644 index 0000000..b2e389a --- /dev/null +++ b/simplex.cpp @@ -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 + +// 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 constraints, double val) { + resize_tmpbuf(); + vector::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 constraints, double val) { + resize_tmpbuf(); + map::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 &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); +} + diff --git a/spfa.H b/spfa.H new file mode 100644 index 0000000..cfc33a7 --- /dev/null +++ b/spfa.H @@ -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 + + +typedef map WordSFunc; +typedef map StateSFunc; +typedef map StateWordFunction; +typedef set 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 faon 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 diff --git a/spfa.cpp b/spfa.cpp new file mode 100644 index 0000000..c6833f7 --- /dev/null +++ b/spfa.cpp @@ -0,0 +1,1284 @@ +/*************************************************************************** + spfa.cpp + ------------------- + begin : Sun 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. * + * * + ***************************************************************************/ + +/* + Pour les notes, voir le fichier "spfa.h". + See "ffa.h" file to view notes. +*/ + +#include "spfa.H" +#include + +// Ajoute un Ètat +RESULT SPFA::addNewState (const float init, const float term) +{ + if (PFA_SAFE) + { + assert (init >= 0); + assert (init <= 1); + assert (term >= 0); + assert (term <= 1); + } + return MA::addNewState (init, term); + if (PFA_SAFE) + { + assert (isSPFA ()); + } +} + +// Fonction qui ajoute une transition +RESULT SPFA::addTransition (const Transition & t, const float val) +{ + return MA::addTransition (t, val); + if (PFA_SAFE) + assert (isSPFA ()); +} + +// Ajout d'une transition +RESULT SPFA::addTransition (const State qdep, const Lettre a, const State qarr, const float val) +{ + return MA::addTransition (qdep, a, qarr, val); + if (PFA_SAFE) + { + assert (isSPFA ()); + } +} + +// Donne un SPFA aleatoire +RESULT SPFA::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 gÈnËre un MA alÈatoire avec seulement des arÃtes positives + MA::becomeRandom (nb_etats, nb_lettres, + num_graphe, densite, + prob_init, prob_term, min_trans, max_trans); + + // On rend le MA en SPFA + return renormalise (); +} + +// Cree un MA aleatoire avec un nombre maximal d'aretes +RESULT SPFA::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) +{ + MA::becomeRandomMax(nb_etats, nb_lettres, num_graphe, nb_succ, nb_init, nb_term,min_trans,max_trans); + return renormalise(); +} + + +RESULT SPFA::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 + MA::becomeRandomPrefix (nb_etats, nb_lettres, + num_graphe, densite, + prob_init, prob_term, min_trans, max_trans); + + // on rend un SPFA + return renormalise (); +} + + +RESULT SPFA::renormalise () +{ + if (!Q.empty()) + { + // --- On renormalise la fonction d'initialisation --- + SFunc::iterator s; + double sum, sum2; + // on gere le cas ou il n'y a pas d'etat initial + if (iota.empty ()) + { + iota[*(Q.begin ())] = 1; + } + else + { + // on calcule 1/somme des iota + sum = 0; + for (s = iota.begin (); s != iota.end (); ++s) + { + sum += s->second; + } + + // on renormalise tous les iota + sum2 = 0; + for (s = iota.begin (); s != iota.end (); s++) + { + s->second = s->second / sum; + sum2 += s->second; + } + // on repare encore un peu + iota.begin()->second += 1 - sum2; + } + + // Pour chaque etat on regarde la somme de ce qui sort + StateSet::const_iterator q; + Graph::iterator g; + LettreSFunc::iterator a; + for (q = Q.begin (); q != Q.end (); q++) + { // pour tous les Ètats + // on calcule ce qui sort de l'etat + sum = val_outstate(*q); + if (sum == 0) // si rien ne sort de l'etat, on met ‡ jour tau + { + tau[*q] = 1; + } + else + { + // on renormalise en prenant en compte les problËmes de virgule + g=phi.find(*q); + sum2 = 0; + if (g != phi.end ()) + { + for (a = g->second.begin (); a != g->second.end (); ++a) + { + for (s = a->second.begin (); s != a->second.end (); ++s) + { + s->second /= sum; + sum2 += s->second; + } + } + } + // si la somme ne fait pas encore 1 on + // met ‡ jour la valeur d'une arete ou de tau + if (sum2 != 1) + { + // si tau est non nul c'est lui que l'on modifie + if ((tau.find (*q) != tau.end ()) || (g == phi.end())) + { + tau[*q] = 1 - sum2; + } + else + { // sinon on repare un peu une transition + bool trouve = false; + for (a = g->second.begin (); + (a != g->second.end ()) && !trouve; + ++a) + { + s = a->second.begin (); + if (s != a->second.end ()) + { + trouve = true; + s->second += 1 - sum2; + } + } + } + } + } + } + + if (PFA_DEBUG) + { + if (!isSPFA ()) + { + cerr << "ERREUR de la fonction SPFA::renormalise()" << + endl; + } + } + return isSPFA (); + } + else + return false; +} +// le logarithme de la fonction phi Ètendue aux mots +double +SPFA::philog (const State q, const Word & u, const State s, + const Dictionnaire * dico) const +{ + Word::const_iterator a; + PreciseSFunc V; // Le vecteur contenant log(p(w)) + PreciseSFunc Vbis; + StateSet::const_iterator r; + PreciseSFunc::iterator si; + double tmp; + + if (dico == NULL) + { + V[q] = 0; + for (a = u.begin (); a != u.end (); a++) + { + + + Vbis.clear (); + for (r = Q.begin (); r != Q.end (); r++) + { + // Calcul du nouveau vecteur + tmp = 0; + for (si = V.begin (); si != V.end (); si++) + { + if (val_phi (si->first, *a, *r) != 0) + { + if (Vbis.find (*r) != + Vbis.end ()) + { + Vbis[*r] = + sumlog (Vbis[*r], si->second + log(val_phi(si->first,*a, *r))); + } + else + { + Vbis[*r] = si->second + log(val_phi(si->first,*a, *r)); + } + } + } + } + V = Vbis; + } + return V[s]; + } + else // les dictionnaires ne sont peut-etre pas Èquivalents + { + Word w; + Dictionnaire::const_iterator tl; + TrueLettre b; + + w.clear (); + for (a = u.begin (); a != u.end (); ++a) + { + tl = dico->find (*a); + if (tl == dico->end ()) + { + cerr << "Erreur !!! SPFA::philog, bad dictionnary !" << endl; + } + else + { + b = tl->second; + for (tl = alph.begin (); + (tl->second != b) + && (tl != alph.end ()); ++tl) + ; + if (tl == alph.end ()) + { + cerr << "Erreur 2 !!! SPFA::philog, bad dictionnary" << endl; + } + else + { + w += tl->first; + } + } + } + + V[q] = 0; + for (a = w.begin (); a != w.end (); ++a) + { + Vbis.clear (); + for (r = Q.begin (); r != Q.end (); ++r) + { + // Calcul du nouveau vecteur + tmp = 0; + for (si = V.begin (); si != V.end (); ++si) + { + if (val_phi (si->first, *a, *r) != 0) + { + if (Vbis. + find (*r) != Vbis.end ()) + { + Vbis[*r] =sumlog (Vbis[*r],si->second+log(val_phi(si-> first, *a,*r))); + } + else + { + Vbis[*r] =si->second +log (val_phi(si-> first,*a,*r)); + } + } + } + } + V = Vbis; + } + return V[s]; + } + +} + +// la proba conditionnÈe i.e. p(q|u) +double +SPFA::plog (const State q, const Word & u, const Dictionnaire * dico) const +{ + Word::const_iterator a; + PreciseSFunc V; // Le vecteur contenant log(p(w)) + PreciseSFunc Vbis; + SFunc::const_iterator e; + StateSet::const_iterator r; + PreciseSFunc::iterator s; + double res, tmp; + + for (e = iota.begin (); e != iota.end (); ++e) + V[e->first] = log (e->second); + + if ((dico == NULL) || (*dico == alph)) + { + for (a = u.begin (); a != u.end (); ++a) + { + Vbis.clear (); + for (r = Q.begin (); r != Q.end (); ++r) + { + // Calcul du nouveau vecteur + tmp = 0; + for (s = V.begin (); s != V.end (); ++s) + { + if (val_phi (s->first, *a, *r) != 0) + { + if (Vbis.find (*r) != + Vbis.end ()) + { + Vbis[*r] = sumlog(Vbis[*r], + s->second + log(val_phi(s->first,*a, *r))); + } + else + { + Vbis[*r] = + s->second + log(val_phi(s->first,*a, *r)); + } + } + } + } + V = Vbis; + } + + // res=exp(V[q] - sum_r V[r]) + if (V.find (q) != V.end ()) + { + res = log ((double) 0); + for (s = V.begin (); s != V.end (); ++s) + res = sumlog (res, s->second); + res = V[q] - res; + } + else + { + res = log ((double) 0); + } + + return res; + } + else // dico != NULL + { + Word w; + Dictionnaire::const_iterator tl; + TrueLettre b; + + w.clear (); + for (a = u.begin (); a != u.end (); ++a) + { + tl = dico->find (*a); + if (tl == dico->end ()) + { + cerr << "Erreur !!! SPFA::philog, bad dictionnary !" << endl; + } + else + { + b = tl->second; + tl = alph.begin() ; + while ((tl != alph.end()) && (tl->second != b)) + ++tl; + if (tl == alph.end ()) + { + cerr << "Erreur 2 !!! SPFA::philog, bad dictionnary" << endl; + } + else + { + w += tl->first; + } + } + } + + + for (a = w.begin (); a != w.end (); ++a) + { + Vbis.clear (); + for (r = Q.begin (); r != Q.end (); ++r) + { + // Calcul du nouveau vecteur + tmp = 0; + for (s = V.begin (); s != V.end (); ++s) + { + if (val_phi (s->first, *a, *r) != 0) + { + if (Vbis.find (*r) != Vbis.end ()) + { + Vbis[*r] = + sumlog(Vbis[*r], + s->second + log(val_phi(s->first,*a, *r))); + } + else + { + Vbis[*r] = s->second + log(val_phi(s->first,*a, *r)); + } + } + } + } + V = Vbis; + } + + // res=exp(V[q] - sum_r V[r]) + if (V.find (q) != V.end ()) + { + res = log ((double) 0); + for (s = V.begin (); s != V.end (); ++s) + res = sumlog (res, s->second); + res = V[q] - res; + } + else + { + res = log ((double) 0); + } + + return res; + } +} + +// la fonction p directe +double SPFA::p_directe (const Word & u, const Dictionnaire * dico) const +{ + PreciseSFunc F; + PreciseSFunc::const_iterator x; + SFunc::const_iterator t; + double res; + if ((dico == NULL) || (*dico == alph)) { + forward(F,u); + res = 0.0; + for (x=F.begin() ; x!=F.end() ; ++x) { + t = tau.find(x->first); + if (t != tau.end()) { + res += x->second * double(t->second); + } + } + return res; + } + else { + // le dictionnaire n'est pas identique, on doit traduire le mot + Word v; + Word::const_iterator a; + Dictionnaire::const_iterator tl; + Dictionnaire::const_iterator tl2; + map traducteur; + for (tl = dico->begin() ; tl != dico->end() ; ++tl) + { + tl2 = alph.begin(); + while ((tl2 != alph.end()) && (tl2->second != tl->second)) + ++tl2; + if (tl2 == alph.end()) + { + cerr << "Erreur !!! SPFA::philog, bad dictionnary ! lettre " << tl->second << endl; + } + else + { + traducteur[tl->first] = tl2->first; + } + } + for (a=u.begin() ; a != u.end() ; ++a) { + v += traducteur[*a]; + } + + forward(F,v); + res = 0.0; + for (x=F.begin() ; x!=F.end() ; ++x) { + t = tau.find(x->first); + if (t != tau.end()) { + cout << "^^" << x->second << " * " << t->second << endl; + res += x->second * double(t->second); + } + } + return res; + } +} + + +// la fonction p directe +double SPFA::p_bar_directe (const Word & u, const Dictionnaire * dico) const +{ + PreciseSFunc F; + PreciseSFunc::const_iterator x; + SFunc::const_iterator t; + double res; + if ((dico == NULL) || (*dico == alph)) { + forward(F,u); + res = 0.0; + for (x=F.begin() ; x!=F.end() ; ++x) { + res += x->second; + } + return res; + } + else { + // le dictionnaire n'est pas identique, on doit traduire le mot + Word v; + Word::const_iterator a; + Dictionnaire::const_iterator tl; + Dictionnaire::const_iterator tl2; + map traducteur; + for (tl = dico->begin() ; tl != dico->end() ; ++tl) + { + tl2 = alph.begin(); + while ((tl2 != alph.end()) && (tl2->second != tl->second)) + ++tl2; + if (tl2 == alph.end()) + { + cerr << "Erreur !!! SPFA::philog, bad dictionnary ! lettre " << tl->second << endl; + } + else + { + traducteur[tl->first] = tl2->first; + } + } + for (a=u.begin() ; a != u.end() ; ++a) { + v += traducteur[*a]; + } + + forward(F,v); + res = 0.0; + for (x=F.begin() ; x!=F.end() ; ++x) { + res += x->second; + } + return res; + } +} + + +// le logarithme de la fonction p +double SPFA::plog (const Word & u, const Dictionnaire * dico) const +{ + PreciseSFunc F; + PreciseSFunc::const_iterator x; + SFunc::const_iterator t; + double res; + double tmp; + if ((dico == NULL) || (*dico == alph)) { + logforward(F,u); + res = log(0.0); + for (x=F.begin() ; x!=F.end() ; ++x) { + t = tau.find(x->first); + if (t != tau.end()) { + tmp=x->second+log(double(t->second)); + if (!isinf(tmp)) { + res = sumlog(res, tmp); + } + } + } + return res; + } + else { + // le dictionnaire n'est pas identique, on doit traduire le mot + Word v; + Word::const_iterator a; + Dictionnaire::const_iterator tl; + Dictionnaire::const_iterator tl2; + map traducteur; + for (tl = dico->begin() ; tl != dico->end() ; ++tl) + { + tl2 = alph.begin(); + while ((tl2 != alph.end()) && (tl2->second != tl->second)) + ++tl2; + if (tl2 == alph.end()) + { + cerr << "Erreur !!! SPFA::philog, bad dictionnary ! lettre " << tl->second << endl; + } + else + { + traducteur[tl->first] = tl2->first; + } + } + for (a=u.begin() ; a != u.end() ; ++a) { + v += traducteur[*a]; + } + + logforward(F,v); + res = log(0.0); + for (x=F.begin() ; x!=F.end() ; ++x) { + t = tau.find(x->first); + if (t != tau.end()) { + res = sumlog(res,x->second + log(double(t->second))); + } + } + return res; + } +} + +// ---------------- calcul des probas + +double SPFA::p_bar(const Word &u, const Dictionnaire * dico) const { + return exp(plog_bar(u)); +} + +double SPFA::plog_bar(const Word &u, const Dictionnaire * dico) const { + // PreciseSFunc F; + // PreciseSFunc::const_iterator f; + // double res; + // logforward(F,u); + // res = log(0.0); + // for (f=F.begin() ; f != F.end() ; f++) { + // res = sumlog(res, f->second); + // } + // return res; + // ------------- + + + PreciseSFunc F; + PreciseSFunc::const_iterator x; + SFunc::const_iterator t; + double res; + if ((dico == NULL) || (*dico == alph)) { + logforward(F,u); + res = log(0.0); + for (x=F.begin() ; x!=F.end() ; ++x) { + if (!isinf(x->second)) { + res = sumlog(res,x->second); + } + } + return res; + } + else { + // le dictionnaire n'est pas identique, on doit traduire le mot + Word v; + Word::const_iterator a; + Dictionnaire::const_iterator tl; + Dictionnaire::const_iterator tl2; + map traducteur; + for (tl = dico->begin() ; tl != dico->end() ; ++tl) + { + tl2 = alph.begin(); + while ((tl2 != alph.end()) && (tl2->second != tl->second)) + ++tl2; + if (tl2 == alph.end()) + { + cerr << "Erreur !!! SPFA::philog, bad dictionnary ! lettre " << tl->second << endl; + } + else + { + traducteur[tl->first] = tl2->first; + } + } + for (a=u.begin() ; a != u.end() ; ++a) { + v += traducteur[*a]; + } + + logforward(F,v); + res = log(0.0); + for (x=F.begin() ; x!=F.end() ; ++x) { + if (!isinf(x->second)) { + res = sumlog(res,x->second); + } + } + return res; + } + +} + +RESULT SPFA::forward(PreciseSFunc &F, const Word &u) const { + PreciseSFunc init; + SFunc::const_iterator q; + for (q=iota.begin() ; q!= iota.end() ; q++) + { + init[q->first] = q->second; + } + return forwardprecalc(F,u,init); +} + +RESULT SPFA::logforward( + PreciseSFunc &F, + const Word &u) const +{ + PreciseSFunc init; + SFunc::const_iterator q; + for (q=iota.begin() ; q!=iota.end() ; ++q) + { + init[q->first] = q->second; + } + return logforwardprecalc(F,u,init); +} + + +RESULT SPFA::forwardprecalc( + PreciseSFunc &F, + const Word &u, + const PreciseSFunc &init_vector) const +{ + F.clear(); + + PreciseSFunc V; + PreciseSFunc::const_iterator e; + Word::const_iterator a; + PreciseSFunc Vbis; + PreciseSFunc::iterator s; + Graph::const_iterator q; + LettreSFunc::const_iterator b; + SFunc::const_iterator r; + + + for (e = init_vector.begin (); e != init_vector.end (); ++e) { + if (e->second != 0) { + V[e->first] = e->second; + } + } + + for (a = u.begin (); a != u.end (); ++a) + { + Vbis.clear (); + for (s=V.begin() ; s != V.end() ; ++s) { + q=phi.find(s->first); + if (q != phi.end() ) { + b=q->second.find(*a); + if (b != q->second.end()) { + for (r=b->second.begin() ; r != b->second.end() ; ++r) { + if (Vbis.find(r->first) != Vbis.end()) { + Vbis[r->first] = Vbis[r->first] + r->second*s->second; + } + else { + Vbis[r->first] = r->second*s->second; + } + } + } + } + } + V = Vbis; + } + F=V; + return VAL(0); +} + +RESULT SPFA::logforwardprecalc( + PreciseSFunc &F, + const Word &u, + const PreciseSFunc &init_vector) const +{ + F.clear(); + + PreciseSFunc V; + PreciseSFunc::const_iterator e; + + for (e = init_vector.begin (); e != init_vector.end (); ++e) { + if (e->second != 0) { + V[e->first] = log (e->second); + } + } + + Word::const_iterator a; + PreciseSFunc Vbis; + PreciseSFunc::iterator s; + + Graph::const_iterator q; + LettreSFunc::const_iterator b; + SFunc::const_iterator r; + + for (a = u.begin (); a != u.end (); ++a) + { + Vbis.clear (); + for (s=V.begin() ; s != V.end() ; ++s) { + q=phi.find(s->first); + if (q != phi.end() ) { + b=q->second.find(*a); + if (b != q->second.end()) { + for (r=b->second.begin() ; r != b->second.end() ; ++r) { + if (Vbis.find(r->first) != Vbis.end()) { + Vbis[r->first] = sumlog(Vbis[r->first], + log(r->second) + s->second); + } + else { + Vbis[r->first] = log(r->second) + s->second; + } + } + } + } + } + V = Vbis; + + //~ for (e=Vbis.begin() ; e!=Vbis.end() ; ++e) { + //~ if (!isinf(e->second)) { + //~ V[e->first]=e->second; + //~ } + //~ } + } + F=V; + return VAL(0); +} + + +// ---------------- LA PARTIE BAULM WELCH + +RESULT SPFA::logforward( + list < PreciseSFunc > &F, + const Word &u) const +{ + PreciseSFunc init; + SFunc::const_iterator q; + for (q=iota.begin() ; q!=iota.end() ; ++q) + { + init[q->first] = q->second; + } + return logforwardprecalc(F,u,init); +} + +RESULT SPFA::logforwardprecalc( + list < PreciseSFunc > &F, + const Word &u, + const PreciseSFunc &init_vector) const +{ + F.clear(); + + PreciseSFunc V; + PreciseSFunc::const_iterator e; + for (e = init_vector.begin (); e != init_vector.end (); ++e) { + if (e->second != 0) { + V[e->first] = log (e->second); + } + } + F.push_back(V); + + Word::const_iterator a; + PreciseSFunc Vbis; + PreciseSFunc::iterator s; + + Graph::const_iterator q; + LettreSFunc::const_iterator b; + SFunc::const_iterator r; + + for (a = u.begin (); a != u.end (); ++a) + { + Vbis.clear (); + for (s=V.begin() ; s != V.end() ; ++s) { + q=phi.find(s->first); + if (q != phi.end() ) { + b=q->second.find(*a); + if (b != q->second.end()) { + for (r=b->second.begin() ; r != b->second.end() ; ++r) { + if (Vbis.find(r->first) != Vbis.end()) { + Vbis[r->first] = sumlog(Vbis[r->first], + log(r->second) + s->second); + } + else { + Vbis[r->first] = log(r->second) + s->second; + } + } + } + } + } + V = Vbis; + //~ for (e=Vbis.begin() ; e!=Vbis.end() ; ++e) { + //~ if (!isinf(e->second)) { + //~ V[e->first]=e->second; + //~ } + //~ } + F.push_back(V); + } + return VAL(0); +} + +RESULT SPFA::logbackward( + list < PreciseSFunc > &B, + const Word &u) const +{ + // copie de tau dans term + PreciseSFunc term; + SFunc::const_iterator q; + for (q=tau.begin() ; q != tau.end() ; ++q) + { + term[q->first]=q->second; + } + return logbackwardprecalc(B,u,term); +} + +RESULT SPFA::logbackwardprecalc( + list < PreciseSFunc > &B, + const Word &u, + const PreciseSFunc &term) const +{ + + B.clear(); + + PreciseSFunc::const_iterator e; + PreciseSFunc V; + for (e = term.begin (); e != term.end (); ++e) { + if (e->second != 0) { + V[e->first] = log (e->second); + } + } + + B.push_front(V); + + Word::const_reverse_iterator a; + Graph::const_iterator q; + LettreSFunc::const_iterator b; + SFunc::const_iterator s; + PreciseSFunc Vbis; + + + for (a = u.rbegin (); a != u.rend (); ++a) + { + Vbis.clear (); + for (q=phi.begin() ; q != phi.end() ; ++q) { + b=q->second.find(*a); + if (b != q->second.end()) { + for (s=b->second.begin() ; s != b->second.end() ; ++s) { + if (V.find(s->first) != V.end()) { + if (Vbis.find(q->first) == Vbis.end()) { + Vbis[q->first] = log(s->second) + V[s->first]; + } + else { + Vbis[q->first] = sumlog( Vbis[q->first], + log(s->second) + V[s->first]); + } + } + } + } + } + + V=Vbis; + B.push_front(V); + } + return VAL(0); +} + +// Compte le nombre de fois que l'on passe par chaque transition de +// facon pondÈree. +RESULT SPFA::TransitionCount(const Sample &S, + TransitionFunction &T, + SFunc &Iota, + SFunc &Tau) const +{ + TransitionFunction::iterator t; + SFunc::iterator s; + Sample::const_iterator u; + // on initialise le compte d'utilisation des transitions + for (t=T.begin() ; t != T.end() ; ++t) + { + t->second = 0; + } + for (s=Iota.begin() ; s != Iota.end() ; ++s) { + s->second = 0; + } + for (s=Tau.begin() ; s != Tau.end() ; ++s) { + s->second=0; + } + + for (u=S.begin() ; u != S.end() ; ++u) + { + TransitionCount(u->first, T, Iota, Tau, u->second); + //~ // ---- + //~ cout << "\t: " << affiche(u->first) << "," << u->second << " : "; + //~ for (t=T.begin() ; t != T.end() ; ++t) { + //~ cout << "("; + //~ cout << t->first.qdep << ","; + //~ cout << t->first.a << ","; + //~ cout << t->first.qarr << ")="; + //~ cout << t->second << ","; + //~ } + //~ for (s=Iota.begin() ; s != Iota.end() ; ++s) { + //~ cout << " i(" << s->first << ")=" << s->second; + //~ } + //~ for (s=Tau.begin() ; s!=Tau.end() ; ++s) { + //~ cout << " t(" << s->first << ")=" << s->second; + //~ } + //~ cout << endl; + //~ // ---- + } + return VAL(0); +} + + +// Compte le nombre de fois que l'on passe par chaque transition de +// facon pondÈree. +RESULT SPFA::TransitionCount(const Word &u, + TransitionFunction &T, + SFunc &Iota, + SFunc &Tau, + const int nb_occurences) const +{ + + // Algorithme renvoie sum_{t} \eta_t(i, a) + // \eta_t(i,a) = \alph_t(i) x \phi(i, w_t=a ,j) x \beta_t(j) / P(w) + // on calcule alpha et beta pour tout i + + list < PreciseSFunc > F; // forward + list < PreciseSFunc > B; // backward + list < PreciseSFunc >::const_iterator f; + list < PreciseSFunc >::const_iterator b; + logforward(F,u); + logbackward(B,u); + + + Word::const_iterator a; + PreciseSFunc::const_iterator x; + PreciseSFunc::const_iterator y; + Transition t; + double plogu=log(0.);// =plog(u); + double tmp; + + //~ // AFFICHAGE DE F et B + //~ cout << "Forward" << endl; + //~ for (f=F.begin() ; f != F.end() ; ++f) { + //~ for (x = f->begin() ; x != f->end() ; ++x) { + //~ cout << "(" << x->first << "," << x->second << ") "; + //~ } + //~ cout << endl; + //~ } + + //~ cout << "Backward" << endl; + //~ for (b=B.begin() ; b != B.end() ; ++b) { + //~ for (y = b->begin() ; y!=b->end() ; ++y) { + //~ cout << "(" << y->first << "," << y->second << ") "; + //~ } + //~ cout << endl; + //~ } + + f=F.begin(); + b=B.begin(); + for (x=f->begin() ; x != f->end() ; ++x) { + y=b->find(x->first); + plogu = sumlog(plogu, x->second + y->second); + } + + //~ cout << "plogu = " << plogu << endl; + //~ cout << "plogu calcule = " << plog(u) << endl; + + + f=F.begin(); + b=B.begin(); + for (x=f->begin() ; x != f->end() ; ++x) { + y=b->find(x->first); + if ((Iota.find(x->first) != Iota.end()) && (y != b->end())) { + tmp = exp(x->second + y->second + log(float(nb_occurences)) - plogu); + if (! isnan(tmp)) { + Iota[x->first] += tmp; + } + else { + cout << "IOTA nan : " << x->first; + cout << "," << y->first; + cout << ":" << x->second; + cout << " " << y->second; + cout << " " << log(float(nb_occurences)); + cout << " " << plogu; + cout << endl; + } + } + } + + f=--F.end(); + b=--B.end(); + for (x=f->begin() ; x != f->end() ; ++x) { + y = b->find(x->first); + if ((Tau.find(x->first) != Tau.end()) && (y != b->end())) { + tmp = exp(x->second + y->second + log(float(nb_occurences)) - plogu); + if (!isnan(tmp)) { + Tau[x->first] += tmp; + } + else { + cout << "TAU nan : " << x->first; + cout << "," << y->first; + cout << ":" << x->second; + cout << " " << y->second; + cout << " " << log(float(nb_occurences)); + cout << " " << plogu; + cout << endl; + } + } + } + + for (a = u.begin(), + f=F.begin() , + b=B.begin() , + b++ ; // on avance de ce qu'il faut + + a != u.end() ; + + ++a, ++f, ++b) + { + for (x=f->begin() ; x != f->end() ; ++x) + { + for (y=b->begin() ; y != b->end() ; ++y) + { + t.qdep = x->first; + t.a = *a; + t.qarr = y->first; + if (T.find(t) != T.end()) + { + if (val_phi(x->first, *a, y->first) != 0) { + tmp= exp(x->second + + y->second + + log(val_phi(x->first, *a, y->first)) - + plogu + log(float(nb_occurences))); + + if (!isnan(tmp)) { + T[t] +=tmp; + } + else { + cout << "PHI nan : " << x->first; + cout << "," << *a; + cout << "," << y->first; + cout << ":" << x->second; + cout << " " << y->second; + cout << " " << log(val_phi(x->first, *a, y->first)); + cout << " " << plogu; + cout << " " << log(float(nb_occurences)); + cout << endl; + } + } + } + } + } + } + return VAL(0); +} + +RESULT SPFA::BaumWelch(const Sample &S, + TransitionFunction &T, + SFunc &Iota, + SFunc &Tau, + int nb_tours, + bool verbose) +{ + + if (S.isprefixiel()) { + cerr << "BaumWelch():: Sample prefixiel !" << endl; + return ERR(1); + } + + // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + // Il faut Iota = tous les Ètats initiaux ou rien + // si (q,a,r) est dans T ou q dans Tau, il faut tous les (q,x,s) + tau(q). + // Sinon la renormalisation devient fausse + Sample::const_iterator u; + TransitionFunction::iterator t; + + // on initialise la probabilite de sortir de chaque etats + SFunc count_out; + Graph::const_iterator q; + LettreSFunc::const_iterator b; + SFunc::iterator s; +// int i=0; + double sum; + + while (nb_tours-- != 0) + { + //~ if (verbose) + //~ { + //~ cout << "[BM " << nb_tours << "] "; + //~ cout.flush(); + //~ } + + TransitionCount(S,T,Iota,Tau); + + for (t=T.begin() ; t != T.end() ; ++t) { + count_out[t->first.qdep] += t->second; + } + for (s=Tau.begin() ; s!=Tau.end() ; ++s) { + count_out[s->first] += s->second; + } + sum=0; + for (s=Iota.begin() ; s!= Iota.end() ; ++s) { + sum +=s->second; + } + + for (t=T.begin() ; t != T.end() ; ++t) + { + if (t->second != 0) { + SPFA::addTransition(t->first, t->second / count_out[t->first.qdep]); + } + else { + SPFA::addTransition(t->first, 0); + } + } + for (s=Tau.begin() ; s != Tau.end() ; ++s) { + if (s->second != 0) { + tau[s->first]= s->second / count_out[s->first]; + } + else { + tau[s->first]=0; + } + } + for (s=Iota.begin() ; s != Iota.end() ; ++s) { + iota[s->first] = s->second / sum; + } + + erase_transitions(); + + //~ if (verbose) + //~ { + //~ cout << endl; + //~ for (t=T.begin() ; t != T.end() ; ++t) + //~ { + //~ cout << "("; + //~ cout << t->first.qdep; + //~ cout << ","; + //~ cout << t->first.a; + //~ cout << ","; + //~ cout << t->first.qarr; + //~ cout << ")="; + //~ cout << t->second / count_out[t->first.qdep]; + //~ if (++i%5 == 0) cout << "\n"; + //~ else cout << " "; + //~ } + //~ for (s = Tau.begin() ; s != Tau.end() ; ++s) { + //~ cout << "t(" << s->first << ")=" << s->second / count_out[s->first]; + //~ if (++i%5 == 0) cout << "\n"; + //~ else cout << " "; + //~ } + //~ for (s = Iota.begin() ; s != Iota.end() ; ++s) { + //~ cout << "i(" << s->first << ")=" << s->second / sum; + //~ if (++i%5 == 0) cout << "\n"; + //~ else cout << " "; + //~ } + //~ cout << endl; + //~ } + + count_out.clear(); + } + + return VAL(0); +} + +// fonction qui calcule les probas qui sortes d'un Ètat +// transitions + arret +float SPFA::val_outstate(const State q) const { + float sum; + Graph::const_iterator r; + LettreSFunc::const_iterator a; + SFunc::const_iterator s; + + sum=val_tau(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) { + sum += s->second; + } + } + } + return sum; +} + +RESULT SPFA::erase_bad_states(void) { + + StateSet::iterator q; + LettreSFunc::iterator a; + SFunc::iterator s; + for (q=Q.begin() ; q != Q.end() ; ++q) { + if (val_outstate(*q) == 0) { + erase(*q); + } + } + return VAL(0); +} diff --git a/test.H b/test.H new file mode 100644 index 0000000..a9d8342 --- /dev/null +++ b/test.H @@ -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); diff --git a/test.cpp b/test.cpp new file mode 100644 index 0000000..f593bfb --- /dev/null +++ b/test.cpp @@ -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 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(); +} diff --git a/toto b/toto new file mode 100644 index 0000000..e69de29 diff --git a/ySimplex.cpp b/ySimplex.cpp new file mode 100644 index 0000000..e3b2adb --- /dev/null +++ b/ySimplex.cpp @@ -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(dsecond = -(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 systme :" << 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