How to export cplex' solution? - file-io

I have a file quadratic_obj.lp with the following content:
Minimize
obj: a + b + [ a^2 + 4 a * b + 7 b^2 ]/2
Subject To
c1: a + b >= 10
End
In an interactive cplex session, I read in the file using read, I optimize using optimize. Then I can display the solution using
display solution variables -
which gives me
Variable Name Solution Value
a 10.000000
b 0.000000
Is there a way to pipeline this output? So in an ideal world there would be something like:
display solution variables - -> myoutput.csv
I used write but the file type options there are not what I look for. E.g. sol is returned as an xml which I would have to parse again.
Is there a way to just export the variables and their values to e.g. a tab- or comma-separated file?

There is no automatic way to do this from the interactive. If you do something like the following, it gets you close:
./cplex -c "read quadratic_obj.lp" "opt" "set logfile tmp.log" "display solution variables -" "quit"
This will put the output into a file named tmp.log, but there is still some extra stuff in there that you'd need to post-process with a script (or something like this). See this link (for version 12.6.3) for more information on this technique.
Another alternative would be to use the API's. Then, you have complete control over the output. For example, using the Python API, you could do something like the following:
import cplex
cpx = cplex.Cplex()
cpx.read('quadratic_obj.lp')
cpx.solve()
# Check solution status here via cpx.solution.get_status()
for name, value in zip(cpx.variables.get_names(),
cpx.solution.get_values()):
print name, value

you can do that within CPLEX with OPL:
dvar float+ a;
dvar float+ b;
minimize a + b + ( a*a + 4 *a * b + 7 *b*b )/2;
subject to
{
c1: a + b >= 10;
}
execute
{
var f=new IloOplOutputFile("res.csv");
f.writeln(a);
f.writeln(b);
f.close();
}
and this will create a csv file res.csv
regards

Related

How to print the variable loaded and assigned from file

I am just learning machine learning using Octave. I want to load the data from the file and assign the data to one variable, then I just want to print the data to the console.The data in data.txt file is several-rows and two-columns matrix.
data = load('data.txt');
x = data(:, 1);
y = data(:, 2);
printf x;
printf y;
After executing the code, x and y will show up on the console, it is not what I expected, I just want to check the data loaded from the file, how to print this? Do I use wrong command?
Just type data in console and press enter . This will print the contents of the data variable with all its elements. Do NOT add a semicolon at end of line. This would suppress output.
The explicit way doing this is the command
display(data)

Find and Replace an operation in Verilog using Yosys

I am trying to see if Yosys fits my requirements or no.
What i want to do is to find an operation in Verilog code (e.g. temp = 16*val1 + 8*val2 ) and replace this with another op like ( temp = val1 << 4 + val2 << 3 ).
Which parts i need to learn & use from Yosys? if anyone knows the set of command to use, can he/she please let me know to boost my learning curve ?
Thanks.
For example consider the following verilog input (test.v):
module test(input [7:0] val1, val2, output [7:0] temp);
assign temp = 16*val1 + 8*val2;
endmodule
The command yosys -p 'prep; opt -full; show' test.v will produce the following circuit diagram:
And the output written to the console contains this:
3.1. Executing OPT_EXPR pass (perform const folding).
Replacing multiply-by-16 cell `$mul$test.v:2$1' in module `\test' with shift-by-4.
Replacing multiply-by-8 cell `$mul$test.v:2$2' in module `\test' with shift-by-3.
Replacing $shl cell `$mul$test.v:2$1' (B=3'100, SHR=-4) in module `test' with fixed wiring: { \val1 [3:0] 4'0000 }
Replacing $shl cell `$mul$test.v:2$2' (B=2'11, SHR=-3) in module `test' with fixed wiring: { \val2 [4:0] 3'000 }
The two lines reading Replacing multiply-by-* cell are the transformation you mentioned. The two lines after that replace the constant shift operations with wiring, using {val1[3:0], 4'b0000} and {val2[4:0], 3'b000} as inputs for the adder.
This is done in the opt_expr pass. See passes/opt/opt_expr.cc for its source code to see how it's done.

psychopy website does not give a fix for output file doubeling data

Here is some of the code...
Whenever I get an output file I get a doubling of data.
#For each record in keypress, a line is created in the file
keyPress = []
keyPress.append(event.waitKeys(keyList=['s','d'],timeStamped=clock))
for key in keyPress:
for l, t in key:
f.write(str(images[index]) + "\t iteration \t" + str(k + 1) + "\t" + l + "\t" + str(t)+"\n")
f.close()
There's a few things that are unclear here and I haven't managed to reproduce it. But I will give my shot at an answer anyway. First, event.waitKeys returns just one response, so it is really not necessary to loop over them. So I'd just do
l, t = event.waitKeys(keyList=['s','d'],timeStamped=clock)[0]
... which is much nicer. So a full reproducible solution would be this:
# Set things up
from psychopy import visual, event, core
win = visual.Window()
clock = core.Clock()
f = open('log.tsv', 'a')
# Record responses for a few trials and save
for trial in range(5):
l, t = event.waitKeys(keyList=['s','d'], timeStamped=clock)[0] # [0] extracts the first (and only) element, i.e. the (key, rt) tuple which is then unpacked into l and t.
f.write('trial' + trial + '\tkey' + l + "\tRT" + str(t) + "\n")
f.close()
Instead of creating your log files manually like this, consider using the csv module or psychopy's own data.TrialHandler. Usually it's nice to represent trials using a dict and save responses together with the properties of each trial. the csv module has a DictWriter method.

How to run same syntax on multiple spss files

I have 24 spss files in .sav format in a single folder. All these files have the same structure. I want to run the same syntax on all these files. Is it possible to write a code in spss for this?
You can use the SPSSINC PROCESS FILES user submitted command to do this or write your own macro. So first lets create some very simple fake data to work with.
*FILE HANDLE save /NAME = "Your Handle Here!".
*Creating some fake data.
DATA LIST FREE / X Y.
BEGIN DATA
1 2
3 4
END DATA.
DATASET NAME Test.
SAVE OUTFILE = "save\X1.sav".
SAVE OUTFILE = "save\X2.sav".
SAVE OUTFILE = "save\X3.sav".
EXECUTE.
*Creating a syntax file to call.
DO IF $casenum = 1.
PRINT OUTFILE = "save\TestProcess_SHOWN.sps" /"FREQ X Y.".
END IF.
EXECUTE.
Now we can use the SPSSINC PROCESS FILES command to specify the sav files in the folder and apply the TestProcess_SHOWN.sps syntax to each of those files.
*Now example calling the syntax.
SPSSINC PROCESS FILES INPUTDATA="save\X*.sav"
SYNTAX="save\TestProcess_SHOWN.sps"
OUTPUTDATADIR="save" CONTINUEONERROR=YES
VIEWERFILE= "save\Results.spv" CLOSEDATA=NO
MACRONAME="!JOB"
/MACRODEFS ITEMS.
Another (less advanced) way is to use the command INSERT. To do so, repeatedly GET each sav-file, run the syntax with INSERT, and sav the file. Probably something like this:
get 'file1.sav'.
insert file='syntax.sps'.
save outf='file1_v2.sav'.
dataset close all.
get 'file2.sav'.
insert file='syntax.sps'.
save outf='file2_v2.sav'.
etc etc.
Good luck!
If the Syntax you need to run is completely independent of the files then you can either use: INSERT FILE = 'Syntax.sps' or put the code in a macro e.g.
Define !Syntax ()
* Put Syntax here
!EndDefine.
You can then run either of these 'manually';
get file = 'file1.sav'.
insert file='syntax.sps'.
save outfile ='file1_v2.sav'.
Or
get file = 'file1.sav'.
!Syntax.
save outfile ='file1_v2.sav'.
Or if the files follow a reasonably strict naming structure you can embed either of the above in a simple bit of python;
Begin Program.
imports spss
for i in range(0, 24 + 1):
syntax = "get file = 'file" + str(i) + ".sav.\n"
syntax += "insert file='syntax.sps'.\n"
syntax += "save outfile ='file1_v2.sav'.\n"
print syntax
spss.Submit(syntax)
End Program.

how to make a variable global inside a while loop

Following is the TCL script to print numbers between 1 to 10 using while loop.
set b 1
while {$b<11} {
puts $b
incr b
}
In the above script, how to make "puts $b" output as global. So that we can use this where ever we want in the script?
I need the following:
set b 1
while {$b<11} {
set a $b
incr b
}
puts "This is number $a"
If I use $a in outside loop, it should print the output as :
This is number 1
This is number 2
This is number 3
.
.
.
This is number 10
Tcl is really strictly operational; it does things at the point where you tell it to. However, one of the things that you can do is to put a trace on a variable so that some code gets run whenever the variable is written to.
# This is Tcl 8.5 syntax; let me know if you want it for 8.4 and before
trace add variable ::a write {apply {args {
puts "This is number $::a"
}}}
I've used fully-qualified variable names above; the trace is really on the variable a in the namespace ::.
Then, after setting the trace, when we do:
set b 1
while {$b<11} {
set a $b
incr b
}
The output then is:
This is number 1
This is number 2
This is number 3
This is number 4
This is number 5
This is number 6
This is number 7
This is number 8
This is number 9
This is number 10
Which is what you wanted.
Your question isn't entirely clear: I think Donal Fellows may have given you the right answer, but I think I may see another question lurking in your text, namely: how can I write a generic command that will, as it were, take a variable for a brief spin?
As in:
set b 1
myLoop b {
set a $b
puts "This is number $a"
}
puts "Again, this is number $a"
You would write myLoop like this:
proc myLoop {varName body} {
upvar 1 $varName i
for {} {$i < 11} {incr i} {
uplevel 1 $body
}
}
Note that this is not the best way to write a command like this: I'm writing it this way to accommodate your example code.
The command works by calling uplevel to evaluate the script in body in the context of the caller, whichever that is. To allow myLoop to manipulate the variable in the script, we need to set up things so that the command will share the variable with the caller. The upvar command does that.