Skip to content
Snippets Groups Projects
draw.ts 16.8 KiB
Newer Older
Francesco Giacomini's avatar
Francesco Giacomini committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
import "./globals";
import $ from "jquery";
import Dygraph from "dygraphs";

//la funzione drawImg disegna il canvas con l'immagine desiderata ed è responsabile
//della gestione di tutti gli eventi ad essa associati
export function drawImg(pixel1: coordinates, pixel2: coordinates, xMinRange: number, xMaxRange: number)
{

  //alert("disegno in corso");

  //numero di pixel per dimensione
  let nPixelX: number = pixel2.xp - pixel1.xp + 1;
  let nPixelY: number = pixel2.yp - pixel1.yp + 1;

  //dimensione dei canvas
  let mappaPannelDim: any = document.querySelector('#mappa-pannel').getBoundingClientRect();
  let mappaWidth: number = mappaPannelDim.right - mappaPannelDim.left - 40;
  let mappaHeigth: number = 400;

  //dimensione reale dei pixel
  let dimPixelx: number = Math.floor(mappaWidth / nPixelX);
  let dimPixely: number = Math.floor(mappaHeigth / nPixelY);
  pixelDim = (dimPixelx < dimPixely) ? dimPixelx : dimPixely;

  //dimensioni esatte dei canvas
  (<HTMLCanvasElement>document.getElementById("myCanvas")).height = nPixelY * pixelDim;
  (<HTMLCanvasElement>document.getElementById("myCanvas")).width = nPixelX * pixelDim;
  (<HTMLCanvasElement>document.getElementById("selectionCanvas")).height = nPixelY * pixelDim;
  (<HTMLCanvasElement>document.getElementById("selectionCanvas")).width = nPixelX * pixelDim;
  let ctx = (<HTMLCanvasElement>document.getElementById('myCanvas')).getContext('2d'); //contesto del canvas

  if (xMaxRange - xMinRange >= channelDepth) { //range completo
    let max: number; //massimo relativo o assoluto
    if (rePrint) {
      max = findMax(nOfCounts, pixel1, pixel2);
    } else {
      max = maxAbsolute;
    }
    max = (max * $("#SaturationSlider").val()) / 100;
    drawCanvas(nOfCounts, max);

  } else { //range parziale (solo alcuni canali)
    let xMinRangeCh: number = Math.floor((((xMinRange * 1000) + b) / a) - 1); //16
    let xMaxRangeCh: number = Math.floor((((xMaxRange * 1000) + b) / a) - 1); //16371
    //calcolo il numero di conteggi solo dei canali selezionati
    let nOfCountsRelative: number[][];
    nOfCountsRelative = new Array(xDim);
    for (let i: number = 0; i < xDim; i++) {
      nOfCountsRelative[i] = new Array(yDim);
      for (let j: number = 0; j < yDim; j++) {
        nOfCountsRelative[i][j] = sumVect(DataMatrix[i][j], xMinRangeCh, xMaxRangeCh);
      }
    }
    //calcolo il massimo
    let max: number;
    if (rePrint) {
      max = findMax(nOfCountsRelative, pixel1, pixel2);
    } else {
      max = findMax(nOfCountsRelative, { xp: 0, yp: 0 }, { xp: xDim - 1, yp: yDim - 1 });
    }
    max = (max * $("#SaturationSlider").val()) / 100;
    drawCanvas(nOfCountsRelative, max);
  }

  //La funzione, ricevuti dati e massimo, disegna la mappa nel canvas
  function drawCanvas(noc, max)
  {

    //controllo il valore della trasparenza 
    let setTrsp: number = 1 - ($("#TrasparencySlider").val() / 100);
    //let setTrsp: number = 1-(parseInt($("#TrasparencySlider").attr("value"))/100);

    //scorro tutti i pixel: ne determino il colore e li disegno      
    let color: string = "";
    for (let i: number = pixel1.xp; i <= pixel2.xp; i++) {
      for (let j: number = pixel1.yp; j <= pixel2.yp; j++) {
        let intensity: number = noc[i][j] / max;
        if (intensity < 1 / 5) //blu
          color = "rgba(0, 0, " + Math.floor(intensity * 5 * 255) + "," + setTrsp + ")";
        else if (1 / 5 <= intensity && intensity < 2 / 5) //blu+verde
          color = "rgba(0, " + Math.floor((intensity - 1 / 5) * 5 * 255) + ",255, " + setTrsp + ")";
        else if (2 / 5 <= intensity && intensity < 3 / 5) // verde-blu
          color = "rgba(0, 255, " + (255 - Math.floor((intensity - 2 / 5) * 5 * 255)) + ", " + setTrsp + ")";
        else if (3 / 5 <= intensity && intensity < 4 / 5) //verde + rosso 
          color = "rgba(" + Math.floor((intensity - 3 / 5) * 5 * 255) + ",255,0," + setTrsp + ")";
        else //rosso -verde
          color = "rgba(255," + (255 - Math.floor((intensity - 4 / 5) * 5 * 255)) + ", 0, " + setTrsp + ")";
        ctx.fillStyle = color;
        ctx.fillRect((i - pixel1.xp) * pixelDim, (j - pixel1.yp) * pixelDim, pixelDim, pixelDim);
      }
    }
    rePrint = false; //annullo rePrint
    zoomRect();
  }

  $("#SaturationSlider").mouseup(function ()
  { //Slider della saturazione
    drawImg(pixel1, pixel2, xMinRange, xMaxRange);
  });

  $("#rePlot").click(function ()
  { //bottone per colorare con il max relativo
    rePrint = true;
    (<HTMLInputElement>document.getElementById("SaturationSlider")).value = "100";
    drawImg(pixel1, pixel2, xMinRange, xMaxRange);
  });

  $("#TrasparencySlider").mouseup(function ()
  { //Slider della trasparenza
    drawImg(pixel1, pixel2, xMinRange, xMaxRange);
  });

  $("#reset").click(function ()
  { //bottone per il reset dell'applicazione
    newOrigin = { xp: 0, yp: 0 };
    rePrint = false;
    calibrated = false;
    globalxMinRange = 0;
    globalxMaxRange = channelDepth;
    (<HTMLInputElement>document.getElementById("SaturationSlider")).value = "100";
    (<HTMLInputElement>document.getElementById("TrasparencySlider")).value = "0";
    document.getElementById("spinBoxMin").setAttribute("value", "-");
    document.getElementById("spinBoxMax").setAttribute("value", "-");
    drawImg({ xp: 0, yp: 0 }, { xp: xDim - 1, yp: yDim - 1 }, 0, channelDepth);
    drawChart({ xp: 0, yp: 0 }, { xp: xDim - 1, yp: yDim - 1 }, 0, channelDepth);
  });

  $("#ExportImage").click(function ()
  { //esportazione immagine
    let img = (<HTMLCanvasElement>document.getElementById("myCanvas")).toDataURL("image/png");
    $("#ExportLink").attr("href", img);
    //document.write('<img src="'+img+'"/>');
  });

}

//la funzione drawChart (input: estremi dell'immagine, estremi dell'intervallo)
//disegna il grafico richiesto relativo alla mappa visualizzata
export function drawChart(pixel1: coordinates, pixel2: coordinates, xMinRange: number, xMaxRange: number)
{

  //definisco la variabile "grafico", i bottoni relativi al grafico, il tag
  //select e le due spinbox con il relativo botton
  let g: any;
  let box1 = <HTMLElement>document.getElementById("spinBoxMin");
  let box2 = <HTMLElement>document.getElementById("spinBoxMax");

  //disegno il grafico completo
  if (pixel1.xp == 0 && pixel1.yp == 0 && pixel2.xp == xDim - 1 && pixel2.yp == yDim - 1) {
    if (!calibrated) { //canali
      let chartTitle: string = "Chart from (0, 0) to (" + (xDim - 1) + ", " + (yDim - 1) + ")";
      g = setChart(dataCompleteChart, chartTitle);
    } else { //energie
      let chartTitle: string = "Calibrated chart from (0, 0) to (" + (xDim - 1) + ", " + (yDim - 1) + ")";
      g = setChart(dataCompleteChartCalibrated, chartTitle);
    }

    //disegno il grafico parzialmente 
  } else {
    //determino i conteggi dei pixel da disegnare
    let dataForChart: number[] = new Array(depth);
    for (let i: number = 0; i < depth; i++) {
      dataForChart[i] = 0;
    }
    for (let i: number = pixel1.xp; i <= pixel2.xp; i++) {
      for (let j: number = pixel1.yp; j <= pixel2.yp; j++) {
        for (let k: number = 0; k < depth; k++) {
          dataForChart[k] += DataMatrix[i][j][k];
        }
      }
    }

    if (!calibrated) { //disegno in canali
      let dataChart: string = "Channel,Counts\n";
      for (let i: number = 0; i < depth; i++) {
        dataChart += i + "," + dataForChart[i] + "\n";
      }
      let chartTitle: string;
      if (pixel1.xp == pixel2.xp && pixel1.yp == pixel2.yp) {
        chartTitle = "Chart pixel (" + pixel1.xp + ", " + (yDim - pixel1.yp - 1) + ")";
      } else {
        chartTitle = "Chart from (" + pixel1.xp + "," + pixel2.xp + ") to (" +
          (yDim - pixel1.yp - 1) + ", " + (yDim - pixel2.yp - 1) + ")";
      }
      g = setChart(dataChart, chartTitle);

    } else { //disegno in energie
      let dataChartCalibrated: string = "Energy,Counts\n";
      for (let i: number = 0; i < depth; i++) {
        dataChartCalibrated += round3(((i + 1) * a - b) / 1000) + "," + dataForChart[i] + "\n";
      }
      let chartTitle: string;
      if (pixel1.xp == pixel2.xp && pixel1.yp == pixel2.yp) {
        chartTitle = "Calibrated chart pixel (" + pixel1.xp + ", " + (yDim - pixel1.yp - 1) + ")";
      } else {
        chartTitle = "Calibrated chart from (" + pixel1.xp + ", " + pixel2.xp +
          ") to (" + (yDim - pixel1.yp - 1) + ", " + (yDim - pixel2.yp - 1) + ")";
      }
      g = setChart(dataChartCalibrated, chartTitle);
    }
  }

  $('#setlinearButton').on('click', function ()
  { //selezione scala lineare
    g.updateOptions({ logscale: false });
  });
  $('#setlogButton').on('click', function ()
  { //selezione scala logaritmica
    g.updateOptions({ logscale: true });
  });
  $('#setEnergyButton').on('click', function ()
  { //selezione energie
    calibrated = true;
    drawChart(pixel1, pixel2, 0, channelDepth);
    box1.setAttribute("value", "0");
    box2.setAttribute("value", "channelDepth");
  });
  $('#setChannelsButton').on('click', function ()
  { //selezione canali
    calibrated = false;
    drawChart(pixel1, pixel2, 0, channelDepth);
    box1.setAttribute("value", "-");
    box2.setAttribute("value", "-");
  });
  $('#ExportGraph').on('click', function ()
  { //esportazione grafico
    let img = <HTMLImageElement>document.getElementById("chartToImg");
    Dygraph.Export.asPNG(g, img);
    $("#ExportGraph").attr("href", img.src.replace('image/png', 'image/octet-stream'));
  });
  $('#readSpinbox').on('click', function ()
  { //esportazione grafico
    peackSelection(0, 0);
  });
  $('#chart').on('click', function ()
  { //zoom manuale sul grafico
    let r: number[];
    r = g.xAxisRange();
    if (!calibrated) {
      r[0] = Math.floor((((r[0] + 1) * a) - b) / 1000);
      r[1] = Math.floor((((r[1] + 1) * a) - b) / 1000);
    } else {
      r[0] = round3(r[0]);
      r[1] = round3(r[1]);
      box1.setAttribute("value", r[0].toString());
      box2.setAttribute("value", r[1].toString());
    }
    globalxMinRange = r[0];
    globalxMaxRange = r[1];
    drawImg(pixel1, pixel2, r[0], r[1]);
  });
  $('#elementSelect').on('change', function ()
  { //selezione elemento
    let element: string = (<HTMLInputElement>document.getElementById("elementSelect")).value;
    switch (element) {
      case "1": //Ca 
        peackSelection(3.6, 3.8);
        box1.setAttribute("value", "3.60");
        box2.setAttribute("value", "3.80");
        break;
      case "2": //Pb
        peackSelection(10.4, 10.7);
        box1.setAttribute("value", "10.40");
        box2.setAttribute("value", "10.70");
        break;
      case "3":  //Hg
        peackSelection(9.8, 10.15);
        box1.setAttribute("value", "9.80");
        box2.setAttribute("value", "10.15");
        break;
      case "4": //Fe
        peackSelection(6.3, 6.5);
        box1.setAttribute("value", "6.30");
        box2.setAttribute("value", "6.50");
        break;
      case "5":  //Cu
        peackSelection(7.85, 8.2);
        box1.setAttribute("value", "7.85");
        box2.setAttribute("value", "8.20");
        break;
      case "6": //Zn
        peackSelection(8.5, 8.72);
        box1.setAttribute("value", "8.50");
        box2.setAttribute("value", "8.72");
        break;
      case "7": //Ti
        peackSelection(4.35, 4.65);
        box1.setAttribute("value", "4.35");
        box2.setAttribute("value", "4.65");
        break;
      case "8": //K
        peackSelection(3.2, 3.42);
        box1.setAttribute("value", "3.20");
        box2.setAttribute("value", "3.42");
        break;
      case "9": //Co
        peackSelection(6.8, 7.05);
        box1.setAttribute("value", "6.80");
        box2.setAttribute("value", "7.05");
        break;
      default:
        peackSelection(0, channelDepth);
        box1.setAttribute("value", "0");
        box2.setAttribute("value", "channelDepth");
        break;
    }
  });

  //la funzione setChart riceve in input i dati e il titolo del grafico da disegnare
  //il quale è restituito il output
  function setChart(dataString: string, charTitle: string)
  {

    let xArrayRange: number[]; //estremi asse x da visualizzare
    let xLab: string;
    if (!calibrated) {
      xArrayRange = [0, depth];
      xLab = "ADC Channel";
    } else {
      xArrayRange = [xMinRange, xMaxRange];
      xLab = "Energy (keV)";
    }

    //dimensioni grafico
    let chartDim: any = document.querySelector('#chart-pannel').getBoundingClientRect();
    let chartWidth = chartDim.right - chartDim.left - 50;
    $('#chart').css('width', chartWidth);
    $('#chart').css('height', "400");

    //disegno il grafico
    let graphs: any = new Dygraph(document.getElementById("chart"), dataString, {
      title: charTitle,
      ylabel: 'Counts',
      xlabel: xLab,
      //legend: 'always',
      labelsDivStyles: { 'textAlign': 'right' },
      dateWindow: xArrayRange,
      showRangeSelector: true,
      logscale: false
    });

    return graphs;

  }

  //la funzione, dati gli estremi dell'intervallo da rappresentare, aggiorna mappa e grafico
  function peackSelection(xMinRange: number, xMaxRange: number)
  {

    //se l'intervallo è [0, 0] devo leggere dalle i valori dalle spinbox
    if (xMinRange == 0 && xMaxRange == 0) {
      xMinRange = parseInt((<HTMLInputElement>box1).value);
      xMaxRange = parseInt((<HTMLInputElement>box2).value);
    }

    globalxMinRange = xMinRange;
    globalxMaxRange = xMaxRange;
    newOrigin = { xp: 0, yp: 0 };
    rePrint = false;
    calibrated = true;
    drawImg({ xp: 0, yp: 0 }, { xp: xDim - 1, yp: yDim - 1 }, globalxMinRange, globalxMaxRange);
    drawChart({ xp: 0, yp: 0 }, { xp: xDim - 1, yp: yDim - 1 }, globalxMinRange, globalxMaxRange);
  }
}

//la funzione disegna il rettangolo durante la selezione di un'area della mappa
function zoomRect()
{
  let selectCanvas = <HTMLCanvasElement>document.getElementById("selectionCanvas");
  let ctx = selectCanvas.getContext("2d");

  // style the context
  ctx.fillStyle = "rgba(0, 110, 255, 0.25)";

  // this flage is true when the user is dragging the mouse
  let isDown = false;

  // these vars will hold the starting mouse position
  let startX: number;
  let startY: number;
  let mouseX: number;
  let mouseY: number;

  // these vars will hold the starting mouse position

  function handleMouseDown(e)
  {
    e.preventDefault();
    e.stopPropagation();

    //calculate mouse position
    let scrollTOP: number = (document.documentElement.scrollTop) ?
      document.documentElement.scrollTop : document.body.scrollTop;
    let scrollLEFT: number = (document.documentElement.scrollLeft) ?
      document.documentElement.scrollLeft : document.body.scrollLeft;
    let allX: number = e.clientX + scrollLEFT;
    let allY: number = e.clientY + scrollTOP;
    let elParent: any = document.getElementById('myCanvas');
    let objX: number = 0, objY: number = 0;
    while (elParent) {
      objX += elParent.offsetLeft;
      objY += elParent.offsetTop;
      elParent = elParent.offsetParent;
    }
    startX = allX - objX;
    startY = allY - objY;

    // set a flag indicating the drag has begun
    isDown = true;
  }

  function handleMouseUp(e)
  {
    e.preventDefault();
    e.stopPropagation();

    // the drag is over, clear the dragging flag
    isDown = false;
    ctx.clearRect(0, 0, selectCanvas.width, selectCanvas.height);
  }

  function handleMouseOut(e)
  {
    e.preventDefault();
    e.stopPropagation();

    // the drag is over, clear the dragging flag
    isDown = false;
    ctx.clearRect(0, 0, selectCanvas.width, selectCanvas.height);
  }

  function handleMouseMove(e)
  {
    e.preventDefault();
    e.stopPropagation();

    // if we're not dragging, just return
    if (!isDown) { return; }

    //calculate mouse position
    let scrollTOP: number = (document.documentElement.scrollTop) ?
      document.documentElement.scrollTop : document.body.scrollTop;
    let scrollLEFT: number = (document.documentElement.scrollLeft) ?
      document.documentElement.scrollLeft : document.body.scrollLeft;

    let allX: number = e.clientX + scrollLEFT;
    let allY: number = e.clientY + scrollTOP;
    let elParent: any = document.getElementById('myCanvas');
    let objX: number = 0, objY: number = 0;
    while (elParent) {
      objX += elParent.offsetLeft;
      objY += elParent.offsetTop;
      elParent = elParent.offsetParent;
    }
    mouseX = allX - objX;
    mouseY = allY - objY;

    // Put your mousemove stuff here

    // clear the canvas
    ctx.clearRect(0, 0, selectCanvas.width, selectCanvas.height);

    // calculate the rectangle width/height based
    // on starting vs current mouse position
    let width = mouseX - startX;
    let height = mouseY - startY;

    // draw a new rect from the start position 
    // to the current mouse position
    ctx.fillRect(startX, startY, width, height);

  }

  // listen for mouse events
  $("#selectionCanvas").mousedown(function (e) { handleMouseDown(e); });
  $("#selectionCanvas").mousemove(function (e) { handleMouseMove(e); });
  $("#selectionCanvas").mouseup(function (e) { handleMouseUp(e); });
  $("#selectionCanvas").mouseout(function (e) { handleMouseOut(e); });

}