source: xssim/branches/tpiontek/src/simulator/stats/implementation/GSSimStatistics.java @ 241

Revision 241, 45.2 KB checked in by piontek, 13 years ago (diff)
  • Property svn:mime-type set to text/plain
Line 
1package simulator.stats.implementation;
2
3import gridsim.gssim.GssimConstants;
4import gridsim.gssim.ResourceHistoryItem;
5import gssim.schedframe.scheduling.AbstractExecutable;
6import gssim.schedframe.scheduling.ExecTaskInterface;
7
8import java.awt.Color;
9import java.awt.Paint;
10import java.io.File;
11import java.io.FileOutputStream;
12import java.io.IOException;
13import java.io.PrintStream;
14import java.text.NumberFormat;
15import java.util.ArrayList;
16import java.util.Calendar;
17import java.util.Collections;
18import java.util.Comparator;
19import java.util.Date;
20import java.util.HashMap;
21import java.util.List;
22import java.util.Map;
23import java.util.SortedMap;
24import java.util.TreeMap;
25
26import org.apache.commons.logging.Log;
27import org.apache.commons.logging.LogFactory;
28import org.jfree.chart.ChartFactory;
29import org.jfree.chart.ChartRenderingInfo;
30import org.jfree.chart.ChartUtilities;
31import org.jfree.chart.JFreeChart;
32import org.jfree.chart.axis.AxisLocation;
33import org.jfree.chart.axis.DateAxis;
34import org.jfree.chart.axis.NumberAxis;
35import org.jfree.chart.encoders.ImageFormat;
36import org.jfree.chart.labels.CategoryItemLabelGenerator;
37import org.jfree.chart.labels.ItemLabelAnchor;
38import org.jfree.chart.labels.ItemLabelPosition;
39import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
40import org.jfree.chart.plot.CategoryPlot;
41import org.jfree.chart.plot.CombinedDomainXYPlot;
42import org.jfree.chart.plot.PlotOrientation;
43import org.jfree.chart.plot.XYPlot;
44import org.jfree.chart.renderer.category.CategoryItemRenderer;
45import org.jfree.chart.renderer.category.GanttRenderer;
46import org.jfree.chart.renderer.xy.XYStepAreaRenderer;
47import org.jfree.chart.title.TextTitle;
48import org.jfree.chart.title.Title;
49import org.jfree.data.gantt.TaskSeries;
50import org.jfree.data.gantt.TaskSeriesCollection;
51import org.jfree.data.time.FixedMillisecond;
52import org.jfree.data.xy.XYDataset;
53import org.jfree.data.xy.XYSeries;
54import org.jfree.data.xy.XYSeriesCollection;
55import org.jfree.ui.TextAnchor;
56import org.joda.time.DateTime;
57import org.joda.time.DateTimeUtilsExt;
58
59import schedframe.resources.profile.PowerUsage;
60import schedframe.resources.units.ResourceUnit;
61import schedframe.scheduling.Job;
62import schedframe.scheduling.JobInterface;
63import schedframe.scheduling.utils.ResourceParameterName;
64import simulator.ConfigurationOptions;
65import simulator.GenericUser;
66import simulator.GridSchedulingSimulator;
67import simulator.stats.GSSAccumulator;
68import simulator.stats.SimulationStatistics;
69import simulator.stats.implementation.out.AbstractStringSerializer;
70import simulator.stats.implementation.out.FormatedStringSerializer;
71import simulator.stats.implementation.out.StringSerializer;
72import test.rewolucja.energy.extension.EnergyExtension;
73import test.rewolucja.extensions.Extension;
74import test.rewolucja.extensions.ExtensionList;
75import test.rewolucja.extensions.ExtensionType;
76import test.rewolucja.resources.ProcessingElements;
77import test.rewolucja.resources.ResourceType;
78import test.rewolucja.resources.exception.ResourceException;
79import test.rewolucja.resources.physical.base.ComputingResource;
80import test.rewolucja.resources.physical.implementation.ComputingNode;
81import test.rewolucja.resources.physical.implementation.Processor;
82import test.rewolucja.resources.utils.ResourceController;
83import test.rewolucja.scheduling.JobRegistry;
84import csiro.mit.utils.jfreechart.timetablechart.TimetableChartFactory;
85import csiro.mit.utils.jfreechart.timetablechart.data.Timetable;
86import csiro.mit.utils.jfreechart.timetablechart.data.TimetableEventGroup;
87import csiro.mit.utils.jfreechart.timetablechart.data.TimetableEventSource;
88import csiro.mit.utils.jfreechart.timetablechart.renderer.TimetableRenderer;
89
90public class GSSimStatistics implements SimulationStatistics {
91
92        private Log log = LogFactory.getLog(GSSimStatistics.class);
93
94        protected static float ALPHA = 0.5f;
95        protected static int GANTT_WIDTH = 1200;
96
97        //protected static final int BITS = 8;
98        //protected static final int MILLI_SEC = 1000;
99
100        protected static final String RAW_TASKS_STATISTICS_OUTPUT_FILE_NAME = "Tasks.txt";
101        protected static final String JOBS_STATISTICS_OUTPUT_FILE_NAME = "Jobs.txt";
102
103        protected static final String SIMULATION_STATISTICS_OUTPUT_FILE_NAME = "Simulation.txt";
104        protected static final String ENERGYUSAGE_STATISTICS_OUTPUT_FILE_NAME = "Energy.txt";
105        protected static final String RESOURCEUSAGE_STATISTICS_OUTPUT_FILE_NAME = "ResourceUtilization.txt";
106
107        protected static final String DIAGRAMS_FILE_NAME_PREFIX = "Chart_";
108        protected static final String STATS_FILE_NAME_PREFIX = "Stats_";
109
110        protected static final String TASK_SEPARATOR = ";";
111        protected static final String JOB_SEPARATOR = ";";
112
113        protected String outputFolderName;
114
115        protected String simulationIdentifier;
116        protected ConfigurationOptions configuration;
117
118
119
120
121        protected GSSAccumulatorsStats accStats;
122       
123        private GenericUser users;
124        protected ResourceController resourceController;
125        protected boolean generateDiagrams = true;
126        protected AbstractStringSerializer serializer;
127        protected long startSimulationTime;
128        protected long endSimulationTime;
129       
130       
131        //RESOURCES
132        protected Timetable ganttDiagramPeTimetable;
133        protected Map<ResourceType, List<XYDataset>> resourceEnergyDiagrams;
134        protected Map<ResourceType, List<XYDataset>> resourceLoadDiagrams;
135        protected Map<String,List<ResStat>> basicResStats;
136        protected HashMap<String, Double> basicResLoad;
137       
138        protected Map<String, TimetableEventSource> peGanttMap;
139        protected Map<String, TimetableEventGroup> taskGanttMap;
140       
141       
142        //TASKS
143        protected int numOfdelayedTasks = 0;
144        protected int numOfNotExecutedTasks = 0;
145        protected double maxCj = 0;
146
147        protected boolean allTasksFinished;
148        protected TaskSeriesCollection ganttDiagramTaskSeriesCollection;
149        protected TaskSeriesCollection ganttDiagramWaitingTimeSeriesCollection;
150        protected HashMap<String, List<String>> task_processorsMap;
151
152       
153
154
155        JobRegistry jr;
156
157       
158        public GSSimStatistics(String simulationIdentifier, ConfigurationOptions co, GenericUser users,
159                        String outputFolderName, ResourceController resourceController) {
160                this.simulationIdentifier = simulationIdentifier;
161                this.configuration = co;
162                this.users = users;
163
164                this.outputFolderName = outputFolderName;
165
166                if (this.configuration.formatstatisticsoutput)
167                        this.serializer = new FormatedStringSerializer();
168                else
169                        this.serializer = new StringSerializer();
170
171                this.serializer.setDefaultNumberFormat(GridSchedulingSimulator.DFAULT_NUMBER_FORMAT);
172
173                this.resourceController = resourceController;
174                 jr = new JobRegistry("COMPUTING_GRID_0#BROKER");
175                init();
176        }
177
178        public void generateStatistics() {
179
180                this.startSimulationTime = DateTimeUtilsExt.getOffsetTime().getTimeInMillis();
181
182                this.endSimulationTime = DateTimeUtilsExt.currentTimeMillis();
183
184                long s = 0;
185                long e = 0;
186
187                log.info("gatherResourceStatistics");
188                s = System.currentTimeMillis();
189                gatherResourceStatistics();
190                e = System.currentTimeMillis();
191                log.info("time in sec: " + ((e - s) / 1000));
192               
193                log.info("gatherTaskStatistics");
194                s = System.currentTimeMillis();
195                gatherTaskStatistics();
196                e = System.currentTimeMillis();
197                log.info("time in sec: " + ((e - s) / 1000));
198
199                log.info("saveSimulationStatistics");
200                s = System.currentTimeMillis();
201                saveSimulationStatistics();
202                e = System.currentTimeMillis();
203                log.info("time in sec: " + ((e - s) / 1000));
204        }
205
206
207        public String getOutputFolderName() {
208                return outputFolderName;
209        }
210
211        private void init() {
212
213                task_processorsMap = new HashMap<String, List<String>>();
214                accStats = new GSSAccumulatorsStats();
215        }
216
217        public void saveSimulationStatistics() {
218                PrintStream simulationStatsFile = null;
219                if (configuration.createsimulationstatistics) {
220                        try {
221                                File file = new File(outputFolderName + STATS_FILE_NAME_PREFIX + simulationIdentifier + "_"
222                                                + SIMULATION_STATISTICS_OUTPUT_FILE_NAME);
223                                simulationStatsFile = new PrintStream(new FileOutputStream(file));
224                        } catch (IOException e) {
225                                e.printStackTrace();
226                        }
227                }
228                if (simulationStatsFile != null) {
229                        Object txt = accStats.serialize(this.serializer);
230                        simulationStatsFile.println(txt);
231                }
232
233                if (simulationStatsFile != null) {
234                        simulationStatsFile.close();
235                }
236
237        }
238
239
240
241        /************* RESOURCE STATISTICS SECTION **************/
242        private void gatherResourceStatistics() {
243               
244               
245                //TEMPORARY CONFIGURATION SECTION
246                ResourceType [] resForAnalyze = {ResourceType.DATA_CENTER, ResourceType.COMPUTING_NODE, ResourceType.CPU};
247                HashMap<ResourceType, List<Stats>> type_stats = new HashMap<ResourceType, List<Stats>>();
248               
249                List<Stats> crStats = new ArrayList<Stats>();
250                crStats.add(Stats.textLoad);
251                crStats.add(Stats.chartLoad);
252                crStats.add(Stats.textEnergy);
253                crStats.add(Stats.chartEnergy);
254                type_stats.put(ResourceType.DATA_CENTER, crStats);
255               
256                List<Stats> cnStats = new ArrayList<Stats>();
257                cnStats.add(Stats.textLoad);
258                //cnStats.add(Stats.chartLoad);
259                cnStats.add(Stats.textEnergy);
260                //cnStats.add(Stats.chartEnergy);
261                type_stats.put(ResourceType.COMPUTING_NODE, cnStats);
262               
263                List<Stats> cpuStats = new ArrayList<Stats>();
264                cpuStats.add(Stats.textLoad);
265                //cpuStats.add(Stats.chartLoad);
266                cpuStats.add(Stats.textEnergy);
267                //cpuStats.add(Stats.chartEnergy);
268                type_stats.put(ResourceType.CPU, cpuStats);
269               
270               
271               
272                peGanttMap = new HashMap<String, TimetableEventSource>();
273                taskGanttMap = new HashMap<String, TimetableEventGroup>();
274               
275               
276                resourceLoadDiagrams = new HashMap<ResourceType, List<XYDataset>>();
277                resourceEnergyDiagrams = new HashMap<ResourceType, List<XYDataset>>();
278               
279                ganttDiagramPeTimetable = new Timetable(new FixedMillisecond(
280                                startSimulationTime), new FixedMillisecond(endSimulationTime));
281               
282                PrintStream resourceLoadStatsFile = null;
283                try {
284                        File file = new File(outputFolderName + STATS_FILE_NAME_PREFIX
285                                        + simulationIdentifier + "_"
286                                        + RESOURCEUSAGE_STATISTICS_OUTPUT_FILE_NAME);
287                        resourceLoadStatsFile = new PrintStream(new FileOutputStream(file));
288                } catch (IOException e) {
289                        resourceLoadStatsFile = null;
290                }
291               
292                PrintStream energyStatsFile = null;
293                try {
294                        File file = new File(outputFolderName + STATS_FILE_NAME_PREFIX
295                                        + simulationIdentifier + "_"
296                                        + ENERGYUSAGE_STATISTICS_OUTPUT_FILE_NAME);
297                        energyStatsFile = new PrintStream(new FileOutputStream(file));
298                } catch (IOException e) {
299                        energyStatsFile = null;
300                }
301               
302                basicResStats = gatherPEStats(JobRegistry.getAllocationHistory());
303                peStatsPostProcessing(basicResStats);
304                basicResLoad = calculatePELoad( basicResStats);
305
306                if (configuration.creatediagrams_processors) {
307                        createPEGanttDiagram(basicResStats);
308                }
309               
310                for(ResourceType resType: resForAnalyze){
311                        List<ComputingResource> resources = null;
312                        try {
313                                resources = (List<ComputingResource>) resourceController.getResources().getDescendantsByType(resType);
314                        } catch (Exception e) {
315                                continue;
316                        }
317                        if(type_stats.containsKey(resType)){
318                                Map<String, GSSAccumulator> energyCategoryStats = new TreeMap<String, GSSAccumulator>();
319                                Map<String, GSSAccumulator> loadCategoryStats = new TreeMap<String, GSSAccumulator>();
320                                for(ComputingResource resource: resources){
321                                        ResourceUsageStats resourceUsage = null;
322                                        ResourceEnergyStats energyUsage = null;
323                                        if(type_stats.get(resType).contains(Stats.textLoad)){
324                                                resourceUsage = gatherResourceLoadStats(resource, basicResStats);
325                                                resourceUsage.setMeanUsage(calculateResourceLoad(resource, basicResLoad));
326                                                if (resourceLoadStatsFile != null) {
327                                                        Object txt = resourceUsage.serialize(serializer);
328                                                        if( resType == ResourceType.DATA_CENTER)
329                                                                resourceLoadStatsFile.println(txt);
330                                                }
331                                        }
332                                        if(type_stats.get(resType).contains(Stats.chartLoad)){
333                                                if (configuration.creatediagrams_resources) {
334                                                        createResourceLoadDiagram(resourceUsage);
335                                                }
336                                        }
337                                        if(type_stats.get(resType).contains(Stats.textEnergy)){
338                                                energyUsage = gatherResourceEnergyStats(resource);
339                                                energyUsage.setMeanUsage(calculateEnergyLoad(energyUsage));
340                                                energyUsage.setSumUsage(energyUsage.getMeanUsage() * (endSimulationTime-startSimulationTime)/(3600*1000));
341                                                if (energyStatsFile != null) {
342                                                        Object txt = energyUsage.serialize(serializer);
343                                                        if( resType == ResourceType.DATA_CENTER)
344                                                                energyStatsFile.println(txt);
345                                                }
346                                        }
347                                        if(type_stats.get(resType).contains(Stats.chartEnergy)){
348
349                                                if (configuration.creatediagrams_energyusage) {
350                                                        createResourceEnergyGanttDiagram(energyUsage);
351                                                }
352                                        }
353                                       
354                                       
355                                        if(resType == ResourceType.COMPUTING_NODE){
356                                                ComputingNode compNode = (ComputingNode) resource;
357                                                if(energyCategoryStats.containsKey(resType+"#"+compNode.getCategory().getName())){
358                                                        GSSAccumulator acc = energyCategoryStats.get(resType+"#"+compNode.getCategory().getName());
359                                                        acc.add(energyUsage.meanUsage);
360                                                        energyCategoryStats.put(resType+"#"+compNode.getCategory().getName(), acc);
361                                                } else{
362                                                        GSSAccumulator acc = new GSSAccumulator();
363                                                        acc.add(energyUsage.meanUsage);
364                                                        energyCategoryStats.put(resType+"#"+compNode.getCategory().getName(), acc);
365                                                }
366                                               
367                                                if(loadCategoryStats.containsKey(resType+"#"+compNode.getCategory().getName())){
368                                                        GSSAccumulator acc = loadCategoryStats.get(resType+"#"+compNode.getCategory().getName());
369                                                        acc.add(resourceUsage.meanUsage);
370                                                        loadCategoryStats.put(resType+"#"+compNode.getCategory().getName(), acc);
371                                                } else{
372                                                        GSSAccumulator acc = new GSSAccumulator();
373                                                        acc.add(resourceUsage.meanUsage);
374                                                        loadCategoryStats.put(resType+"#"+compNode.getCategory().getName(), acc);
375                                                }
376                                        } else if(resType == ResourceType.CPU){
377                                                Processor proc = (Processor)resource;
378                                                if(energyCategoryStats.containsKey(resType+"#"+proc.getComputingNode().getCategory().getName())){
379                                                        GSSAccumulator acc = energyCategoryStats.get(resType+"#"+proc.getComputingNode().getCategory().getName());
380                                                        acc.add(energyUsage.meanUsage);
381                                                        energyCategoryStats.put(resType+"#"+proc.getComputingNode().getCategory().getName(), acc);
382                                                } else{
383                                                        GSSAccumulator acc = new GSSAccumulator();
384                                                        acc.add(energyUsage.meanUsage);
385                                                        energyCategoryStats.put(resType+"#"+proc.getComputingNode().getCategory().getName(), acc);
386                                                }
387                                               
388                                                if(loadCategoryStats.containsKey(resType+"#"+proc.getComputingNode().getCategory().getName())){
389                                                        GSSAccumulator acc = loadCategoryStats.get(resType+"#"+proc.getComputingNode().getCategory().getName());
390                                                        acc.add(resourceUsage.meanUsage);
391                                                        loadCategoryStats.put(resType+"#"+proc.getComputingNode().getCategory().getName(), acc);
392                                                } else{
393                                                        GSSAccumulator acc = new GSSAccumulator();
394                                                        acc.add(resourceUsage.meanUsage);
395                                                        loadCategoryStats.put(resType+"#"+proc.getComputingNode().getCategory().getName(), acc);
396                                                }
397                                        }
398                                }
399                               
400                                if(energyCategoryStats.size()>0)
401                                {
402                                        energyStatsFile.println("\n=========BY CATEGORY===========");
403                                        for(String key: energyCategoryStats.keySet()){
404                                                GSSAccumulator acc = energyCategoryStats.get(key);
405                                                energyStatsFile.println(key + "- mean: "  +acc.getMean()+ " sum: " +acc.getMean()*(endSimulationTime-startSimulationTime)/(3600*1000)*acc.getCount());
406                                        }
407                                        energyStatsFile.println("\n\n");
408                                }
409                               
410                                if(loadCategoryStats.size()>0)
411                                {
412                                        resourceLoadStatsFile.println("\n=========BY CATEGORY===========");
413                                        for(String key: loadCategoryStats.keySet()){
414                                                GSSAccumulator acc = loadCategoryStats.get(key);
415                                                resourceLoadStatsFile.println(key + "- mean: "  +acc.getMean());
416                                        }
417                                        resourceLoadStatsFile.println("\n\n");
418                                }
419
420                        }
421                }
422               
423                saveResourceGanttDiagrams();
424                createAccumulatedResourceSimulationStatistic();
425                if (energyStatsFile != null) {
426                        energyStatsFile.close();
427                }
428                if (resourceLoadStatsFile != null) {
429                        resourceLoadStatsFile.close();
430                }
431       
432        }
433       
434        private void peStatsPostProcessing(Map<String, List<ResStat>> basicResStats){
435                ResourceType resType = null;
436
437                for(String key: basicResStats.keySet()){
438                        List<ResStat> resStats = basicResStats.get(key);
439                        resType = resStats.get(0).getResType();
440                        break;
441                }
442                List<ComputingResource> resources = null;
443                try {
444                        resources = (List<ComputingResource>) resourceController.getResources().getDescendantsByType(resType);
445                } catch (Exception e) {
446                        return;
447                }
448                for(ComputingResource resource: resources){
449                        if(!basicResStats.containsKey(resource.getName())){
450                                basicResStats.put(resource.getName(), new ArrayList<ResStat>());
451                        }
452                }
453        }
454        private Map<String, List<ResStat>> gatherPEStats(Map<Integer, Map<String, Object>> history) {
455
456                Map<String, List<ResStat>> basicResStats = new TreeMap<String, List<ResStat>>(new MapPEIdComparator());
457               
458                for (Integer executableID : history.keySet()) {
459
460                        Map<String, Object> historyItem = (Map<String, Object>) history.get(executableID);
461                        List<ResourceHistoryItem> resHistItemList = (List<ResourceHistoryItem>) historyItem.get(GssimConstants.RESOURCES);
462                        Map<ResourceParameterName, ResourceUnit> res = resHistItemList.get(resHistItemList.size() - 1).getResourceUnits();
463                        ResourceUnit resUnit = res.get(ResourceParameterName.PROCESSINGELEMENTS);
464                        ProcessingElements pes = (ProcessingElements) resUnit ;
465                       
466                        for(ComputingResource pe: pes){
467                                String peName = pe.getName();
468                                long startDate = ((DateTime) historyItem.get(GssimConstants.START_TIME)).getMillis();
469                                long endDate = ((DateTime) historyItem.get(GssimConstants.END_TIME)).getMillis();
470                                JobRegistry jr = new JobRegistry("stats");
471                                ExecTaskInterface execTask = jr.getTaskExecutable(executableID);
472                                String uniqueTaskID = execTask.getJobId() + "_" + execTask.getId();
473                               
474                                ResStat resStat = new ResStat(peName, pe.getType(), startDate, endDate, uniqueTaskID);
475                               
476                                List<ResStat> resStats = basicResStats.get(peName);
477                                if (resStats == null) {
478                                        resStats = new ArrayList<ResStat>();
479                                        resStats.add(resStat);
480                                        basicResStats.put(peName, resStats);
481                                } else {
482                                        resStats.add(resStat);
483                                }
484
485                                List<String> peNames = task_processorsMap.get(uniqueTaskID);
486                                if (peNames == null) {
487                                        peNames = new ArrayList<String>();
488                                        peNames.add(peName);
489                                        task_processorsMap.put(uniqueTaskID, peNames);
490                                } else {
491                                        peNames.add(peName);
492                                }
493                        }
494                }
495                return basicResStats;
496        }
497       
498        private ResourceUsageStats gatherResourceLoadStats(ComputingResource resource, Map<String,List<ResStat>> basicStats) {
499                ResourceUsageStats usageStats = new ResourceUsageStats(resource.getName(), resource.getType(), "resourceLoadStats");
500                for(String resName: basicStats.keySet()){
501                        try {
502                                if(resource.getDescendantsByName(resName) != null || resource.getName().compareTo(resName) == 0){
503                                        createResourceLoadData(usageStats, basicStats.get(resName));
504                                }
505                        } catch (ResourceException e) {
506                                // TODO Auto-generated catch block
507                                e.printStackTrace();
508                        }
509                }
510                return usageStats;
511        }
512       
513        private TreeMap<Long, Integer> createResourceLoadData(ResourceUsageStats usageStats, List<ResStat> resStats) {
514
515                TreeMap<Long, Integer> ganttData = (TreeMap)usageStats.getUsage();
516                for (ResStat resStat : resStats) {
517                       
518                        long start_time = resStat.getStartDate();
519                        long end_time = resStat.getEndDate();
520                        if (end_time > start_time) {
521                                Integer end = ganttData.get(end_time);
522                                if (end == null) {
523                                        ganttData.put(end_time, 0);
524                                        Long left = getLeftKey(ganttData, end_time);
525                                        if (left != null) {
526                                                Integer leftValue = ganttData.get(left);
527                                                ganttData.put(end_time, leftValue);
528                                        }
529                                }
530
531                                Integer start = ganttData.get(start_time);
532                                if (start == null) {
533                                        ganttData.put(start_time, 0);
534                                        Long left = getLeftKey(ganttData, start_time);
535                                        if (left != null) {
536                                                Integer leftValue = ganttData.get(left);
537                                                ganttData.put(start_time, leftValue);
538                                        }
539                                }
540
541                                SortedMap<Long, Integer> sm = ganttData.subMap(start_time,
542                                                end_time);
543                                for (Long key : sm.keySet()) {
544                                        Integer keyVal = ganttData.get(key);
545                                        ganttData.put(key, keyVal + 1);
546                                }
547                        }
548                }
549                return ganttData;
550        }
551
552        private Long getLeftKey(TreeMap<Long, Integer> ganttData, Long toKey) {
553
554                SortedMap<Long, Integer> sm = ganttData.headMap(toKey);
555                if (sm.isEmpty()) {
556                        return null;
557                }
558                return sm.lastKey();
559        }
560       
561       
562        private ResourceEnergyStats gatherResourceEnergyStats(ComputingResource resource) {
563                double power = 0;
564                ResourceEnergyStats resEnergyUsage = new ResourceEnergyStats(resource.getName(), resource.getType(), "resourceEnergyStats");
565                Map<Long, Double> usage = resEnergyUsage.getEnergy();
566               
567                ExtensionList extensionList = resource.getExtensionList();
568                if(extensionList != null){
569                        for (Extension extension : extensionList) {
570                                if (extension.getType() == ExtensionType.ENERGY_EXTENSION) {
571                                        EnergyExtension ee = (EnergyExtension)extension;
572                                        List<PowerUsage> powerUsage = ee.getPowerUsageHistory();
573                                        if(powerUsage.size()==0)
574                                                break;
575                                        long lastTime = DateTimeUtilsExt.getOffsetTime().getTimeInMillis();
576                                        long endSimulationTime = DateTimeUtilsExt.currentTimeMillis();
577                                        double lastPower = 0;
578                                        powerUsage.add(new PowerUsage(endSimulationTime, ee.getPowerUsageHistory().get(ee.getPowerUsageHistory().size()-1).getValue()));
579                                        for(PowerUsage pu:powerUsage){
580                                                usage.put(pu.getTimestamp(), pu.getValue());
581                                               
582                                        ///     System.out.println(resource.getName() + ":"+new DateTime(pu.getTimestamp())+";"+pu.getValue());
583                                                power = power + (pu.getTimestamp() - lastTime) * lastPower/ (3600 * 1000);
584                                                lastPower = pu.getValue();
585                                                lastTime = pu.getTimestamp();
586                                        }
587                                }
588                        }
589                }
590                //System.out.println(power);
591                return resEnergyUsage;
592        }
593       
594        private void createResourceEnergyGanttDiagram(ResourceEnergyStats energyUsage) {
595
596                XYDataset dataset = createResourceEnergyGanttDataSet(energyUsage,
597                                startSimulationTime, endSimulationTime);
598               
599                List<XYDataset> energyDiagram = resourceEnergyDiagrams.get(energyUsage.getResourceType());
600                if(energyDiagram == null){
601                        energyDiagram = new ArrayList<XYDataset>();
602                        energyDiagram.add(dataset);
603                        resourceEnergyDiagrams.put(energyUsage.getResourceType(), energyDiagram);
604                } else {
605                        energyDiagram.add(dataset);
606                }
607
608        }
609
610        private XYDataset createResourceEnergyGanttDataSet(
611                        ResourceEnergyStats energyUsage, long start, long end) {
612
613                TreeMap<Long, Double> ganttdata = createResourceEnergyGanttData(energyUsage);
614                XYSeriesCollection dataset = new XYSeriesCollection();
615                XYSeries data = new XYSeries(energyUsage.getResourceName(), false, true);
616                //data.add(start, 0);
617                for (Long key : ganttdata.keySet()) {
618                        Double val = ganttdata.get(key);
619                        data.add(key, val);
620                }
621                data.add(end, 0);
622                dataset.addSeries(data);
623                return dataset;
624        }
625
626        private TreeMap<Long, Double> createResourceEnergyGanttData(
627                        ResourceEnergyStats energyUsage) {
628
629                Map<Long, Double> energy = energyUsage.getEnergy();
630                TreeMap<Long, Double> ganttData = new TreeMap<Long, Double>();
631                for (Long euKey : energy.keySet()) {
632
633                        ganttData.put(euKey, energy.get(euKey));
634                }
635                return ganttData;
636        }
637
638
639        private boolean saveResourceGanttDiagrams() {
640                JFreeChart resourceDiagram = null;
641                JFreeChart peDiagram = null;
642                JFreeChart resourceEnergyDiagram = null;
643                if (!generateDiagrams)
644                        return false;
645
646                String fileName = new File(outputFolderName, DIAGRAMS_FILE_NAME_PREFIX
647                                + simulationIdentifier + "_").getAbsolutePath();
648
649                String chartName = "Gantt diagram for "
650                                + GridSchedulingSimulator.SIMULATOR_NAME;
651                String simulationTime = "Simulation time";
652                Title subtitle = new TextTitle("created for \"" + simulationIdentifier
653                                + "\" at " + Calendar.getInstance().getTime().toString());
654
655               
656                if (configuration.creatediagrams_processors) {
657                        peDiagram = getPeGanttDiagram(chartName, subtitle,
658                                        simulationTime);
659                        if (!saveCategoryChart(peDiagram, fileName + "Processing_Elements",
660                                        "{0}"))
661                                return false;
662                }
663
664                if (configuration.creatediagrams_resources) {
665                        for(ResourceType resType: resourceLoadDiagrams.keySet()){
666                                resourceDiagram = getResourcesLoadDiagram(resType, chartName, subtitle,
667                                                simulationTime);
668                                if (!saveXYPlotChart(resourceDiagram, fileName + "Resources Load - "+resType))
669                                        return false;
670                        }
671
672                }
673                if (configuration.creatediagrams_energyusage) {
674                        for(ResourceType resType: resourceEnergyDiagrams.keySet()){
675                                resourceEnergyDiagram = getResourcesEnergyDiagram(resType, chartName,
676                                                subtitle, simulationTime);
677                                if (!saveXYPlotChart(resourceEnergyDiagram, fileName + "Energy - "+resType))
678                                        return false;
679                        }
680                }
681                return true;
682        }
683       
684        private JFreeChart getResourcesLoadDiagram(ResourceType resType, String chartName, Title subtitle,
685                        String simulationTime) {
686                String cpu = "CPU";
687                boolean urls = false;
688                boolean tooltip = true;
689                boolean legend = true;
690                CombinedDomainXYPlot cPlot = new CombinedDomainXYPlot();
691                DateAxis xAxis = new DateAxis(simulationTime);
692                JFreeChart chart = null;
693
694                List<XYDataset> loadDiagram = resourceLoadDiagrams.get(resType);
695                for (XYDataset dataset : loadDiagram) {
696                        JFreeChart tChart = ChartFactory.createXYStepAreaChart("", "",
697                                null, dataset, PlotOrientation.VERTICAL, legend, tooltip,
698                                urls);
699                        XYPlot tPlot = tChart.getXYPlot();
700                        NumberAxis yAxis = new NumberAxis(cpu);
701                        yAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
702                        tPlot.setRangeAxis(yAxis);
703                        XYStepAreaRenderer rend = (XYStepAreaRenderer) tPlot.getRenderer();
704                        rend.setShapesVisible(false);
705                        cPlot.add(tPlot);
706                }
707                cPlot.setDomainAxis(xAxis);
708                cPlot.setDomainAxisLocation(AxisLocation.TOP_OR_LEFT);
709                chart = new JFreeChart(chartName, cPlot);
710                chart.addSubtitle(subtitle);
711                return chart;
712        }
713
714        private JFreeChart getResourcesEnergyDiagram(ResourceType resType, String chartName,
715                        Title subtitle, String simulationTime) {
716                String energy = "ENERGY [W]";
717                boolean urls = false;
718                boolean tooltip = true;
719                boolean legend = true;
720                CombinedDomainXYPlot cPlot = new CombinedDomainXYPlot();
721                DateAxis xAxis = new DateAxis(simulationTime);
722
723                List<XYDataset> energyDiagram = resourceEnergyDiagrams.get(resType);
724                for (XYDataset dataset : energyDiagram) {
725
726                        JFreeChart tChart = ChartFactory.createXYStepAreaChart("", "",
727                                        null, dataset, PlotOrientation.VERTICAL, legend, tooltip,
728                                        urls);
729
730                        XYPlot tPlot = tChart.getXYPlot();
731                        NumberAxis yAxis = new NumberAxis(energy);
732                        yAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
733                        tPlot.setRangeAxis(yAxis);
734                        XYStepAreaRenderer rend = (XYStepAreaRenderer) tPlot.getRenderer();
735                        rend.setShapesVisible(false);
736                        cPlot.add(tPlot);
737                }
738                cPlot.setDomainAxis(xAxis);
739                cPlot.setDomainAxisLocation(AxisLocation.TOP_OR_LEFT);
740                JFreeChart chart = new JFreeChart(chartName, cPlot);
741                chart.addSubtitle(subtitle);
742                return chart;
743        }
744       
745       
746        private JFreeChart getPeGanttDiagram(String chartName, Title subtitle,
747                        String simulationTime) {
748                String processors = "Processing Elements";
749                boolean tooltip = true;
750                boolean legend = true;
751                JFreeChart chart = TimetableChartFactory.createTimetableChart(
752                                chartName, processors, simulationTime,
753                                ganttDiagramPeTimetable, legend, tooltip);
754                chart.addSubtitle(subtitle);
755                TimetableRenderer rend = (TimetableRenderer) chart.getCategoryPlot()
756                                .getRenderer();
757                rend.setBackgroundBarPaint(null);
758                return chart;
759        }
760       
761       
762        private boolean saveXYPlotChart(JFreeChart c, String fileName) {
763                c.setNotify(false);
764                c.setAntiAlias(true);
765                c.setTextAntiAlias(true);
766                c.setBorderVisible(false);
767
768                int height = 900;
769
770                CombinedDomainXYPlot cPlot = (CombinedDomainXYPlot) c.getPlot();
771                int nPlots = cPlot.getSubplots().size();
772
773                if (nPlots > 3) {
774                        height = nPlots * 300;
775                }
776                int width = GANTT_WIDTH;
777
778                if (configuration.creatediagrams_resources_scale != -1)
779                        width = (int) ((endSimulationTime - startSimulationTime) * configuration.creatediagrams_resources_scale);
780                ChartRenderingInfo info = new ChartRenderingInfo();
781                File f = new File(fileName + "." + ImageFormat.PNG);
782                final String gssimSubtitle = "Created by "
783                                + GridSchedulingSimulator.SIMULATOR_NAME
784                                + " http://www.gssim.org/";
785                c.addSubtitle(new TextTitle(gssimSubtitle));
786                boolean encodeAlpha = false;
787                int compression = 9;// values 0-9
788                try {
789                        ChartUtilities.saveChartAsPNG(f, c, width, height, info,
790                                        encodeAlpha, compression);
791                } catch (IOException e) {
792                        e.printStackTrace();
793                        return false;
794                }
795                return true;
796        }
797       
798        private void createPEGanttDiagram(Map<String,List<ResStat>> basicResStats) {
799                for(String peName: basicResStats.keySet()){
800                        TimetableEventSource pe = new TimetableEventSource(peName);
801                        ganttDiagramPeTimetable.addEventSource(pe);
802                        peGanttMap.put(peName, pe);
803                        for(ResStat resStat: basicResStats.get(peName)){
804
805                                pe = peGanttMap.get(resStat.getPeName());
806                                if(pe == null){
807                                        //pe = new TimetableEventSource(resStat.getPeName());
808                                //      ganttDiagramPeTimetable.addEventSource(pe);
809                                //      peGanttMap.put(resStat.getPeName(), pe);
810                                }
811                                TimetableEventGroup task = taskGanttMap.get(resStat.getTaskID());
812                                long startDate = resStat.getStartDate();
813                                long endDate = resStat.getEndDate();
814                                if (task == null) {
815                                        task = new TimetableEventGroup(resStat.getTaskID());
816                                        taskGanttMap.put(resStat.getTaskID(), task);
817                                        ganttDiagramPeTimetable.addEventGroup(task);
818                                }
819                                ganttDiagramPeTimetable.addEvent(pe, task,
820                                                new FixedMillisecond(startDate), new FixedMillisecond(endDate));
821                        }
822                }
823        }
824
825        private void createResourceLoadDiagram(ResourceUsageStats resStats) {
826
827                XYDataset dataset = createResourceLoadDataSet(resStats);
828
829                List<XYDataset> loadDiagram = resourceLoadDiagrams.get(resStats.getResourceType());
830                if(loadDiagram == null){
831                        loadDiagram = new ArrayList<XYDataset>();
832                        loadDiagram.add(dataset);
833                        resourceLoadDiagrams.put(resStats.getResourceType(), loadDiagram);
834                } else {
835                        loadDiagram.add(dataset);
836                }
837        }
838
839        private XYDataset createResourceLoadDataSet(ResourceUsageStats resStats) {
840
841                XYSeriesCollection dataset = new XYSeriesCollection();
842                XYSeries data = new XYSeries(resStats.resourceName, false, true);
843                Map<Long, Integer> usage = resStats.getUsage();
844               
845                for (Long key : usage.keySet()) {
846                        Integer val = usage.get(key);
847                        data.add(key, val);
848                }
849                dataset.addSeries(data);
850                return dataset;
851        }
852
853        private void createAccumulatedResourceSimulationStatistic() {
854
855                ComputingResource resource = resourceController.getResources();
856
857                for(ComputingResource child :resource.getChildren()){
858                        double load = calculateResourceLoad(child, basicResLoad);
859                        accStats.meanTotalLoad.add(load);
860                        //ResourceEnergyStats energyUsage = gatherResourceEnergyStats(child);
861                        //energyUsage.setMeanUsage(calculateEnergyLoad(energyUsage));
862                        //accStats.meanEnergyUsage.add(energyUsage.meanUsage);
863                }
864
865        }
866
867        private HashMap<String, Double> calculatePELoad(Map<String,List<ResStat>> basicResStats){
868                HashMap<String, Double> peLoad = new HashMap<String, Double>();
869                for(String resName: basicResStats.keySet()){
870                        List<ResStat> resStats = basicResStats.get(resName);
871                        double sum = 0;
872                        for(ResStat resStat:resStats){
873                                sum += (resStat.endDate-resStat.startDate);
874                        }
875                        double load = sum/(endSimulationTime-startSimulationTime);
876                        peLoad.put(resName, load);
877                }
878                return peLoad;
879        }
880       
881        private  Double calculateResourceLoad(ComputingResource resource, HashMap<String, Double> peLoad ){
882                int peCnt = 0;
883                double sum = 0;
884                for(String resName: peLoad.keySet()){
885
886                        try {
887                                if(resource.getDescendantsByName(resName)!= null || resource.getName().compareTo(resName)==0){
888                                        Double load = peLoad.get(resName);
889                                        sum += load;
890                                        peCnt++;
891                                }
892                        } catch (ResourceException e) {
893                                // TODO Auto-generated catch block
894                                e.printStackTrace();
895                        }
896                }
897               
898                return sum/peCnt;
899        }
900       
901        private double calculateEnergyLoad(ResourceEnergyStats resEnergyStats ){
902                double meanEnergyUsage = 0;
903                long time = 0;
904                double usage = 0;
905                Map<Long, Double> enUsage = resEnergyStats.getEnergy();
906                for (Long key : enUsage.keySet()) {
907                       
908                        if (time != 0) {
909                                meanEnergyUsage += (usage * (key - time))
910                                                / (endSimulationTime - startSimulationTime);
911
912                                time = key;
913                        } else {
914                                time = key;
915                        }
916                        usage = (double) enUsage.get(key);
917                }
918                return meanEnergyUsage;
919        }
920       
921        /*private void createPEGanttDiagram(String peName,
922                        String uniqueTaskID, Map<String, Object> historyItem) {
923                TimetableEventSource pe = peGanttMap.get(peName);
924                if(pe == null){
925                        pe = new TimetableEventSource(peName);
926                        ganttDiagramPETimetable.addEventSource(pe);
927                        peGanttMap.put(peName, pe);
928                }
929                TimetableEventGroup task = taskGanttMap.get(uniqueTaskID);
930                long startDate = ((DateTime) historyItem.get(GssimConstants.START_TIME))
931                                .getMillis();
932                long endDate = ((DateTime) historyItem.get(GssimConstants.END_TIME))
933                                .getMillis();
934                if (task == null) {
935                        task = new TimetableEventGroup(uniqueTaskID);
936                        taskGanttMap.put(uniqueTaskID, task);
937                        ganttDiagramPETimetable.addEventGroup(task);
938                }
939                ganttDiagramPETimetable.addEvent(pe, task,
940                                new FixedMillisecond(startDate), new FixedMillisecond(endDate));
941        }*/
942       
943
944
945        /************* TASK STATISTICS SECTION **************/
946        public void gatherTaskStatistics() {
947
948                List<JobInterface<?>> jobs = users.getAllReceivedJobs();
949                Collections.sort(jobs, new JobIdComparator());
950
951                ganttDiagramTaskSeriesCollection = new TaskSeriesCollection();
952                ganttDiagramWaitingTimeSeriesCollection = new TaskSeriesCollection();
953
954                PrintStream taskStatsFile = null;
955                try {
956                        File file = new File(outputFolderName + STATS_FILE_NAME_PREFIX + simulationIdentifier + "_"
957                                        + RAW_TASKS_STATISTICS_OUTPUT_FILE_NAME);
958                        taskStatsFile = new PrintStream(new FileOutputStream(file));
959                } catch (IOException e) {
960                        taskStatsFile = null;
961                }
962
963                PrintStream jobStatsFile = null;
964                if (configuration.createjobsstatistics) {
965                        try {
966                                File file = new File(outputFolderName + STATS_FILE_NAME_PREFIX + simulationIdentifier + "_"
967                                                + JOBS_STATISTICS_OUTPUT_FILE_NAME);
968                                jobStatsFile = new PrintStream(new FileOutputStream(file));
969                        } catch (IOException e) {
970                                jobStatsFile = null;
971                        }
972                }
973
974                for (int i = 0; i < jobs.size(); i++) {
975                        Job job = (Job) jobs.get(i);
976
977                        //List<TaskInterface> execList = JobRegistry.getInstance("COMPUTING_GRID_0#BROKER").getAllSubmittedTasks();
978                        List<AbstractExecutable> execList = jr.getJobExecutables(job.getId());
979                        List<TaskStats> taskStatsList = new ArrayList<TaskStats>();
980
981                        this.serializer.setFieldSeparator(TASK_SEPARATOR);
982
983                        for (int j = 0; j < execList.size(); j++) {
984
985                                AbstractExecutable task = (AbstractExecutable) execList.get(j);
986
987                                TaskStats taskStats = createTaskStats(task);
988                                if (taskStats != null && taskStatsFile != null) {
989                                        Object txt = taskStats.serialize(serializer);
990                                        taskStatsFile.println(txt);
991                                }
992                                if (taskStats != null && taskStats.getExecFinishDate() != -1) {
993                                        if (configuration.createsimulationstatistics) {
994                                                createAccumulatedTaskSimulationStatistic(taskStats);
995                                        }
996                                        allTasksFinished &= task.isFinished();
997                                        if (generateDiagrams) {
998                                                if (configuration.creatediagrams_tasks)
999                                                        createTaskDiagramData(task);
1000                                                if (configuration.creatediagrams_taskswaitingtime)
1001                                                        createTaskWaitingTimeDiagramData(task);
1002
1003                                        }
1004                                        taskStatsList.add(taskStats);
1005                                }
1006                        }
1007                        if (configuration.createjobsstatistics && taskStatsList.size() > 0) {
1008
1009                                this.serializer.setFieldSeparator(JOB_SEPARATOR);
1010
1011                                JobStats jobStats = createJobStats(taskStatsList);
1012                                if (jobStatsFile != null) {
1013                                        Object txt = jobStats.serialize(serializer);
1014                                        jobStatsFile.println(txt);
1015                                }
1016                        }
1017                }
1018
1019                if (configuration.createsimulationstatistics) {
1020                        accStats.makespan.add(maxCj);
1021                        accStats.delayedTasks.add(numOfdelayedTasks);
1022                        accStats.failedRequests.add(users.getAllSentTasks().size() - users.getFinishedTasksCount());
1023
1024                }
1025
1026                saveTaskGanttDiagrams();
1027
1028                if (taskStatsFile != null) {
1029                        taskStatsFile.close();
1030                }
1031                if (jobStatsFile != null) {
1032                        jobStatsFile.close();
1033                }
1034        }
1035
1036        private TaskStats createTaskStats(AbstractExecutable task) {
1037                TaskStats taskStats = new TaskStats(task, startSimulationTime);
1038
1039                String uniqueTaskID = taskStats.getJobID() + "_" + taskStats.getTaskID();
1040
1041                taskStats.setProcessorsName(task_processorsMap.get(uniqueTaskID));
1042
1043                return taskStats;
1044        }
1045
1046        private JobStats createJobStats(List<TaskStats> tasksStats) {
1047
1048                String jobID = ((TaskStats) tasksStats.get(0)).getJobID();
1049                JobStats jobStats = new JobStats(jobID);
1050                double maxCj = 0;
1051
1052                for (int i = 0; i < tasksStats.size(); i++) {
1053
1054                        TaskStats task = (TaskStats) tasksStats.get(i);
1055                        jobStats.meanTaskStartTime.add(task.getStartTime());
1056                        jobStats.meanTaskCompletionTime.add(task.getCompletionTime());
1057                        maxCj = Math.max(maxCj, task.getCompletionTime());
1058                        jobStats.meanTaskExecutionTime.add(task.getExecutionTime());
1059                        jobStats.meanTaskWaitingTime.add(task.getWaitingTime());
1060                        jobStats.meanTaskFlowTime.add(task.getFlowTime());
1061                        jobStats.meanTaskGQ_WaitingTime.add(task.getGQ_WaitingTime());
1062                        jobStats.lateness.add(task.getLateness());
1063                        jobStats.tardiness.add(task.getTardiness());
1064                }
1065                jobStats.makespan.add(maxCj);
1066
1067                return jobStats;
1068        }
1069
1070        private void createAccumulatedTaskSimulationStatistic(TaskStats taskStats) {
1071                accStats.meanTaskFlowTime.add(taskStats.getFlowTime());
1072                accStats.meanTaskExecutionTime.add(taskStats.getExecutionTime());
1073                accStats.meanTaskCompletionTime.add(taskStats.getCompletionTime());
1074                accStats.meanTaskWaitingTime.add(taskStats.getWaitingTime());
1075                accStats.meanTaskStartTime.add(taskStats.getStartTime());
1076
1077                accStats.lateness.add(taskStats.getLateness());
1078                accStats.tardiness.add(taskStats.getTardiness());
1079
1080                if (taskStats.getExecFinishDate() == -1) {
1081                        numOfNotExecutedTasks++;
1082                }
1083                if (taskStats.getTardiness() > 0.0) {
1084                        numOfdelayedTasks++;
1085                }
1086
1087                maxCj = Math.max(maxCj, taskStats.getCompletionTime());
1088        }
1089
1090        private void createTaskDiagramData(AbstractExecutable task) {
1091                String uniqueTaskID = task.getJobId() + "_" + task.getId();
1092
1093                String resIDlist[] = task.getAllResourceName();
1094                String resID = resIDlist[resIDlist.length - 1];
1095
1096                long execStartTime = Double.valueOf(task.getExecStartTime()).longValue() * 1000;
1097                long execEndTime = Double.valueOf(task.getFinishTime()).longValue() * 1000;
1098
1099                TaskSeries taskRes = ganttDiagramTaskSeriesCollection.getSeries(resID);
1100                if (taskRes == null) {
1101                        taskRes = new TaskSeries(resID);
1102                        ganttDiagramTaskSeriesCollection.add(taskRes);
1103                }
1104                org.jfree.data.gantt.Task ganttTask = new org.jfree.data.gantt.Task(uniqueTaskID, new Date(execStartTime),
1105                                new Date(execEndTime));
1106                if (!task.isFinished()) {
1107                        ganttTask.setPercentComplete(1.0);
1108                }
1109                taskRes.add(ganttTask);
1110        }
1111
1112        private void createTaskWaitingTimeDiagramData(AbstractExecutable task) {
1113                String uniqueTaskID = task.getJobId() + "_" + task.getId();
1114
1115                String resIDlist[] = task.getAllResourceName();
1116                String resID = resIDlist[resIDlist.length - 1];
1117
1118                long execStartTime = Double.valueOf(task.getExecStartTime()).longValue() * 1000;
1119                long execEndTime = Double.valueOf(task.getFinishTime()).longValue() * 1000;
1120
1121                TaskSeries waitRes = ganttDiagramWaitingTimeSeriesCollection.getSeries(resID);
1122                if (waitRes == null) {
1123                        waitRes = new TaskSeries(resID);
1124                        ganttDiagramWaitingTimeSeriesCollection.add(waitRes);
1125                }
1126
1127                long sub = Double.valueOf(task.getSubmissionTime()).longValue() * 1000;
1128                org.jfree.data.gantt.Task wait_exec = new org.jfree.data.gantt.Task(uniqueTaskID, new Date(sub), new Date(
1129                                execEndTime));
1130                org.jfree.data.gantt.Task exec = new org.jfree.data.gantt.Task(uniqueTaskID, new Date(execStartTime), new Date(
1131                                execEndTime));
1132                if (!task.isFinished()) {
1133                        exec.setPercentComplete(1.0);
1134                }
1135                wait_exec.addSubtask(wait_exec);
1136                wait_exec.addSubtask(exec);
1137                waitRes.add(wait_exec);
1138        }
1139
1140        private boolean saveTaskGanttDiagrams() {
1141
1142                JFreeChart taskDiagram = null;
1143                JFreeChart waitingTimeDiagram = null;
1144
1145                if (!generateDiagrams)
1146                        return false;
1147
1148                String fileName = new File(outputFolderName, DIAGRAMS_FILE_NAME_PREFIX + simulationIdentifier + "_")
1149                                .getAbsolutePath();
1150
1151                String chartName = "Gantt diagram for " + GridSchedulingSimulator.SIMULATOR_NAME;
1152                String simulationTime = "Simulation time";
1153                Title subtitle = new TextTitle("created for \"" + simulationIdentifier + "\" at "
1154                                + Calendar.getInstance().getTime().toString());
1155
1156                if (configuration.creatediagrams_tasks) {
1157                        taskDiagram = getTaskDiagram(chartName, subtitle, simulationTime);
1158                        if (!saveCategoryChart(taskDiagram, fileName + "Tasks", null /* "{0}" */))
1159                                return false;
1160                }
1161
1162                if (configuration.creatediagrams_taskswaitingtime) {
1163                        waitingTimeDiagram = getWaitingTimeDiagram(chartName, subtitle, simulationTime);
1164                        if (!saveCategoryChart(waitingTimeDiagram, fileName + "Waiting_Time", null /* "Task {1} at {0}" */))
1165                                return false;
1166                }
1167
1168                return true;
1169        }
1170
1171        private JFreeChart getTaskDiagram(String chartName, Title subtitle, String simulationTime) {
1172                String tasks = "Tasks";
1173                boolean urls = false;
1174                boolean tooltip = true;
1175                boolean legend = true;
1176                JFreeChart chart = ChartFactory.createGanttChart(chartName, tasks, simulationTime,
1177                                ganttDiagramTaskSeriesCollection, legend, tooltip, urls);
1178                chart.addSubtitle(subtitle);
1179                GanttRenderer re = (GanttRenderer) chart.getCategoryPlot().getRenderer();
1180                re.setCompletePaint(Color.black);
1181                return chart;
1182        }
1183
1184        private JFreeChart getWaitingTimeDiagram(String chartName, Title subtitle, String simulationTime) {
1185                String tasks = "Tasks";
1186                boolean urls = false;
1187                boolean tooltip = true;
1188                boolean legend = true;
1189                JFreeChart chart = ChartFactory.createGanttChart(chartName, tasks, simulationTime,
1190                                ganttDiagramWaitingTimeSeriesCollection, legend, tooltip, urls);
1191                chart.addSubtitle(subtitle);
1192                chart.getPlot().setForegroundAlpha(ALPHA);
1193                GanttRenderer re = (GanttRenderer) chart.getCategoryPlot().getRenderer();
1194                re.setCompletePaint(Color.black);
1195                return chart;
1196        }
1197
1198        private boolean saveCategoryChart(JFreeChart c, String fileName, String labelFormat) {
1199                c.setNotify(false);
1200                c.setAntiAlias(true);
1201                c.setTextAntiAlias(true);
1202                c.setBorderVisible(false);
1203
1204                CategoryPlot categoryplot = (CategoryPlot) c.getPlot();
1205                categoryplot.setDomainGridlinesVisible(true);
1206
1207                if (labelFormat != null) {
1208                        CategoryItemRenderer rend = categoryplot.getRenderer();
1209                        rend.setBaseItemLabelsVisible(true);
1210                        ItemLabelPosition position = new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER);
1211                        rend.setBasePositiveItemLabelPosition(position);
1212                        NumberFormat nf = NumberFormat.getInstance();
1213                        CategoryItemLabelGenerator gen = new StandardCategoryItemLabelGenerator(labelFormat, nf);
1214                        rend.setBaseItemLabelGenerator(gen);
1215                }
1216
1217                int rows = c.getCategoryPlot().getDataset().getColumnKeys().size();
1218
1219                int height = 900;
1220                if (rows > 45) {
1221                        height = rows * 20;
1222                }
1223                int width = calculateChartWidth(c);
1224                CategoryItemRenderer rend = c.getCategoryPlot().getRenderer();
1225
1226                for (int i = 0; i < c.getCategoryPlot().getDataset().getRowKeys().size(); i++) {
1227                        Paint collor = c.getCategoryPlot().getDrawingSupplier().getNextPaint();
1228                        rend.setSeriesOutlinePaint(i, collor);
1229                        rend.setSeriesPaint(i, collor);
1230                }
1231
1232                ChartRenderingInfo info = new ChartRenderingInfo();
1233                // info.setEntityCollection(null);
1234                File f = new File(fileName + "." + ImageFormat.PNG);
1235                final String gssimSubtitle = "Created by " + GridSchedulingSimulator.SIMULATOR_NAME + " http://www.gssim.org/";
1236                c.addSubtitle(new TextTitle(gssimSubtitle));
1237                boolean encodeAlpha = false;
1238                int compression = 9;
1239                try {
1240                        ChartUtilities.saveChartAsPNG(f, c, width, height, info, encodeAlpha, compression);
1241
1242                } catch (IOException e) {
1243                        e.printStackTrace();
1244                        return false;
1245                } catch (Exception e) {
1246                        if (log.isErrorEnabled())
1247                                log.error("The png file (" + fileName
1248                                                + ")\nwill not be generated (It can be too large data size problem)", e);
1249                } catch (Throwable t) {
1250                        log.error("The png file (" + fileName + ")\nwill not be generated (It can be too large data size problem)",
1251                                        t);
1252                }
1253
1254                return true;
1255        }
1256
1257        private int calculateChartWidth(JFreeChart c) {
1258
1259                int ganttWidth = GANTT_WIDTH;
1260                int rows = c.getCategoryPlot().getDataset().getColumnKeys().size();
1261
1262                if (rows > 45) {
1263                        int height = rows * 20;
1264                        ganttWidth = Math.max((int) (height * 1.5), GANTT_WIDTH);
1265                }
1266                return ganttWidth;
1267        }
1268
1269        private static class JobIdComparator implements Comparator<JobInterface<?>> {
1270
1271                public int compare(JobInterface<?> o1, JobInterface<?> o2) {
1272                        try {
1273                                Integer o1int;
1274                                Integer o2int;
1275                                try{
1276                                        o1int = Integer.parseInt(o1.getId());
1277                                        o2int = Integer.parseInt(o2.getId());
1278                                        return o1int.compareTo(o2int);
1279                                } catch(NumberFormatException e){
1280                                        return o1.getId().compareTo(o2.getId());
1281                                }
1282
1283                        } catch (NoSuchFieldException e) {
1284                                e.printStackTrace();
1285                        }
1286                        return -1;
1287                }
1288        }
1289       
1290        private static class MapPEIdComparator implements Comparator<String> {
1291
1292                public int compare(String o1, String o2)  {
1293                        Integer o1int;
1294                        Integer o2int;
1295
1296                        o1int = Integer.parseInt(o1.substring(o1.indexOf("_")+1));
1297                        o2int = Integer.parseInt(o2.substring(o2.indexOf("_")+1));
1298                        return o1int.compareTo(o2int);
1299                }
1300        }
1301
1302}
1303
1304class ResStat{
1305       
1306       
1307        public long getStartDate() {
1308                return startDate;
1309        }
1310        public void setStartDate(long startDate) {
1311                this.startDate = startDate;
1312        }
1313        public long getEndDate() {
1314                return endDate;
1315        }
1316        public void setEndDate(long endDate) {
1317                this.endDate = endDate;
1318        }
1319        public String getTaskID() {
1320                return taskID;
1321        }
1322        public void setTaskID(String taskID) {
1323                this.taskID = taskID;
1324        }
1325
1326        public ResStat( String peName, long startDate, long endDate, String taskID) {
1327                super();
1328                this.startDate = startDate;
1329                this.endDate = endDate;
1330                this.taskID = taskID;
1331                this.peName = peName;
1332        }
1333        public String getPeName() {
1334                return peName;
1335        }
1336        public void setPeName(String peName) {
1337                this.peName = peName;
1338        }
1339        public ResStat(String peName, ResourceType resType, long startDate, long endDate, String taskID) {
1340                super();
1341                this.peName = peName;
1342                this.resType = resType;
1343                this.startDate = startDate;
1344                this.endDate = endDate;
1345                this.taskID = taskID;
1346        }
1347        String peName;
1348        ResourceType resType;
1349        long startDate;
1350        long endDate;
1351        String taskID;
1352
1353        public ResourceType getResType() {
1354                return resType;
1355        }
1356        public void setResType(ResourceType resType) {
1357                this.resType = resType;
1358        }
1359}
1360
1361enum Stats{
1362        textLoad,
1363        chartLoad,
1364        textEnergy,
1365        chartEnergy;
1366}
Note: See TracBrowser for help on using the repository browser.