Warning: Can't use blame annotator:
svn blame failed on trunk/src/atmsdriver/model/Highways.java: ("Can't find a temporary directory: Internal error", 20014)

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

Revision 176, 10.1 KB checked in by jtorres, 9 years ago (diff)

Highways.java, LoopDetector?.java: updateByDirection() methods now take float occ value. ConsoleDriver?.java: DOTCOLOR enum now contains valid vol and occ values. atmsBatchEvents.txt: updated to fullBatchEvents script.

RevLine 
1package atmsdriver.model;
2
3import atmsdriver.FEPLineLoader;
4import java.io.File;
5import java.io.FileWriter;
6import java.io.IOException;
7import java.io.PrintWriter;
8import java.io.StringWriter;
9import java.io.Writer;
10import java.net.Socket;
11import java.util.ArrayList;
12import java.util.Collections;
13import java.util.HashMap;
14import java.util.Map;
15import java.util.Observable;
16import java.util.Observer;
17import java.util.Set;
18import java.util.logging.Level;
19import java.util.logging.Logger;
20import javax.xml.parsers.DocumentBuilder;
21import javax.xml.parsers.DocumentBuilderFactory;
22import javax.xml.transform.OutputKeys;
23import javax.xml.transform.Transformer;
24import javax.xml.transform.TransformerFactory;
25import javax.xml.transform.dom.DOMSource;
26import javax.xml.transform.stream.StreamResult;
27import org.w3c.dom.Document;
28import org.w3c.dom.Element;
29import tmcsim.common.SimulationException;
30
31/** The Highways class aggregates all Highway instances within a geographic
32 *  region, and all of the FEPLines within an electronic detector
33 *  network, in the same geographic region. An instance of Highways.java
34 *  comprises the underlying model for the ATMSDriver application.
35 *
36 *  Highways uses method writeToFEP() to communicate with the FEP Simulator.
37 *  It creates a socket client which sends the FEP Simulator a highways status
38 *  message over the socket. This message is in the XML format required by the
39 *  FEP Simulator, which is provided by the resident toXML() method.
40 *
41 *  Currently, there is no driving logic within the highways class. It is only
42 *  done through an instance of the ConsoleDriver.java class. Eventually, it
43 *  will receive incident data (from exchange.xml or better yet, directly from
44 *  the TMCSimulator itself) and drive the highways using resident logic.
45 *
46 * @author John A. Torres
47 */
48public class Highways {
49
50    final private ArrayList<FEPLine> lines;
51    final private String FEPHostName;
52    final private int FEPPortNum;
53   
54    final public ArrayList<Highway> highways;
55   
56    public Highways(String ldsFileName, String loopsFileName,
57            String highwayMetaFileName, String FEPHostName, int FEPPortNum) {
58        /*
59         lines = loadLines(highwayMetaFileName);
60         System.out.println("SIZE: " + toXML().toCharArray().length);
61         */
62
63        FEPLineLoader ldr = new FEPLineLoader(new File(ldsFileName), new File(loopsFileName));
64        this.lines = (ArrayList<FEPLine>) ldr.getFEPLines();
65        this.FEPHostName = FEPHostName;
66        this.FEPPortNum = FEPPortNum;
67        this.highways = loadHighways();
68        //writeHighwaysMeta("hard.txt");
69    }
70   
71    private ArrayList<Highway> loadHighways() {
72        System.out.println("Loading highways...");
73        // The list of highways to return
74        ArrayList<Highway> highways = new ArrayList<Highway>();
75       
76        Map<Integer, ArrayList<Station>>
77                highwayMap = new HashMap<>();
78       
79        for (FEPLine line : lines)
80        {
81            ArrayList<Station> lineStations = (ArrayList<Station>) line.stations;
82            for(Station station : lineStations)
83            {
84                Integer hwyNum = station.routeNumber;
85
86                if(!highwayMap.containsKey(hwyNum))
87                {
88                    ArrayList<Station> stnList = new ArrayList<>();
89                    stnList.add(station);
90                    highwayMap.put(hwyNum, stnList);
91                }
92                else
93                {
94                    highwayMap.get(hwyNum).add(station);
95                }
96            }
97        }
98       
99        Set<Integer> hwyKeys = highwayMap.keySet();
100        for(Integer hwyKey : hwyKeys)
101        {
102            ArrayList<Station> hwyStations = highwayMap.get(hwyKey);
103            Collections.sort(hwyStations);
104            System.out.println("Loaded highway " + hwyKey + "...");
105            highways.add(new Highway(hwyKey, 
106                    hwyStations));
107        }
108        System.out.println("");
109        return highways;
110    }
111   
112    /*
113     private ArrayList<FEPLine> loadLines(String highwayMetaFileName) {
114     ArrayList<FEPLine> lines = new ArrayList<>();
115     try {
116     Scanner sc = new Scanner(new File(highwayMetaFileName));
117     String firstLine = sc.nextLine();
118
119     Scanner linesc = new Scanner(firstLine);
120     int numLines = linesc.nextInt();
121     linesc.close();
122
123     for (int i = 0; i < numLines; i++) {
124     System.out.println("CURR: " + i);
125     lines.add(loadLine(sc));
126     }
127     sc.close();
128
129     } catch (FileNotFoundException ex) {
130     Logger.getLogger(Highways.class.getName()).log(Level.SEVERE, null, ex);
131     }
132     return lines;
133     }
134
135     private FEPLine loadLine(Scanner sc) {
136     String line = sc.nextLine();
137     System.out.println(line);
138     Scanner scline = new Scanner(line);
139
140     int lineNum = scline.nextInt();
141     int count = scline.nextInt();
142     int numStations = scline.nextInt();
143     ArrayList<Station> stations = new ArrayList<>();
144     for (int i = 0; i < numStations; i++) {
145     stations.add(loadStation(sc, lineNum));
146     }
147
148     return new FEPLine(lineNum, stations, count);
149     }
150
151     private Station loadStation(Scanner sc, int lineNum) {
152     String line = sc.nextLine();
153     System.out.println(line);
154     Scanner scline = new Scanner(line);
155     int ldsID = scline.nextInt();
156     int drop = scline.nextInt();
157     int fwy = scline.nextInt();
158     DIRECTION dir = DIRECTION.getEnum(scline.next());
159     double postmile = scline.nextDouble();
160     int numLoops = scline.nextInt();
161     String location = getStationLoc(line);
162     ArrayList<LoopDetector> loops = new ArrayList<>();
163     for (int i = 0; i < numLoops; i++) {
164     loops.add(loadLoop(sc));
165     }
166
167     return new Station(lineNum, ldsID, drop, location, loops, fwy, dir, postmile);
168     }
169
170     private LoopDetector loadLoop(Scanner sc) {
171     String line = sc.nextLine();
172     Scanner scline = new Scanner(line);
173
174     int loopID = scline.nextInt();
175     int laneNum = scline.nextInt();
176     String loopLoc = getLoopLoc(line); // NEED GET LOOPLOC
177     scline.close();
178     return new LoopDetector(loopID, loopLoc, laneNum);
179     }
180
181     private String getLoopLoc(String line) {
182     Scanner sc = new Scanner(line);
183     sc.nextInt();
184     sc.nextInt();
185
186     // GRABS FROM CURRENT TO END OF LINE
187         
188     sc.useDelimiter("\\z");
189     String loc = sc.next().trim();
190     sc.close();
191     return loc;
192     }
193
194     // Returns the loction given the whole line from the lookup file
195     private String getStationLoc(String line) {
196     Scanner scline = new Scanner(line);
197     scline.nextInt();
198     scline.nextInt();
199     scline.nextInt();
200     scline.next();
201     scline.nextDouble();
202     scline.nextInt();
203
204     // GRABS FROM CURRENT TO END OF LINE
205     scline.useDelimiter("\\z");
206     String loc = scline.next().trim();
207     scline.close();
208     return loc;
209     }
210     */
211
212    public void writeToFEP() throws SimulationException {
213        try {
214            Socket sock = new Socket(FEPHostName /*"192.168.251.130"*/, 8080);
215            PrintWriter out = new PrintWriter(sock.getOutputStream(), true);
216            System.out.println("BYTES: " + this.toXML().toCharArray().length + 1);
217            out.println(this.toXML());
218            sock.close();
219        } catch (IOException ex) {
220            Logger.getLogger(Highways.class.getName()).log(Level.SEVERE, null, ex);
221            System.out.println("Highway Model failed writing to FEPSim.");
222            throw new SimulationException(SimulationException.BINDING);
223        }
224        updateSequences();
225    }
226
227    // CHECK: DO WE EVEN NEED TO DO THIS?
228    private void updateSequences() {
229        for (FEPLine line : lines) {
230            line.updateSequences();
231        }
232    }
233
234    /**
235     * Returns the network metadata in condensed form. This is just a quick
236     * script function to make a proper highway metadata configuration file, so
237     * that we can read the network faster.
238     *
239     * @return Network metadata
240     */
241    public void writeHighwaysMeta(String fileName) {
242
243        try {
244            FileWriter fw = new FileWriter(new File(fileName));
245            StringBuilder build = new StringBuilder();
246            build.append(lines.size());
247            build.append("\n");
248            System.out.println(lines.size());
249            fw.write(build.toString());
250            int count = 1;
251            for (FEPLine line : lines) {
252                System.out.println("Writing num: " + count);
253                count++;
254                fw.write(line.getLineMeta());
255
256            }
257        } catch (IOException ex) {
258            Logger.getLogger(Highways.class.getName()).log(Level.SEVERE, null, ex);
259        }
260    }
261
262    public String toXML() {
263        String xml = null;
264        try {
265            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
266            DocumentBuilder builder = factory.newDocumentBuilder();
267            Document theDoc = builder.newDocument();
268
269            Element networkElement = theDoc.createElement(XML_TAGS.NETWORK.tag);
270            theDoc.appendChild(networkElement);
271
272            for (FEPLine line : lines) {
273                line.toXML(networkElement);
274            }
275
276            Transformer tf = TransformerFactory.newInstance().newTransformer();
277
278            tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
279            tf.setOutputProperty(OutputKeys.INDENT, "yes");
280            tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
281
282            Writer out = new StringWriter();
283            tf.transform(new DOMSource(theDoc), new StreamResult(out));
284            xml = out.toString();
285            out.close();
286        } catch (Exception ex) {
287            Logger.getLogger(Highways.class.getName()).log(Level.SEVERE, null, ex);
288        }
289        return xml;
290
291    }
292
293    public Highway getHighwayByRouteNumber(Integer routeNum) {
294        Highway returnHwy = null;
295        for(Highway hwy : highways)
296        {
297            if(hwy.routeNumber.equals(routeNum))
298            {
299                returnHwy = hwy;
300                break;
301            }
302        }
303        return returnHwy;
304    }
305
306    private static enum XML_TAGS {
307
308        NETWORK("Network");
309
310        String tag;
311
312        private XML_TAGS(String n) {
313            tag = n;
314        }
315    }
316}
Note: See TracBrowser for help on using the repository browser.