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

Last change on this file since 370 was 370, checked in by garnier, 11 years ago

Ajout des paramètres width et height à la méthode chartPlot2vec + ... (see History)

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