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

Revision 345, 24.1 KB checked in by jdalbey, 7 years ago (diff)

minor changes to output messages to get unit tests to pass. All passing now.

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