Multiple color tweens on Sprites - actionscript

I try to make a grid of squares, where I could control every square's color parameters individually ie. make them flash one by one or all at the same time.
I'm trying to do it with tweens, running the parameters with for-loop.
The code below tries to flash all the squares at the same time, once in every second. but for some reason all of the squares don't tween, only some do. Or they tween partly and sometimes they don't tween at all. However, the pattern doesn't repeat itself.
Is this too many tweens at the same time? Is the for-loop right way to do this? Should I use MovieClips instead of Sprites? If I want to control colors in many differeng objects in a very fast phase, what would be the best way to do it?
import fl.transitions.Tween;
import fl.transitions.easing.*;
import fl.transitions.TweenEvent;
import flash.display.*;
import flash.events.*;
import flash.display.Sprite;
import flash.geom.Rectangle;
import flash.geom.ColorTransform;
import Math;
import flash.utils.Timer;
import flash.events.TimerEvent;
import resolumeCom.*;
import resolumeCom.parameters.*;
import resolumeCom.events.*;
public class LightGrid extends MovieClip
{
private var t1:Tween;
private var resolume:Resolume = new Resolume();
private var tempo:FloatParameter = resolume.addFloatParameter("Tempo", 0.6);
private var pad = 3;
private var dim = 20;
private var posX = 0 + pad;
private var posY = 0 + pad;
private var a:Number = new Number();
private var b:Number = new Number();
private var blk:Number = new Number();
var newCol:ColorTransform = new ColorTransform();
public function LightGrid()
{
resolume.addParameterListener(parameterChanged);
for (var b = 0; b < 16; b++)
{
posY = (b*dim) + (b*pad) + pad;
trace("New row");
for (var a = 0; a < 24; a++)
{
posX = (a*dim) + (a*pad) + pad;
// l = line, f = fill
var l:Sprite = new Sprite;
l.graphics.lineStyle(2, 0xFFFFF, 1);
l.graphics.drawRect(posX, posY, dim, dim);
l.name = "line_Row" + b + "Col" + a;
addChild(l);
var f:Sprite = new Sprite;
f.graphics.beginFill(0x990000, 1);
f.graphics.drawRect(posX, posY, dim, dim);
f.graphics.endFill();
f.name = "fill_Row" + b + "Col" + a;
addChild(f);
trace(getChildByName("fill_Row" + b + "Col" + a).name);
}
}
var myTimer:Timer = new Timer(1000, 100);
myTimer.addEventListener("timer", timerHandler);
myTimer.start();
}
public function timerHandler(event:TimerEvent):void {
flashTheLights();
}
public function parameterChanged(e:ChangeEvent):void
{
if (e.object == tempo)
{
}
}
public function flashTheLights():void
{
blk = 0;
for (var blk = 0; blk < (24/3); blk++)
{
for (var d = 0; d < 16; d++)
{
for (var c = (0+(3*blk)); c < (3+(3*blk)); c++)
{
newCol.redOffset=30-(35*blk);
newCol.blueOffset=200+(7*blk);
newCol.greenOffset=200;
trace(getChildByName("fill_Row" + d + "Col" + c).name);
var fill:Sprite = getChildByName("fill_Row" + d + "Col" + c) as Sprite;
fill.transform.colorTransform.alphaMultiplier = -255;
fill.transform.colorTransform = newCol;
trace("Run tween");
var myTween = new Tween(fill,'alpha',Regular.easeIn,1,0,0.3,true);
}
}
trace("Done!" + blk);
}
}
}

I kinda solved the problem by stacking the sprites under movieclips so I only tween couple of elements instead of tens or hundreds
for (var k = 0; k < (grdX/ptrnSz); k++)
{
var ptrn:MovieClip = new MovieClip();
ptrn.name = "ptrn" + k;
addChild(ptrn);
ptrn.alpha = 0.01;
ptrnAm++;
for (var d = 0; d < grdY; d++)
{
posY = (d*dim) + (d*pad) + top;
for (var c = (0+(ptrnSz*k)); c < (ptrnSz+(ptrnSz*k)); c++)
{
posX = (c*dim) + (c*pad) + left;
// l = line, f = fill
var f:Sprite = new Sprite;
f.graphics.beginFill(0xFFFFFF, 1);
f.graphics.drawRect(posX-0.5, posY, dim, dim);
f.graphics.endFill();
f.name = "fill_Block" + k + "Row" + d + "Col" + c;
ptrn.addChild(f);
}
}
}
grdX = Grid size in X-axis (how many columns)
ptrnSz = size of the movieclips containing the Sprites (how many columns)
After that I just tween movieclips with TweenMax, calling them each with getChildByName.

Related

Is there a way to call 4 APIs and then create a list and draw a Pie Chart

I need to call 4 APIs on a same server and then use the result to create a list and want to pass the same list to create a pie chart.
I have created a list but unable to pass that list in pie chart.
main() async {
// returned dataset example:
// [{females: 1367341, country: Brazil, age: 18, males: 1368729,
year: 1980, total: 2736070}]
final age18data = await getJson(
'http://api.population.io:80/1.0/population/2019/India/18/');
final age30data = await getJson(
'http://api.population.io:80/1.0/population/2019/India/30/');
final age45data = await getJson(
'http://api.population.io:80/1.0/population/2019/India/45/');
final age60data = await getJson(
'http://api.population.io:80/1.0/population/2019/India/60/');
final values = [
age18data[0]["total"],
age30data[0]["total"],
age45data[0]["total"],
age60data[0]["total"]
];
I have done till here now I want to use these values list to draw the pie chart using charts_flutter package
Here you go, 4 api calls to same server, and a pie chart:
import "dart:math" as math;
import "dart:io";
import "dart:convert";
main() async {
// returned dataset example:
// [{females: 1367341, country: Brazil, age: 18, males: 1368729, year: 1980, total: 2736070}]
final age18data = await getJson(
'http://api.population.io:80/1.0/population/2019/India/18/');
final age30data = await getJson(
'http://api.population.io:80/1.0/population/2019/India/30/');
final age45data = await getJson(
'http://api.population.io:80/1.0/population/2019/India/45/');
final age60data = await getJson(
'http://api.population.io:80/1.0/population/2019/India/60/');
final values = [
age18data[0]["total"],
age30data[0]["total"],
age45data[0]["total"],
age60data[0]["total"]
];
final allTotal = values[0] + values[1] + values[2] + values[3];
final proportion = values.map((v) => v / allTotal).toList();
print("Population of India:");
print("A - 18 y.o. ${values[0]} (${proportion[0]})");
print("B - 25 y.o. ${values[1]} (${proportion[1]})");
print("C - 45 y.o. ${values[2]} (${proportion[2]})");
print("D - 60 y.o. ${values[3]} (${proportion[3]})");
final labels = ["A", "B", "C", "D"];
asciiPieChart(labels, proportion);
}
Future<dynamic> getJson(String url) async {
var request =
await HttpClient().getUrl(Uri.parse(url)); // produces a request object
var response = await request.close(); // sends the request
var body = await response.transform(Utf8Decoder()).join("");
return json.decode(body);
}
void asciiPieChart(dynamic k, dynamic v) {
// adapted from javascript version:
// https://codegolf.stackexchange.com/a/23351/18464
dynamic d, y, s, x, r, a, i, f, p, t, j;
r = 10.0;
d = r * 2;
p = [];
for (y = 0; y < d; y++) {
p.add([]);
for (x = 0; x < d; x++) p[y].add(" ");
}
t = 0;
i = -1;
for (f = 0; f < 1; f += 1 / (r * 20)) {
if (f > t) t += v[++i];
a = math.pi * 2 * f;
for (j = 0; j < r; j++) {
int px = ((math.sin(a) * j).round() + r).toInt();
int py = ((math.cos(a) * j).round() + r).toInt();
p[px][py] = k[i < 0 ? k.length + i : i];
}
}
s = "";
for (y = 0; y < d; y++) {
for (x = 0; x < d; x++) s += p[y][x];
s += "\n";
}
print(s);
}
Run dart example.dart prints out:
Population of India:
A - 18 y.o. 25026690 (0.33671242865945705)
B - 25 y.o. 22643410 (0.30464746133954734)
C - 45 y.o. 16325200 (0.21964142043359983)
A - 60 y.o. 10331300 (0.13899868956739578)
CCCCCCC
CCCCCCCCCCC
CCCCCCCCCCCCD
BBCCCCCCCCCCDDD
BBBBCCCCCCCCDDDDD
BBBBBCCCCCCDDDDDD
BBBBBBBCCCCCDDDDDDD
BBBBBBBCCCDDDDDDDDD
BBBBBBBBCCDDDDDDDDD
BBBBBBBBBDDDDDDDDDD
BBBBBBBBBAAAAAAAAAA
BBBBBBBBBAAAAAAAAAA
BBBBBBBBAAAAAAAAAAA
BBBBBBAAAAAAAAAAA
BBBBBBAAAAAAAAAAA
BBBBAAAAAAAAAAA
BBBAAAAAAAAAA
BAAAAAAAAAA
AAAAAAA
You can of-course apply same ideas and use different charting method for example as described in
https://google.github.io/charts/flutter/example/pie_charts/donut.html
Doing http requests also is easier with https://pub.dartlang.org/packages/http

Why at high circle division, the cone not complete itself?

I created in webgl a javascript file that needs to draw a cone. If I choose a low circle division, it work perfectly, and all the lines are displayed. But at high one, high from 255, it breaks. It seems not all of the vertices are linked. I can not understand why the difference.
case 'cone':{
var CONE_DIV = 255;
var angolo = 360 / CONE_DIV;
var altezza = 1.0;
// Coordinates
var vertices = [];
vertices.push(0.0); //v0t X
vertices.push(0.0); //v0t Y
vertices.push(0.0); //v0t Z
vertices.push(0.0); //v0 X
vertices.push(altezza); //v0 Y
vertices.push(0.0); //v0 Z
for (var i = 0; i < CONE_DIV; i++) {
var ai = i * 2 * Math.PI / CONE_DIV;
var si = Math.sin(ai);
var ci = Math.cos(ai);
vertices.push(ci); //coordinate X
vertices.push(0.0); //coordinate Y
vertices.push(si); //coordinate Z
}
// Colors
var colors = [];
for (var k = 0; k < CONE_DIV; k++) {
for (var t = 0; t < 2; t++) {
colors.push(a);
colors.push(b);
colors.push(c);
}
}
// Indices of the vertices
var indices = [];
//index high vertex
for (var j = 1; j <= CONE_DIV; j++) {
indices.push(1);
indices.push(j+1);
var l = j + 2; //last vertex base - return to first
if (l == CONE_DIV + 2) {
indices.push(2);
} else {
indices.push(l);
}
}
//index base
for (var j = 1; j <= CONE_DIV; j++) {
indices.push(0);
indices.push(j+1);
var l = j+2;
if (l == CONE_DIV + 2) { //last vertex base - return to first
indices.push(2);
} else {
indices.push(l);
}
}

Floyd Warshall using Alea GPU

I've been trying to use Alea GPU to write the parallel Floyd-Warshall algorithm in F#, and basing myself on the CUDA code another user presented here
The Floyd-Warshall algorithm in CUDA
I wrote the following simple implementation
type FWModule<'T>(target:GPUModuleTarget, tileDim:int) =
inherit GPUModule(target)
[<Kernel;ReflectedDefinition>]
member this.FloydWKernel (width:int) (k:int) (data:deviceptr<float>) =
let col = blockIdx.x * blockDim.x + threadIdx.x
let row = blockIdx.y
if col >= width then () //out of bounds
let index = width * row + col
let best = __shared__.Variable<float>()
if threadIdx.x = 0 then best := data.[width*row+k]
__syncthreads()
let tmp = data.[k*width+col]
let candidate = !best + tmp
data.[index] <- min data.[index] candidate
member this.LaunchParams width =
let blockdim = dim3(tileDim)
let griddim = dim3(divup width tileDim, width)
LaunchParam(griddim, blockdim)
member this.FloydW (width:int) (k:int) (data:deviceptr<float>) =
let lp = this.LaunchParams width
this.GPULaunch <# this.FloydWKernel #> lp width k idata odata
member this.FW(size:int, A:float[])=
use deviceArr = this.GPUWorker.Malloc(A)
for k in 0 .. size-1 do
this.FloydW size k deviceArr.Ptr deviceArr.Ptr
deviceArr.Gather()
let tileDim = 256
let apsp = new FWModule<float>(GPUModuleTarget.DefaultWorker, tileDim)
However, when the following lines are ran in fsi
let m = [|0.0 ; 5.0 ; 9.0 ; infinity;
infinity; 0.0 ; 1.0 ; infinity;
infinity; infinity; 0.0 ; 2.0;
infinity; 3.0 ; infinity; 0.0|];;
apsp.FW (4,m);;
The output is
[|0.0; 5.0; 6.0; 8.0;
4.0; 0.0; 1.0; 3.0;
3.0; 3.0; 0.0; 1.0;
1.0; 1.0; 1.0; 0.0|]
Which it should not be given that the usual iterative, sequential floydwarshall
let floydwarshall (l:int, mat:float[]) =
let a = Array.copy mat
for k in 0 .. (l-1) do
for i in 0 .. (l-1) do
for j in 0 .. (l-1) do
a.[i*l+j] <- min a.[i*l+j] (a.[i*l+k] + a.[k*l+j])
a
gives me
floydwarshall (4,m);;
[|0.0 ; 5.0; 6.0; 8.0;
infinity; 0.0; 1.0; 3.0;
infinity; 5.0; 0.0; 2.0;
infinity; 3.0; 4.0; 0.0|]
My question is, what's happening?
Here is some source code snip from our sample gallery you can find on the Alea GPU sample gallery http://www.quantalea.com/gallery.
Here is the single stage algorithm. It is not the fastest but reasonably simple to understand.
public static class FloydWarshallSingleStage
{
const int BlockWidth = 16;
/// <summary>
/// Kernel for parallel Floyd Warshall algorithm on GPU.
/// </summary>
/// <param name="u">Number vertex of which is performed relaxation paths [v1, v2]</param>
/// <param name="n">Number of vertices in the graph G:=(V,E), n := |V(G)|</param>
/// <param name="d">Matrix of shortest paths d(G)</param>
/// <param name="p">Matrix of predecessors p(G)</param>
public static void KernelSingleStage(int u, int[,] d, int[,] p)
{
var n = d.GetLength(0);
var v1 = blockDim.y * blockIdx.y + threadIdx.y;
var v2 = blockDim.x * blockIdx.x + threadIdx.x;
if (v1 < n && v2 < n)
{
var newPath = d[v1, u] + d[u, v2];
var oldPath = d[v1, v2];
if (oldPath > newPath)
{
d[v1, v2] = newPath;
p[v1, v2] = p[u, v2];
}
}
}
[GpuManaged]
public static void Run(Gpu gpu, int[,] d, int[,] p)
{
var n = d.GetLength(0);
var gridDim = new dim3((n - 1) / BlockWidth + 1, (n - 1) / BlockWidth + 1, 1);
var blockDim = new dim3(BlockWidth, BlockWidth, 1);
var lp = new LaunchParam(gridDim, blockDim);
for (var u = 0; u < n; u++)
{
gpu.Launch(KernelSingleStage, lp, u, d, p);
}
}
}
The multi-stage is more complicated and the listing is longer. Here I paste a version that uses automatic memory management which simplifies the code quite a bit but also has some performance implication. The multi-stage version uses three kernels to complete the job and uses tiling to improve memory access.
public class FloydWarshallMultiStage
{
private const int None = -1;
private const int Inf = 1061109567;
//[GpuParam]
//private readonly Constant<int> BlockSize;
//[GpuParam]
//private readonly Constant<int> ThreadSize;
//[GpuParam]
//private readonly Constant<int> VirtualBlockSize;
private const int BlockSize = 16;
private const int ThreadSize = 2;
private const int VirtualBlockSize = BlockSize*ThreadSize;
public FloydWarshallMultiStage(int blockSize, int threadSize)
{
//BlockSize = new Constant<int>(blockSize);
//ThreadSize = new Constant<int>(threadSize);
//VirtualBlockSize = new Constant<int>(blockSize * threadSize);
}
/// <summary>
/// Kernel for parallel Floyd Warshall algorithm on GPU computing independent blocks.
/// </summary>
/// <param name="block">Number block of which is performed relaxation paths [v1, v2]</param>
/// <param name="n">Number of vertices in the graph G:=(V,E), n := |V(G)|</param>
/// <param name="pitch">Width to get to next row in number of int</param>
/// <param name="d">Matrix of shortest paths d(G)</param>
/// <param name="p">Matrix of predecessors p(G)</param>
public void KernelPhaseOne(int block, int n, int pitch, int[,] d, int[,] p)
{
var newPred = 0;
var tx = threadIdx.x;
var ty = threadIdx.y;
var v1 = VirtualBlockSize*block + ty;
var v2 = VirtualBlockSize*block + tx;
var primaryD = __shared__.Array2D<int>(VirtualBlockSize, VirtualBlockSize);
var primaryP = __shared__.Array2D<int>(VirtualBlockSize, VirtualBlockSize);
if (v1 < n && v2 < n)
{
primaryD[ty, tx] = d[v1, v2];
primaryP[ty, tx] = p[v1, v2];
newPred = primaryP[ty, tx];
}
else
{
primaryD[ty, tx] = Inf;
primaryP[ty, tx] = None;
}
DeviceFunction.SyncThreads();
for (var i = 0; i < VirtualBlockSize; i++)
{
var newPath = primaryD[ty, i] + primaryD[i, tx];
DeviceFunction.SyncThreads();
if (newPath < primaryD[ty, tx])
{
primaryD[ty, tx] = newPath;
newPred = primaryP[i, tx];
}
DeviceFunction.SyncThreads();
primaryP[ty, tx] = newPred;
}
if (v1 < n && v2 < n)
{
d[v1, v2] = primaryD[ty, tx];
p[v1, v2] = primaryP[ty, tx];
}
}
/// <summary>
/// Kernel for parallel Floyd Warshall algorithm on GPU to compute block depending on a single independent block.
/// </summary>
/// <param name="block">Number block of which is performed relaxation paths [v1, v2]</param>
/// <param name="n">Number of vertices in the graph G:=(V,E), n := |V(G)|</param>
/// <param name="pitch"></param>
/// <param name="d">Matrix of shortest paths d(G)</param>
/// <param name="p">Matrix of predecessors p(G)</param>
public void KernelPhaseTwo(int block, int n, int pitch, int[,] d, int[,] p)
{
if (blockIdx.x == block) return;
var newPath = 0;
var newPred = 0;
var tx = threadIdx.x;
var ty = threadIdx.y;
var v1 = VirtualBlockSize*block + ty;
var v2 = VirtualBlockSize*block + tx;
var primaryD = __shared__.Array2D<int>(VirtualBlockSize, VirtualBlockSize);
var currentD = __shared__.Array2D<int>(VirtualBlockSize, VirtualBlockSize);
var primaryP = __shared__.Array2D<int>(VirtualBlockSize, VirtualBlockSize);
var currentP = __shared__.Array2D<int>(VirtualBlockSize, VirtualBlockSize);
if (v1 < n && v2 < n)
{
primaryD[ty, tx] = d[v1, v2];
primaryP[ty, tx] = p[v1, v2];
}
else
{
primaryD[ty, tx] = Inf;
primaryP[ty, tx] = None;
}
// load i-aligned singly dependent blocks
if (blockIdx.y == 0)
{
v1 = VirtualBlockSize*block + ty;
v2 = VirtualBlockSize*blockIdx.x + tx;
}
// load j-aligned singly dependent blocks
else
{
v1 = VirtualBlockSize*blockIdx.x + ty;
v2 = VirtualBlockSize*block + tx;
}
if (v1 < n && v2 < n)
{
currentD[ty, tx] = d[v1, v2];
currentP[ty, tx] = p[v1, v2];
newPred = currentP[ty, tx];
}
else
{
currentD[ty, tx] = Inf;
currentP[ty, tx] = None;
}
DeviceFunction.SyncThreads();
// compute i-aligned singly dependent blocks
if (blockIdx.y == 0)
{
for (var i = 0; i < VirtualBlockSize; i++)
{
newPath = primaryD[ty, i] + currentD[i, tx];
DeviceFunction.SyncThreads();
if (newPath < currentD[ty, tx])
{
currentD[ty, tx] = newPath;
newPred = currentP[i, tx];
}
DeviceFunction.SyncThreads();
currentP[ty, tx] = newPred;
}
}
// compute j-aligned singly dependent blocks
else
{
for (var i = 0; i < VirtualBlockSize; i++)
{
newPath = currentD[ty, i] + primaryD[i, tx];
DeviceFunction.SyncThreads();
if (newPath < currentD[ty, tx])
{
currentD[ty, tx] = newPath;
currentP[ty, tx] = primaryP[i, tx];
}
DeviceFunction.SyncThreads();
}
}
if (v1 < n && v2 < n)
{
d[v1, v2] = currentD[ty, tx];
p[v1, v2] = currentP[ty, tx];
}
}
/// <summary>
/// Kernel for parallel Floyd Warshall algorithm on GPU to compute dependent block depending on the singly dependent blocks.
/// </summary>
/// <param name="block">Number block of which is performed relaxation paths [v1, v2]</param>
/// <param name="n">Number of vertices in the graph G:=(V,E), n := |V(G)|</param>
/// <param name="pitch"></param>
/// <param name="d">Matrix of shortest paths d(G)</param>
/// <param name="p">Matrix of predecessors p(G)</param>
public void KernelPhaseThree(int block, int n, int pitch, int[,] d, int[,] p)
{
if (blockIdx.x == block || blockIdx.y == block) return;
var tx = threadIdx.x*ThreadSize;
var ty = threadIdx.y*ThreadSize;
var v1 = blockDim.y*blockIdx.y*ThreadSize + ty;
var v2 = blockDim.x*blockIdx.x*ThreadSize + tx;
var primaryRowD = __shared__.Array2D<int>(BlockSize*ThreadSize, BlockSize*ThreadSize);
var primaryColD = __shared__.Array2D<int>(BlockSize*ThreadSize, BlockSize*ThreadSize);
var primaryRowP = __shared__.Array2D<int>(BlockSize*ThreadSize, BlockSize*ThreadSize);
var v1Row = BlockSize*block*ThreadSize + ty;
var v2Col = BlockSize*block*ThreadSize + tx;
// load data for virtual block
for (var i = 0; i < ThreadSize; i++)
{
for (var j = 0; j < ThreadSize; j++)
{
var idx = tx + j;
var idy = ty + i;
if (v1Row + i < n && v2 + j < n)
{
primaryRowD[idy, idx] = d[v1Row + i, v2 + j];
primaryRowP[idy, idx] = p[v1Row + i, v2 + j];
}
else
{
primaryRowD[idy, idx] = Inf;
primaryRowP[idy, idx] = None;
}
if (v1 + i < n && v2Col + j < n)
{
primaryColD[idy, idx] = d[v1 + i, v2Col + j];
}
else
{
primaryColD[idy, idx] = Inf;
}
}
}
DeviceFunction.SyncThreads();
// compute data for virtual block
for (var i = 0; i < ThreadSize; i++)
{
for (var j = 0; j < ThreadSize; j++)
{
if (v1 + i < n && v2 + j < n)
{
var path = d[v1 + i, v2 + j];
var predecessor = p[v1 + i, v2 + j];
var idy = ty + i;
var idx = tx + j;
for (var k = 0; k < BlockSize*ThreadSize; k++)
{
var newPath = primaryColD[idy, k] + primaryRowD[k, idx];
if (path > newPath)
{
path = newPath;
predecessor = primaryRowP[k, idx];
}
}
d[v1 + i, v2 + j] = path;
p[v1 + i, v2 + j] = predecessor;
}
}
}
}
/// <summary>
/// Parallel multi-stage Floyd Warshall algorithm on GPU.
/// </summary>
/// <param name="gpu">The GPU on which the kernels should run</param>
/// <param name="n">Number of vertices in the graph G:=(V,E), n := |V(G)|</param>
/// <param name="g">The graph G:=(V,E)</param>
/// <param name="d">Matrix of shortest paths d(G)</param>
/// <param name="p">Matrix of predecessors p(G)</param>
public void Run(Gpu gpu, int[,] d, int[,] p, bool verbose = false)
{
var n = d.GetLength(0);
var gridDim1 = new dim3(1, 1, 1);
var gridDim2 = new dim3((n - 1)/VirtualBlockSize + 1, 2, 1);
var gridDim3 = new dim3((n - 1)/VirtualBlockSize + 1, (n - 1)/VirtualBlockSize + 1, 1);
var blockDim1 = new dim3(VirtualBlockSize, VirtualBlockSize, 1);
var blockDim2 = new dim3(VirtualBlockSize, VirtualBlockSize, 1);
var blockDim3 = new dim3(BlockSize, BlockSize, 1);
var numOfBlock = (n - 1)/VirtualBlockSize + 1;
var pitchInt = n;
if (verbose)
{
Console.WriteLine($"|V| {n}");
Console.WriteLine($"Phase 1: grid dim {gridDim1} block dim {blockDim1}");
Console.WriteLine($"Phase 2: grid dim {gridDim2} block dim {blockDim2}");
Console.WriteLine($"Phase 3: grid dim {gridDim3} block dim {blockDim3}");
}
for (var block = 0; block < numOfBlock; block++)
{
gpu.Launch(KernelPhaseOne, new LaunchParam(gridDim1, blockDim1), block, n, pitchInt, d, p);
gpu.Launch(KernelPhaseTwo, new LaunchParam(gridDim2, blockDim2), block, n, pitchInt, d, p);
gpu.Launch(KernelPhaseThree, new LaunchParam(gridDim3, blockDim3), block, n, pitchInt, d, p);
}
}
}
The version with explicit memory management you better download the sample from http://www.quantalea.com/gallery and search for Floyd-Warshall.
Hope that answers the question.
The implementation is based on the following paper:
Ben Lund, Justin W Smith, A Multi-Stage CUDA Kernel for Floyd-Warshall, 2010.
https://arxiv.org/abs/1001.4108

Highcharts Scatter Plot - How to Fix Overlapping Data Labels?

I have seen many posts on this topic, but it doesn't seem the issue has ever been properly addressed.
We have a large scatter with about 30 points on it (nothing overwhelming). But in certain cases, the dots will be very close together or overlapping (not much we can really do about that, I guess).
The main problem is that we want the data labels visible at all times, and these data labels are overlapping when the points are close to each other.
We have tried allowOverlap: false, but that's not really what we need/want. Our ideal outcome is allowing all datalabels to be displayed on screen inside the scatter while still being able to read each one at all times.
Do we fix this by adjusting the separation of the dots or by adjusting the separation/padding of the datalabels? Any suggestions? Thank you.
I haven't found a working configuration solution of this problem from Highcharts (although I cannot guarantee there isn't one in latest version). However there are some algorithms for acceptable randomization of the labels coordinates that split data labels.
Here are some useful links that could help you with the algorithm:
wordcloud package in R (cloud.R is the file containing the algorithm)
direct labels package in R
And some dummy pseudo code translation in JavaScript of the R code would be:
splitLabels: function() {
// Create an array of x-es and y-es that indicate where your data lie
var xArr = getAllDataX();
var yArr = getAllDataY();
var labelsInfo = {};
this.chartSeries.forEach(function(el) {
var text = el.data.name;
labelsInfo[el.data.id] = {
height: getHeight(text),
width: getWidth(text),
text: text
};
}, this);
var sdx = getStandardDeviation(xArr);
var sdy = getStandardDeviation(yArr);
if(sdx === 0) sdx = 1;
if(sdy === 0) sdy = 1;
var boxes = [];
var xlim = [], ylim = [];
xlim[0] = this.chart.xAxis[0].getExtremes().min;
xlim[1] = this.chart.xAxis[0].getExtremes().max;
ylim[0] = this.chart.yAxis[0].getExtremes().min;
ylim[1] = this.chart.yAxis[0].getExtremes().max;
for (var i = 0; i < data.length; i++) {
var pointX = data[i].x;
var pointY = data[i].y;
if (pointX<xlim[0] || pointY<ylim[0] || pointX>xlim[1] || pointY>ylim[1]) continue;
var theta = Math.random() * 2 * Math.PI,
x1 = data[i].x,
x0 = data[i].x,
y1 = data[i].y,
y0 = data[i].y,
width = labelsInfo[data[i].id].width,
height = labelsInfo[data[i].id].height ,
tstep = Math.abs(xlim[1] - xlim[0]) > Math.abs(ylim[1] - ylim[0]) ? Math.abs(ylim[1] - ylim[0]) / 100 : Math.abs(xlim[1] - xlim[0]) / 100,
rstep = Math.abs(xlim[1] - xlim[0]) > Math.abs(ylim[1] - ylim[0]) ? Math.abs(ylim[1] - ylim[0]) / 100 : Math.abs(xlim[1] - xlim[0]) / 100,
r = 0;
var isOverlapped = true;
while(isOverlapped) {
if((!hasOverlapped(x1-0.5*width, y1-0.5*height, width, height, boxes)
&& x1-0.5*width>xlim[0] && y1-0.5*height>ylim[0] && x1+0.5*width<xlim[1] && y1+0.5*height<ylim[1]) )
{
boxes.push({
leftX: x1-0.5*width,
bottomY: y1-0.5*height,
width: width,
height: height,
icon: false,
id: data[i].id,
name: labelsInfo[data[i].id].text
});
data[i].update({
name: labelsInfo[data[i].id].text,
dataLabels: {
x: (x1 - data[i].x),
y: (data[i].y - y1)
}
}, false);
isOverlapped = false;
} else {
theta = theta+tstep;
r = r + rstep*tstep/(2*Math.PI);
x1 = x0+sdx*r*Math.cos(theta);
y1 = y0+sdy*r*Math.sin(theta);
}
}
}
// You may have to redraw the chart here
},
You can call this function on redraw or optimized to call it less often.
Please note that if you have some big points or shapes or icons indicating where your data items lie you will have to check if any of the proposed solutions does not interfere(overlap) with the icons as well.
You can try to adapt this algorithm:
function StaggerDataLabels(series) {
sc = series.length;
if (sc < 2) return;
for (s = 1; s < sc; s++) {
var s1 = series[s - 1].points,
s2 = series[s].points,
l = s1.length,
diff, h;
for (i = 0; i < l; i++) {
if (s1[i].dataLabel && s2[i].dataLabel) {
diff = s1[i].dataLabel.y - s2[i].dataLabel.y;
h = s1[i].dataLabel.height + 2;
if (isLabelOnLabel(s1[i].dataLabel, s2[i].dataLabel)) {
if (diff < 0) s1[i].dataLabel.translate(s1[i].dataLabel.translateX, s1[i].dataLabel.translateY - (h + diff));
else s2[i].dataLabel.translate(s2[i].dataLabel.translateX, s2[i].dataLabel.translateY - (h - diff));
}
}
}
}
}
//compares two datalabels and returns true if they overlap
function isLabelOnLabel(a, b) {
var al = a.x - (a.width / 2);
var ar = a.x + (a.width / 2);
var bl = b.x - (b.width / 2);
var br = b.x + (b.width / 2);
var at = a.y;
var ab = a.y + a.height;
var bt = b.y;
var bb = b.y + b.height;
if (bl > ar || br < al) {
return false;
} //overlap not possible
if (bt > ab || bb < at) {
return false;
} //overlap not possible
if (bl > al && bl < ar) {
return true;
}
if (br > al && br < ar) {
return true;
}
if (bt > at && bt < ab) {
return true;
}
if (bb > at && bb < ab) {
return true;
}
return false;
}
http://jsfiddle.net/menXU/6/

JtextField Variable Grab and Use for Numerical Iteration from GUI

this is my complete code for a small gui to take variables from user and return them to the rest of program(r.o.p) for calculations, however doesn't seem to be passing to r.o.p. and no output file is observerd.
Any help would be much appreciated, I think the problem is with the listener for the Draw New Graph command. Thanks
Code:
import java.text.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class RungeKutta {
// class to create slider and window
private static File file1;
public static double A(double v, double x, double wc, double beta) {
return (-2 * beta * v - (Math.pow(wc, 2)) * Math.sin(x));
}
public static File getFile1() {
return file1;
}
public static void setFile1(File file1) {
RungeKutta.file1 = file1;
}
public static void main(String[] argv) throws IOException, ParseException {
createAndShowGUI();
}
private static void createAndShowGUI() {
//create and set up the window.
JFrame frame = new JFrame("RungeKutta");
GridLayout first = new GridLayout(14,1);
frame.setLayout(first);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create, name and Populate TextField
JTextField PL = new JTextField("Pendulum Length", 20);
//Set TextField to Uneditable. Each will have Empty Field Below For Variables
PL.setEditable(false);
//Set Textfield for user entered dat
JTextField PLv = new JTextField();
//Allow input from text field to be taken
JTextField AD = new JTextField("Angular Displacement", 20);
AD.setEditable(false);
JTextField ADv = new JTextField();
JTextField AV = new JTextField("Angular Velocity", 20);
AV.setEditable(false);
JTextField Avv = new JTextField();
JTextField TS= new JTextField("Time Steps", 20);
TS.setEditable(false);
JTextField TSv = new JTextField();
JTextField MT = new JTextField("Max Time", 20);
MT.setEditable(false);
JTextField MTv = new JTextField();
JTextField V = new JTextField("Viscosity (0-1)", 20);
V.setEditable(false);
JTextField Vv = new JTextField();
//Create Button to Restart and Button to take in Values for usage
JLabel emptyLabel = new JLabel("");
emptyLabel.setPreferredSize(new Dimension(600,500));
frame.getContentPane().add(PL, first);
frame.getContentPane().add(PLv, first);
frame.getContentPane().add(AD, first);
frame.getContentPane().add(ADv, first);
frame.getContentPane().add(AV, first);
frame.getContentPane().add(Avv, first);
frame.getContentPane().add(TS, first);
frame.getContentPane().add(TSv, first);
frame.getContentPane().add(MT, first);
frame.getContentPane().add(MTv, first);
frame.getContentPane().add(V, first);
frame.getContentPane().add(Vv, first);
JButton BNewGraph = new JButton("Draw New Graph"); //Button to restart entire drawing process
frame.getContentPane().add(BNewGraph, first);
//display the window
frame.pack();
frame.setVisible(true);
class intakegui implements ActionListener
{
public intakegui()
{
BNewGraph.addActionListener((ActionListener) this);
BNewGraph.setActionCommand("Click to Draw");
}
#Override
public void actionPerformed(ActionEvent e) {
double l = Double.parseDouble(PLv.getText());
double xi = Double.parseDouble(ADv.getText());
double vi = Double.parseDouble(Avv.getText());
double dt = Double.parseDouble(TSv.getText());
double n = Double.parseDouble(MTv.getText());
double beta = Double.parseDouble(Vv.getText());
SimpleDateFormat dform = new SimpleDateFormat("ddMMyyyysmH");
Date d = Calendar.getInstance().getTime();
String dstr = dform.format(d);
String filename = ("result " + dstr + ".txt");
file1 = new File(filename);
PrintWriter savedValues = null;
try {
savedValues = new PrintWriter(filename);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//declare variable for gravity and omega*c
double g = 9.8;
double wc = Math.sqrt(g / l);
savedValues.println("#Initial Values Entered");
savedValues.println("#" + l + "," + vi + "," + xi + "," + dt + "," + n
+ "," + beta);
double[] dispTime = new double[(int) n];
double[] velTime = new double[(int) n];
// let a = angular acceleration
for (double j = 0; j < (int) n; j++) {
// int time = 1;
double k1v = dt * j * A(vi, xi, wc, beta);
double k1x = dt * j * vi;
double k2v = dt * j * A(vi, xi + (0.5 * k1x), wc, beta);
double k2x = dt * j * (vi + (0.5 * k1v));
double k3v = dt * j * A(vi, xi + (0.5 * k2x), wc, beta);
double k3x = dt * j * (vi + (0.5 * k2v));
double k4v = dt * j * A(vi, xi + k3x, wc, beta);
double k4x = dt * j * (vi + k3v);
xi += k1x / 6 + k2x / 3 + k3x / 3 + k4x / 6;
vi += k1v / 6 + k2v / 3 + k3v / 3 + k4v / 6;
dispTime[(int) j] = xi;
velTime[(int) j] = vi;
System.out.println(xi + "," + vi);
}
for (int i = 0; i < (int) n; i++) {
savedValues.println(dispTime[i] + " " + velTime[i]);
}
savedValues.close();
System.out.println("File saved. File name: " + filename);
}
}
}
}
You forgot to add listener to your button. You need to add listener as below:
BNewGraph.addActionListener(new intakegui());
Now when user clicks on button, you would see the file.

Resources