source: PSPA/Interface_Web/trunk/pspaWT/sources/userInterface/src/GWt_pspaApplication.cc @ 341

Last change on this file since 341 was 341, checked in by lemeur, 11 years ago

fin dessins esp. phase + noms de fichiers

File size: 30.2 KB
Line 
1#include <stdio.h>
2#include <string.h>
3#include <vector>
4
5#include "GWt_pspaApplication.h"
6#include "GWt_ligneFaisceau.h"
7#include "GWt_softwarePanel.h"
8#include "GWt_globalParameters.h"
9// #include "GWt_dialog.h"
10#include "GWt_draggableImage.h"
11#include "particleBeam.h"
12#include "bareParticle.h"
13#include "nomDeLogiciel.h"
14#include "mixedTools.h"
15#include "nomdElements.h"
16#include "environmentVariables.h"
17#include "GWt_console.h"
18#include "GWt_serverFileSelector.h"
19#include "trivaluedBool.h"
20
21#include <Wt/WGridLayout>
22#include <Wt/WVBoxLayout>
23#include <Wt/WHBoxLayout>
24#include <Wt/WImage>
25#include <Wt/WMenu>
26#include <Wt/WStackedWidget>
27#include <Wt/WBreak>
28#include <Wt/WDialog>
29#include <Wt/WStandardItemModel>
30#include <Wt/WFileUpload>
31#include <Wt/WPainter>
32#include <Wt/WPdfImage>
33#include <Wt/WRasterImage>
34#include <Wt/WScrollArea>
35#include <Wt/WLineEdit>
36#include <Wt/WRadioButton>
37
38using namespace Wt::Chart;
39
40/*
41 * The env argument contains information about the new session, and
42 * the initial request. It must be passed to the WApplication
43 * constructor so it is typically also an argument for your custom
44 * application constructor.
45 */
46
47PspaApplication::PspaApplication(const WEnvironment& env) : WApplication(env)
48{
49   
50    workingDir_ = WApplication::docRoot()+ "/"+WORKINGAREA;
51    nameOfCase_ = "pspa"; // default
52   
53    setTitle("portail PSPA");                               // application title
54    if (!wApp->environment().javaScript()) {
55        new WText("<i>This examples requires that javascript support is enabled.</i>",root());
56    }
57   
58    // register the absractElementFactory
59    abstractElementFactory_ = new GWt_abstractElementFactory();
60    abstractElementFactory_->setRFGunEnable(true);
61    abstractElementFactory_->setDriftEnable(true);
62    abstractElementFactory_->setCellEnable(true);
63    abstractElementFactory_->setBendEnable(true);
64    abstractElementFactory_->setSolenoEnable(true);
65    abstractElementFactory_->setBeamEnable(true);
66    abstractElementFactory_->setFitEnable(true);
67   
68    // include the styleSheet
69    WContainerWidget *widroot = root();
70    useStyleSheet       ("htdocs/pspa.css");
71    dtmanage_ = new dataManager(this);
72    //    dtmanage_->setWorkingDir(workingDir_);
73    /*
74     * The main layout is a 3x2 grid layout.
75     */
76    WGridLayout *layout = new WGridLayout();
77    //  layout->addWidget(createTitle("<a href='workingArea/parmin'> Menu (In future)</a>"), 0, 0, 1, 2);
78    //  layout->addWidget(createTitle("Menu (In future)"), 0, 0, 1, 2);
79   
80    WHBoxLayout *toolbarLayout = new WHBoxLayout();
81   
82    WPushButton* boutonSauve = new WPushButton();
83    WPushButton* boutonRestaure = new WPushButton();
84    WPushButton* boutonLoadNew = new WPushButton();
85    WPushButton* boutongraphicalAnalysis = new WPushButton();
86   
87    boutonSauve->setStyleClass("saveButton");
88    boutonRestaure->setStyleClass("restoreButton");
89    boutonLoadNew->setStyleClass("loadNewButton");
90    boutongraphicalAnalysis->setStyleClass("histoButton");
91   
92    boutonSauve->setToolTip ("sauvegarder la config");
93    boutonRestaure->setToolTip (" restaurer la config");
94    boutonLoadNew->setToolTip ("upload config");
95    boutongraphicalAnalysis->setToolTip ("analyse graphique");
96   
97    boutonSauve->setMaximumSize(38,38);
98    boutonSauve->setMinimumSize(38,38);
99    boutonRestaure->setMaximumSize(38,38);
100    boutonRestaure->setMinimumSize(38,38);
101    boutonLoadNew->setMaximumSize(38,38);
102    boutonLoadNew->setMinimumSize(38,38);
103    boutongraphicalAnalysis->setMaximumSize(38,38);
104    boutongraphicalAnalysis->setMinimumSize(38,38);
105   
106    boutonSauve->clicked().connect(this, &PspaApplication::sauver);
107    boutonRestaure->clicked().connect(this, &PspaApplication::restaurer);
108    // Upload when the button is clicked.
109    // React to a succesfull upload.
110    boutonLoadNew->clicked().connect(this, &PspaApplication::openFileSelector);
111   
112    boutongraphicalAnalysis->clicked().connect(this, &PspaApplication::dialogOnGraphics);
113   
114    toolbarLayout->addWidget(boutonSauve , 0,Wt::AlignMiddle);
115    toolbarLayout->addWidget(boutonRestaure , 0,Wt::AlignMiddle);
116    toolbarLayout->addWidget(boutonLoadNew , 0,Wt::AlignMiddle);
117    toolbarLayout->addWidget(boutongraphicalAnalysis , 0,Wt::AlignMiddle);
118    toolbarLayout->addWidget(new WText("") , 1,Wt::AlignMiddle);
119   
120    WContainerWidget * layoutContainer = new WContainerWidget();
121    layoutContainer->setLayout(toolbarLayout);
122    layoutContainer->decorationStyle().setBackgroundImage ("/htdocs/fond_toolbar.png");
123    layout->addWidget(layoutContainer, 1, 0, 1, 2);
124    layout->addWidget(createPalette(), 2, 0, 4, 1);
125   
126    createBeamLine();
127
128    WScrollArea* scroll = new  WScrollArea();
129    scroll->setWidget(beamLine_);
130    layout->addWidget(scroll, 2, 1, 1, 1);
131   
132   
133    // console_ = new WContainerWidget();
134    // console_->decorationStyle().setBackgroundColor (WColor("lightgray"));
135    // console_->setMaximumSize(600,200);
136    // layout->addWidget(console_, 3, 1);
137    // console_->setMinimumSize(300,100);
138    // console_->setOverflow(WContainerWidget::OverflowAuto);
139   
140   
141    console_ = new GWt_console();
142    console_->clear();
143    console_->decorationStyle().setBackgroundColor (WColor("lightgray"));
144    console_->setMaximumSize(600,200);
145    console_->setMinimumSize(300,100);
146    console_->setOverflow(WContainerWidget::OverflowAuto);
147    layout->addWidget(console_, 3, 2);
148   
149    //-----------
150    // A supprimer et a mettre en fenetre
151    globalParam_ = createGlobalParamWidget();
152    //  leDessin_ = new WContainerWidget();
153    //  leDessin_ = createDrawingWidget();
154    graphicsDialog_ = new GWt_dialog("graphical analysis",createDrawingWidget(),false);
155    graphicsDialog_->setMinimumSize(400,400);
156    graphicsDialog_->setClosable(true);
157   
158    executeWidget_ = new GWt_softwarePanel(dtmanage_,this);
159   
160    layout->addWidget( globalParam_, 3, 1);
161    //  layout->addWidget( leDessin_, 3, 2);
162    layout->addWidget( executeWidget_ , 4, 1);
163    //-----------
164     
165    layout->setColumnResizable(1);
166    layout->setRowResizable(2);
167    /*
168     * Let row 2 and column 1 take the excess space.
169     */
170    layout->setRowStretch(2, 1);
171    layout->setColumnStretch(1, 1);
172   
173    widroot->setLayout(layout);
174}
175
176WWidget* PspaApplication::createPalette()
177{
178  WContainerWidget* palette = new WContainerWidget();
179  vector <GWt_abstractElement*> elems = abstractElementFactory_->getAllElements();
180  for (unsigned a = 0; a < elems.size(); a++) {
181    elems[a]->createDragImage(palette);
182    new WBreak(palette);
183  }
184
185  return palette; 
186}
187
188void PspaApplication::createDragImage(const char *url,const char *smallurl,const char *mimeType,WContainerWidget *p,WString())
189{
190  GWt_draggableImage *result = new GWt_draggableImage(url,p);
191 
192  /*
193   * Set the image to be draggable, showing the other image (dragImage)
194   * to be used as the widget that is visually dragged.
195   */
196  result->setDraggable(mimeType,new WImage(smallurl,p),true);
197}
198
199void PspaApplication::createBeamLine()
200{
201  beamLine_ = new GWt_LigneFaisceau(this);
202  beamLine_->setMinimumSize(300,100);
203}
204
205WWidget* PspaApplication::createGlobalParamWidget()
206{
207    WContainerWidget* globalParam = new GWt_globalParameters(this);
208    globalParam->setMaximumSize(600,150);
209    globalParam->setMinimumSize(600,150);
210    return globalParam;
211}
212
213
214void PspaApplication::dialogOnGraphics()
215{
216  graphicsDialog_->show();
217}
218
219WContainerWidget* PspaApplication::createDrawingWidget()
220{
221  WGridLayout *glayout= new WGridLayout();
222  WContainerWidget* dessin = new WContainerWidget();
223  dessin->setLayout(glayout);
224
225  group_ = new Wt::WButtonGroup(this);
226 
227  /////////////////////////////////////////////////////////////////////
228       
229  choixEnveloppeDessin_ = new WComboBox();
230  choixEnveloppeDessin_->addItem("x");
231  // choixEnveloppeDessin_->addItem("y");
232  Wt::WRadioButton *button1= new WRadioButton(" enveloppe");
233  group_->addButton(button1,1);
234  glayout->addWidget(button1,0,1);
235  glayout->addWidget(choixEnveloppeDessin_,0,2);
236  /////////////////////////////////////////////////////////////////////
237
238  choixElementDessin_ = new WComboBox();
239  choixElementDessin_->setMinimumSize(50,10);
240  choixTypeDessinFaisceau_ = new WComboBox();
241  choixTypeDessinFaisceau_->addItem("courant_snyder");
242  choixTypeDessinFaisceau_->addItem("macroparticles");
243  Wt::WRadioButton *button2= new WRadioButton(" phase space after element");
244
245    choixAbsPhase_ = new WComboBox();
246    choixAbsPhase_->addItem("x");
247    choixAbsPhase_->addItem("y");
248    choixAbsPhase_->addItem("z");
249    choixAbsPhase_->addItem("xp");
250    choixAbsPhase_->addItem("yp");
251    choixAbsPhase_->addItem("dE/E");
252    choixAbsPhase_->setCurrentIndex(0);
253
254    choixOrdPhase_ = new WComboBox();
255    choixOrdPhase_->addItem("x");
256    choixOrdPhase_->addItem("y");
257    choixOrdPhase_->addItem("z");
258    choixOrdPhase_->addItem("xp");
259    choixOrdPhase_->addItem("yp");
260    choixOrdPhase_->addItem("dE/E");
261    choixOrdPhase_->setCurrentIndex(3);
262
263
264
265  group_->addButton(button2,2);
266  glayout->addWidget(button2,1,1);
267  glayout->addWidget(choixElementDessin_,1,2);
268  glayout->addWidget(choixTypeDessinFaisceau_,1,3);
269  //  glayout->addWidget(new WText("abs. :"),2,2);
270  glayout->addWidget(choixAbsPhase_,2,2);
271  //  glayout->addWidget(new WText("ord. :"),2,4);
272  glayout->addWidget(choixOrdPhase_,2,3);
273  /////////////////////////////////////////////////////////////////////
274
275  choixHistoDessin_ = new WComboBox();
276  Wt::WRadioButton *button3= new WRadioButton(" histogram after element");
277  group_->addButton(button3,3);
278  glayout->addWidget(button3,3,1);
279  glayout->addWidget(choixHistoDessin_,3,2);
280  /////////////////////////////////////////////////////////////////////
281 
282  WPushButton *close= new WPushButton("close"); 
283  glayout->addWidget(close,4,1);
284  close->clicked().connect(this,&PspaApplication::closeGraphicDialog);
285 
286  WPushButton *draw= new WPushButton("draw"); 
287  glayout->addWidget(draw,4,2,2,1);
288  draw->clicked().connect(this,&PspaApplication::dessiner);
289  /////////////////////////////////////////////////////////////////////
290
291  toto_ = new WContainerWidget();
292  dessin->addWidget(toto_);
293  return dessin;
294}
295
296void PspaApplication::closeGraphicDialog()
297{
298  cout << " close graphicsDialog_" << endl;
299  for(unsigned i = 0; i < eDialog_.size(); i++) eDialog_[i]->done(WDialog::Rejected);
300  eDialog_.clear();
301  graphicsDialog_->done(WDialog::Rejected);
302}
303
304void PspaApplication::dessiner()
305{
306  int k= group_->checkedId();
307  cout << "dessiner k= " << k << endl;
308
309  switch(k) {
310  case  1: 
311    dessinerEnveloppe();
312    break;
313  case 2:
314    dessinerPhaseSpace();
315    break;
316  case 3:
317    dessinerHistogramme();
318    break;
319  default:
320    GWt_dialog graphicalWarning("graphical analysis","select a button",GWt_dialog::Warning,false,true);
321    graphicalWarning.exec();
322    break;
323  }
324}
325
326void PspaApplication::sauver()
327{
328  cout << " on sauve " << endl;
329  console_->addConsoleMessage("sauvegarde");
330 
331  dialogSave_ = new WDialog("save");
332  new WText("name of case : ",dialogSave_->contents());
333  saveNameEdit_ = new WLineEdit(nameOfCase_.c_str(), dialogSave_->contents());
334  WPushButton *annule = new WPushButton("cancel",dialogSave_->contents());
335  WPushButton *submit = new WPushButton("OK",dialogSave_->contents());
336  annule->clicked().connect(dialogSave_, &Wt::WDialog::reject);
337  submit->clicked().connect(dialogSave_, &Wt::WDialog::accept);
338  dialogSave_->finished().connect(this, &PspaApplication::dialogSaveDone);
339  dialogSave_->show();
340}
341
342void PspaApplication::dialogSaveDone(WDialog::DialogCode code)
343{
344 
345  if ( code != Wt::WDialog::Accepted ) { console_->addConsoleMessage(" pas de sauvegarde"); return;}
346  else { console_->addConsoleMessage("sauvegarde sur repertoire : " + workingDir_);}
347  nameOfCase_ = saveNameEdit_->text().toUTF8();
348  cout << " PspaApplication::dialogSaveDone() sur fichier = " << nameOfCase_ << endl;
349  delete dialogSave_;
350  dialogSave_ = NULL;
351  GWt_globalParameters* bibi = static_cast<GWt_globalParameters*>(globalParam_);
352  bibi->updateGlobals();
353  //  dtmanage_->saveConfiguration(nameOfCase_);
354  dtmanage_->saveConfiguration( nameOfCase_);
355}
356
357
358void PspaApplication::restaurer()
359{
360    GWt_serverFileSelector * fs = new GWt_serverFileSelector("Select a configuration file",workingDir_);
361    string fileName = fs->exec();
362     nameOfCase_ = fileName;
363   
364    removePathFromConfigName(nameOfCase_ );
365    cout << " nom sans path " << nameOfCase_ << endl;
366    removeExtensionFromConfigName(nameOfCase_);
367    cout << " nom sans extension " << nameOfCase_ << endl;
368    if (nameOfCase_ == "")
369        return;
370    cout << " je restaure le fichier " << fileName << endl;
371    dialogSave_ = NULL;
372   
373    bool test = dtmanage_->restoreElements(fileName);
374    if ( !test ) {
375        GWt_dialog restoreWarning(" element restoring", "failure in restoring elements from file : " + fileName , GWt_dialog::Error, false,true);
376        restoreWarning.exec();
377    }
378   
379    GWt_globalParameters* bibi = static_cast<GWt_globalParameters*>(globalParam_);
380    bibi->renew();
381   
382    console_->addConsoleMessage(string("...terminee"));
383}
384
385
386void PspaApplication::openFileSelector()
387{
388   
389  WContainerWidget *result = new WContainerWidget();
390  WVBoxLayout* myLayout = new WVBoxLayout();
391   
392  uploadFileSelectorWidget_ = new WFileUpload();
393   
394  uploadFileSelectorWidget_->setFileTextSize(40);
395   
396  myLayout->addWidget(new WText("Select the configuration file for pspa : "));
397  myLayout->addWidget(uploadFileSelectorWidget_);
398   
399  result->setLayout (myLayout);
400   
401  // Upload automatically when the user entered a file.
402  uploadFileSelectorWidget_->changed().connect(uploadFileSelectorWidget_, &WFileUpload::upload);
403 
404  // React to a succesfull upload.
405  uploadFileSelectorWidget_->uploaded().connect(this, &PspaApplication::chargerConfig);
406 
407  // React to a fileupload problem.
408  uploadFileSelectorWidget_->fileTooLarge().connect(this, &PspaApplication::fileTooLarge);
409 
410 
411  GWt_dialog* fileSelectorDialog = new GWt_dialog("Load a file",result,false);
412 
413  fileSelectorDialog->exec();
414}
415
416void PspaApplication::chargerConfig()
417{
418    GWt_dialog*  message= new GWt_dialog("File successfully upload","The file has been correctly upload to" + uploadFileSelectorWidget_->spoolFileName(),GWt_dialog::Warning,false,true);
419   
420    string nomDuFichier = (uploadFileSelectorWidget_->clientFileName()).toUTF8();
421    cout << " fichier client : " << nomDuFichier << endl;
422    bool test = removeExtensionFromConfigName(nomDuFichier);
423    cout << " fichier client sans extension : " << nomDuFichier << endl;
424   
425    if ( test )
426    {
427        nameOfCase_ = nomDuFichier;
428        console_->addConsoleMessage(string("restauration..."));
429       
430        if ( !dtmanage_->restoreElements(uploadFileSelectorWidget_->spoolFileName()) ) {
431            GWt_dialog restoreWarning(" element restoring", "failure in restoring elements !", GWt_dialog::Error, false,true);
432            restoreWarning.exec();
433        }
434       
435        GWt_globalParameters* bibi = static_cast<GWt_globalParameters*>(globalParam_);
436        bibi->renew();
437               
438        console_->addConsoleMessage(string("...terminee"));
439        message->show();
440    }
441}
442
443
444void PspaApplication::fileTooLarge()
445{
446    std::stringstream stream;
447    stream << maximumRequestSize ();
448    std::string maxRequestSize(stream.str());
449   
450    std::string message = "This file is too large, please select a one\n";
451    message += "Maximum file size is "+ maxRequestSize;
452    message += " bytes\n";
453   
454    GWt_dialog*  messageBox= new GWt_dialog("Error during upload file" ,message ,GWt_dialog::Error,false,true);
455   
456    messageBox->show();
457}
458
459void PspaApplication::faireDessin()
460{
461  choixElementDessin_->clear();
462  choixHistoDessin_->clear();
463  int nombre = dtmanage_->getBeamLineSize();
464  cout << " PspaApplication::faireDessin() nb elements : " << nombre << endl;
465  for(int i = 1; i <= nombre; i++) {
466    choixElementDessin_->addItem(dtmanage_->getLabelFromElementNumero(i));
467    choixHistoDessin_->addItem(dtmanage_->getLabelFromElementNumero(i));
468  } 
469}
470
471void PspaApplication::dessinerPhaseSpace()
472{   
473   
474  int typeFaisceau = choixTypeDessinFaisceau_->currentIndex();
475  int index = choixElementDessin_->currentIndex();
476  unsigned xabs = choixAbsPhase_->currentIndex();
477  unsigned yord = choixOrdPhase_->currentIndex();
478  if ( xabs == yord ) {
479        GWt_dialog phaseSpaceError(" graphical analysis", "the beam coordinates must be different !", GWt_dialog::Error, false,true);
480        phaseSpaceError.exec();
481        return;
482  }
483  string nameAbs = choixAbsPhase_->currentText().toUTF8();
484  string nameOrd = choixOrdPhase_->currentText().toUTF8();
485
486  particleBeam* beam = dtmanage_->getDiagnosticBeam(index);
487   
488  if ( beam == NULL ) {
489    GWt_dialog warningBeamState(" graphical analysis", "the beam does not exist at the end of this element !", GWt_dialog::Error, false,true);
490    warningBeamState.exec();
491    return;
492  }
493   
494    toto_->clear();
495 
496  if ( typeFaisceau == 0 )
497    {
498      if ( !beam->momentRepresentationOk() ) beam->buildMomentRepresentation();
499      faireDessinTransport(toto_, beam, xabs, yord, nameAbs, nameOrd );
500    }
501  else if ( typeFaisceau == 1 )
502    {
503      if ( beam->particleRepresentationOk() ) faireDessinParmela(toto_, beam, xabs, yord, nameAbs, nameOrd );
504      else {
505        GWt_dialog warningBeamState(" graphical analysis", "the beam state does not allow providing a drawing with macroparticles !", GWt_dialog::Error, false,true);
506        warningBeamState.exec();
507      }
508    }
509  else {
510    GWt_dialog warningTypeDrawing(" graphical analysis", "type of  drawing not programmed !", GWt_dialog::Error, false,true);
511    warningTypeDrawing.exec();
512  }
513}
514
515void PspaApplication::dessinerEnveloppe()
516{
517  toto_->clear();
518 
519  int typeEnveloppe = choixEnveloppeDessin_->currentIndex();
520  if ( typeEnveloppe == 0 )
521    {
522      faireDessinEnveloppe(toto_, "x");
523    }
524  else {
525    GWt_dialog warningTypeEnveloppe(" graphical analysis", "type of enveloppe drawing not programmed !", GWt_dialog::Error, false,true);
526    warningTypeEnveloppe.exec();
527  }
528}
529
530void PspaApplication::faireDessinEnveloppe(WContainerWidget* toto, string type)
531{
532   
533  GWt_dialog* envDialog = new GWt_dialog("enveloppe",toto,false);
534  eDialog_.push_back(envDialog);
535  envDialog->setMinimumSize(400,400);
536  envDialog->setClosable(true);
537  envDialog->show();
538     
539  //       new WText(nameOfCase_ + " : enveloppe", toto);
540  unsigned nbel = dtmanage_->getBeamLineSize();
541  vector<double> xcor;
542  vector<double> ycor;
543  dtmanage_->donneesRmsEnveloppe(type,1, nbel, xcor,ycor);
544  scatterPlot1D(envDialog->contents(),xcor,ycor); 
545}
546
547void PspaApplication::setModelComponentForPhaseSpace(WStandardItemModel* model, vector<bareParticle>& partic, unsigned indexParticleComponent, unsigned modelComponent) {
548  double valeur;
549  if ( indexParticleComponent > 5  ) return;
550
551  if ( indexParticleComponent <= 2 ) {
552    for (unsigned i = 0; i < partic.size(); ++i) {
553      valeur = partic.at(i).getPosition().getComponent(indexParticleComponent);
554      model->setData(i, modelComponent, valeur);
555    }
556  } else {
557    if ( indexParticleComponent == 5 ) {
558      cout << " PspaApplication::faireDessinParmela : deltap non programme " << endl;
559      return;
560    } else {
561      for (unsigned i = 0; i < partic.size(); ++i) {
562        double begamz = partic.at(i).getBetaGamma().getComponent(2);
563        if ( begamz != 0.0) {
564          valeur = 1.e3*partic.at(i).getBetaGamma().getComponent(indexParticleComponent-3)/begamz;
565        } else {
566          valeur = 0.0;
567        }
568        model->setData(i, modelComponent, valeur);
569      }
570    }
571  }
572}
573
574void PspaApplication::faireDessinParmela(WContainerWidget* toto, particleBeam* beam, unsigned indexAbs, unsigned indexOrd, string namex, string namey )
575{
576  cout << " faireDessinParmela " << endl;
577  GWt_dialog* pointsDialog = new GWt_dialog("space phase",toto,false);
578  eDialog_.push_back(pointsDialog);
579  pointsDialog->setMinimumSize(400,400);
580  pointsDialog->setClosable(true);
581  // pointsDialog->show();
582     
583  vector<bareParticle>& partic = beam->getParticleVector();
584  new WText(nameOfCase_ + " : phase space " + namex + " ," + namey + " ; particle number : "+ mixedTools::intToString(partic.size()), pointsDialog->contents());
585
586  WStandardItemModel *model = new WStandardItemModel(partic.size(), 2, pointsDialog->contents());
587
588
589  setModelComponentForPhaseSpace(model, partic, indexAbs, 0);
590  setModelComponentForPhaseSpace(model, partic, indexOrd, 1);
591
592  cout << " faireDessinParmela : FAISCEAU VU  " << endl;
593
594  WCartesianChart *chart = new WCartesianChart(pointsDialog->contents());
595  chart->setModel(model);        // set the model
596  chart->setXSeriesColumn(0);    // set the column that holds the X data
597  chart->setLegendEnabled(true); // enable the legend
598   
599  chart->setType(ScatterPlot);   // set type to ScatterPlot
600   
601  // Typically, for mathematical functions, you want the axes to cross
602  // at the 0 mark:
603  chart->axis(XAxis).setLocation(ZeroValue);
604  chart->axis(YAxis).setLocation(ZeroValue);
605   
606  // Provide space for the X and Y axis and title.
607  chart->setPlotAreaPadding(80, Left);
608  chart->setPlotAreaPadding(40, Top | Bottom);
609  // Add the curves
610  WDataSeries s(1, PointSeries, Y1Axis);
611  //  s.setShadow(WShadow(3, 3, WColor(0, 0, 0, 127), 3));
612  //    s.setMarker(SquareMarker);
613  //  s.setMarkerSize(600.);
614  //  cout << "le marker est : " << s.marker() << endl;
615  chart->addSeries(s);
616   
617  chart->resize(400, 400); // WPaintedWidget must be given explicit size
618   
619   
620#ifdef HAS_IMAGEMAGIC
621  Wt::WRasterImage pngImage("png", 600, 600);
622  Wt::WPainter p(&pngImage);
623  chart->paint(p);
624  std::string name;
625  name = workingDir_ + "/chart-"+sessionId ()+".png";
626  std::ofstream f(name.c_str(), std::ios::out |std::ios::trunc | std::ios::binary);
627  pngImage.write(f);
628  new WText("<a href='workingArea/chart-"+sessionId ()+".png' target='_blank'>Afficher l'image</a>",toto);
629#endif
630   
631  pointsDialog->show();
632   
633  //  chart->setMargin(10, Top | Bottom);            // add margin vertically
634  //  chart->setMargin(WLength::Auto, Left | Right); // center horizontally
635}
636
637void PspaApplication::faireDessinTransport(WContainerWidget* toto, particleBeam* beam, unsigned indexAbs, unsigned indexOrd, string namex, string namey)
638{
639  GWt_dialog* ellipseDialog = new GWt_dialog("ellipse",toto,false);
640  eDialog_.push_back(ellipseDialog);
641  ellipseDialog->setMinimumSize(400,400);
642  ellipseDialog->setClosable(true);
643  ellipseDialog->show();
644   
645  new WText(nameOfCase_ + " : emittance " + namex + " , " + namey + " : " + mixedTools::doubleToString(beam->getUnnormalizedEmittanceX()) + " pi.mm.mrad" , ellipseDialog->contents());
646  new WBreak(ellipseDialog->contents());
647  new WText(" xmax = " + mixedTools::doubleToString(beam->getSigmaTransportij(1,1)) + " cm ", ellipseDialog->contents());
648  new WBreak(ellipseDialog->contents());
649  new WText(" x' max = " + mixedTools::doubleToString(beam->getSigmaTransportij(2,2)) + " mrad ", ellipseDialog->contents());
650  new WBreak(ellipseDialog->contents());
651  new WText(" corr. 12 = " + mixedTools::doubleToString(beam->getSigmaTransportij(2,1))  + " sqrt(cm.rad) ", ellipseDialog->contents());
652 
653  vector<double> xcor;
654  vector<double> ycor;
655  beam->donneesDessinEllipse(xcor,ycor,indexAbs, indexOrd);
656  //  beam->donneesDessinEllipseXxp(xcor,ycor);
657  scatterPlot1D(ellipseDialog->contents(),xcor,ycor); 
658}
659
660
661
662void PspaApplication::scatterPlot1D(WContainerWidget* toto, vector<double>& xcor, vector<double>& ycor)
663{
664    int nbpts = xcor.size();
665    cout << " PspaApplication::scatterPlot1D nbpts = " << nbpts << endl;
666    WStandardItemModel *model = new WStandardItemModel(nbpts, 2, toto);
667    for (int i = 0; i < nbpts; ++i) {
668        model->setData(i, 0, xcor.at(i));
669        model->setData(i, 1, ycor.at(i));
670        //    cout << " PspaApplication::scatterPlot1D el= " << i+1 << " x= " << xcor.at(i) << " y= " << ycor.at(i) << endl;
671    }
672   
673    WCartesianChart *chart = new WCartesianChart(toto);
674    chart->setTitle("titre");
675   
676    //  chart->initLayout();
677   
678    chart->setModel(model);        // set the model
679    chart->setXSeriesColumn(0);    // set the column that holds the X data
680    chart->setLegendEnabled(true); // enable the legend
681   
682    chart->setType(ScatterPlot);   // set type to ScatterPlot
683   
684    // Typically, for mathematical functions, you want the axes to cross
685    // at the 0 mark:
686    chart->axis(XAxis).setLocation(ZeroValue);
687    chart->axis(YAxis).setLocation(ZeroValue);
688   
689    // Provide space for the X and Y axis and title.
690    //   chart->setPlotAreaPadding(80, Left);
691    //   chart->setPlotAreaPadding(40, Top | Bottom);
692    // Add the curves
693    WDataSeries s(1, LineSeries, Y1Axis);
694    chart->addSeries(s);
695   
696    // chart->setBackground (WBrush(WColor("blue")));
697    chart->resize(500, 300); // WPaintedWidget must be given explicit size
698   
699#ifdef HAS_IMAGEMAGIC
700    Wt::WRasterImage pngImage("png", 600, 600);
701    Wt::WPainter p(&pngImage);
702   
703    chart->paint(p);
704    std::string name;
705    name = workingDir_ + "/chart-"+sessionId ()+".png";
706    std::ofstream f(name.c_str(), std::ios::out |std::ios::trunc | std::ios::binary);
707    pngImage.write(f);
708   
709    new WText("<a href='workingArea/chart-"+sessionId ()+".png' target='_blank'>Afficher l'image</a>",toto);
710   
711    /*
712     Wt::WPdfImage pdfImage("30cm", "30cm");
713     Wt::WPainter p1(&pdfImage);
714     chart->paint(p1);
715     std::ofstream f1("chart.pdf", std::ios::out | std::ios::binary);
716     pdfImage.write(f1);
717     */
718#endif
719}
720
721
722
723WText* PspaApplication::createTitle(const WString& title)
724{
725  WText *result = new WText(title);
726  result->setInline(false);
727  result->setStyleClass("title");
728  result->setMinimumSize(30,30);
729 
730  return result;
731}
732
733// void PspaApplication::addConsoleMessage(WString msg) {
734//   WText *w = new WText(console_);
735//   w->setTextFormat(PlainText);
736//   w->setText(msg);
737//   w->setInline(false);
738
739//   /*
740//    * Little javascript trick to make sure we scroll along with new content
741//    */
742//   WApplication *app = WApplication::instance();
743//   app->doJavaScript(console_->jsRef() + ".scrollTop += "
744//                     + console_->jsRef() + ".scrollHeight;");
745
746// }
747
748bool PspaApplication::removePathFromConfigName(string& config) {
749  string toExtract = workingDir_ + "/";
750  string::size_type nn = config.find(toExtract);
751  if ( nn == string::npos ) {
752        GWt_dialog checkremovePath(" checking config file name", " failed to recognize path name for file  " + config, GWt_dialog::Error,true,true);
753        checkremovePath.exec();
754    return false;
755  }
756  config.replace(nn, toExtract.size(), "");
757  return true;
758}
759
760bool PspaApplication::removeExtensionFromConfigName(string& config)
761{
762    //  string configName;
763    string extension(".save");
764    bool test = true;
765    string::size_type nn = config.rfind('.');
766    if ( nn == string::npos )
767    {
768        // pas de point
769        test = false;
770    }
771    string fin = config.substr(nn);
772    if ( fin != extension )
773    {
774        // l'extension n'est pas la bonne
775        test = false;
776    }
777    if ( test )
778    {
779        string::size_type count = config.length() - extension.length();
780        config = config.substr(0, count);
781    }
782    else
783    {
784        GWt_dialog checkConfigNameDialog(" checking config file name", " the file must have the extension " + extension, GWt_dialog::Error,true,true);
785        checkConfigNameDialog.exec();
786    }
787    return test;
788}
789
790void PspaApplication::dessinerHistogramme()
791{
792  // pour mon test : histo en energie
793  toto_->clear();
794 
795  GWt_dialog* histoDialog = new GWt_dialog("histogramme",toto_,false);
796  eDialog_.push_back(histoDialog);
797  histoDialog->setMinimumSize(400,400);
798  histoDialog->setClosable(true);
799  histoDialog->show();
800 
801  int index = choixHistoDessin_->currentIndex();   
802  particleBeam* beam = dtmanage_->getDiagnosticBeam(index);
803  if (beam == NULL) {
804    GWt_dialog warningBeamState("histogram","the beam does not exist at the end of this element !", GWt_dialog::Error, false,true);
805    warningBeamState.exec();
806    return;
807  }
808 
809  if (!beam->particleRepresentationOk()) {
810    GWt_dialog warningBeamState("histogram", "the beam state does not allow providing a drawing with macroparticles !", GWt_dialog::Error, false,true);
811    warningBeamState.exec();
812    return;
813  }
814
815  vector<double> xcor;
816  vector<int> hist;
817  int cnts;
818  double out[3]= {0.0};
819  beam->histogramme(xcor,hist,cnts,out);
820 
821  cout<<"xcor.size()= "<<xcor.size()<<", hist.size()= "<<hist.size()<<endl;
822  //////////////////////////////////////////////////////////////////////////////////
823
824  WContainerWidget *w= histoDialog->contents();
825  int nbpts= xcor.size()+cnts+1;
826  WStandardItemModel *model = new WStandardItemModel(nbpts,2,w);
827  model->setHeaderData(1, WString("energie"));
828 
829  int j= 0;
830  if(hist[0] > 0) {
831    model->setData(j,0,xcor[0]);
832    model->setData(j,1,hist[0]);
833    j++;
834  }
835  model->setData(j,0,xcor[0]);
836  model->setData(j,1,hist[0]);
837  j++;
838  for (int i = 1; i < nbpts; ++i) {
839    if(hist[i] == 0) {
840      if(hist[i-1] > 0) {
841        model->setData(j,0,xcor[i]);
842        model->setData(j,1,hist[i-1]);
843        j++;
844      }
845      model->setData(j,0,xcor[i]);
846      model->setData(j,1,hist[i]);
847      j++;
848    }
849    if(hist[i] > 0) {
850      model->setData(j,0,xcor[i]);
851      model->setData(j,1,hist[i-1]);
852      j++;
853      model->setData(j,0,xcor[i]);
854      model->setData(j,1,hist[i]);
855      j++;
856    }
857  }
858 
859  // legendes
860  new WText(" entries : "+ mixedTools::intToString((int)out[0]),w);
861  new WBreak(w);
862  new WText(" mean : "+ mixedTools::doubleToString(out[1])+" MeV",w);
863  new WBreak(w);
864  new WText(" rms : "+ mixedTools::doubleToString(out[2])+" KeV",w);
865 
866  WCartesianChart *chart = new WCartesianChart(w);
867  chart->setTitle("Histogram of particle energies");
868  chart->setModel(model);        // set the model
869  chart->setXSeriesColumn(0);    // set the column that holds the categories
870  chart->setLegendEnabled(false); // enable the legend
871   
872  // Provide space for the X and Y axis and title.
873  chart->setPlotAreaPadding(200, Right);
874  chart->setPlotAreaPadding(80, Left);
875  chart->setPlotAreaPadding(40, Top | Bottom);
876   
877  chart->setType(ScatterPlot);
878   
879  WAxis& axis = chart->axis(XAxis);
880  axis.setLabelFormat("%.3f");
881  axis.setGridLinesEnabled(true);
882  axis.setTitle(WString("legende x"));
883
884  chart->axis(Y1Axis).setGridLinesEnabled(true);
885  chart->axis(Y1Axis).setTitle(WString("legende y"));
886   
887  WDataSeries s(1, LineSeries);
888  s.setFillRange(ZeroValueFill);
889  chart->addSeries(s);
890   
891  chart->resize(800, 400);
892  chart->setMargin(10, Top | Bottom);
893  chart->setMargin(WLength::Auto, Left | Right);
894   
895  LegendLocation location = LegendOutside;
896  Side side = Right;
897  AlignmentFlag alignment = AlignMiddle;
898  chart->setLegendLocation(location, side, alignment);
899  chart->setLegendStyle(chart->legendFont(), WPen(black), WBrush(WColor(0xFF, 0xFA, 0xE5)));
900}
Note: See TracBrowser for help on using the repository browser.