Related
I receive the error "pine cannot determine the referencing length of a series. try using max_bars_back in the study or strategy function" when trying to perform a function on the barstate.islast condition.
I am using this condition in order to try and speed up my script as it does not need to perform all actions in the function until the last bar of the script. Even performing the function on the last bar is intensive, so I attempt to bypass unnecessary logic when able by using the stopPocIndexNo bool once the lines requested have been drawn.
If I remove the bool, then the loop on any particular bar takes to long > 500ms.
//#version=5
indicator("High Volume Candle Mid", overlay = true, max_lines_count = 100, max_labels_count = 100, max_bars_back = 5000)
maLengthInput = input.int(defval = 34, title = "Volume - Moving Average Length", group = "Options")
volLengthInput = input.int(defval = 5, title = "Volume - Look Back", group = "Options")
maMultiplierInput = input.float(defval = 2, title = "Volume - MA Multiplier", tooltip = "Filter's out weak volume candles that break MA", group = "Options")
qtyOfClosesInput = input.int(defval = 3, title = "(n) closes to cross POC to invalidate.", group = "Options")
qtyOfLinesInput = input.int(defval = 10, title = "(n) latest POC's to show", group = "Options")
qtyOfBrokenLinesInput = input.int(defval = 10, title = "(n) latest historical POC's to show", group = "Options")
barAlignInput = input.int(defval = 20, title = "Bar Index Offset", tooltip = "How many bars past price to extend labels/lines", group = "Options")
supplyColorInput = input.color(defval = #FF5252, title = "Supply Zone - POC's", group = "Options" )
demandColorInput = input.color(defval = #4CAF50, title = "Demand Zone - POC's", group = "Options")
///// Variables
var float maVol = na
var float highestVol = na
var bool pocCondition = false
var float[] barOpens = array.new_float()
var float[] barCloses = array.new_float()
var float[] barPocs = array.new_float()
var color[] barColors = array.new_color()
///// Functions
deleteLines() =>
a_allLines = line.all
if array.size(a_allLines) > 0
for i = 0 to array.size(a_allLines) - 1
line.delete(array.get(a_allLines, i))
deleteLabels() =>
a_allLabels = label.all
if array.size(a_allLabels) > 0
for i = 0 to array.size(a_allLabels) - 1
label.delete(array.get(a_allLabels, i))
createLines(arrayOfPocs, arrayOfOpens, arrayOfCloses, arrayOfColors, qtyOfCloses, maxLines, maxBrokenLines, barAlign, demandColor, supplyColor) =>
int qtyOfPocs = array.size(arrayOfPocs)
int supplyLinesCount = 0
int supplyBrokenLinesCount = 0
int demandLinesCount = 0
int demandBrokenLinesCount = 0
float lastClose = close[1]
bool stopPocIndexNo = false
deleteLines()
deleteLabels()
for pocIndexNo = (qtyOfPocs > 1 ? qtyOfPocs - 1 : na) to 0
int closeCount = 0
bool lineCrossed = false
int barsSince = (bar_index - pocIndexNo) - 1
float barPoc = array.get(arrayOfPocs, pocIndexNo)
cColor = array.get(arrayOfColors, pocIndexNo)
//string supplyCrossedCloses = na
//string demandCrossedCloses = na
if stopPocIndexNo == false
if barPoc > 0 and barsSince > 2
bool isDemand = barPoc < lastClose
int lineIndex = (bar_index - barsSince) > (bar_index - 2500) ? (bar_index - barsSince) : bar_index - 2500
for indexNo = barsSince to 1
if lineCrossed == false
fClose = array.get(arrayOfCloses, indexNo)
fOpen = array.get(arrayOfOpens, indexNo)
if (fClose > barPoc and fOpen < barPoc) or (fClose < barPoc and fOpen > barPoc)
closeCount := closeCount + 1
if (closeCount > qtyOfCloses)
lineCrossed := true
if lineCrossed
if isDemand and demandBrokenLinesCount < maxBrokenLines
line.new(lineIndex, barPoc, bar_index + barAlign, barPoc, color = color.new(color.white, 50), style = line.style_dotted, width = 1, extend = extend.none)
label.new(bar_index + barAlign, barPoc, text = str.tostring(barPoc), textcolor = color.new(color.white, 50), textalign = text.align_right, style = label.style_none)
demandBrokenLinesCount := demandBrokenLinesCount + 1
else
if supplyBrokenLinesCount < maxBrokenLines
line.new(lineIndex, barPoc, bar_index + barAlign, barPoc, color = color.new(color.white, 50), style = line.style_dotted, width = 1, extend = extend.none)
label.new(bar_index + barAlign, barPoc, text = str.tostring(barPoc), textcolor = color.new(color.white, 50), textalign = text.align_right, style = label.style_none)
supplyBrokenLinesCount := supplyBrokenLinesCount + 1
else
if lineCrossed == false
if isDemand and demandLinesCount < maxLines
line.new(lineIndex, barPoc, bar_index + barAlign, barPoc, color = cColor, style = line.style_dashed, width = 1, extend = extend.none)
label.new(bar_index + barAlign, barPoc, text = str.tostring(barPoc), textcolor = cColor, textalign = text.align_right, style = label.style_none)
demandLinesCount := demandLinesCount + 1
else
if supplyLinesCount < maxLines
line.new(lineIndex, barPoc, bar_index + barAlign, barPoc, color = cColor, style = line.style_dashed, width = 1, extend = extend.none)
label.new(bar_index + barAlign, barPoc, text = str.tostring(barPoc), textcolor = cColor, textalign = text.align_right, style = label.style_none)
supplyLinesCount := supplyLinesCount + 1
if supplyBrokenLinesCount == maxBrokenLines and demandBrokenLinesCount == maxBrokenLines and supplyLinesCount == maxLines and demandLinesCount == maxLines
stopPocIndexNo := true
///// Calculations
// Calculate moving average and highest volume bar in the last volLengthInput
maVol := ta.sma(volume, maLengthInput)
highestVol := ta.highest(volume, volLengthInput)
// Detect new POC Lines by finding vars that breached the Moving Average with Multiplier as well as being the most recent highest volume bar
pocCondition := (volume >= maVol * maMultiplierInput) and volume == highestVol
// Store bar POC's if poc condition is met, otherwise store nothing
if pocCondition
array.push(barPocs, (high + low)/2)
if close > open
array.push(barColors, demandColorInput)
else
array.push(barColors, supplyColorInput)
else
array.push(barPocs, 0)
array.push(barColors, na)
// Store opens/closes for later calculations to detect line crosses
array.push(barCloses, close)
array.push(barOpens, open)
// We don't want to calculate line breaches every bar as it would be too slow, so wait until its the last bar to look for POC's
if barstate.islast
aOpens = array.copy(barOpens)
aCloses = array.copy(barCloses)
array.reverse(aOpens)
array.reverse(aCloses)
createLines(barPocs, aOpens, aCloses, barColors, qtyOfClosesInput, qtyOfLinesInput/2, qtyOfBrokenLinesInput/2, barAlignInput, demandColorInput, supplyColorInput)
barcolor(color = pocCondition and close > open ? demandColorInput : pocCondition and open > close ? supplyColorInput : na)
If I remove some of the functionality to speed up the script, only checking for non crossed lines, it works without issue.
/#version=5
indicator("High Volume Candle Mid", overlay = true, max_lines_count = 100, max_labels_count = 100, max_bars_back = 5000)
maLengthInput = input.int(defval = 34, title = "Volume - Moving Average Length", group = "Options")
volLengthInput = input.int(defval = 5, title = "Volume - Look Back", group = "Options")
maMultiplierInput = input.float(defval = 2, title = "Volume - MA Multiplier", tooltip = "Filter's out weak volume candles that break MA", group = "Options")
qtyOfClosesInput = input.int(defval = 3, title = "(n) closes to cross POC to invalidate.", group = "Options")
qtyOfLinesInput = input.int(defval = 10, title = "(n) latest POC's to show", group = "Options")
qtyOfBrokenLinesInput = input.int(defval = 10, title = "(n) latest historical POC's to show", group = "Options")
barAlignInput = input.int(defval = 20, title = "Bar Index Offset", tooltip = "How many bars past price to extend labels/lines", group = "Options")
supplyColorInput = input.color(defval = #FF5252, title = "Supply Zone - POC's", group = "Options" )
demandColorInput = input.color(defval = #4CAF50, title = "Demand Zone - POC's", group = "Options")
///// Variables
var float maVol = na
var float highestVol = na
var bool pocCondition = false
var float[] barOpens = array.new_float()
var float[] barCloses = array.new_float()
var float[] barPocs = array.new_float()
var color[] barColors = array.new_color()
///// Functions
deleteLines() =>
a_allLines = line.all
if array.size(a_allLines) > 0
for i = 0 to array.size(a_allLines) - 1
line.delete(array.get(a_allLines, i))
deleteLabels() =>
a_allLabels = label.all
if array.size(a_allLabels) > 0
for i = 0 to array.size(a_allLabels) - 1
label.delete(array.get(a_allLabels, i))
createLines(arrayOfPocs, arrayOfOpens, arrayOfCloses, arrayOfColors, qtyOfCloses, maxLines, maxBrokenLines, barAlign, demandColor, supplyColor) =>
int qtyOfPocs = array.size(arrayOfPocs)
int supplyLinesCount = 0
int supplyBrokenLinesCount = 0
int demandLinesCount = 0
int demandBrokenLines = 0
float lastClose = close[1]
deleteLines()
deleteLabels()
for pocIndexNo = (qtyOfPocs > 1 ? qtyOfPocs - 1 : na) to 0
int supplyCloseCount = 0
int demandCloseCount = 0
bool supplyLineCrossed = false
bool demandLineCrossed = false
int barsSince = (bar_index - pocIndexNo) - 1
float barPoc = array.get(arrayOfPocs, pocIndexNo)
cColor = array.get(arrayOfColors, pocIndexNo)
//string supplyCrossedCloses = na
//string demandCrossedCloses = na
//if supplyLinesCount < maxLines or supplyBrokenLinesCount < maxBrokenLines
if barPoc > lastClose and barPoc > 0
if barsSince > 1
int lineIndex = (bar_index - barsSince) > (bar_index - 4999) ? (bar_index - barsSince) : bar_index - 4999
for indexNo = barsSince to 1
fClose = array.get(arrayOfCloses, indexNo)
fOpen = array.get(arrayOfOpens, indexNo)
if (fClose > barPoc and fOpen < barPoc) or (fClose < barPoc and fOpen > barPoc)
//supplyCrossedCloses := supplyCrossedCloses + "Crossed Count: " + str.tostring(supplyCloseCount) + "\n" + str.tostring(fClose) + " > " + str.tostring(barPoc) + " and " + str.tostring(fOpen) + " < " + str.tostring(barPoc) + " or " + str.tostring(fClose) + " < " + str.tostring(barPoc) + " and " + str.tostring(fOpen) + " > " + str.tostring(barPoc) + "\n"
supplyCloseCount := supplyCloseCount + 1
if (supplyCloseCount > qtyOfCloses)
supplyLineCrossed := true
// if supplyLineCrossed == true and supplyBrokenLinesCount < maxBrokenLines
// line.new(lineIndex, barPoc, bar_index + barAlign, barPoc, color = color.new(color.white, 50), style = line.style_dotted, width = 1, extend = extend.none)
// label.new(bar_index + barAlign, barPoc, text = str.tostring(barPoc) + " [" + str.tostring(lineIndex) + "]", textcolor = color.new(color.white, 50), textalign = text.align_right, style = label.style_none)
// supplyBrokenLinesCount := supplyBrokenLinesCount + 1
if supplyLineCrossed == false and supplyLinesCount < maxLines
//label.new(lineIndex, close + (supplyLines * 400), text = "barPoc: " + str.tostring(barPoc) + "\nsupplyLines: " + str.tostring(supplyLines) + "\nsupplyCloseCount: " + str.tostring(supplyCloseCount) + "\n" + supplyCrossedCloses, textcolor = color.aqua, style = label.style_label_down, color = color.new(color.white, 100))
line.new(lineIndex, barPoc, bar_index + barAlign, barPoc, color = cColor, style = line.style_dashed, width = 1, extend = extend.none)
label.new(bar_index + barAlign, barPoc, text = str.tostring(barPoc) + " [" + str.tostring(lineIndex) + "]", textcolor = cColor, textalign = text.align_right, style = label.style_none)
supplyLinesCount := supplyLinesCount + 1
///// Calculations
// Calculate moving average and highest volume bar in the last volLengthInput
maVol := ta.sma(volume, maLengthInput)
highestVol := ta.highest(volume, volLengthInput)
// Detect new POC Lines by finding vars that breached the Moving Average with Multiplier as well as being the most recent highest volume bar
pocCondition := (volume >= maVol * maMultiplierInput) and volume == highestVol
// Store bar POC's if poc condition is met, otherwise store nothing
if pocCondition
array.push(barPocs, (high + low)/2)
if close > open
array.push(barColors, demandColorInput)
else
array.push(barColors, supplyColorInput)
else
array.push(barPocs, 0)
array.push(barColors, na)
// Store opens/closes for later calculations to detect line crosses
array.push(barCloses, close)
array.push(barOpens, open)
// We don't want to calculate line breaches every bar as it would be too slow, so wait until its the last bar to look for POC's
if barstate.islast
aOpens = array.copy(barOpens)
aCloses = array.copy(barCloses)
array.reverse(aOpens)
array.reverse(aCloses)
createLines(barPocs, aOpens, aCloses, barColors, qtyOfClosesInput, qtyOfLinesInput/2, qtyOfBrokenLinesInput/2, barAlignInput, demandColorInput, supplyColorInput)
barcolor(color = pocCondition and close > open ? demandColorInput : pocCondition and open > close ? supplyColorInput : na)
Not sure what I am missing about the barstate.islast and how it affects series lengths that could be causing me issue. I stopped referencing bar_index in the arrays I was utilizing to find the historical Mids I needed, but I still use it to create lines. If this is not supported does anyone have a better idea for creating the lines? Or if there is some issue with creating lines under multiple conditionals?
// Inputs
var rsiLength = 14
var macdFastLength = 12
var macdSlowLength = 26
var macdSignalLength = 9
var atrLength = 14
var volumeFactor = 0.1
// Calculate indicators
var rsi = rsi(close, rsiLength)
var macd = macd(close, macdFastLength, macdSlowLength, macdSignalLength)
var atr = atr(atrLength)
var volume = volume * volumeFactor
// Define signals
var buySignal = rsi < 30 and macd.histogram > 0 and volume > atr
var sellSignal = rsi > 70 and macd.histogram < 0 and volume > atr
// Plot signals
plot(buySignal ? 50 : na, color=color.green, linewidth=3, style=plot.style_circles, title='Buy Signal')
plot(sellSignal ? 50 : na, color=color.red, linewidth=3, style=plot.style_circles, title='Sell Signal')
// Capital
strategy.risk = 0.01
strategy.entry("Long", strategy.long, when=buySignal, comment="Buy")
strategy.close("Long", when=sellSignal, comment="Sell")
Script could not be translated from: |B|var rsiLength = 14|E|
It tried to make a strategy which generates buy and sell signal but it showing this
I built a code to import multiple data simultaneously into SAS, but I want to improve it does anyone have any suggestions?
filename indata pipe 'dir E:\Desafio_SAS\Dados /B';
data file_list;
length arquivos$20.;
infile indata truncover ;
input arquivos $20.;
call symput('num_files',_n_);
arquivos=compress(arquivos,',.txt');
run;
CRIANDO UMA MACRO POR PROC SQL PARA GUARDAR O NOME DOS ARQUIVOS
proc sql;
select arquivos into :lista separated by ' ' from file_list;
quit;
%let &lista;
%macro importar(arquivo=);
filename data "E:\Desafio_SAS\Dados\&arquivo..txt";
data &arquivo;
infile data dlm=" " missover dsd firstobs=2;
input v0 (v1 - v8) ($);
format v0 F16.;
run;
%mend importar;
%macro fileout;
%do i=1 %to &num_files;
%importar(arquivo=df&i);
data df&i;
set var_names df&i;
run;
%end;
%mend fileout;
%fileout;
%macro excluiv0;
%do i=1 %to &num_files;
data _null_;
data df&i(drop = v0);
set df&i;
run;
%end;
run;
%mend excluiv0;
%excluiv0;
It's just part of the code.
You can use a wildcard in the infile file-specification. As long as all the files meeting the wildcard are the same layout, you can use a single input to read all the files.
Example
* create three text files having same fields;
data _null_;
file '%temp%\1.txt';
put '1 2 3 abc';
put '3 4 5 def';
file '%temp%\2.txt';
put '6 7 8 ghi';
put '9 10 11 jkl';
file '%temp%\3.txt';
put '12 13 14 xyz';
put '15 16 17 tuv';
run;
* read all three using wildcard in infile. Save name of file whence
* data cometh frometh;
data want;
length _filename_ $250;
infile '%temp%\?.txt' filename=_filename_;
length source $250;
length a b c 8 s $20;
source = _filename_;
input a b c s;
run;
Wildcards are
?, 0 or 1 of any character
*, any number of any character
t1 <- ttheme_default(core=list(
fg_params=list(fontface=c("bold.italic")),
bg_params = list(fill=c("green", "grey90","blue","red"))))
grid.arrange(g1,
tableGrob(iris[1:5, 1:4], theme = t1,, rows=NULL),
g1, g1, nrow = 2)
---
title: "Column Orientation"
output: flexdashboard::flex_dashboard
---
```{r setup, include=FALSE}
library(ggplot2);library(knitr);library(kableExtra)
library(flexdashboard);library(gridExtra);library(grid)
```
<style>
.colored {
background-color: #002080;}
</style>
Column{data-width=200}
-------------------------------------
### Chart 1{.colored}
```{r}
gauge(10, min = 0, max = 100, sectors = gaugeSectors(colors = "#002080"))
gauge(50, min = 0, max = 100, sectors = gaugeSectors(colors = "#002080"))
gauge(20, min = 0, max = 100, sectors = gaugeSectors(colors = "#002080"))
gauge(15, min = 0, max = 100, sectors = gaugeSectors(colors = "#002080"))
gauge(5 , min = 0, max = 100, sectors = gaugeSectors(colors = "#002080"))
```
Column
-------------------------------------
### Chart 2
```{r, include=FALSE}
tt1 <- ttheme_default()
tt2 <- ttheme_minimal()
tt3 <- ttheme_minimal(
core=list(bg_params = list(fill = blues9[1:4], col=NA),
fg_params=list(fontface=3)),
colhead=list(fg_params=list(col="navyblue", fontface=4L)),
rowhead=list(fg_params=list(col="orange", fontface=3L)))
tab <- grid.arrange(tableGrob(iris[c(1:4,1:2), c(1:3,1:2)], theme=tt3), nrow=1)
graf <- ggplot(data=mtcars, aes(x=drat, y=disp, group=vs)) +
geom_line() + ylab("") +
geom_point()
gg.gauge <- function(pos,breaks=c(0,10,25,100)) {
get.poly <- function(a,b,r1=0.5,r2=1.0) {
th.start <- pi*(1-a/100)
th.end <- pi*(1-b/100)
th <- seq(th.start,th.end,length=1000)
x <- c(r1*cos(th),rev(r2*cos(th)))
y <- c(r1*sin(th),rev(r2*sin(th)))
return(data.frame(x,y))
}
ggplot()+
geom_polygon(data=get.poly(breaks[1],breaks[2]),aes(x,y),fill="forestgreen", colour = "white", size = 1.2, alpha = 0.7) +
geom_polygon(data=get.poly(breaks[2],breaks[3]),aes(x,y),fill="gold", colour = "white", size = 1.2, alpha = 0.7) +
geom_polygon(data=get.poly(breaks[3],breaks[4]),aes(x,y),fill="red", colour = "white", size = 1.2, alpha = 0.7) +
geom_polygon(data=get.poly(pos-1,pos+1,0.2),aes(x,y), colour = "white")+
annotate("text",x=0,y=0,label=pos,vjust=0,size=8,fontface="bold")+
coord_fixed()+
theme_bw()+
theme(axis.text=element_blank(),
axis.title=element_blank(),
axis.ticks=element_blank(),
panel.grid=element_blank(),
panel.border=element_blank())
}
gg1 <- gg.gauge(2,breaks=c(0,10,25,100))
gg2 <- gg.gauge(5,breaks=c(0,10,25,100))
gg3 <- gg.gauge(7,breaks=c(0,10,25,100))
```
```{r, fig.width=9.5, fig.height=7}
for (i in 1:5){
title1=textGrob("Test title TESTE", gp=gpar(fontface="bold", fontsize = 15))
lay <- rbind(c(3,3,4,4,5,5),
c(1,1,1,1,1,1),
c(1,1,1,1,1,1),
c(2,2,2,2,2,2),
c(2,2,2,2,2,2))
grid.arrange(graf, tab, gg1, gg2, gg3, top=title1,
layout_matrix= lay)
grid.rect(width = 1, height = 1, gp = gpar(lwd = 2, col = "black", fill = NA))
cat("\n")
}
```
---
title: "BRADESCO"
output:
flexdashboard::flex_dashboard:
orientation: rows
---
```{r setup, include=FALSE}
library(ggplot2);library(knitr);library(kableExtra)
library(flexdashboard);
library(gridExtra);library(grid)
```
Geral {data-icon="fa-signal"}
=====================================
### Chat 1
```{r}
p1 <- qplot(mpg, wt, data = mtcars, colour = cyl)
p2 <- qplot(mpg, data = mtcars)
p3 <- qplot(mpg, data = mtcars, geom = "dotplot")
lay <- rbind(c(1,1,1,2,2,2),
c(3,3,3,3,3,3))
grid.arrange(p2, p3, p1, nrow = 2, layout_matrix= lay)
```
### Table 1
```{r}
kable(mtcars[1:10, c(1:6,1:4)], caption = "Group Rows") %>%
kable_styling("striped", full_width = F) %>%
group_rows("Group 1", 4, 7) %>%
group_rows("Group 2", 8, 10)
```
Por segmento {data-icon="fa-signal"}
=====================================
<style>
.colored {
background-color: #002080;}
</style>
Row{data-height=200}
-------------------------------------
### Chart 1{.colored}
```{r, fig.width=55}
dat = data.frame(count=rep(c(10, 60, 30),10), category=rep(c("A", "B", "C"),10), fator=c(1,2,3,4,5))
# Add addition columns, needed for drawing with geom_rect.
dat$fraction = dat$count / sum(dat$count)
dat = dat[order(dat$fraction), ]
dat$ymax = cumsum(dat$fraction)
dat$ymin = c(0, head(dat$ymax, n=-1))
p <- ggplot(dat, aes(x=2, y=fraction, fill=category))+
geom_bar(stat="identity", colour = "white", size = 2) +
xlim(0, 2.5) +
scale_fill_manual(values=c("#002080", "#002080", "white")) +
coord_polar(theta = "y")+
labs(x=NULL, y=NULL)+ guides(fill=FALSE) +
ylab("fsfagafs") + facet_wrap(~ fator,nrow = 1) +
annotate("text", x = 0, y = 0, label = "WW", size = 20, colour = "white") +
theme(
plot.margin = margin(-1.1, 3.6, -1.1, 3.6, "cm"),
panel.spacing = unit(30, "lines"),
axis.ticks=element_blank(),
axis.text=element_blank(),
axis.title=element_blank(),
panel.grid=element_blank(),
plot.background = element_rect(fill = "#002080", colour="#002080"),
panel.background = element_rect(fill = "#002080", colour="#002080"),
strip.background = element_blank(),
strip.text.x = element_blank())
p
```
Row
-------------------------------------
### Chart 2 {data-wight=900}
```{r, include=FALSE}
tt1 <- ttheme_default()
tt2 <- ttheme_minimal()
tt3 <- ttheme_minimal(
core=list(bg_params = list(fill = blues9[1:4], col=NA),
fg_params=list(fontface=3)),
colhead=list(fg_params=list(col="navyblue", fontface=4L)),
rowhead=list(fg_params=list(col="orange", fontface=3L)))
tab <- grid.arrange(tableGrob(iris[c(1:4,1:2), c(1:3,1:2)], theme=tt3), nrow=1)
graf <- ggplot(data=mtcars, aes(x=drat, y=disp, group=vs)) +
geom_line() + ylab("") +
geom_point()
gg.gauge <- function(pos,breaks=c(0,10,25,100)) {
get.poly <- function(a,b,r1=0.5,r2=1.0) {
th.start <- pi*(1-a/100)
th.end <- pi*(1-b/100)
th <- seq(th.start,th.end,length=1000)
x <- c(r1*cos(th),rev(r2*cos(th)))
y <- c(r1*sin(th),rev(r2*sin(th)))
return(data.frame(x,y))
}
ggplot()+
geom_polygon(data=get.poly(breaks[1],breaks[2]),aes(x,y),fill="forestgreen", colour = "white", size = 1.2, alpha = 0.7) +
geom_polygon(data=get.poly(breaks[2],breaks[3]),aes(x,y),fill="gold", colour = "white", size = 1.2, alpha = 0.7) +
geom_polygon(data=get.poly(breaks[3],breaks[4]),aes(x,y),fill="red", colour = "white", size = 1.2, alpha = 0.7) +
geom_polygon(data=get.poly(pos-1,pos+1,0.2),aes(x,y), colour = "white")+
annotate("text",x=0,y=0,label=pos,vjust=0,size=8,fontface="bold")+
coord_fixed()+
theme_bw()+
theme(axis.text=element_blank(),
axis.title=element_blank(),
axis.ticks=element_blank(),
panel.grid=element_blank(),
panel.border=element_blank())
}
gg1 <- gg.gauge(2,breaks=c(0,10,25,100))
gg2 <- gg.gauge(5,breaks=c(0,10,25,100))
gg3 <- gg.gauge(7,breaks=c(0,10,25,100))
```
```{r, fig.width=7.2, fig.height=7}
for (i in 1:5){
title1=textGrob("Test title TESTE", gp=gpar(fontface="bold", fontsize = 15))
lay <- rbind(c(3,3,4,4,5,5),
c(1,1,1,1,1,1),
c(1,1,1,1,1,1),
c(2,2,2,2,2,2),
c(2,2,2,2,2,2))
grid.arrange(graf, tab, gg1, gg2, gg3, top=title1,
layout_matrix= lay)
grid.rect(width = 1, height = 1, gp = gpar(lwd = 2, col = "black", fill = NA))
cat("\n")
}
```
### Chart 2
```{r}
mydata = data.frame(x1 = c(1,2,3),
x2 = c(9,8,7),
label = c("description a",
"description b",
"description c"))
ht = 5
wd1 = 5
wd2 = 12
gap = 0.1
nc = ncol(mydata)
nr = nrow(mydata)
x = rep(c(seq(0,(nc-2)*(wd1+gap), wd1+gap), (nc-2)*(wd1+gap) + gap + 0.5*(wd2+wd1)), nr)
y = rep(seq(0,(nr-1)*(ht+gap), ht+gap), nc) %>% sort()
h = rep(ht, nr * nc)
w = rep(c(rep(wd1, nc-1), wd2), nr)
info = as.vector(t(as.matrix(mydata[nr:1,])))
df = data.frame(x = x, y = y, h = h, w = w, info = info)
ggplot(df, aes(x, y, height = h, width = w, label = info)) +
geom_tile() +
geom_text(color = "white", fontface = "bold") +
coord_fixed() +
scale_fill_brewer(type = "qual",palette = "Dark2") +
theme_void() +
guides(fill = F)
```
teste
I'm optimizing via Genetic Algorithm a machine simulator (of a MultiheadWeigher machine) in order to solve the well known "Setup problem". I based all the code on matricies but with the multiproduct case I think there is still some inefficiency...
Code
function [f] = MHW(position_matrix, HA, HB, HC)
global W_best_tot
global Function
global n_b_global
nComb = size(position_matrix,1);
dim = size(position_matrix,2);
WL = 241;
%SIMULATIONS VARIABLES
alpha = 0.123;
nSim = 3000;
CellUncertainty = 0.5 * 10^(-6);
%// Define Product Hopper allocation
WT_A = 130; WL_A = 129;
WT_B = 30; WL_B = 29;
%HC = 2;
WT_C = 90; WL_C = 89;
%// COMBINATION MATRIX
CombinantionMatrix_A = combn([0 1], HA);
CombinantionMatrix_B = combn([0 1], HB);
CombinantionMatrix_C = combn([0 1], HC);
if HA == 1
CombinantionMatrix_A = CombinantionMatrix_A.';
end
if HB == 1
CombinantionMatrix_B = CombinantionMatrix_B.';
end
if HC == 1
CombinantionMatrix_C = CombinantionMatrix_C.';
end
CombinantionMatrix_A_Transp = CombinantionMatrix_A.';
CombinantionMatrix_B_Transp = CombinantionMatrix_B.';
CombinantionMatrix_C_Transp = CombinantionMatrix_C.';
% OBJECTIVE FUNCTION COST COEFFICIENTS
Cu_A = 0.03; c_p = 0.6; c_f = 734; c_l = 3.2;
Cu_B = 0.09;
Cu_C = 0.04;
[HopperWeight UncertainWeight] = Weight(nComb, dim, alpha, ...
position_matrix, CellUncertainty);
HopperWeight_A = HopperWeight(:,1:HA);
HopperWeight_B = HopperWeight(:,HA+1:HA+HB);
HopperWeight_C = HopperWeight(:,HA+HB+1:HA+HB+HC);
UncertainWeight_A = UncertainWeight(:,1:HA);
UncertainWeight_B = UncertainWeight(:,HA+1:HA+HB);
UncertainWeight_C = UncertainWeight(:,HA+HB+1:HA+HB+HC);
W_best_tot = zeros(nComb, nSim);
W_best_ABC = zeros(nComb, 3, nSim);
for ii=1:nSim
W_A = HopperWeight_A * CombinantionMatrix_A_Transp;
W_B = HopperWeight_B * CombinantionMatrix_B_Transp;
W_C = HopperWeight_C * CombinantionMatrix_C_Transp;
W_Unc_A = UncertainWeight_A * CombinantionMatrix_A_Transp;
W_Unc_B = UncertainWeight_B * CombinantionMatrix_B_Transp;
W_Unc_C = UncertainWeight_C * CombinantionMatrix_C_Transp;
[~,comb_A] = min(abs(W_Unc_A - WT_A),[],2);
[~,comb_B] = min(abs(W_Unc_B - WT_B),[],2);
[~,comb_C] = min(abs(W_Unc_C - WT_C),[],2);
W_best_A = W_A(sub2ind_mod(size(W_A),1:size(W_A,1),comb_A.')).';
W_best_B = W_B(sub2ind_mod(size(W_B),1:size(W_B,1),comb_B.')).';
W_best_C = W_C(sub2ind_mod(size(W_C),1:size(W_C,1),comb_C.')).';
W_best_ABC(:,:,ii) = [W_best_A W_best_B W_best_C];
W_best_tot(:,ii) = sum(W_best_ABC(:,:,ii),2);
[HopperWeight_2_A UncertainWeight_2_A] = Weight(nComb, HA, alpha, ...
position_matrix(:,1:HA), CellUncertainty);
[HopperWeight_2_B UncertainWeight_2_B] = Weight(nComb, HB, alpha, ...
position_matrix(:,HA+1:HA+HB), CellUncertainty);
[HopperWeight_2_C UncertainWeight_2_C] = Weight(nComb, HC, alpha, ...
position_matrix(:,HA+HB+1:HA+HB+HC), CellUncertainty);
idx = CombinantionMatrix_A(comb_A,:)~=0;
HopperWeight_A(idx) = HopperWeight_2_A(idx);
UncertainWeight_A(idx) = UncertainWeight_2_A(idx);
idx = CombinantionMatrix_B(comb_B,:)~=0;
HopperWeight_B(idx) = HopperWeight_2_B(idx);
UncertainWeight_B(idx) = UncertainWeight_2_B(idx);
idx = CombinantionMatrix_C(comb_C,:)~=0;
HopperWeight_C(idx) = HopperWeight_2_C(idx);
UncertainWeight_C(idx) = UncertainWeight_2_C(idx);
clear HopperWeight_2_A HopperWeight_2_B HopperWeight_2_C ...
UncertainWeight_2_A UncertainWeight_2_B UncertainWeight_2_C;
end
n_b = logical(W_best_tot >= WL);
n_bA = logical(reshape(W_best_ABC(:,1,:), nComb, nSim) >= WL_A);
n_bB = logical(reshape(W_best_ABC(:,2,:), nComb, nSim) >= WL_B);
n_bC = logical(reshape(W_best_ABC(:,3,:), nComb, nSim) >= WL_C);
n_b_global = sum(n_b .* n_bA .* n_bB .* n_bC, 2);
GAvg_A = sum(reshape(W_best_ABC(:,1,:), nComb, nSim).*(reshape(...
W_best_ABC(:,1,:), nComb, nSim) > WT_A),2)./sum(reshape(...
W_best_ABC(:,1,:), nComb, nSim) > WT_A,2);
GAvg_B = sum(reshape(W_best_ABC(:,2,:), nComb, nSim).*(reshape(...
W_best_ABC(:,2,:), nComb, nSim) > WT_B),2)./sum(reshape(...
W_best_ABC(:,2,:), nComb, nSim) > WT_B,2);
GAvg_C = sum(reshape(W_best_ABC(:,3,:), nComb, nSim).*(reshape(...
W_best_ABC(:,3,:), nComb, nSim) > WT_C),2)./sum(reshape(...
W_best_ABC(:,3,:), nComb, nSim) > WT_C,2);
f = Cu_A .* GAvg_A + Cu_B .* GAvg_B + Cu_C .* GAvg_C + (nSim./...
n_b_global) .* c_p + (c_f./n_b_global) + ((nSim - n_b_global)./...
n_b_global) .* c_l;
Function = f;
Profiler
This is the Main Profiler and these are: the MHW function and the Weight function. The main problems are in the Weight since it's called 3000times for each GA generation...Above the Weight function code:
Weight Function Code
function [ HopperWeight UncertainWeight ] = Weight( nComb, H, alpha, AllComb, CellUncertainty )
HopperWeight = randn(nComb,H) * alpha;
HopperWeight = (1+HopperWeight) .* AllComb;
idx = HopperWeight<0;
random = randn(sum(idx(:)), 1);
HopperWeight(idx) = random .* ((1+alpha) .* AllComb(idx));
%ADD ERROR
RandomizeUncertainty = randn(nComb,H) * CellUncertainty;
UncertainWeight = abs((1+RandomizeUncertainty) .* HopperWeight);
end
Is there something that I am missing in order to optimize better the Weight function and in general the time consuming part in the MHW function? (If you need the GA launcher in order to try the MHW function use THIS code)
TIA
am trying to devalope a lights out game with CORONA SDK
but am not able to figure out a way for looping it !!!
how many functions to create and the way to keep this going
here is my code (its dummy but a friend gave it to me as am trying to go on from there )
obj = nil
px = 35
py = 50
r = 22
xi = 60
yi = 60
x1y1 = display.newCircle(px+xi*0,py+yi*0,r) x1y1.id = "x1y1"
x2y1 = display.newCircle(px+xi*1,py+yi*0,r) x2y1.id = "x2y1"
x3y1 = display.newCircle(px+xi*2,py+yi*0,r) x3y1.id = "x3y1"
x4y1 = display.newCircle(px+xi*3,py+yi*0,r) x4y1.id = "x4y1"
x5y1 = display.newCircle(px+xi*4,py+yi*0,r) x5y1.id = "x5y1"
x1y2 = display.newCircle(px+xi*0,py+yi*1,r) x1y2.id = "x1y2"
x2y2 = display.newCircle(px+xi*1,py+yi*1,r) x2y2.id = "x2y2"
x3y2 = display.newCircle(px+xi*2,py+yi*1,r) x3y2.id = "x3y2"
x4y2 = display.newCircle(px+xi*3,py+yi*1,r) x4y2.id = "x4y2"
x5y2 = display.newCircle(px+xi*4,py+yi*1,r) x5y2.id = "x5y2"
x1y3 = display.newCircle(px+xi*0,py+yi*2,r) x1y3.id = "x1y3"
x2y3 = display.newCircle(px+xi*1,py+yi*2,r) x2y3.id = "x2y3"
x3y3 = display.newCircle(px+xi*2,py+yi*2,r) x3y3.id = "x3y3"
x4y3 = display.newCircle(px+xi*3,py+yi*2,r) x4y3.id = "x4y3"
x5y3 = display.newCircle(px+xi*4,py+yi*2,r) x5y3.id = "x5y3"
x1y4 = display.newCircle(px+xi*0,py+yi*3,r) x1y4.id = "x1y4"
x2y4 = display.newCircle(px+xi*1,py+yi*3,r) x2y4.id = "x2y4"
x3y4 = display.newCircle(px+xi*2,py+yi*3,r) x3y4.id = "x3y4"
x4y4 = display.newCircle(px+xi*3,py+yi*3,r) x4y4.id = "x4y4"
x5y4 = display.newCircle(px+xi*4,py+yi*3,r) x5y4.id = "x5y4"
x1y5 = display.newCircle(px+xi*0,py+yi*4,r) x1y5.id = "x1y5"
x2y5 = display.newCircle(px+xi*1,py+yi*4,r) x2y5.id = "x2y5"
x3y5 = display.newCircle(px+xi*2,py+yi*4,r) x3y5.id = "x3y5"
x4y5 = display.newCircle(px+xi*3,py+yi*4,r) x4y5.id = "x4y5"
x5y5 = display.newCircle(px+xi*4,py+yi*4,r) x5y5.id = "x5y5"
bb = {x1y1,x2y1,x3y1,x4y1,x5y1,x1y2,x2y2,x3y2,x4y2,x5y2,x1y3,x2y3,x3y3,x4y3,x5y3,x1y4,x2y4,x3y4,x4y4,x5y4,x1y5,x2y5,x3y5,x4y5,x5y5}
iClicked = 0
function click(e)
if(e.phase == "ended") then
--circleID = e.target.id
--whichCircle()
print(e.target.id)
obj = e.target
for u=1,25 do
if(obj==bb[u]) then
iClicked = u
end
end
if((iClicked-5) > 0 and (iClicked-5) < 26) then
bb[iClicked-5]:setFillColor(1,0,0)
end
if((iClicked-1) > 0 and (iClicked-1) < 26) then
bb[iClicked-1]:setFillColor(1,0,0)
end
obj:setFillColor(1,0,0)
if((iClicked+1) > 0 and (iClicked+1) < 26) then
bb[iClicked+1]:setFillColor(1,0,0)
end
if((iClicked+5) > 0 and (iClicked+5) < 26) then
bb[iClicked+5]:setFillColor(1,0,0)
end
end
end
for k=1,25 do
bb[k]:addEventListener("touch",click)
end
its all about having 25 circles and lighting them on and off but it doesnt seem to work for me
any good help will be great
Thanks
local myCircles = {}
for y = 1, 5 do
myCircles[y] = {}
for x = 1, 5 do
myCircles[y][x] = display.newCircle(px+xi*0,py+yi*4,r)
myCircles[y][x].id = .id = "x" .. x .. "y" .. y
end
end
or something like that.
Rob