How Can I Solve Syntax and Declaration Erros in my AMPL Code? - ampl

I'm new to developing code in AMPL. I started studying some tutorials and I'm trying to solve some exercises available on the internet.
I tried to develop a code for the problem shown at the end of this video link: https://www.youtube.com/watch?v=6XBoPbfsk_M
I’ve attached the .mod, .dat and .run files I wrote.
.mod file
.dat file
.run file
The error that I can´t solve right now is:
“j is not defined”
context: maximize profit: sum{j in J} Pj[j] * Xj[j] - sum{j in J} Kj[j] * DELTAj[j] + >>> Cj[j] <<< * Xj[j] ;
I would greatly appreciate it if anyone could help me with any other errors you may encounter.

It looks like you have missing parenthesis in your objective fuction:
maximize profit: sum{j in J} Pj[j]*Xj[j] - Kj[j]*DELTAj[j] + Cj[j]*Xj[j];
You should add the parenthesis as follows:
maximize profit: sum{j in J} (Pj[j]*Xj[j] - Kj[j]*DELTAj[j] + Cj[j]*Xj[j]) ;
An index that appears in a sum operator is defined only until the next + or - sign that is outside of parentheses, or until the end of the statement.

Related

gnuplot 'set title' with sprintf : representing angle in terms of fractions of pi

I'd like to run a gnuplot .inp file so all the angles in the script show up automatically in the title as fractions based on the Greek letter pi - instead of a decimal form for the angle. I already know how to use {/Symbol p}, but that is a manual intervention that is impractical in this case.
I have an example sprintf line in a gnuplot input file which can produce nice title information :
angle=( (3*pi) /4 )
set title sprintf ("the angle is %g radians", angle)
plot sin(x)
... the output file (e.g. svg) or terminal (e.g. wxt) shows "2.35619", which is correct, however ; it would be nice to see the Greek letter for pi and the fraction itself, as is typically read off of a polar plot, e.g " 3/4 pi". Likewise for more complex or interesting representations of pi, such as "square root of two over two".
I already know I can manually go into the file and type in by hand "3{/Symbol p}/4", but this needs to be done automatically, because the actual title I am working with has numerous instances of pi showing up as a result of a setting of an angle.
I tried searching for examples of gnuplot being used with sprintf to produce the format of the angle I am interested in, and could not find anything. I am not aware of sprintf being capable of this. So if this is in fact impossible with gnuplot and sprintf, it will be helpful to know. Any tips on what to try next appreciated.
UPDATE: not a solution, but very interesting, might help :
use sprintf after the 'plot' to set the title that appears in the key (but not the overall title):
gnuplot setting line titles by variables
so for example here, the idea would be :
foo=20
plot sin(x)+foo t sprintf ("The angle is set to %g", foo)```
Here is an attempt to define a function to find fractions of Pi.
Basically, sum (check help sum) is used to find suitable multiples/fractions of Pi within a certain tolerance (here: 0.0001). It is "tested" until a denominator of 32. If no integer number is found, the number itself is returned.
In principle, the function could be extended to find multiples or fractions of roots, sqrt(2) or sqrt(3), etc.
This approach can certainly be improved, maybe there are smarter solutions.
Script:
### format number as multiple of pi
reset session
$Data <<EOD
1.5707963267949
-1.5707963267949
6.28318530717959
2.35619449019234
2.0943951023932
-0.98174770424681
2.24399475256414
1.0
1.04
1.047
1.0471
1.04719
EOD
set xrange[-10:10]
set yrange[:] reverse
set offset 0.25,0.25,0.25,0.25
set key noautotitle
dx = 0.0001
fPi(x) = (_x=x/pi, _p=sprintf("%g",x), _d=NaN, sum [_i=1:32] \
(_d!=_d && (abs(_x*_i - floor(_x*_i+dx)) < dx) ? \
(_n=floor(_x*_i+dx),_d=_i, \
_p=sprintf("%sπ%s",abs(_n)==1?_n<0?'-':'':sprintf("%d",_n),\
abs(_d)==1 ? '' : sprintf("/%d",_d)),0) : 0 ), _p)
plot $Data u (0):0:(fPi($1)) w labels font "Times New Roman, 16"
### end of script
Result:
I have [1] a workaround below that might be feasible, and [2] apparently what I was looking for below that (I am writing this in haste). I will mark the question "answered" anyway. To avoid reproducing theozh's script, I offer :
[1]:
add three lines to theozh's script - ideally, immediately before the 'plot' command :
set title sprintf ("Test: %g $\\sqrt{\\pi \\pi \\pi \\pi}$", pi)
set terminal tikz standalone
set output 'gnuplot_test.tex'
one can observe a little testing going on with nonsensical expressions of pi - it is just to see the vinculum extend, and this is a hasty thing - and the double-escapes - they appear to have made it to Stack Overflow correctly.
change the 'plot' line to remove the Times Roman part, but this might not be necessary :
plot $Data u (0):0:(fPi($1)) w labels
importantly, edit gnuplot_test.tex so an \end{document} is on the last line.
run 'pdflatex gnuplot_test.tex'.
This should help move things along - it appears the best approach is to go into the LaTeX world for this - thanks. I tried cairolatex pdf and eps but I was very confused with the LaTeX output. the tikz works almost perfectly.
[2]: What I was looking for : put this below the fPi(x) expression in gnuplot :
set title sprintf ("Testing : \n wxt terminal : \
%g %s %s %s \n tikz output : $\\sqrt{\\pi \\pi \\pi \\pi}$", \
pi, fPi(myAngle01), fPi(myAngle02), fPi(myAngle03) )
# set terminal tikz standalone
# set output 'gnuplot_test.tex'
plot $Data u (0):0:(fPi($1)) w labels t sprintf ("{/Symbol p}= %g, %s, %s, %s, %s", \
pi, fPi(pi), fPi(myAngle01), fPi(myAngle02), fPi(myAngle03) )
... the wxt terminal displays the angles as fractions of pi. I didn't test the output in the LaTeX pipeline - remove if undesired. I think the gnuplot script has to be written for the terminal or output desired - but at least the values can be computed - instead of writing them in "manually".

How do you encrypt a message into a picture using Jython

I'm having problems with an assignment and am in no means looking for someone to do my homework for me. Our professor does not answer or provide adequate resources to our questions for our assignments. I have copied an example code that was given to us, but I am unable to make this itself run.
When I run this program all I receive in the command line is an ellipsis and nothing else.
Does anyone have an idea what the ellipsis means?
My code and command line screenshot
Screenshot of my example code
Attached will be the code:
def encode(msgPic,original):
# Assume msgPic and original have same dimensions
# First, make all red pixels even
for pxl in getPixels(original):
# Using modulo operator to test oddness
if (getRed(pxl) % 2) == 1:
setRed(pxl, getRed(pxl) - 1)
# Second, wherever there???s black in msgPic
# make odd the red in the corresponding original pixel
for x in range(0,getWidth(original)):
for y in range(0,getHeight(original)):
msgPxl = getPixel(msgPic,x,y)
origPxl = getPixel(original,x,y)
if (distance(getColor(msgPxl),black) < 100.0):
# It's a message pixel! Make the red value odd.
setRed(origPxl, getRed(origPxl)+1)
Below is the code that the example prompts to input into the command line:
- beach = makePicture(getMediaPath("beach.jpg"))
- explore(beach)"
- msg = makePicture(getMediaPath("msg.jpg"))
- encode(msg,beach)
- explore(beach)
- writePictureTo(beach,getMediaPath("beachHidden.png"))

How to export cplex' solution?

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

Is it possible to implement a break statement using a user input in python

time=0
stop=input()
while time<1000000000000000000000000000000000000000000000000000:
if stop==input("999"):
break
print (time)
time= time+1
print("time taken is",time)
This is a program for an average speed camera. I was wondering whether it is possible for the while loop to stop when the user inputs "999". The value at which the code is broken would then be the new content of the time variable.
It's a bit unclear of what you're trying to accomplish, but based on the code you provided and your question, it sounds like you want to measure how long it takes for someone to enter a specific value. You can modify: Python - Infinite while loop, break on user input:
#guess_999.py
import sys
import os
import fcntl
import time
fl = fcntl.fcntl(sys.stdin.fileno(), fcntl.F_GETFL)
fcntl.fcntl(sys.stdin.fileno(), fcntl.F_SETFL, fl | os.O_NONBLOCK)
time_started = time.time()
while True:
try:
stdin = sys.stdin.read()
if "999" in stdin:
print "It took %f seconds" % (time.time() - time_started)
break
except IOError:
pass
Then running it:
$ python guess_999.py
$ 6
$ 999
$ It took 2.765054 seconds
EDIT: PO wanted to do something completely different. I refer to Mark's answer.
You messed it up a little bit ;)
Do:
answer = input("type something")
if answer == "999":
break
Explanation:
- input() will return a string of what the user typed into the console. What you write into the brackets is what will be written on the line when you are asked to type something. This is usually a question like "what's your name?"
- if the answer is "999", the command break will be executed => loop stops

Error in SQL-Oracle Code when raising value to the nth power - Need assistance

I'm running SQL code within Oracle and need help revising the below "Update" script. The below script gives me the error “missing equal sign” due to the " ^ " in the last line of the code that is meant to take the Table-B.ValueY value to the Table-A.ValueZ power. I tried changing the last line to a Power (x,y) formula, but that gives me "%s: invalid identifier" error. I also went so far as to change the code completely into a CREATE TABLE, but that just appears be caught in a loop and never finishes.
Any help is much appreciated.
Original code:
UPDATE Table-A
SET Column-X = 0
WHERE
TABLE-A.mid = TABLE-B.mid AND
TABLE-A.tdlinx = TABLE-B.tdlinx AND
TABLE-B.ValueY ^ TABLE-A.ValueZ > 0.1;
there is a POWER function
SELECT POWER(10,2) FROM DUAL;
yours should look similar to this:
POWER( TABLE-B.ValueY, TABLE-A.ValueZ ) > 0.1