For a better structure of my Constraints, I want to summarize multiple constraints into a block, so that a don't have to scroll through a long list of separate functions representing my constraints.
My problem is that I'm using an Abstract model and don't know how to define that Block for a set that has not been initialized yet
M.s = pe.Set(dimen=1)
M.chp_minPower = pe.Param(within=pe.Reals,mutable=True)
M.chp_maxPower = pe.Param(within=pe.Reals,mutable=True)
M.chp_posGrad = pe.Param(within=pe.Reals,mutable=True)
M.chp_negGrad = pe.Param(within=pe.Reals,mutable=True)
M.chp_k = pe.Param(within=pe.Reals,mutable=True)
M.chp_c = pe.Param(within=pe.Reals,mutable=True)
M.chp_f1 = pe.Param(within=pe.Reals,mutable=True)
M.chp_f2 = pe.Param(within=pe.Reals,mutable=True)
M.gasCost = pe.Param(within=pe.Reals,mutable=True)
M.chpOn = pe.Var(M.s, within=pe.Binary)
M.chpSwitchON = pe.Var(M.s,within=pe.Binary)
M.chpPel = pe.Var(M.s,within=pe.NonNegativeReals)
M.chpPth = pe.Var(M.s, within=pe.NonNegativeReals)
M.chpQGas = pe.Var(M.s, within=pe.NonNegativeReals)
def chp_block_rule1(nb,i):
#Constraints
nb.chpPelMax = pe.Constraint(expr=M.chpPel[i] <= M.chp_maxPower * M.chpOn[i])
nb.chpPelMin = pe.Constraint(expr=M.chpPel[i] >= M.chp_minPower * M.chpOn[i])
#b.sellBin = pe.Constraint(expr=b.sell[i]/M.maxSell <= M.sellBin[i]
nb.chpCogen = pe.Constraint(expr=M.chpPth[i] == M.chp_f1 * M.chpPel[i] + M.chp_f2 * M.chpOn[i])
nb.chpConsumption = pe.Constraint(expr=M.chpQGas[i] == M.chp_c * M.chpOn[i] + M.chp_k + M.chpPel[i])
M.chp_block = pe.Block(M.s, rule=chp_block_rule1)
ValueError: Error retrieving component chpPel[1]: The component has
not been constructed.
Does anybody know how to work with blocks in Abstract models?
I'm not 100% sure but I guess expr tries to actually evaluate the expression, and because chpPel is a variable (thus has no value) it breaks.
In order to delay the evaluation of the expression (i.e. pass the expression into the solver as symbolic), you can use rule instead of expr.
As you probably know rule takes a function. If the expression is short enough, you can use a lambda function.
nb.chpPelMax = pe.Constraint(rule=lambda M: M.chpPel[i] <= M.chp_maxPower * M.chpOn[i])
Side note: you can just use list(range(...)) instead of the list comprehension.
Related
I have estimated nested logit in R using the mlogit package. However, I encountered some problems when trying to estimate the marginal effect. Below is the code I implemented.
library(mlogit)
# data
data2 = read.csv(file = "neat_num_energy.csv")
new_ener2 <- mlogit.data(
data2,
choice="alter4", shape="long",
alt.var="energy_altern",chid.var="id")
# estimate model
nest2 <- mlogit(
alter4 ~ expendmaint + expendnegy |
educ + sex + ppa_power_sp + hu_price_powersupply +
hu_2price +hu_3price + hu_9price + hu_10price +
hu_11price + hu_12price,
data = data2,
nests = list(
Trad = c('Biomas_Trad', 'Solar_Trad'),
modern = c('Biomas_Modern', 'Solar_Modern')
), unscaled=FALSE)
# create Z variable
z3 <- with(data2, data.frame(
expendnegy = tapply(expendnegy, idx(nest2,2), mean),
expendmaint= tapply(expendmaint, idx(nest2,2), mean),
educ= mean(educ),
sex = mean(sex),
hu_price_powersupply = mean(hu_price_powersupply),
ppa_power_sp = mean(ppa_power_sp),
hu_2price = mean(hu_2price),
hu_3price = mean(hu_3price),
hu_9price = mean(hu_9price),
hu_10price = mean(hu_10price),
hu_11price = mean(hu_11price),
ppa_power_sp = mean(ppa_power_sp),
hu_12price = mean(hu_12price)
))
effects(nest2, covariate = "sex", data = z3, type = "ar")
#> ** Error in Solve.default (H, g[!fixed]): Lapack routine dgesv: #> system is exactly singular:U[6,6] =0.**
My data is in long format with expendmaint and expendnegy being the only alternative specific while every other variable is case specific.
altern4 is a nominal variable representing each alternative
How can I add a method to the string table and modify self inside it ?
Basically, I'm trying to mimic the behaviour of the io.StringIO.read method in python, which reads n char in the string and returns them, modifying the string by "consuming" it.
I tried this:
function string.read(str, n)
to_return = str:sub(1, n)
str = str:sub(n + 1)
return to_return
end
local foo = "heyfoobarhello"
print(string.read(foo, 3))
print(foo)
Output is:
hey
heyfoobarhello
I expected the second line to be only foobarhello.
How can I achieve this ?
To mimic Python's io.StringIO class, you must make an object that stores both the underlying string and the current position within that string. Reading from an IO stream normally does not modify the underlying data.
local StringIO_mt = {
read = function(self, n)
n = n or #self.buffer - self.position + 1
local result = self.buffer:sub(self.position, self.position + n - 1)
self.position = self.position + n
return result
end,
}
StringIO_mt.__index = StringIO_mt
local function StringIO(buffer)
local o = {buffer = buffer, position = 1}
setmetatable(o, StringIO_mt)
return o
end
local foo = StringIO"heyfoobarhello"
print(foo:read(3))
print(foo:read())
Output:
hey
foobarhello
I don't recommend adding this class or method to Lua's string library, because the object has to be more complex than just a string.
You can add methods to the datatype string independently from the string table.
Short example that shows that the string methods even work if string table gets deleted...
string=nil
return _VERSION:upper():sub(1,3)
-- Returning: LUA
So you can add a method...
-- read.lua
local read = function(self, n1, n2)
return self:sub(n1, n2)
end
getmetatable(_VERSION).__index.read=read
return read
...for all strings.
( Not only _VERSION )
And use it...
do require('read') print(_VERSION:read(1,3):upper()) end
-- Print out: LUA
I am currently trying to implement some different actions instead of attack, but I want to focus on a party function, that looks like this, I can figure out the types of actions I want but I want to change the battle function to fit into a role that can accept multiple actions and not just attack
func change_party(inventory,index): # Inventory being if enemy or player
if inventory[index].fainted == false: # Checks if the monster is not dead
var hold = inventory[0] # Holds the first slot and then applys it later to the selected slot
inventory[0] = inventory[index]
inventory[index] = hold
This changes the index that was inputed by buttons and swaps it around with the first slot in the array this is because the first slot is what monster is shown first, I also have this battle function:
func _battle():
participants = [player_inventory[0],enemy_inventory[0]]
participants.sort_custom(self, "check_speed")
for attacker in participants:
var player_move = player_inventory[0].move_slot[action_index]
var random_move = randi() % 3 + 1
var enemy_move = attacker.move_slot[0] # Use random_move currently 0
var target = _choose_target(attacker, participants)
if attacker == player_inventory[0]:
yield(attack(attacker, target, player_move), "completed")
else:
yield(attack(attacker, target, enemy_move), "completed")
if player_inventory[0].current_hp <= 0:
player_inventory[0].current_hp = 0
player_inventory[0].fainted = true
Battle_Ui_Updater()
self.current_state = GameState.LOST
return
if enemy_inventory[0].current_hp <= 0:
enemy_inventory[0].current_hp = 0
enemy_inventory[0].fainted = true
Battle_Ui_Updater()
self.current_state = GameState.WON
return
self.current_state = GameState.ACTION
One solution that came to me was trying to have all the actions in a array and just call the action I want based on input but I have no clue how I would make that look readable or bug-free
In this function is how it decides who´s turn it is based on speed, but sometimes I want the player to go first for example when I want to change party members and when the player has changed I want the enemy to start attacking, But I am scratching my head on how would I make it change actions, I know the attack function should be changed if I want it to do something else but I also want to be able to control who´s turn based on what type of action is used, I am sorry if I didnt explain it well, hope you guys understand, I don't want to repeat my self by making another similar to battle function so how do I avoid being repetitive while also doing what I want?
BattleScript:
func attack(attacker, target, move):
print(str(attacker.name) + " used " + str(move.name) + " " + str((move)))
var new_text = (attacker.name + " attacked with " + move.name)
text_scroller(new_text)
var data = recieve_damage(move,attacker,target)
#var data = target.take_damage(move,attacker) # Calls the function to take damage
yield(get_tree().create_timer(2), "timeout") #Wait for 2 seconds
Battle_Ui_Updater()
if data:
yield(critical_hit(attacker),"completed")
func critical_hit(attacker):
var new_text = (attacker.name + " has landed a critical hit! ")
text_scroller(new_text)
print(attacker.name + " has landed a critical hit!")
yield(get_tree().create_timer(2.5), "timeout")
func Get_effectiveness(attack_type,defence_type):
if attack_type == TypeData.types.none or defence_type == TypeData.types.none:
return 1
print("row : " + str(attack_type))
print("col : " + str(defence_type))
return TypeData.chart[attack_type][defence_type]
func recieve_damage(action,attacker,defender):
var critical = 1
var critical_chance = randi() % 100 + 1
if critical_chance <= 6.25:
critical = 2
var attack_mode
var defence_mode
if action.is_special == true:
attack_mode = attacker.special_attack
defence_mode = defender.special_defence
else:
attack_mode = attacker.attack
defence_mode = defender.defence
var type : float = Get_effectiveness(action.type,defender.type_1) * Get_effectiveness(action.type,defender.type_2)
var modifier : float = rand_range(0.85,1.0) * type * critical
var a : float = (2.0 * attacker.level / 5.0 + 2.0)
var b : float = (a * attack_mode * action.power / defence_mode) / 50.0
var c : float = (b + 2.0) * modifier
var damage = int(c)
defender.current_hp -= damage
print(str(attacker.name) + " = " + str(damage))
return critical > 1
Swap Party member with the current one:
func change_party(inventory,index):
if inventory[index].fainted == false:
var hold = inventory[0]
inventory[0] = inventory[index]
inventory[index] = hold
print(inventory[0].hp)
Battle_Ui_Updater()
move_ui_updater(player_inventory[0])
yield(get_tree().create_timer(2),"timeout")
I came up with this:
class_name Task
class Skipper:
signal skip
func emit() -> void:
emit_signal("skip")
var _instance:Object
var _method:String
var _parameters:Array
var _result = null
func _init(instance:Object, method:String, parameters:Array = []) -> void:
_instance = instance
_method = method
_parameters = parameters
func execute():
var instance = _instance
var parameters = _parameters
if instance != null and instance.has_method(_method):
_instance = null
_parameters = []
_result = instance.callv(_method, parameters)
if _result is GDScriptFunctionState && _result.is_valid():
_result = yield(_result, "completed")
return _result
var skipper = Skipper.new()
skipper.call_deferred("emit")
yield(skipper, "skip")
return _result
And this is how you initialize it:
var parameters = [player_inventory[0], enemy_inventory[0], player_inventory[0].move_slot[action_index]]
player_action = Task.new(self, "attack", parameters)
And this is how you use it:
yield(player_action.execute(), "completed")
The new thing about this class is that it will be asynchronous regardless of whether the method it calls is asynchronous or not (so you don't have to worry if what it calls yields or not). And it will complete after the method it calls completes, either way. And it even returns (null if what it calls does not return)!
Note: This code will memoize the result, and get rid of the parameters and instance it was linked to. Subsequent calls to execute will simply return the memoized result. This way it does not hold references unecesarily.
How do we do that?
Well, first of all, we are using callv to call a method by name with an array of parameters. There is a class FuncRef in Godot that can be used in similar fashion. However, not using it resulted more convinient.
Second, calling something asynchronous would be yield(..., "completed") but we don't know if what we are calling is asynchronous. So we check. How? If it is asynchronous, it actually returns the state it left the execution as a GDScriptFunctionState, so we check that.
If it is GDScriptFunctionState, then we can use yield(..., "completed") on it.
If it isn't. We need to somehow make the function asynchronous. We are going to do that by emitting a signal with call_deferred. I decided in making it an inner class so that it is not exposed outside of the script.
Also note that the code checks if the instance is not null and has the method passed. But if it does not, it will simply return the result it had stored. This is part of the memoization mechanism, however, it also means that you have no feedback if you passed the wrong instance of wrote the method name wrong.
Finally, it should work with this version of _battle:
func _battle():
participants = [player_inventory[0],enemy_inventory[0]]
participants.sort_custom(self, "check_speed")
for current_participant in participants:
if current_participant == player_inventory[0]:
yield(player_action.execute(), "completed")
else:
yield(enemy_action.execute(), "completed")
var state = decide_battle_state()
if state != GameState.BATTLE:
self.current_state = state
return
self.current_state = GameState.ACTION
func decide_battle_state():
if check_fainted(player_inventory[0]):
return GameState.LOST
if check_fainted(enemy_inventory[0]):
return GameState.WON
return GameState.BATTLE
func check_fainted(participant) -> bool:
if participant.current_hp > 0:
return false
participant.current_hp = 0
participant.fainted = true
Battle_Ui_Updater()
return true
You could make an Task with speed:
class_name BattleAction extends Task
# warning-ignore:unused_class_variable
var speed
func _init(instance:Object, method:String, parameters:Array = []).(instance, method, parameters) -> void:
pass
Then use like this:
var parameters = [player_inventory[0], enemy_inventory[0], player_inventory[0].move_slot[action_index]]
player_action = BattleAction.new(self, "attack", parameters)
player_action.speed = player_inventory[0].speed
And finally _battle can look like this:
With your BattleAction which has speed, you can do this:
func _battle():
actions = [player_action, enemy_action]
actions.sort_custom(self, "check_speed")
for action in actions:
yield(action.execute(), "completed")
var state = decide_battle_state()
if state != GameState.BATTLE:
self.current_state = state
return
self.current_state = GameState.ACTION
Question: Is it possible to adjust the above to produce all possible results instead of an optimized one.
Details: Given a data set of armor, I want to produce a set of combinations where my constraints are fulfilled.
Variable helm1 = model.addVariable("Helm 1").binary();
Variable helm2 = model.addVariable("Helm 2").binary();
Variable helm3 = model.addVariable("Helm 3").binary();
Variable arm1 = model.addVariable("Arm 1").binary();
Variable arm2 = model.addVariable("Arm 2").binary();
Variable arm3 = model.addVariable("Arm 3").binary();
Expression statA = model.addExpression().lower(0).weight(1);
Expression statB = model.addExpression().lower(0).weight(1);
Expression statC = model.addExpression().lower(0).weight(1);
//Lower Limit set for desired stat
Expression statD = model.addExpression().lower(2).weight(1);
// Limit number of helms you can equip
model.addExpression().upper(1).set(helm1,1).set(helm2,1).set(helm3,1);
model.addExpression().upper(1).set(arm1,1).set(arm2,1).set(arm3,1);
statA.set(arm1, 1);
statB.set(helm2, 1);
statB.set(helm3, 1);
statB.set(arm2, 1);
statC.set(helm1, 1);
statC.set(arm2, 1);
statC.set(arm3, 1);
statD.set(helm3, 3);
statD.set(arm1, 1);
Optimisation.Result result = model.maximise();
BasicLogger.debug(result);
Note: Before recommending libraries, please not that the library must be compatible with Android.
Answer: No - ojAlgo will output 1 (the optimal if it can find it) solution.
Does anyone know of a truly declarative language? The behavior I'm looking for is kind of what Excel does, where I can define variables and formulas, and have the formula's result change when the input changes (without having set the answer again myself)
The behavior I'm looking for is best shown with this pseudo code:
X = 10 // define and assign two variables
Y = 20;
Z = X + Y // declare a formula that uses these two variables
X = 50 // change one of the input variables
?Z // asking for Z should now give 70 (50 + 20)
I've tried this in a lot of languages like F#, python, matlab etc, but every time I tried this they come up with 30 instead of 70. Which is correct from an imperative point of view, but I'm looking for a more declarative behavior if you know what I mean.
And this is just a very simple calculation. When things get more difficult it should handle stuff like recursion and memoization automagically.
The code below would obviously work in C# but it's just so much code for the job, I'm looking for something a bit more to the point without all that 'technical noise'
class BlaBla{
public int X {get;set;} // this used to be even worse before 3.0
public int Y {get;set;}
public int Z {get{return X + Y;}}
}
static void main(){
BlaBla bla = new BlaBla();
bla.X = 10;
bla.Y = 20;
// can't define anything here
bla.X = 50; // bit pointless here but I'll do it anyway.
Console.Writeline(bla.Z);// 70, hurray!
}
This just seems like so much code, curly braces and semicolons that add nothing.
Is there a language/ application (apart from Excel) that does this? Maybe I'm no doing it right in the mentioned languages, or I've completely missed an app that does just this.
I prototyped a language/ application that does this (along with some other stuff) and am thinking of productizing it. I just can't believe it's not there yet. Don't want to waste my time.
Any Constraint Programming system will do that for you.
Examples of CP systems that have an associated language are ECLiPSe, SICSTUS Prolog / CP package, Comet, MiniZinc, ...
It looks like you just want to make Z store a function instead of a value. In C#:
var X = 10; // define and assign two variables
var Y = 20;
Func<int> Z = () => X + Y; // declare a formula that uses these two variables
Console.WriteLine(Z());
X = 50; // change one of the input variables
Console.WriteLine(Z());
So the equivalent of your ?-prefix syntax is a ()-suffix, but otherwise it's identical. A lambda is a "formula" in your terminology.
Behind the scenes, the C# compiler builds almost exactly what you presented in your C# conceptual example: it makes X into a field in a compiler-generated class, and allocates an instance of that class when the code block is entered. So congratulations, you have re-discovered lambdas! :)
In Mathematica, you can do this:
x = 10; (* # assign 30 to the variable x *)
y = 20; (* # assign 20 to the variable y *)
z := x + y; (* # assign the expression x+y to the variable z *)
Print[z];
(* # prints 30 *)
x = 50;
Print[z];
(* # prints 70 *)
The operator := (SetDelayed) is different from = (Set). The former binds an unevaluated expression to a variable, the latter binds an evaluated expression.
Wanting to have two definitions of X is inherently imperative. In a truly declarative language you have a single definition of a variable in a single scope. The behavior you want from Excel corresponds to editing the program.
Have you seen Resolver One? It's like Excel with a real programming language behind it.
Here is Daniel's example in Python, since I noticed you said you tried it in Python.
x = 10
y = 10
z = lambda: x + y
# Output: 20
print z()
x = 20
# Output: 30
print z()
Two things you can look at are the cells lisp library, and the Modelica dynamic modelling language, both of which have relation/equation capabilities.
There is a Lisp library with this sort of behaviour:
http://common-lisp.net/project/cells/
JavaFX will do that for you if you use bind instead of = for Z
react is an OCaml frp library. Contrary to naive emulations with closures it will recalculate values only when needed
Objective Caml version 3.11.2
# #use "topfind";;
# #require "react";;
# open React;;
# let (x,setx) = S.create 10;;
val x : int React.signal = <abstr>
val setx : int -> unit = <fun>
# let (y,sety) = S.create 20;;
val y : int React.signal = <abstr>
val sety : int -> unit = <fun>
# let z = S.Int.(+) x y;;
val z : int React.signal = <abstr>
# S.value z;;
- : int = 30
# setx 50;;
- : unit = ()
# S.value z;;
- : int = 70
You can do this in Tcl, somewhat. In tcl you can set a trace on a variable such that whenever it is accessed a procedure can be invoked. That procedure can recalculate the value on the fly.
Following is a working example that does more or less what you ask:
proc main {} {
set x 10
set y 20
define z {$x + $y}
puts "z (x=$x): $z"
set x 50
puts "z (x=$x): $z"
}
proc define {name formula} {
global cache
set cache($name) $formula
uplevel trace add variable $name read compute
}
proc compute {name _ op} {
global cache
upvar $name var
if {[info exists cache($name)]} {
set expr $cache($name)
} else {
set expr $var
}
set var [uplevel expr $expr]
}
main
Groovy and the magic of closures.
def (x, y) = [ 10, 20 ]
def z = { x + y }
assert 30 == z()
x = 50
assert 70 == z()
def f = { n -> n + 1 } // define another closure
def g = { x + f(x) } // ref that closure in another
assert 101 == g() // x=50, x + (x + 1)
f = { n -> n + 5 } // redefine f()
assert 105 == g() // x=50, x + (x + 5)
It's possible to add automagic memoization to functions too but it's a lot more complex than just one or two lines. http://blog.dinkla.net/?p=10
In F#, a little verbosily:
let x = ref 10
let y = ref 20
let z () = !x + !y
z();;
y <- 40
z();;
You can mimic it in Ruby:
x = 10
y = 20
z = lambda { x + y }
z.call # => 30
z = 50
z.call # => 70
Not quite the same as what you want, but pretty close.
not sure how well metapost (1) would work for your application, but it is declarative.
Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio
x = 10
y = 20
z = function() return x + y; end
x = 50
= z()
70
It's not what you're looking for, but Hardware Description Languages are, by definition, "declarative".
This F# code should do the trick. You can use lazy evaluation (System.Lazy object) to ensure your expression will be evaluated when actually needed, not sooner.
let mutable x = 10;
let y = 20;
let z = lazy (x + y);
x <- 30;
printf "%d" z.Value