I have an object with its own inventory, for which I use a list of maps.
Each item has a name and x and y offsets.
I want to draw each item with its offset on top of my other object, and have them turn along with the original object, so inside the draw function I have this:
draw_sprite_ext(spr_cart2, 0, x, y,1,1,direction, c_white, 1)
for(i = 0; i < ds_list_size(products); i++){
product = products[| i]
rad_dir = degtorad(direction)
x_rot = cos(rad_dir)*(product[? "x"]-x) - sin(rad_dir)*(product[? "y"]-y)
y_rot = cos(rad_dir)*(product[? "y"]-y) - sin(rad_dir)*(product[? "x"]-x)
draw_sprite_ext(asset_get_index("spr_"+product[? "product"]), 0, x_rot, y_rot, 1, 1, direction, c_white, 1)
}
However, it doesn't work at all.
I tried logging product[? "x"]-x, and it gave a very large negative number, whereas logging just product[? "x"] did give the expected result.
What worked in the end was not directly subtracting from the map
There were also some errors in the rotational logic.
Working code:
draw_sprite_ext(spr_cart2, 0, x, y,1,1,direction, c_white, 1)
for(i = 0; i < ds_list_size(products); i++){
product = products[| i]
x_rot = (cos(rad_dir)*(product[? "x"])) - (sin(rad_dir)*(product[? "y"]))
y_rot = (cos(rad_dir)*(product[? "y"])) + (sin(rad_dir)*(product[? "x"]))
draw_sprite_ext(asset_get_index("spr_"+product[? "product"]), 0, x-x_rot, y+y_rot, 0.5, 0.5, direction, c_white, 1)
}
Related
I'm trying to understand what's going on with my calculation of canberra distance. I write my own simple canberra.distance function, however the results are not consistent with dist function. I added option na.rm = T to my function, to be able calculate the sum when there is zero denominator. From ?dist I understand that they use similar approach: Terms with zero numerator and denominator are omitted from the sum and treated as if the values were missing.
canberra.distance <- function(a, b){
sum( (abs(a - b)) / (abs(a) + abs(b)), na.rm = T )
}
a <- c(0, 1, 0, 0, 1)
b <- c(1, 0, 1, 0, 1)
canberra.distance(a, b)
> 3
# the result that I expected
dist(rbind(a, b), method = "canberra")
> 3.75
a <- c(0, 1, 0, 0)
b <- c(1, 0, 1, 0)
canberra.distance(a, b)
> 3
# the result that I expected
dist(rbind(a, b), method = "canberra")
> 4
a <- c(0, 1, 0)
b <- c(1, 0, 1)
canberra.distance(a, b)
> 3
dist(rbind(a, b), method = "canberra")
> 3
# now the results are the same
Pairs 0-0 and 1-1 seem to be problematic. In the first case (0-0) both numerator and denominator are equal to zero and this pair should be omitted. In the second case (1-1) numerator is 0 but denominator is not and the term is then also 0 and the sum should not change.
What am I missing here?
EDIT:
To be in line with R definition, function canberra.distance can be modified as follows:
canberra.distance <- function(a, b){
sum( abs(a - b) / abs(a + b), na.rm = T )
}
However, the results are the same as before.
This might shed some light on the difference. As far as I can see this is the actual code being run for computing the distance
static double R_canberra(double *x, int nr, int nc, int i1, int i2)
{
double dev, dist, sum, diff;
int count, j;
count = 0;
dist = 0;
for(j = 0 ; j < nc ; j++) {
if(both_non_NA(x[i1], x[i2])) {
sum = fabs(x[i1] + x[i2]);
diff = fabs(x[i1] - x[i2]);
if (sum > DBL_MIN || diff > DBL_MIN) {
dev = diff/sum;
if(!ISNAN(dev) ||
(!R_FINITE(diff) && diff == sum &&
/* use Inf = lim x -> oo */ (int) (dev = 1.))) {
dist += dev;
count++;
}
}
}
i1 += nr;
i2 += nr;
}
if(count == 0) return NA_REAL;
if(count != nc) dist /= ((double)count/nc);
return dist;
}
I think the culprit is this line
if(!ISNAN(dev) ||
(!R_FINITE(diff) && diff == sum &&
/* use Inf = lim x -> oo */ (int) (dev = 1.)))
which handles a special case and may not be documented.
I am calculating the average drawdown, average length, recovery length, etc. in R for a PnL data series rather than return data. This is data frame like this
PNL
2008-11-03 3941434
2008-11-04 4494446
2008-11-05 2829608
2008-11-06 2272070
2008-11-07 -2734941
2008-11-10 -2513580
I used the maxDrawDown function from fTrading package and it worked. How could I get the other drawdown functions? If I directly run AverageDrawdown(quantbook) function, it will give out error message like this
Error in if (thisSign == priorSign) { : missing value where TRUE/FALSE needed
I checked the documentation for AverageDrawdown and it is as below:
findDrawdowns(R, geometric = TRUE, ...)
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
My quantbook is a data frame but doesn't work for this function.
Or do you have anything other packages to get the same funciton, please advise.
I've modified the package's functions. Here is one solution in PnL case (or any other case you want to get the value rather than the return) and hope you find it useful. The parameter x is a dataframe and the row.names for x are dates so you don't bother to convert amongst different data types (which I actually suffer a lot). With the function findPnLDrawdown, you could perform a lot other functions to calculate averageDrawDown, averageLength, recovery, etc.
PnLDrawdown <- function(x) {
ts = as.vector(x[,1])
cumsum = cumsum(c(0, ts))
cmaxx = cumsum - cummax(cumsum)
cmaxx = cmaxx[-1]
cmaxx = as.matrix(cmaxx)
row.names(cmaxx) = row.names(x)
cmaxx = timeSeries(cmaxx)
cmaxx
}
findPnLDrawdown <- function(R) {
drawdowns = PnLDrawdown(R)
draw = c()
begin = c()
end = c()
length = c(0)
trough = c(0)
index = 1
if (drawdowns[1] >= 0) {
priorSign = 1
} else {
priorSign = 0
}
from = 1
sofar = as.numeric(drawdowns[1])
to = 1
dmin = 1
for (i in 1:length(drawdowns)) {
thisSign =ifelse(drawdowns[i] < 0, 0, 1)
if (thisSign == priorSign) {
if (as.numeric(drawdowns[i]) < as.numeric(sofar)) {
sofar = drawdowns[i]
dmin = i
}
to = i+ 1
}
else {
draw[index] = sofar
begin[index] = from
trough[index] = dmin
end[index] = to
from = i
sofar = drawdowns[i]
to = i + 1
dmin = i
index = index + 1
priorSign = thisSign
}
}
draw[index] = sofar
begin[index] = from
trough[index] = dmin
end[index] = to
list(pnl = draw, from = begin, trough = trough, to = end,
length = (end - begin + 1),
peaktotrough = (trough - begin + 1),
recovery = (end - trough))
}
I have been trying to run this code (below here) and I have gotten that message "Error in if (temp[ii] == 0) { : missing value where TRUE/FALSE needed"...
temp = c(2.15, 3.5, 0, 0, 0, 1.24, 5.42, 6.87)
tm = length(temp)
for (i in 1:tm){
if (temp[i] == 0) {
counter3 = 1
last = temp[i - 1]
for (ii in i + 1:tm){
if (temp[ii] == 0) {
counter3 = counter3 + 1
}
if (temp[ii] != 0) {
nxt = temp[i + counter3]
}
}
}
}
Your problem is that temp[ii] is returning NA because ii goes out of bounds:
ii = i + 1:tm #Your declaration for ii
ii = 1:tm + 1:tm #Evaluates to
So ii will definitely be larger than tm (and therefore length(temp) at some point.
In order to better understand/debug for loops, consider printing just the indices:
for(i in 1:tm)
{
print(i)
for(ii in i + 1:tm)
print(ii)
}
At a guess I'm going to say that this is in R - if so I'm guessing that this line:
if (temp[i] == 0) (or temp[ii] == 0)
is resulting in an NA, and if conditions must have a TRUE or FALSE value.
Using a debugger if you can, I'd interrogate the value of temp[i] before the if block.
Difficult without knowing the language, but i think the issue is that the value in ii can be greater than the length of temp when i is at its upper bound. I'd have expected an index out of range or something similar but, without knowing the language, who knows! Hope you get your problem fixed.
I'm trying to draw a simple grid on a canvas. First I did this
function start()
{
var x = 0;
var y = 0;
for (x = 0; x < 500; x += 50)
{
line(0 + x, 50 + y, 50 + x, 50 + y, 1, "#111");
line(50 + x, 0 + y, 50 + x, 50 + y, 1, "#111");
if (x == 450)
{
x = -50;
y += 50;
}
if (y == 500)
{
x = 500;
}
}
}
It works fine. But I want to be able to easily change the size of the grid and canvas. So I did this:
function start()
{
var x = 0;
var y = 0;
var cW = canvas.width;
var cH = canvas.hight;
var gS = 50; //gS = gridSpace
for (x = 0; x < cW; x += gS)
{
line(0 + x, gS + y, gS + x, gS + y, 1, "#111");
line(gS + x, 0 + y, gS + x, gS + y, 1, "#111");
if (x == cW - gS)
{
x = -gS;
y += gS;
}
if (y == cH)
{
x = cW;
}
}
}
It does not work! Please help me.
PS. I'm using a library.
`
You might want to approach this a little differently. I'm not entirely sure of what you're trying to accomplish here, but here are some pointers/questions that may guide you toward what you're trying to do:
When drawing a grid, you are drawing a series of horizontal lines and a series of vertical lines. Use two loops to simplify that process.
For the horizontal lines, the y-value varies, but the x-coords for the line endpoints stay the same (e.g. 0 and cW). The converse applies to the vertical lines.
What kind of spacing are you really trying to achieve? Typically you're looking at either dividing the space into a certain number of areas (say 6 rows and 4 columns), or spacing that doesn't adapt to the specific canvas you're drawing on (this is what you're code seems to be trying to do). So, the first will adapt to the size of the canvas while the latter will just display more/fewer rows/columns as the canvas size varies.
I hope that helps you solve your problem, please let me know if you need any more help!
One possibility, is that you have height spelled incorrectly. I believe javascript, if this is javascript, won't complain about incorrectly named variables. (I could be wrong on that).
var cH = canvas.hight;
should be
var cH = canvas.height;
In this answer to my recent question, there is some code that draws a graph, but I can't manage to edit it into something that accepts any list of points as a parameter.
I'd like the Drawing method to accept these parameters:
List of Vector2, Point or VertexPositionColor, I can work with whichever.
Offset for the whole graph
These optional requirements would be appreciated:
Color that may override VertexPositionColor's color and apply to all points.
Size of the graph, so it can be shrunk or expanded, either as Vector2 as multiplier, or Point as target size. Maybe even combine this with offset in Rectangle.
And if it's possible, I'd like to have it all in a class, so graphs can be used separately from each other, each with its own Effect.world matrix, etc.
Here is that code (by Niko Drašković):
Matrix worldMatrix;
Matrix viewMatrix;
Matrix projectionMatrix;
BasicEffect basicEffect;
VertexPositionColor[] pointList;
short[] lineListIndices;
protected override void Initialize()
{
int n = 300;
//GeneratePoints generates a random graph, implementation irrelevant
pointList = new VertexPositionColor[n];
for (int i = 0; i < n; i++)
pointList[i] = new VertexPositionColor() { Position = new Vector3(i, (float)(Math.Sin((i / 15.0)) * height / 2.0 + height / 2.0 + minY), 0), Color = Color.Blue };
//links the points into a list
lineListIndices = new short[(n * 2) - 2];
for (int i = 0; i < n - 1; i++)
{
lineListIndices[i * 2] = (short)(i);
lineListIndices[(i * 2) + 1] = (short)(i + 1);
}
worldMatrix = Matrix.Identity;
viewMatrix = Matrix.CreateLookAt(new Vector3(0.0f, 0.0f, 1.0f), Vector3.Zero, Vector3.Up);
projectionMatrix = Matrix.CreateOrthographicOffCenter(0, (float)GraphicsDevice.Viewport.Width, (float)GraphicsDevice.Viewport.Height, 0, 1.0f, 1000.0f);
basicEffect = new BasicEffect(graphics.GraphicsDevice);
basicEffect.World = worldMatrix;
basicEffect.View = viewMatrix;
basicEffect.Projection = projectionMatrix;
basicEffect.VertexColorEnabled = true; //important for color
base.Initialize();
}
And the drawing method:
foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
{
pass.Apply();
GraphicsDevice.DrawUserIndexedPrimitives<VertexPositionColor>(
PrimitiveType.LineList,
pointList,
0,
pointList.Length,
lineListIndices,
0,
pointList.Length - 1
);
}
The Graph class that does the requested can be found here.About 200 lines of code seemed too much to paste here.
The Graph is drawn by passing a list of floats (optionally with colors) to its Draw(..) method.
Graph properties are:
Vector2 Position - the bottom left corner of the graph
Point Size - the width (.X) and height (.Y) of the graph. Horizontally, values will be distributed to exactly fit the width. Vertically, all values will be scaled with Size.Y / MaxValue.
float MaxValue - the value which will be at the top of the graph. All off the chart values (greater than MaxValue) will be set to this value.
GraphType Type - with possible values GraphType.Line and GraphType.Fill, determines if the graph will be drawn line only, or bottom filled.
The graph is drawn with a line list / triangle strip.