SCIP: How to resolve LP after catching a 'node infeasibility' event, - c++

I have a working column generation algorithm in SCIP. Due to specific constraints that I include while generating columns, it might happen that the last pricing round determines that the root node is infeasible (by the Farkas pricer of course).
In case that happens, I would like to 1) relax those specific constraints, 2) resolve the LP, and 3) start pricing columns again.
So, I have created my own EventHandler class, catching the node infeasibility event:
SCIP_DECL_EVENTINITSOL(EventHandler::scip_initsol)
{
SCIP_CALL( SCIPcatchEvent(scip_, SCIP_EVENTTYPE_NODEINFEASIBLE, eventhdlr, NULL, NULL));
return SCIP_OKAY;
}
And, corresponding, the scip_exec virtual method:
SCIP_DECL_EVENTEXEC(EventHandler::scip_exec)
{
double cur_rhs = SCIPgetRhsLinear(scip_, *d_varConsInfo).c_primal_obj_cut);
SCIPchgRhsLinear (scip_, (*d_varConsInfo).c_primal_obj_cut, cur_rhs + DELTA);
return SCIP_OKAY;
}
Where (*d_varConsInfo).c_primal_obj_cut is the specific constraint to be changed, DELTA is a global parameter, and cur_rhs is the current right hand side of the specific constraint. This function is neately called after the node infeasibility proof, however, I do not know how to 'tell' scip that the LP should be resolved and possible new columns should be included. Can somebody help me out with this?

When the event handler catches the NODEINFEASIBLE event, it is already too late to change something about the infeasibility of the problem, the node processing is already finished. Additionally, you are not allowed to change the rhs of a constraint during the solving process (because this means that reductions done before would potentially be invalid).
I would suggest the following: if your Farkas pricing is not able to identify new columns to render the LP feasible again, the node will be declared to be infeasible in the following. Therefore, at the end of Farkas pricing (if you are at the root node), you could just price an auxiliary variable that you add to the constraint that you want to relax, with bounds corresponding to your DELTA. Note that you need to have marked the constraint to be modifiable when creating it. Then, since a variable was added, SCIP will trigger another pricing round.

maybe you should take a look into the PRICERFARKAS method of SCIP (https://scip.zib.de/doc/html/PRICER.php#PRICER_FUNDAMENTALCALLBACKS).
If the current LP relaxation is infeasible, it is the task of the
pricer to generate additional variables that can potentially render
the LP feasible again. In standard branch-and-price, these are
variables with positive Farkas values, and the PRICERFARKAS method
should identify those variables.

Related

Entity component architecture : want to split big entity -> hard to refactor

In the first step of development, I design Car and AI as 1 entity.
It works nice (pseudo code):-
for(every entity that is "racing car"){
//^ know type by using flag
// or iterate special component (e.g. "RacingCarComponent")
Entity entity=...
AI* ai=get<AI>(entity);
ai->setInformation(...)
}
for(every entity that is "bicycle"){
Entity entity=...
AI* ai=get<AI>(entity);
ai->setInformation(...) //the info is very different from "racing car"
}
Later, I want a new feature : switch in-out Driver (which effect AI).
I split the entity as shown in the following diagram :-
The above code will be updated to be :-
for(every entity that is "racing car"){
Entity entity=...
AttachAI* aiAttach=get<AttachAI>(entity); //<-- edit
aiAttach->ai->setInformation(...) //<-- edit
}
for(every entity that is "bicycle"){
Entity entity=...
AttachAI* aiAttach=get<AttachAI>(entity); //<-- edit
aiAttach->ai->setInformation(...) //<-- edit
}
Problem
It works nice both before and after the change, but it is hard to maintain.
If there are N types of vehicle in version1 e.g. truck, motercycle, plane, boat, rocket,
I will have to edit N*2 lines of which potentially have already scattered around many .cpp.
Main issue : If I forget to refactor any code, it will still compile fine.
Problem will appear in only run-time.
In real life, I face such issue whenever new design wish to divide an entity into many simpler entities.
The refactoring is always just adding another one indirection.
Question
Suppose that in version1, I don't expect that I will want to switch in/out Driver.
Is it possible to prevent the problem? How?
I may be mistaken, but it seems as though you may be looping through all of the entities multiple times, checking a condition. I am not exactly sure about c++ syntax, so please bear with me:
for (entities as entity) {
info = null;
//Check type to get specific info
if (type is a "racing car"){
info = "fast car";
}
elseif (type is a "bicycle") {
info = "rad spokes";
}
//If we found info, we know we had a valid type
if (info isnt null) {
aiAttach = get(entity);
aiAttach->ai->setInformation(info);
}
}
I'm not sure if the get function requires anything specific for each type. In my pseudocode example, I assume we are only sending the entity and not something type specific. If it does, an additional variable could be used.

c++ best way to realise global switches/flags to control program behaviour without tying the classes to a common point

Let me elaborate on the title:
I want to implement a system that would allow me to enable/disable/modify the general behavior of my program. Here are some examples:
I could switch off and on logging
I could change if my graphing program should use floating or pixel coordinates
I could change if my calculations should be based upon some method or some other method
I could enable/disable certain aspects like maybe a extension api
I could enable/disable some basic integrated profiler (if I had one)
These are some made-up examples.
Now I want to know what the most common solution for this sort of thing is.
I could imagine this working with some sort of singelton class that gets instanced globally or in some other globally available object. Another thing that would be possible would be just constexpr or other variables floating around in a namespace, again globally.
However doing something like that, globally, feels like bad practise.
second part of the question
This might sound like I cant decide what I want, but I want a way to modify all these switches/flags or whatever they are actually called in a single location, without tying any of my classes to it. I don't know if this is possible however.
Why don't I want to do that? Well I like to make my classes somewhat reusable and I don't like tying classes together, unless its required by the DRY principle and or inheritance. I basically couldn't get rid of the flags without modifying the possible hundreds of classes that used them.
What I have tried in the past
Having it all as compiler defines. This worked reasonably well, however I didnt like that I couldnt make it so if the flag file was gone there were some sort of default settings that would make the classes themselves still operational and changeable (through these default values)
Having it as a class and instancing it globally (system class). Worked ok, however I didnt like instancing anything globally. Also same problem as above
Instancing the system class locally and passing it to the classes on construction. This was kinda cool, since I could make multiple instruction sets. However at the same time that kinda ruined the point since it would lead to things that needed to have one flag set the same to have them set differently and therefore failing to properly work together. Also passing it on every construction was a pain.
A static class. This one worked ok for the longest time, however there is still the problem when there are missing dependencies.
Summary
Basically I am looking for a way to have a single "place" where I can mess with some values (bools, floats etc.) and that will change the behaviour of all classes using them for whatever, where said values either overwrite default values or get replaced by default values if said "place" isnt defined.
If a Singleton class does not work for you , maybe using a DI container may fit in your third approach? It may help with the construction and make the code more testable.
There are some DI frameworks for c++, like https://github.com/google/fruit/wiki or https://github.com/boost-experimental/di which you can use.
If you decide to use switch/flags, pay attention for "cyclometric complexity".
If you do not change the skeleton of your algorithm but only his behaviour according to the objets in parameter, have a look at "template design pattern". This method allow you to define a generic algorithm and specify particular step for a particular situation.
Here's an approach I found useful; I don't know if it's what you're looking for, but maybe it will give you some ideas.
First, I created a BehaviorFlags.h file that declares the following function:
// Returns true iff the given feature/behavior flag was specified for us to use
bool IsBehaviorFlagEnabled(const char * flagName);
The idea being that any code in any of your classes could call this function to find out if a particular behavior should be enabled or not. For example, you might put this code at the top of your ExtensionsAPI.cpp file:
#include "BehaviorFlags.h"
static const enableExtensionAPI = IsBehaviorFlagEnabled("enable_extensions_api");
[...]
void DoTheExtensionsAPIStuff()
{
if (enableExtensionsAPI == false) return;
[... otherwise do the extensions API stuff ...]
}
Note that the IsBehaviorFlagEnabled() call is only executed once at program startup, for best run-time efficiency; but you also have the option of calling IsBehaviorFlagEnabled() on every call to DoTheExtensionsAPIStuff(), if run-time efficiency is less important that being able to change your program's behavior without having to restart your program.
As far as how the IsBehaviorFlagEnabled() function itself is implemented, it looks something like this (simplified version for demonstration purposes):
bool IsBehaviorFlagEnabled(const char * fileName)
{
// Note: a real implementation would find the user's home directory
// using the proper API and not just rely on ~ to expand to the home-dir path
std::string filePath = "~/MyProgram_Settings/";
filePath += fileName;
FILE * fpIn = fopen(filePath.c_str(), "r"); // i.e. does the file exist?
bool ret = (fpIn != NULL);
fclose(fpIn);
return ret;
}
The idea being that if you want to change your program's behavior, you can do so by creating a file (or folder) in the ~/MyProgram_Settings directory with the appropriate name. E.g. if you want to enable your Extensions API, you could just do a
touch ~/MyProgram_Settings/enable_extensions_api
... and then re-start your program, and now IsBehaviorFlagEnabled("enable_extensions_api") returns true and so your Extensions API is enabled.
The benefits I see of doing it this way (as opposed to parsing a .ini file at startup or something like that) are:
There's no need to modify any "central header file" or "registry file" every time you add a new behavior-flag.
You don't have to put a ParseINIFile() function at the top of main() in order for your flags-functionality to work correctly.
You don't have to use a text editor or memorize a .ini syntax to change the program's behavior
In a pinch (e.g. no shell access) you can create/remove settings simply using the "New Folder" and "Delete" functionality of the desktop's window manager.
The settings are persistent across runs of the program (i.e. no need to specify the same command line arguments every time)
The settings are persistent across reboots of the computer
The flags can be easily modified by a script (via e.g. touch ~/MyProgram_Settings/blah or rm -f ~/MyProgram_Settings/blah) -- much easier than getting a shell script to correctly modify a .ini file
If you have code in multiple different .cpp files that needs to be controlled by the same flag-file, you can just call IsBehaviorFlagEnabled("that_file") from each of them; no need to have every call site refer to the same global boolean variable if you don't want them to.
Extra credit: If you're using a bug-tracker and therefore have bug/feature ticket numbers assigned to various issues, you can creep the elegance a little bit further by also adding a class like this one:
/** This class encapsulates a feature that can be selectively disabled/enabled by putting an
* "enable_behavior_xxxx" or "disable_behavior_xxxx" file into the ~/MyProgram_Settings folder.
*/
class ConditionalBehavior
{
public:
/** Constructor.
* #param bugNumber Bug-Tracker ID number associated with this bug/feature.
* #param defaultState If true, this beheavior will be enabled by default (i.e. if no corresponding
* file exists in ~/MyProgram_Settings). If false, it will be disabled by default.
* #param switchAtVersion If specified, this feature's default-enabled state will be inverted if
* GetMyProgramVersion() returns any version number greater than this.
*/
ConditionalBehavior(int bugNumber, bool defaultState, int switchAtVersion = -1)
{
if ((switchAtVersion >= 0)&&(GetMyProgramVersion() >= switchAtVersion)) _enabled = !_enabled;
std::string fn = defaultState ? "disable" : "enable";
fn += "_behavior_";
fn += to_string(bugNumber);
if ((IsBehaviorFlagEnabled(fn))
||(IsBehaviorFlagEnabled("enable_everything")))
{
_enabled = !_enabled;
printf("Note: %s Behavior #%i\n", _enabled?"Enabling":"Disabling", bugNumber);
}
}
/** Returns true iff this feature should be enabled. */
bool IsEnabled() const {return _enabled;}
private:
bool _enabled;
};
Then, in your ExtensionsAPI.cpp file, you might have something like this:
// Extensions API feature is tracker #4321; disabled by default for now
// but you can try it out via "touch ~/MyProgram_Settings/enable_feature_4321"
static const ConditionalBehavior _feature4321(4321, false);
// Also tracker #4222 is now enabled-by-default, but you can disable
// it manually via "touch ~/MyProgram_Settings/disable_feature_4222"
static const ConditionalBehavior _feature4222(4222, true);
[...]
void DoTheExtensionsAPIStuff()
{
if (_feature4321.IsEnabled() == false) return;
[... otherwise do the extensions API stuff ...]
}
... or if you know that you are planning to make your Extensions API enabled-by-default starting with version 4500 of your program, you can set it so that Extensions API will be enabled-by-default only if GetMyProgramVersion() returns 4500 or greater:
static ConditionalBehavior _feature4321(4321, false, 4500);
[...]
... also, if you wanted to get more elaborate, the API could be extended so that IsBehaviorFlagEnabled() can optionally return a string to the caller containing the contents of the file it found (if any), so that you could do shell commands like:
echo "opengl" > ~/MyProgram_Settings/graphics_renderer
... to tell your program to use OpenGL for its 3D graphics, or etc:
// In Renderer.cpp
std::string rendererType;
if (IsDebugFlagEnabled("graphics_renderer", &rendererType))
{
printf("The user wants me to use [%s] for rendering 3D graphics!\n", rendererType.c_str());
}
else printf("The user didn't specify what renderer to use.\n");

How to sort with beginMoveRows without persistent index corruption / duplication?

I'm trying to use beginMoveRows / endMoveRows to make persistent indexes stick, but sometimes expanded state flags / persistent indexes are duplicated, where they should not be.
There is quite a lot of code, so I'll go through what I think I have told the machine to do:
There is a method, sortChildrenOf(item) which does all the magic.
Find children from item and call sortChildrenOf with each child as a
parameter
save old order
quickSort children
find differences in old order and the new
for each difference:
beingMoveRows
apply change
endMoveRows
Everything works perfectly when there are 2 levels, but when I input a "long" tree of data, persistent indexes get corrupted.
The data in the tree is updated from network, but the actual update is done in the gui thread.
Is there some precise order I should do stuff in? Might I have forgotten to inherit some method that causes this?
I'v got these methods implemented:
- data
- flags
- getItem
- index
- parent
- setData
Edit:
forgot to mention, i got emit layoutAboutToBeChanged and emit layoutChanged before and after the main sortChildrenOf call.
I got it to work, but not with beginMoveRows and endMoveRows. I used the old system of emitting layoutAboutToChange getting the list of persistent indexes manipulating that and setting it back with changePersistentIndexList and finally emitting layout changed.
Since this was the fix, I'm lead to believe that there is some bug withtin beginMoveRows, endMoveRows and persistent indexes with tree type data.
Ask if you need a better example of the code.

Am I violating an OOP design guideline here? Couple of interesting design pickles

I'm designing a new power-up system for a game I'm creating. It's a side scroller, the power ups appear as circular objects and the player has to touch / move through them to pick up their power. The power up then becomes activated, and deactivates itself a few seconds later. Each power-up has its own duration defined. For simplicity's sake the power ups are spawned (placed on the screen) every X seconds.
I created a PowerUpManager, a singleton whose job is to decide when to create new power ups and then where to place them.
I then created the Powerup base class, and a class that inherits from that base class for every new Powerup. Every Power-up can be in one of three states: Disabled, placed on the screen, and picked up by the player. If the player did not pick up the power up but moved on, the power up will exit the screen and should go back from the placed state to the disabled state, so it can be placed again.
One of the requirements (that I) put in place is that there should be minimal code changes when I code up a new Power up class. The best I could do was one piece of code: The PowerUpManager's constructor, where you must add the new power-up to the to the container that holds all power-ups:
PowerupManager::PowerupManager()
{
available = {
new PowerupSpeed(),
new PowerupAltWeapon(),
...
};
}
The PowerUpManager, in more details (Question is coming up!):
Holds a vector of pointers to PowerUp (The base class) called available. This is the initial container that holds one copy of each power up in the game.
To handle the different states, it has a couple of lists: One that holds pointers to currently placed power ups, and another list that holds pointers to currently active power ups.
It also has a method that gets called every game tick that decides if and where to place a new power up and clean up power ups that weren't picked up. Finally it has a method that gets called when the player runs into a power up, that activates the power up (Moves it from the placed to the active list, and calls the power up's activate method).
Finally, once you understand the full picture, the question:
I needed a way for client code to ask if a particular power-up is currently active. For example: The player has a weapon, but there is a power up that replaces that weapon temporarily. Where I poll for input and recognize that the player wants to fire his weapon, I need to call the correct fire method - The alternative weapon power up fire method, and not the regular weapon fire method.
I thought of this particular demand for a while and came up with this:
template <typename T>
T* isActivated() // Returns a pointer to the derived Powerup if it exists in the activated list, or nullptr if it doesn't
{
for(Powerup *i : active) // Active is a list of currently active power ups
{
T *result = dynamic_cast<T*>(i);
if(result)
return result;
}
return nullptr;
}
So client code looks like this:
PowerUpAltWeapon *weapon = powerUpManager->isActivated<PowerUpAltWeapon>();
if(weapon)
...
I thought the solution is elegant and kind of neat, but essentially what it is is trying to convert a base type to a derived type. If that doesn't work, you try the next derived type... A long chain of if / else if, it's just disguised in a loop. Does this violate the guideline that I just described? Not casting a base type to all of its derived types in a long chain of if / else if until you get a hit? Is there another solution?
A secondary question is: Is there a way to get rid of the need to construct all the different power ups in the PowerupManager constructor? That is currently the only place you need to make a change if you want to introduce a new power up. If I can get rid of that, that'd be interesting...
This is based on your design, but if it was me I choose an ID for each PowerUp and a set of IDs in the client, and each time a user posses a PowerUp that ID will be added to its set and ... you know the rest. Using this technique I can do fast look up for every PowerUp and avoid dynamic_cast:
std::set<PowerUp::ID> my_powerUps;
template< class T > bool isActivated() {
return my_powerUps.find( T::id() ) != my_powerUps.end();
}
And about your second question, I have a similar program that load some plugins instead of PowerUp, I have a pure virtual base class that contain all methods that required by that plugin and implement it in shared modules and then at startup I load them from an specific folder. For example each shared module contain a create_object that return a plugin* (in your case PowerUp* of course) and then I iterate the folder, load modules and call create_object to create my plugins from them and register them in my plugin_manager

Suggested flow-control structure for order-dependant operations

I've run into the following issue which is not difficult to solve by any stretch of the imagination but I would like to know what the best / most elegant solution is.
I have the following method that the prototype of looks like this:
bool Team::isEveryoneDead(int teamOnTurn);
There are two teams available and depending on what instance of the team is currently on turn, I would like to check whether every Character in the team is dead in this very particular order:
Loop trough all the Characters in the team that's not on turn first. Should there be any character that's alive, stop looping (and goto step 2.). Should there be noone alive, terminate the function and return.
Now that I know that the team that's not on turn contains at least one character that's alive, loop trough the team that's currently on turn and check for the same thing. Should I find someone alive, stop looping and terminate / return.
The argument int teamOnTurn allows me to resolve the instance of Team that's currently on turn. The order in which i evaluate the "alive condition" is of great importance here.
Now, there are several approaches that can be taken, say hardcoding the order (since there are only 2 possible orders) and resolving the order by checking who's on turn and then executing the branch that already has the specific order like this:
bool Team::isEveryoneDead(int teamOnTurn) {
if (Team::Blue == teamOnTurn) {
checkThis();
checkThat();
} else {
checkThat();
checkThis();
}
}
This solution however wouldn't quite work for say 5! permutations for specific call-ordering for more items. What technique should one deploy to solve this with the utmost elegance :) ?
Thanks in advance, Scarlet.
Try creating another internal method that actually does the checking, and let the isEveryoneDead() method orchestrate the order in which the teams are checked, maybe something like this:
bool Team::isEveryoneDead(int teamOnTurn) {
bool isFound = isEveryoneDeadInternal( /* params for team not on turn */ );
if(isFound) {
isFound = isEveryoneDeadInternal( /* params for team on turn */ );
}
return isFound;
}
// This method know nothing about on turn or off turn
bool Team:isEveryoneDeadInternal() {
// Loop through all characters in the team, checking if any are alive
// When the first live character is found, return true
// else return false
}
This is a concept called DRY : Dont Repeat Yourself