AMPL - param that maps from set to set - ampl

I'm new to AMPL, and I would like to create a param C that map from a set A to set B:
file.mod:
set A;
set B;
param C{i in A} =
if i == "AA"
then
BA
else if i == "AB"
then
BB
else if i == "AC"
then
BC
else
BA;
data file.dat;
file.dat:
data;
set A := AA, AB, AC;
set B := BA, BB, BC;
When I try to compile this code, I get BA is not defined. If I replace the set element by string (BA becomes "BA"), then the error `Cannot convert character string to a number.``showed up.
Is there a way to achieve what I want to do?

Parameters in AMPL default to number. If you want to set a string parameter, you have to declare it as symbolic. (And yes, you need the quotes on those values.)
This seems to do what you want:
set A;
set B;
param C{i in A} in B symbolic =
if i == "AA"
then
"BA"
else if i == "AB"
then
"BB"
else if i == "AC"
then
"BC"
else
"BA";
data;
set A := AA, AB, AC;
set B := BA, BB, BC;
See section 7.8 of the AMPL Book for more information about symbolic parameters.

Related

Remove duplicate elements of string1 from string2 in Tcl

I want to remove duplicate elements of string1 from string 2 and then output new string. My code works only if duplicate elements are in sequential order.
I want to work it any order of elements. Please advise.
Current Code:
set str1 "a 1 b 2 c 3 X Y Z"
set str2 "a 1 b 2 c 3 P Q R"
set results {}
set results [lmap a_elem $str1 b_elem $str2 {
if {$a_elem != $b_elem} {string cat $b_elem} else continue
}]
puts $results
Output of the following code :
P Q R
However, if
set str1 "a 1 b 2 c 3 X Y Z"
set str2 "P a 2 1 R c Q 3 b"
then Output will be : P a 2 1 R c Q 3 b
Basically same as str2 without the duplicate elimnation.
If you want to output those elements of the list in str2 that are nowhere in str1, you should first build a dictionary of the elements of str1 so that you can use efficient lookup (dicts are internally hash tables). You are strongly recommended to use a procedure for this as it makes the implementation rather more efficient.
proc removeItems {str1 str2} {
foreach item $str1 {
dict set items $item ""; # Value unimportant
}
lmap item $str2 {
if {[dict exists $items $item]} continue
string cat $item
}
}
puts [removeItems "a 1 b 2 c 3 X Y Z" "P a 2 1 R c Q 3 b"]
# P R Q
The code naturally assumes that the order of str2 is important.
If performance is not important, you can use the more straight forward:
set results [lmap elem $str2 {
if {$elem ni $str1} {string cat $elem} else continue
}]

OCaml modules and signatures

In my exercise I have to write OCaml module given its signiture:
module type Range
= sig
type t
val range : int * int -> t
(*val list_of_range : t -> int list*)
end
The module I have so far:
module Range =
struct
type t = int
let range (n,m) =
if m > n then () else (n,m)
end
The task for range (n,m) is to take 2 integers and if n <= m then give out a tuple (n,m). Otherwise (). If I try to run this code, I get error The expression has 'a * 'b but an expression was expected of type unit. Can anyone help me to move forward with this?
PS. It's my first day with OCaml.
PPS. I have commented out the list of range.. part because this is the second part of the exercise and wouldn't work anyway if the first part isn't working.
UPDATE
I have updated my code and results seem promising.
module type Range
= sig
type t
val range : int * int -> t
val list_of_range : t -> int list
end
module Range =
struct
type t = int
let range (m,n) =
if m > n then (0,0) else (m,n)
let rec list_of_range (m,n) =
let t = range(m,n) in
let x = fst(t) in let y = snd(t) in
if x = 0 && y = 0 then [0] else x :: list_of_range(x+1,y)
end
The code above gives me almost perfect expected result. If I give input (1,5), the result is [1;2;3;4;5;0]. The problem is the 0 as the last element in the list. Why is is there? Where does it come from?
the issue comes from your function range, it cannot return a unit type (i.e. () ) and a tuple. In addition, it violates the signature, where you define range as a function that returns an int.

How to change string value label

Suppose I have a string variable that takes on several string values:
gen rand = runiform()
sort rand
gen var1 = ""
replace var1 = "A" if rand < .3
replace var1 = "B" if rand>=.3 & rand < .7
replace var1 = "C" if var1==""
How would I change the values of var1? For example, A to be Aaa, B to be Bbb, and C to be Ccc?
I want to do something like the following (but rather replace the variables), which I know is incorrect:
label define var1L "A" "Aa" B "Bbb" C "Ccc"
label values var1 var1L
String variables can't have value labels. You can interpret this as if labels for string variables are meant to be the content of the variable itself. But you can replace:
clear
set more off
input ///
str1 var1
A
B
C
end
list
replace var1 = "Aaa" if var1 == "A"
replace var1 = "Bbb" if var1 == "B"
replace var1 = "Ccc" if var1 == "C"
list
You need to say more about your data and objectives for a more useful answer.

SQL query to update list of records by looping through a table records and check some logic?

I do not want to use cursors for performance reasons.
Input Parameters for stored procedure: arg1, arg2,arg3 & arg4
For example:
Table A > A1 Column and A2 Column,
Table B > B1 Column (A.A1 <=>B.B1) foreign n primary key relation and B2 Column.
I want to update A.A2 value based on the following if condition,
if(arg1 == B.B2 && arg2 == B.B2)
{
Update A set A.A2 = 1 where A.A1 = arg4
}
else{
if(arg1 == 1 && arg3 == B.B2){
Update A set A.A2 = 0 where A.A1 = arg4
}
}
this is simple for one record but the Table A has 1000's records that match A.A1 = arg4 so i have to apply the above logic or case for all records and want to avoid using cursors...how do i do it?
Try the below query.
UPDATE tmp
SET tmp.A2 =
(CASE WHEN (tmp1.B2 == arg1 && tmp1.B2 == arg2) THEN 1 WHEN (arg1 == 1 && tmp1.B2 == arg3) THEN 0 ELSE tmp.A2)
FROM
A tmp
INNER JOIN
B tmp1
ON tmp.A1 = tmp1.B1
WHERE
tmp.A1 = arg4
Hope this Helps!!
In general, non-specific SQL-92 you could do this:
UPDATE A
SET A.A2 = CASE WHEN B.B2 IN (#Arg1,#Arg2) THEN 1
WHEN #arg1 = 1 AND B.B2 = #arg3 THEN 0 END
FROM A
JOIN B ON A.A1=B.B1
WHERE A.A1 = #arg4
You may need an ELSE before END if you don't want any values falling through (without the ELSE it would set A.A2 to NULL).

Lua table.toString(tableName) and table.fromString(stringTable) functions?

I am wanting to convert a 2d lua table into a string, then after converting it to a string convert it back into a table using that newly created string. It seems as if this process is called serialization, and is discussed in the below url, yet I am having a difficult time understanding the code and was hoping someone here had a simple table.toString and table.fromString function
http://lua-users.org/wiki/TableSerialization
I am using the following code in order to serialize tables:
function serializeTable(val, name, skipnewlines, depth)
skipnewlines = skipnewlines or false
depth = depth or 0
local tmp = string.rep(" ", depth)
if name then tmp = tmp .. name .. " = " end
if type(val) == "table" then
tmp = tmp .. "{" .. (not skipnewlines and "\n" or "")
for k, v in pairs(val) do
tmp = tmp .. serializeTable(v, k, skipnewlines, depth + 1) .. "," .. (not skipnewlines and "\n" or "")
end
tmp = tmp .. string.rep(" ", depth) .. "}"
elseif type(val) == "number" then
tmp = tmp .. tostring(val)
elseif type(val) == "string" then
tmp = tmp .. string.format("%q", val)
elseif type(val) == "boolean" then
tmp = tmp .. (val and "true" or "false")
else
tmp = tmp .. "\"[inserializeable datatype:" .. type(val) .. "]\""
end
return tmp
end
the code created can then be executed using loadstring(): http://www.lua.org/manual/5.1/manual.html#pdf-loadstring if you have passed an argument to 'name' parameter (or append it afterwards):
s = serializeTable({a = "foo", b = {c = 123, d = "foo"}})
print(s)
a = loadstring(s)()
The code lhf posted is a much simpler code example than anything from the page you linked, so hopefully you can understand it better. Adapting it to output a string instead of printing the output looks like:
t = {
{11,12,13},
{21,22,23},
}
local s = {"return {"}
for i=1,#t do
s[#s+1] = "{"
for j=1,#t[i] do
s[#s+1] = t[i][j]
s[#s+1] = ","
end
s[#s+1] = "},"
end
s[#s+1] = "}"
s = table.concat(s)
print(s)
The general idea with serialization is to take all the bits of data from some data structure like a table, and then loop through that data structure while building up a string that has all of those bits of data along with formatting characters.
How about a JSON module? That way you have also a better exchangeable data. I usually prefer dkjson, which also supports utf-8, where cmjjson won't.
Under the kong works this
local cjson = require "cjson"
kong.log.debug(cjson.encode(some_table))
Out of the kong should be installed package lua-cjson https://github.com/openresty/lua-cjson/
Here is a simple program which assumes your table contains numbers only. It outputs Lua code that can be loaded back with loadstring()(). Adapt it to output to a string instead of printing it out. Hint: redefine print to collect the output into a table and then at the end turn the output table into a string with table.concat.
t = {
{11,12,13},
{21,22,23},
}
print"return {"
for i=1,#t do
print"{"
for j=1,#t[i] do
print(t[i][j],",")
end
print"},"
end
print"}"
Assuming that:
You don't have loops (table a referencing table b and b referencing a)
Your tables are pure arrays (all keys are consecutive positive integers, starting on 1)
Your values are integers only (no strings, etc)
Then a recursive solution is easy to implement:
function serialize(t)
local serializedValues = {}
local value, serializedValue
for i=1,#t do
value = t[i]
serializedValue = type(value)=='table' and serialize(value) or value
table.insert(serializedValues, serializedValue)
end
return string.format("{ %s }", table.concat(serializedValues, ', ') )
end
Prepend the string resulting from this function with a return, store it on a .lua file:
-- myfile.lua
return { { 1, 2, 3 }, { 4, 5, 6 } }
You can just use dofile to get the table back.
t = dofile 'myfile.lua'
Notes:
If you have loops, then you will have
to handle them explicitly - usually with an extra table to "keep track" of repetitions
If you don't have pure arrays, then
you will have to parse t differently,
as well as handle the way the keys are rendered (are they strings? are they other tables? etc).
If you have more than just integers
and subtables, then calculating
serializedValue will be more
complex.
Regards!
I have shorter code to convert table to string but not reverse
function compileTable(table)
local index = 1
local holder = "{"
while true do
if type(table[index]) == "function" then
index = index + 1
elseif type(table[index]) == "table" then
holder = holder..compileTable(table[index])
elseif type(table[index]) == "number" then
holder = holder..tostring(table[index])
elseif type(table[index]) == "string" then
holder = holder.."\""..table[index].."\""
elseif table[index] == nil then
holder = holder.."nil"
elseif type(table[index]) == "boolean" then
holder = holder..(table[index] and "true" or "false")
end
if index + 1 > #table then
break
end
holder = holder..","
index = index + 1
end
return holder.."}"
end
if you want change the name just search all compileTable change it to you preferred name because this function will call it self if it detect nested table but escape sequence I don't know if it work
if you use this to create a lua executable file that output the table it will ge compilation error if you put new line and " sequence
this method is more memory efficient
Note:
Function not supported
User data I don't know
My solution:
local nl = string.char(10) -- newline
function serialize_list (tabl, indent)
indent = indent and (indent.." ") or ""
local str = ''
str = str .. indent.."{"
for key, value in pairs (tabl) do
local pr = (type(key)=="string") and ('["'..key..'"]=') or ""
if type (value) == "table" then
str = str..nl..pr..serialize_list (value, indent)..','
elseif type (value) == "string" then
str = str..nl..indent..pr..'"'..tostring(value)..'",'
else
str = str..nl..indent..pr..tostring(value)..','
end
end
str = str:sub(1, #str-1) -- remove last symbol
str = str..nl..indent.."}"
return str
end
local str = serialize_list(tables)
print('return '..nl..str)