source: tmcsimulator/trunk/src/atmsdriver/model/Highways.java @ 287

Revision 287, 23.4 KB checked in by jdalbey, 7 years ago (diff)

Highways.java: fixed defect #95 by checking if result of highway lookup is null.

Line 
1package atmsdriver.model;
2
3import atmsdriver.trafficeventseditor.TrafficLaneEvent;
4import atmsdriver.model.LoopDetector.DOTCOLOR;
5import atmsdriver.model.Station.DIRECTION;
6import java.io.File;
7import java.io.FileInputStream;
8import java.io.FileNotFoundException;
9import java.io.IOException;
10import java.io.PrintWriter;
11import java.io.StringWriter;
12import java.io.Writer;
13import java.net.Socket;
14import java.util.ArrayList;
15import java.util.Collections;
16import java.util.HashMap;
17import java.util.List;
18import java.util.Map;
19import java.util.Scanner;
20import java.util.Set;
21import java.util.logging.Level;
22import java.util.logging.Logger;
23import javax.xml.parsers.DocumentBuilder;
24import javax.xml.parsers.DocumentBuilderFactory;
25import javax.xml.transform.OutputKeys;
26import javax.xml.transform.Transformer;
27import javax.xml.transform.TransformerFactory;
28import javax.xml.transform.dom.DOMSource;
29import javax.xml.transform.stream.StreamResult;
30import org.w3c.dom.Document;
31import org.w3c.dom.Element;
32import tmcsim.common.SimulationException;
33
34/**
35 * The Highways class aggregates all Highway instances within a geographic
36 * region, and all of the FEPLines within an electronic detector network, in the
37 * same geographic region. An instance of Highways.java comprises the underlying
38 * model for the ATMSDriver application.
39 *
40 * Highways uses method writeToFEP() to communicate with the FEP Simulator. It
41 * creates a socket client which sends the FEP Simulator a highways status
42 * message over the socket. This message is sent in the format required by the
43 * FEP Simulator.
44 *
45 * Currently, there is no driving logic within the highways class. It is only
46 * done through an instance of the ConsoleDriver.java class. Eventually, it will
47 * receive incident data (from exchange.xml or better yet, directly from the
48 * TMCSimulator itself) and drive the highways using resident logic.
49 *
50 * @author John A. Torres
51 */
52final public class Highways
53{
54
55    final private String FEPHostName;
56    final private int FEPPortNum;
57   
58    final private List<FEPLine> lines;
59    final public List<Highway> highways;
60
61    public Highways(String highwaysMapFileName, String FEPHostName, int FEPPortNum)
62    {
63        // load FEP Lines
64        lines = loadLines(highwaysMapFileName);
65        // build highways data structure
66        this.highways = buildHighways();
67
68        // write to FEP host and port number
69        this.FEPHostName = FEPHostName;
70        this.FEPPortNum = FEPPortNum;
71    }
72
73    private ArrayList<Highway> buildHighways()
74    {
75        System.out.println("Building highways...");
76        // The list of highways to return
77        ArrayList<Highway> highways = new ArrayList<Highway>();
78       
79        // map of hwy number to its list of stations
80        Map<Integer, ArrayList<Station>> highwayMap = new HashMap<>();
81       
82        // iterate through FEPLines and get data to add to the above map
83        for (FEPLine line : lines)
84        {
85            // grab all stations from the current FEPLine
86            ArrayList<Station> lineStations = (ArrayList<Station>) line.stations;
87            // iterate through each station in the list of stations
88            for (Station station : lineStations)
89            {
90                Integer hwyNum = station.routeNumber;
91                // if the map does not contain an entry for the highway, create
92                // a new entry (key/value pair) for the highway and instantiate
93                // the empty list of stations
94                if (!highwayMap.containsKey(hwyNum))
95                {
96                    ArrayList<Station> stnList = new ArrayList<>();
97                    stnList.add(station);
98                    highwayMap.put(hwyNum, stnList);
99                } 
100                // if the map does have an entry for the highway, add the current
101                // station to its list of stations
102                else
103                {
104                    highwayMap.get(hwyNum).add(station);
105                }
106            }
107        }
108       
109        // get the set of highway numbers
110        Set<Integer> hwyKeys = highwayMap.keySet();
111        // get the highway number and associated stations and create a new hwy
112        // and add the hwy to this.highways
113        for (Integer hwyKey : hwyKeys)
114        {
115            ArrayList<Station> hwyStations = highwayMap.get(hwyKey);
116            Collections.sort(hwyStations);
117            System.out.println("Loaded highway " + hwyKey + " with " +
118                    hwyStations.size() + " stations.");
119            highways.add(new Highway(hwyKey,
120                    hwyStations));
121        }
122        System.out.println("");
123        return highways;
124    }
125
126    /**
127     * Applies specified color to the specified highway stretch. Route number
128     * and direction specify the highway. Postmile and range specify the stretch
129     * of specified highway. Dot color is the color to be applied to the
130     * stretch.
131     *
132     * @param routeNumber highway route number
133     * @param direction highway direction
134     * @param postmile origin postmile value
135     * @param range range from origin postmile
136     * @param dotColor the color to be applied to specified highway stretch
137     */
138    public void applyColorToHighwayStretch(Integer routeNumber, Station.DIRECTION direction,
139            Double postmile, Double range, LoopDetector.DOTCOLOR dotColor)
140    {
141        System.out.println("Applying " + dotColor.name() + " dots to highway "
142                + routeNumber + " " + direction.name() + " at postmile "
143                + postmile + " with a range of " + range + " miles...");
144
145        // Get the highway by route number
146        Highway highway = getHighwayByRouteNumber(routeNumber);
147        if (highway == null)
148        {
149            Logger.getLogger(Highways.class.getName()).log(Level.SEVERE, 
150                    "Highway "+routeNumber+" not found trying to applyColor", "");
151            return;
152        }
153        // start value for highway section, and end value for highway section
154        // by postmile
155        Double startPost;
156        Double endPost;
157
158        // postmiles increase from s to n and w to e
159        // if the direction is south or west
160        if (direction.equals(Station.DIRECTION.SOUTH) || direction.equals(Station.DIRECTION.WEST))
161        {
162            // add range value to startPost to get
163            // the end postmile value of the highway section
164            startPost = postmile;
165            endPost = postmile + range;
166            //TODO: Catch NPE exception for situation when the events file
167            //   specifies a highway that doesn't exist in the network.
168            //   Also the case where a desired postmile to color isn't in
169            //   the network.
170            // iterate through the stations, if within the specified highway
171            // stretch, update the station by direction and apply dot color
172            for (Station station : highway.stations)
173            {
174                if (station.postmile >= startPost && station.postmile <= endPost)
175                {
176                    station.updateByDirection(direction, dotColor);
177                }
178            }
179        } // if the direction is north or east
180        else
181        {
182            // subtract range value from startPost
183            // to get the end postmile value of the highway section
184            startPost = postmile;
185            endPost = postmile - range;
186
187            // iterate through the stations, if within the specified highway
188            // section, update the station by direction and apply dot color
189            for (Station station : highway.stations)
190            {
191                if (station.postmile <= startPost && station.postmile >= endPost)
192                {
193                    station.updateByDirection(direction, dotColor);
194                }
195            }
196        }
197        System.out.println("");
198    }
199   
200    /**
201     * Loads all FEPLines from the specified highways map file.
202     *
203     * @param highwaysMapFileName
204     * @return List of FEPLines
205     */
206    private ArrayList<FEPLine> loadLines(String highwaysMapFileName)
207    {
208        ArrayList<FEPLine> lines = new ArrayList<>();
209        try
210        {
211            Scanner sc = new Scanner(new File(highwaysMapFileName));
212            // first line of file contains number of FEP Lines
213            String firstLine = sc.nextLine();
214            Scanner linesc = new Scanner(firstLine);
215            int numLines = linesc.nextInt();
216            linesc.close();
217            // FOR each FEP Line
218            for (int i = 0; i < numLines; i++)
219            {
220                lines.add(loadLine(sc));
221            }
222            sc.close();
223
224        } catch (FileNotFoundException ex)
225        {
226            Logger.getLogger(Highways.class.getName()).log(Level.SEVERE, null, ex);
227        }
228        return lines;
229    }
230   
231    /**
232     * Load all the stations for a single FEP Line from the highways map file.
233     *
234     * @param sc scanner at the current FEPLine line
235     * @return FEPLine
236     */
237    private FEPLine loadLine(Scanner sc)
238    {
239        String line = sc.nextLine();
240        Scanner scline = new Scanner(line);
241        // Get the attributes of this FEP Line
242        int lineNum = scline.nextInt();
243        int count = scline.nextInt();
244        int numStations = scline.nextInt();
245       
246        // initialze stations array
247        ArrayList<Station> stations = new ArrayList<>();
248        // Read all the stations for thie FEP Line
249        for (int i = 0; i < numStations; i++)
250        {
251            stations.add(loadStation(sc, lineNum));
252        }
253
254        return new FEPLine(lineNum, stations, count);
255    }
256   
257    /**
258     * Loads a single Station from the highways map file
259     * @param sc scanner at the current station line
260     * @param lineNum the FEPLine number for the station
261     * @return Station
262     */
263    private Station loadStation(Scanner sc, int lineNum)
264    {
265        String line = sc.nextLine();
266        Scanner scline = new Scanner(line);
267       
268        int ldsID = scline.nextInt();
269        int drop = scline.nextInt();
270        int fwy = scline.nextInt();
271        DIRECTION dir = DIRECTION.toDirection(scline.next());
272        double postmile = scline.nextDouble();
273        int numLoops = scline.nextInt();
274        String location = getStationLoc(line);
275        ArrayList<LoopDetector> loops = new ArrayList<>();
276        for (int i = 0; i < numLoops; i++)
277        {
278            loops.add(loadLoop(sc));
279        }
280
281        return new Station(lineNum, ldsID, drop, location, loops, fwy, dir, postmile);
282    }
283   
284    /**
285     * Loads a single loop from the highways map file
286     *
287     * @param sc scanner at the current loop line
288     * @return LoopDetector
289     */
290    private LoopDetector loadLoop(Scanner sc)
291    {
292        String line = sc.nextLine();
293        Scanner scline = new Scanner(line);
294
295        int loopID = scline.nextInt();
296        String loopLocID = scline.next();
297        String loopLoc = scline.next();
298        scline.close();
299        return new LoopDetector(loopID, loopLocID, loopLoc);
300    }
301
302    /**
303     * Scans the LoopDetector line and grabs the String location from the line.
304     *
305     * @param line the line containing the location
306     * @return A String loop location.
307     */
308    private String getLoopLoc(String line)
309    {
310        Scanner sc = new Scanner(line);
311        sc.nextInt();
312
313     // GRABS FROM CURRENT TO END OF LINE
314        sc.useDelimiter("\\z");
315        String loc = sc.next().trim();
316        sc.close();
317        return loc;
318    }
319
320    /**
321     * Scans the Station line and grabs the String location from the line.
322     *
323     * @param line the line containing the location
324     * @return A String station location.
325     */
326    private String getStationLoc(String line)
327    {
328        Scanner scline = new Scanner(line);
329        scline.nextInt();
330        scline.nextInt();
331        scline.nextInt();
332        scline.next();
333        scline.nextDouble();
334        scline.nextInt();
335
336        // GRABS FROM CURRENT TO END OF LINE
337        scline.useDelimiter("\\z");
338        String loc = scline.next().trim();
339        scline.close();
340        return loc;
341    }
342   
343    /**
344     * Creates a socket client that writes the Highways data to the FEP Simulator.
345     *
346     * @throws SimulationException
347     */
348    public void writeToFEP() throws SimulationException
349    {
350        try
351        {
352            // Create the socket to the FEP Simulator
353            Socket sock = new Socket(FEPHostName, FEPPortNum);
354            PrintWriter out = new PrintWriter(sock.getOutputStream(), true);
355           
356            // Print the number of bytes the highways data message contains
357            System.out.println("Highways sending " + this.toCondensedFormat(false).toCharArray().length + 1 + "bytes to FEPSIM.");
358            String outMsg = this.toCondensedFormat(false);
359            // Write the highways data over the socket
360            out.println(outMsg);
361           
362            // close the socket
363            sock.close();
364        } catch (java.net.ConnectException ex)
365        {
366            //Logger.getLogger(Highways.class.getName()).log(Level.SEVERE, null, ex);
367            System.out.println("writeToFEP() can't connect, no data sent to FEP.");
368            throw new SimulationException(SimulationException.BINDING);
369        } catch (IOException ex)
370        {
371            //Logger.getLogger(Highways.class.getName()).log(Level.SEVERE, null, ex);
372            System.out.println("Highway Model failed writing to FEPSim.");
373            throw new SimulationException(SimulationException.BINDING);
374        }
375    }
376   
377    /** Returns a string of highways data. If MetaDataOnly is true, you get a full
378     *  dump of the highways meta data, which does not include dynamic loop values,
379     *  and does include the string location names. If MetaDataOnly is false,
380     *  dynamic loop values are included, and unnecessary information like string
381     *  location values are not included.
382     *
383     *  The FEPSimulator takes in the toCondensedFormat() output, with a MetaDataOnly
384     *  value of false, over the socket.
385     *
386     *  The MetaDataOnly flag should be used to get a full dump of the highways
387     *  information. This was used to get the highways_fullmap.txt output.
388     *
389     * @param MetaDataOnly Whether you want meta data, or a full dump for FEPSim
390     * @return String, highways data in condensed format
391     *
392     * Example toCondensedFormat(MetaDataOnly = false) output:
393     *
394     * 43                       // "number of lines"
395     * 32 0 13                  // "line id" "count num" "number of stations"
396     * 1210831 1 5 S 0.9 8      // "station id" "drop num" "route num"...
397     *                          //      ..."direction" "postmile" "number of loops"
398     * 1210832  0.0 0  ML_1     // "loop id" "occ" "vol"
399     * 1210833  0.0 0  ML_2     // ..
400     * 1210834  0.0 0  ML_3     // ..
401     * 1210835  0.0 0  ML_4     // ..
402     * 1210836  0.0 0  PASSAGE  // ..
403     * 1210837  0.0 0  DEMAND   // ..
404     * 1210838  0.0 0  QUEUE    // ..
405     * 1210839  0.0 0  RAMP_OFF // ..
406     * ...
407     *
408     * Example toCondensedFormat(MetaDataOnly = true) output:
409     *
410     * 43                           // "number of lines"
411     * 32 0 13                      // "line id" "count num" "number of stations"
412     * 1210831 1 5 S 0.9 8 CALAFIA  // "station id" "drop num" "route num"...
413     *                              //      ..."direction" "postmile"...
414     *                              //      ..."number of loops" "string location"
415     * 1210832 ML_1                 // "loop id" "loop location"
416     * 1210833 ML_2                 // "            "
417     * 1210834 ML_3                 // "            "
418     * 1210835 ML_4                 // "            "
419     * 1210836 PASSAGE              // "            "
420     * 1210837 DEMAND               // "            "
421     * 1210838 QUEUE                // "            "
422     * 1210839 RAMP_OFF             // "            "
423     * ...
424     */
425    public String toCondensedFormat(boolean MetaDataOnly)
426    {
427        // first line: number of FEPLines
428        StringBuilder build = new StringBuilder();
429        build.append(lines.size());
430        build.append("\n");
431        // append each fep line to the string
432        for(FEPLine line : lines)
433        {
434            build.append(line.toCondensedFormat(MetaDataOnly));
435        }
436        // return the full condensed format string
437        return build.toString();
438    }
439   
440    /**
441     * Returns the Highways model data in XML format.
442     *
443     * @return highways data in XML format
444     */
445    public String toXML()
446    {
447        String xml = null;
448        try
449        {
450            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
451            DocumentBuilder builder = factory.newDocumentBuilder();
452            Document theDoc = builder.newDocument();
453
454            Element networkElement = theDoc.createElement(XML_TAGS.NETWORK.tag);
455            theDoc.appendChild(networkElement);
456
457            for (FEPLine line : lines)
458            {
459                line.toXML(networkElement);
460            }
461
462            Transformer tf = TransformerFactory.newInstance().newTransformer();
463
464            tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
465            tf.setOutputProperty(OutputKeys.INDENT, "yes");
466            tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
467
468            Writer out = new StringWriter();
469            tf.transform(new DOMSource(theDoc), new StreamResult(out));
470            xml = out.toString();
471            out.close();
472        } catch (Exception ex)
473        {
474            Logger.getLogger(Highways.class.getName()).log(Level.SEVERE, null, ex);
475        }
476        return xml;
477
478    }
479
480    /**
481     * Returns a highway by given highway number.
482     *
483     * @param routeNum
484     * @return Highway with specified route number, or null if no highway with
485     *          the specified route num
486     */
487    public Highway getHighwayByRouteNumber(Integer routeNum)
488    {
489        Highway returnHwy = null;
490        // search through highways and check routeNums
491        for (Highway hwy : highways)
492        {
493            if (hwy.routeNumber.equals(routeNum))
494            {
495                returnHwy = hwy;
496                break;
497            }
498        }
499        return returnHwy;
500    }
501
502    /** Return a string representation of the Highways */
503    public String toString()
504    {
505        StringBuilder result = new StringBuilder();
506        for (Highway hwy: highways)
507        {
508            // Consider each route direction
509            for (DIRECTION dir: DIRECTION.values())
510            {
511                String rowLabel = ""+String.format("%3s ",hwy.routeNumber)+dir.getLetter()+' ';
512                StringBuilder lineout = new StringBuilder();
513                // Examine every station on this highway and direction
514                for (Station stat: hwy.stations)
515                {
516                    //lineout.append("" + dir.getLetter() + stat.postmile);
517                    lineout.append(stat.getColor());
518                    //lineout.append("  ");
519                }
520                // See if there were stations for this direction
521                String checkMe = lineout.toString().trim();
522                // if any stations were colored, output the line
523                if (checkMe.length() > 1)
524                {
525                    result.append(rowLabel);
526                    result.append(lineout + "\n");
527                }
528            }
529        }
530        result.append("\n");
531        return result.toString();
532    }
533    /** Return a json representation of the Highways, readable by Google Maps */
534    public String toJson()
535    {
536        // TODO: move loading this file to init method so it doesn't get
537        // called every time.
538        PostmileCoords pmList = new PostmileCoords();
539        FileInputStream fis = null;
540        try
541        {
542            fis = new FileInputStream("config/vds_data/postmile_coordinates.txt");
543        }
544        catch (FileNotFoundException ex)
545        {
546            Logger.getLogger(Highways.class.getName()).log(Level.SEVERE, null, ex);
547        }
548        Scanner s = new Scanner(fis).useDelimiter("\\A");
549        pmList.load(s);
550       
551        String header = "{\n" +
552        "  \"type\": \"FeatureCollection\",\n" +
553        "  \"features\": [";
554        StringBuilder result = new StringBuilder();
555        result.append(header);
556        for (Highway hwy: highways)
557        {
558            // Consider each route direction
559            for (DIRECTION dir: DIRECTION.values())
560            {
561                // Examine every station on this highway and direction
562                StringBuilder lineout = new StringBuilder();
563                for (Station stat: hwy.stations)
564                {
565                    String pmID = "" + hwy.routeNumber + " " 
566                            + stat.direction.getLetter() + " " 
567                            + stat.postmile;
568                    PostmileCoords.Postmile currentPM = pmList.find(pmID);
569                    if (currentPM == null)
570                    { 
571                    Logger.getLogger(Highways.class.getName()).log(Level.INFO, 
572                            "Postmile Coords lookup couldn't find Station: "+pmID,
573                            " ");
574                    }
575                    if (currentPM != null)
576                    {   
577                        //lineout.append("" + dir.getLetter() + stat.postmile);
578                        //lineout.append(stat.getColorByDirection(dir));
579                        String outString = currentPM.toJson();
580                        // replace the color code with the color name
581                        String colorName=stat.getColorName();
582                        outString = outString.replace("desiredcolor",colorName);
583                        lineout.append(outString);
584                        lineout.append("  ");
585                    }
586                }
587                //result.append(rowLabel);
588                result.append(lineout + "\n");
589
590            }
591        }
592        // remove last trailing comma
593        result.replace(result.lastIndexOf(","), result.lastIndexOf(",") + 1, " "  );
594
595        result.append("  ]\n" +  "}");
596        return result.toString();
597    }
598   
599    /**
600     * Generates the route number list, used for user input validation.
601     * @return list of route numbers.
602     */
603    public List<Integer> getAllRouteNums()
604    {
605        ArrayList<Integer> routeNums = new ArrayList<>();
606        // add the route number for each highway to the list
607        for(Highway hwy : highways)
608        {
609            routeNums.add(hwy.routeNumber);
610        }
611        return routeNums;
612    }
613   
614    /**
615     * XML tags used in writeToXML()
616     */
617    private static enum XML_TAGS
618    {
619
620        NETWORK("Network");
621
622        String tag;
623
624        private XML_TAGS(String n)
625        {
626            tag = n;
627        }
628    }
629   
630    public void reset()
631    {
632        for(FEPLine line : lines)
633        {
634            for(Station stn : line.stations)
635            {
636                for(LoopDetector ld : stn.loops)
637                {
638                    ld.occ = 0;
639                    ld.vol = 0;
640                }
641            }
642        }
643    }
644   
645    public void applyTrafficLaneEvent(TrafficLaneEvent event)
646    {
647        Integer routeNum = event.routeNum;
648        Highway hwy = getHighwayByRouteNumber(routeNum);
649        for(Station stn: hwy.stations)
650        {
651            if(stn.equals(event.station))
652            {
653                for(LoopDetector ld : stn.loops)
654                {
655                    if(ld.equals(event.loopDetector))
656                    {
657                        ld.occ = event.color.occupancy();
658                        ld.vol = event.color.volume();
659                        break;
660                    }
661                }
662                break;
663            }
664        }
665    }
666}
Note: See TracBrowser for help on using the repository browser.