1 package org.opentrafficsim.core.network.factory.xml.units;
2
3 import java.util.HashMap;
4 import java.util.Map;
5
6 import org.djunits.unit.AngleUnit;
7 import org.djunits.unit.DirectionUnit;
8 import org.djunits.unit.UNITS;
9 import org.djunits.value.AngleUtil;
10 import org.djunits.value.vdouble.scalar.Angle;
11 import org.djunits.value.vdouble.scalar.Direction;
12 import org.opentrafficsim.core.network.NetworkException;
13
14
15
16
17
18
19
20
21
22
23
24 public final class AngleUnits implements UNITS
25 {
26
27 public static final Map<String, AngleUnit> ANGLE_UNITS = new HashMap<>();
28
29
30 public static final Map<String, DirectionUnit> DIRECTION_UNITS = new HashMap<>();
31
32 static
33 {
34 ANGLE_UNITS.put("deg", DEGREE);
35 ANGLE_UNITS.put("rad", RADIAN);
36
37 DIRECTION_UNITS.put("deg", DirectionUnit.EAST_DEGREE);
38 DIRECTION_UNITS.put("rad", DirectionUnit.EAST_RADIAN);
39 }
40
41
42 private AngleUnits()
43 {
44
45 }
46
47
48
49
50
51
52 public static String parseAngleUnit(final String s) throws NetworkException
53 {
54 String u = null;
55 for (String us : ANGLE_UNITS.keySet())
56 {
57 if (s.toString().contains(us))
58 {
59 if (u == null || us.length() > u.length())
60 {
61 u = us;
62 }
63 }
64 }
65 if (u == null)
66 {
67 throw new NetworkException("Parsing network: cannot instantiate angle unit in: " + s);
68 }
69 return u;
70 }
71
72
73
74
75
76
77 public static Angle parseAngle(final String s) throws NetworkException
78 {
79 String us = parseAngleUnit(s);
80 AngleUnit u = ANGLE_UNITS.get(us);
81 String sv = s.substring(0, s.indexOf(us));
82 try
83 {
84 double value = Double.parseDouble(sv);
85 Angle angle = new Angle(value, u);
86 return new Angle(AngleUtil.normalize(angle).si, AngleUnit.SI);
87 }
88 catch (NumberFormatException nfe)
89 {
90 throw new NetworkException("Parsing network: cannot instantiate scalar: " + s, nfe);
91 }
92 }
93
94
95
96
97
98
99 public static String parseDirectionUnit(final String s) throws NetworkException
100 {
101 String u = null;
102 for (String us : DIRECTION_UNITS.keySet())
103 {
104 if (s.toString().contains(us))
105 {
106 if (u == null || us.length() > u.length())
107 {
108 u = us;
109 }
110 }
111 }
112 if (u == null)
113 {
114 throw new NetworkException("Parsing network: cannot instantiate direction unit in: " + s);
115 }
116 return u;
117 }
118
119
120
121
122
123
124 public static Direction parseDirection(final String s) throws NetworkException
125 {
126 String us = parseDirectionUnit(s);
127 DirectionUnit u = DIRECTION_UNITS.get(us);
128 String sv = s.substring(0, s.indexOf(us));
129 try
130 {
131 double value = Double.parseDouble(sv);
132 Direction direction = new Direction(value, u);
133 return new Direction(AngleUtil.normalize(direction).si, DirectionUnit.EAST_RADIAN);
134 }
135 catch (NumberFormatException nfe)
136 {
137 throw new NetworkException("Parsing network: cannot instantiate scalar: " + s, nfe);
138 }
139 }
140
141 }