Optimist R-Forge project - r-forge

I´m studing the bin packing problem begining with the knapsack code of Martello algorithm. It wrote in Old Fortran IV or 66 code. I found a very interesting project at R-Forge calling Optimist (Administrator Hans W. Borchers) that by R console you can call the subroutine that it was written in Fortran 66 and run it to check the results. This is util if you want write the code in a more modern lenguage and check if arrives to the same results.
I downloaded R x64 3.3.1 and the Optimist packages.
I don´t know how to run this packages from R. I´m saying: invoke the subroutine in Fortran, input data and view the results from the R IDE.
Any suggestions?
Thank in advance.
Eduardo

The original Martello and Toth Fortran routines are available in the 'knapsack' package of the Optimist R-Forge project (and not in the 'adagio' package). Unfortunately, these Fortran codes cannot be distributed through CRAN. The reason being that they are published under the ACM license, not compatible with GPL. I asked Prof. Silvano Martello whether he would be willing to change the license, but he could not or did not want to do so (as he explicitly told me).
To give you a start: I guess you have installed R or, even better, R and RStudio. When you have started R, first you have to install the package once and to load it everytime you start R anew with:
(You will need to have a Fortran compiler available, but I guess you have that.)
> install.packages("knapsack", repos="http://R-Forge.R-project.org")
> library(knapsack)
Then you can call help or example on, e.g., the knapsack function. The functions implemented at the moment are knapsack and subsetsum. The help pages will show you how to apply these routines. p and w (the profits and weights) must be vectors of integer values of equal length, with p[i]/w[i] a strictly decreasing sequence:
> p = c(15, 100, 90, 60, 40, 15, 10, 1)
> w = c( 2, 20, 20, 30, 40, 30, 60, 10)
> cap = 102
Now you can call the knapsack function and display the result:
> res = knapsack(p, w, cap)
> res
# [1] 1 2 3 4 6
There is also the subsetsum routine. Other codes from the book of Martello and Toth have not yet been wrapped in the 'knapsack' package. But it could easily been done if you are interested. These additional routines are solving the bin packing, assignment, and change making problems.

Related

is there an API for Julia packages

Hi I am an old Java/Haskell/Cobol programmer. And Julia has many fantastic features but I am struggling with what I consider the basics. Particularly how to find what is in the many packages (Flux, Plots, DifferentialEquations, etc).
I have tried both VSCode and Jupiter notebook and the Julia REPL but have found no way to extract this essential information while working on a program.
I have also failed to find the information on line without it being spread very thinly over tutorial for each package.
Is there and "cheetsheet" or "summary" or java like API?
For the basics, I would recommend two "cheatsheets" in particular
"The fast track to Julia" https://juliadocs.github.io/Julia-Cheat-Sheet/ -- covers the language itself, the stdlibs, and a couple useful packages
If you have previous experience in Python or Matlab, https://cheatsheets.quantecon.org
However, the package ecosystem is too diverse for any cheatsheet to cover all the useful packages out there, so for individual packages I would recommend a few tricks built in to the language:
Tab-complete in the REPL. Typing PackageName.<tab><tab> will print everything in the namespace of PackageName, e.g.:
julia> using Statistics
julia> Statistics.
_conj _vmean covm quantile!
_getnobs centralize_sumabs2 covzm range_varm
_mean centralize_sumabs2! eval realXcY
_mean_promote centralizedabs2fun include sqrt!
_median clampcor mean std
_quantile cor mean! stdm
_quantilesort! corm median unscaled_covzm
_std corzm median! var
_var cov middle varm
_varm cov2cor! quantile varm!
Note that since this prints everything in the package, this includes functions that may not be intended for general use. By general convention, any function beginning with an underscore _ is not intended for public use.
The names function -- will give you a list of all the functions exported by a given package (and thus is a bit more selective than just typing PackageName.<tab><tab>). This is effectively the public API of any given Julia package:
julia> using Statistics
julia> names(Statistics)
14-element Vector{Symbol}:
:Statistics
:cor
:cov
:mean
:mean!
:median
:median!
:middle
:quantile
:quantile!
:std
:stdm
:var
:varm
Once you find a function that looks promising, the built-in help, accessed by just typing ? at the REPL prompt:
help?> cov
search: cov convert StackOverflowError CUSOLVER has_cusolvermg code_llvm #code_llvm cudaconvert
cov(x::AbstractVector; corrected::Bool=true)
Compute the variance of the vector x. If corrected is true (the default) then the sum is scaled with
n-1, whereas the sum is scaled with n if corrected is false where n = length(x).
────────────────────────────────────────────────────────────────────────────────────────────────────
cov(X::AbstractMatrix; dims::Int=1, corrected::Bool=true)
Compute the covariance matrix of the matrix X along the dimension dims. If corrected is true (the
default) then the sum is scaled with n-1, whereas the sum is scaled with n if corrected is false
where n = size(X, dims).
────────────────────────────────────────────────────────────────────────────────────────────────────
...
...
...
The methodswith function -- will give you a list of all functions that can operate on objects of a given Type:
julia> using LinearAlgebra, SparseArrays
julia> methodswith(SparseMatrixCSC)
[1] sizehint!(S::SparseMatrixCSC, n::Integer) in SparseArrays
[2] cov(X::SparseMatrixCSC; dims, corrected) in Statistics
[3] \(L::SuiteSparse.CHOLMOD.Factor, B::SparseMatrixCSC) in SuiteSparse.CHOLMOD
[4] lu(A::SparseMatrixCSC; check) in SuiteSparse.UMFPACK a
[5] lu!(F::SuiteSparse.UMFPACK.UmfpackLU, A::SparseMatrixCSC; check) in SuiteSparse.UMFPACK
[6] qr(A::SparseMatrixCSC; tol) in SuiteSparse.SPQR
[7] rank(S::SparseMatrixCSC) in SuiteSparse.SPQR
...
...
...
On #OscarSmith's suggestion -- you can search for functions, types, and other symbols across multiple packages, as well as searching the full text of all Julia packages, on JuliaHub. For example: sprandn
Finally, for getting a feel for what sort of packages are out there in the package ecosystem beyond the stdlib, I can recommend joining one of the several Julia community fora, such as the discourse, the slack, or the zulip.

Lua (CC) GUI class draws all components in the same window when told to draw them in separate windows

Prelude
ComputerCraft is a mod for Minecraft (Forge) that adds a crude lua-based Computer to the game. Using this Computer, one can write programs to interact with the Minecraft world in various ways. Whether a ComputerCraft question is applicable to StackOverflow has been previously debated in other questions, but I believe it is applicable, as the mod is, for the most part, about programming, and while some ComputerCraft proprietary API calls are made, there is no concept in this question that would not apply to other, non-ComputerCraft-related lua programs (unless of course the problem is caused by a bug in ComputerCraft itself). Documentation for the used APIs can be found at http://www.computercraft.info/wiki/Category:APIs.
Note: Do not be alarmed if you have no ComputerCraft experience; I believe that this issue may be completely unrelated to ComputerCraft, and instead be caused by some intricacy of OOP in lua that I have failed to grasp. I have commented the code where I felt it necessary to explain the most important aspects of the proprietary calls I am making. If anything is unclear, please comment and I will clarify.
If you want to be able to run the code examples without Minecraft, there is an excellent ComputerCraft emulator available called CCEmuRedux. I have tested my code on both actual ComputerCraft and CCEmuRedux with identical results, although CCEmuRedux doesn't seem to support Monitors. An "Advanced" Computer is necessary to see the colours.
Problem
In ComputerCraft 1.75 (and CCEmuRedux # ComputerCraft 1.79), given the following class gui, and a test program that attempts to draw a rudimentary button in each of two different windows using the gui class, both buttons are drawn in the second window. Graphically, the result of guiTest.lua is https://i.imgur.com/llFDlYI.png, while I would expect the first (orange) button to be drawn in Window 1. While I have some theories as to why it behaves this way, I don't have the necessary lua experience to figure out how to fix it. This is an MWE.
Code example
gui.lua
--Meta class
gui = {t, vpx, vpy}
function gui:new(t, title) -- I'm aware this constructor is not in keeping with the referenced Tutorialspoint article, it is of no consequence in this example
local o = o or {}
setmetatable(o, self)
self.__index = self
self.t = t
local sX, sY = self.t.getSize() -- get the size of the virtual terminal and save it to vpx, vpy
self.vpx = sX
self.vpy = sY
self.t.setCursorPos(1, 1) -- put cursor at the start of the virtual terminal
self.t.write(tostring(title)) -- note that this WORKS, it prints one title per Window as seen in the screenshot
return o
end
function gui:drawButton(x, y, sX, sY, colour)
self.t.setCursorPos(x, y) -- set the cursor to the button's first x- and y-coords
self.t.setTextColor(colours.black) -- set text colour to black
self.t.setBackgroundColor(colour) -- set background colour to the colour of the button
for iY = 1, sY do
for iX = 1, sX do
self.t.write("#") -- print hashtags to represent the button until we reach sX and sY
end
self.t.setCursorPos(x, y + iY) -- move cursor a line down, and back to button's first x-coord
end
self.t.setCursorPos(self.vpx, self.vpy) -- get cursor out of the way so the screenshot will be prettier
end
guiTest.lua
dofile('gui.lua')
local w1 = window.create(term.current(), 2, 2, 22, 15)
local w2 = window.create(term.current(), 26, 2, 22, 15) -- creates virtual windows in a terminal, acting as terminals of their own
-- window.create() arguments: terminal object to create window on, x position, y position, x size, y size
local g1 = gui:new(w1, "Window 1") -- create gui object for the first window
local g2 = gui:new(w2, "Window 2") -- create gui object for the second window
g1:drawButton(5, 3, 3, 2, colours.orange) -- should draw in w1, draws in w2
g2:drawButton(10, 8, 4, 4, colours.green) -- should draw in w2, draws in w2
Attempted solutions
For what it's worth, I've been following the Lua OOP recipe # https://www.tutorialspoint.com/lua/lua_object_oriented.htm. This is my second lua-based program, so I expect it to be an "easy" problem. I have more than a basic understanding of how OOP works in several other languages (particularly Java), though, and as such my programmer's "Spidey-Sense" is telling me that either some variable, such as t, isn't "local enough" (same variable gets used by both windows), or some reference in one of the gui objects gets overwritten when a new gui object gets created.
Therefore, I tried making the table gui local, to ensure it was not being overwritten:
local gui = {t, vpx, vpy}
... but it spat an error attempt to index ? on line 6 of "gui.lua" (setmetatable(o, self)), so instead I tried (realising that I would be unable to access the function from outside gui.lua, due to it being local):
local function gui:drawButton(x, y, sX, sY, colour)
... which resulted in guiTest.lua:1: bios.lua:14 [string "gui.lua"]:17:'(' expected. Line 17 is the definition of gui:drawButton() in the code tag above. In my admittedly limited ComputerCraft experience, such poorly formatted error messages generally mean that the lua interpreter or CraftOS is Exceptionally Confused™, but I assume the gist of it is "you can't make an object method local", as I can make other functions local in a similar fashion to what I've tried here.
It is not a problem with window.create() or with using the window API in general, as the same thing happens when using separate Monitors instead of just separate windows on the same Monitor. Essentially:
dofile('gui.lua')
local w = window.create(term.current(), 2, 2, 22, 15)
local m = peripheral.wrap('top') -- m becomes the Monitor physically on top of the ComputerCraft Computer
local gw = gui:new(w, "Window") -- create gui object for the Window
-- m is a terminal object, just like w, so we can still do
local gm = gui:new(m, "Monitor") -- create gui object for the Monitor
gw:drawButton(5, 3, 3, 2, colours.orange) -- should draw in w, draws in m
gm:drawButton(10, 8, 4, 6, colours.green) -- should draw in m, draws in m
Perhaps there is a way of storing the function as a local variable, along the lines of
local gui:printFoo = function() print("foo") end
self:printFoo() -- prints "foo"...?
... or perhaps more likely, the issue is something I have entirely missed.
Conclusion
To make a long question short, defining two gui objects, one for each of two virtual console windows, and attempting to draw one button on each of the virtual console windows using their respective gui objects, results in both buttons being drawn on the same virtual console window. Why?
Yes, OOP in Lua is hard for Lua beginners, despite of excellent knowledge of OOP languages (such as Java).
--Meta class
gui = {} -- class is a global variable, no default properties exist
function gui:new(t, title) -- t = window, self = your class "gui"
local o = {} -- creating NEW object
setmetatable(o, self) -- link the object with the class
self.__index = self
o.t = t -- save window into object (not into class)
local sX, sY = t.getSize() -- get the size of the virtual terminal
o.vpx = sX -- save window's properties into object (not into class)
o.vpy = sY
t.setCursorPos(1, 1)
t.write(tostring(title))
return o
end
function gui:drawButton(x, y, sX, sY, colour) -- self = object
....
end

Mathematica can't solve DSolve[{f[0] ==d,f'[0]==v0,f''[t] == -g*m2/f[t]^2}, f, t]?

In[11]:= $Version
Out[11]= 9.0 for Linux x86 (32-bit) (November 20, 2012)
In[12]:= DSolve[{f[0] == d, f'[0] == v0, f''[t] == g*m2/f[t]^2}, f, t]
DSolve::bvimp: General solution contains implicit solutions. In the boundary
value problem these solutions will be ignored, so some of the solutions will
be lost.
Out[12]= {}
The code above pretty much says it all. I get the same error if I replace g*m2 with 1.
This seems like a really simple DFQ to solve. I'd like to tell DSolve to assume all variables are real and that d, g, and m2 are all greater than 0, but there's unfortunately no way to do that.
Thoughts?
You are trying for a symbolic solution. And unfortunately, symbolic integration is hard (while symbolic differentiation is easy).
The way this integration works is to obtain the energy functional by integrating once
E = 1/2*f'[t]^2 + C/f[t]
and then to isolate f'[t]. The resulting integral is not easy to solve and leads to the mentioned implicit solutions.
Did you really want to get the symbolic solution or only some function table to plot the solutions or compute other related quantities?
Since it was clarified that the requested quantity is the maximum of certain solutions: This can be computed by setting v=0 in the energy equation
C/x = E = 1/2*v0^2 + C/x0
or
x = C*x0/(C + 1/2*v0^2*x0 )
One would have to analyze the time aspect to make sure that this extremum is reached before passing again at the initial point x0.

What does E6A mean In fortran code

I'm trying to do some interesting orbit mechanics, I've found some related code in Fortan and I'm going through line by line moving it to Visual Basic. I can't understand what this is though:
IF(ABS(EPW-TEMP2) .LE. E6A) GO TO 140
It's not a variable. I figure E6 might be 10^6 but what's the 'A' mean?
Thanks!
When I google that line of code, I end up with some "Spacetrack Report No.3" with the fortran code listing. And E6A is defined as 1.E-6 in the routine DRIVER (Page. 73)
DATA DE2RA,E6A,PI,PIO2,QO,SO,TOTHRD,TWOPI,X3PIO2,XJ2,XJ3,
1 XJ4,XKE,XKMPER,XMNPDA,AE/.174532925E-1,1.E-6,
2 3.14159265,1.57079633,120.0,78.0,.66666667,
4 6.2831853,4.71238898,1.082616E-3,-.253881E-5,
5 -1.65597E-6,.743669161E-1,6378.135,1440.,1.
I see this code has already been converted to Java and C, perhaps you should use those as reference.

Quick divisibility check in ZX81 BASIC

Since many of the Project Euler problems require you to do a divisibility check for quite a number of times, I've been trying to figure out the fastest way to perform this task in ZX81 BASIC.
So far I've compared (N/D) to INT(N/D) to check, whether N is dividable by D or not.
I have been thinking about doing the test in Z80 machine code, I haven't yet figured out how to use the variables in the BASIC in the machine code.
How can it be achieved?
You can do this very fast in machine code by subtracting repeatedly. Basically you have a procedure like:
set accumulator to N
subtract D
if carry flag is set then it is not divisible
if zero flag is set then it is divisible
otherwise repeat subtraction until one of the above occurs
The 8 bit version would be something like:
DIVISIBLE_TEST:
LD B,10
LD A,100
DIVISIBLE_TEST_LOOP:
SUB B
JR C, $END_DIVISIBLE_TEST
JR Z, $END_DIVISIBLE_TEST
JR $DIVISIBLE_TEST_LOOP
END_DIVISIBLE_TEST:
LD B,A
LD C,0
RET
Now, you can call from basic using USR. What USR returns is whatever's in the BC register pair, so you would probably want to do something like:
REM poke the memory addresses with the operands to load the registers
POKE X+1, D
POKE X+3, N
LET r = USR X
IF r = 0 THEN GOTO isdivisible
IF r <> 0 THEN GOTO isnotdivisible
This is an introduction I wrote to Z80 which should help you figure this out. This will explain the flags if you're not familiar with them.
There's a load more links to good Z80 stuff from the main site although it is Spectrum rather than ZX81 focused.
A 16 bit version would be quite similar but using register pair operations. If you need to go beyond 16 bits it would get a bit more convoluted.
How you load this is up to you - but the traditional method is using DATA statements and POKEs. You may prefer to have an assembler figure out the machine code for you though!
Your existing solution may be good enough. Only replace it with something faster if you find it to be a bottleneck in profiling.
(Said with a straight face, of course.)
And anyway, on the ZX81 you can just switch to FAST mode.
Don't know if RANDOMIZE USR is available in ZX81 but I think it can be used to call routines in assembly. To pass arguments you might need to use POKE to set some fixed memory locations before executing RANDOMIZE USR.
I remember to find a list of routines implemented in the ROM to support the ZX Basic. I'm sure there are a few to perform floating operation.
An alternative to floating point is to use fixed point math. It's a lot faster in these kind of situations where there is no math coprocessor.
You also might find more information in Sinclair User issues. They published some articles related to programming in the ZX Spectrum
You should place the values in some pre-known memory locations, first. Then use the same locations from within Z80 assembler. There is no parameter passing between the two.
This is based on what I (still) remember of ZX Spectrum 48. Good luck, but you might consider upgrading your hw. ;/
The problem with Z80 machine code is that it has no floating point ops (and no integer divide or multiply, for that matter). Implementing your own FP library in Z80 assembler is not trivial. Of course, you can use the built-in BASIC routines, but then you may as well just stick with BASIC.