forked from dakk/libweatherrouting
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpolar.py
More file actions
263 lines (225 loc) · 8.65 KB
/
Copy pathpolar.py
File metadata and controls
263 lines (225 loc) · 8.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
# -*- coding: utf-8 -*-
# Copyright (C) 2017-2025 Davide Gessa
# Copyright (C) 2021 Enrico Ferreguti
# Copyright (C) 2012 Riccardo Apolloni
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# For detail about GNU see <http://www.gnu.org/licenses/>.
import math
import re
from io import TextIOWrapper
from typing import Dict, Optional, Tuple
class PolarError(Exception):
def __init__(self, message):
self.message = message
class Polar:
def __init__(self, polar_path: str, f: Optional[TextIOWrapper] = None):
"""
Parameters
----------
polar_path : string
Path of the polar file
f : File
File object for passing an opened file
"""
self.validate_polar_file(polar_path)
self.tws = []
self.twa = []
self.vmgdict: Dict[Tuple[float, float], Tuple[float, float]] = {}
self.speed_table = []
if f is None:
f = open(polar_path, "r")
tws = f.readline().split()
for i in range(1, len(tws)):
self.tws.append(float(tws[i].replace("\x02", "")))
line = f.readline()
while line != "":
data = line.split()
twa = float(data[0])
self.twa.append(math.radians(twa))
speedline = []
for i in range(1, len(data)):
speed = float(data[i])
speedline.append(speed)
self.speed_table.append(speedline)
line = f.readline()
f.close()
def to_string(self) -> str:
s = "TWA\\TWS"
for x in self.tws:
s += f"\t{x:.0f}"
s += "\n"
l_idx = 0
for y in self.twa:
s += f"{round(math.degrees(y))}"
sl = self.speed_table[l_idx]
for x in sl:
s += f"\t{x:.1f}"
s += "\n"
l_idx += 1
return s
def get_speed(self, tws: float, twa: float) -> float: # noqa: C901
"""Returns the speed (in knots) given tws (in knots) and twa (in radians)"""
tws1 = 0
tws2 = 0
for k in range(0, len(self.tws)):
if tws >= self.tws[k]:
tws1 = k
for k in range(len(self.tws) - 1, 0, -1):
if tws <= self.tws[k]:
tws2 = k
if tws1 > tws2: # TWS over table limits
tws2 = len(self.tws) - 1
twa1 = 0
twa2 = 0
for k in range(0, len(self.twa)):
if twa >= self.twa[k]:
twa1 = k
for k in range(len(self.twa) - 1, 0, -1):
if twa <= self.twa[k]:
twa2 = k
speed1 = self.speed_table[twa1][tws1]
speed2 = self.speed_table[twa2][tws1]
speed3 = self.speed_table[twa1][tws2]
speed4 = self.speed_table[twa2][tws2]
if twa1 != twa2:
speed12 = speed1 + (speed2 - speed1) * (twa - self.twa[twa1]) / (
self.twa[twa2] - self.twa[twa1]
) # interpolazione su twa
speed34 = speed3 + (speed4 - speed3) * (twa - self.twa[twa1]) / (
self.twa[twa2] - self.twa[twa1]
) # interpolazione su twa
else:
speed12 = speed1
speed34 = speed3
if tws1 != tws2:
speed = speed12 + (speed34 - speed12) * (tws - self.tws[tws1]) / (
self.tws[tws2] - self.tws[tws1]
)
else:
speed = speed12
return speed
def get_reaching(self, tws: float) -> Tuple[float, float]:
maxspeed = 0.0
twamaxspeed = 0.0
for twa_ in range(0, 181):
twa = math.radians(twa_)
speed = self.get_speed(tws, twa)
if speed > maxspeed:
maxspeed = speed
twamaxspeed = twa
return (maxspeed, twamaxspeed)
def get_max_vmgtwa(self, tws: float, twa: float) -> Tuple[float, float]:
if (tws, twa) not in self.vmgdict:
twamin = max(0, twa - math.pi / 2)
twamax = min(math.pi, twa + math.pi / 2)
alfa = twamin
maxvmg = -1.0
while alfa < twamax:
v = self.get_speed(tws, alfa)
vmg = v * math.cos(alfa - twa)
if vmg - maxvmg > 10**-3: # 10**-3 errore tollerato
maxvmg = vmg
twamaxvmg = alfa
alfa = alfa + math.radians(1)
self.vmgdict[tws, twa] = (maxvmg, twamaxvmg)
return self.vmgdict[(tws, twa)]
def get_max_vmg_up(self, tws: float) -> Tuple[float, float]:
vmguptupla = self.get_max_vmgtwa(tws, 0)
return (vmguptupla[0], vmguptupla[1])
def get_max_vmg_down(self, tws: float) -> Tuple[float, float]:
vmgdowntupla = self.get_max_vmgtwa(tws, math.pi)
return (-vmgdowntupla[0], vmgdowntupla[1])
def get_routage_speed(self, tws, twa) -> float:
up = self.get_max_vmg_up(tws)
vmgup = up[0]
twaup = up[1]
down = self.get_max_vmg_down(tws)
vmgdown = down[0]
twadown = down[1]
v = 0.0
if twa >= twaup and twa <= twadown:
v = self.get_speed(tws, twa)
else:
if twa < twaup:
v = vmgup / math.cos(twa)
if twa > twadown:
v = vmgdown / math.cos(twa)
return v
def get_twa_routage(self, tws: float, twa: float) -> float:
up = self.get_max_vmg_up(tws)
# vmgup = up[0]
twaup = up[1]
down = self.get_max_vmg_down(tws)
# vmgdown = down[0]
twadown = down[1]
if twa >= twaup and twa <= twadown:
pass
# twa = twa
else:
if twa < twaup:
twa = twaup
if twa > twadown:
twa = twadown
return twa
@staticmethod
def validate_polar_file(filepath): # noqa: C901
try:
with open(filepath, "r") as f:
content = f.read()
lines = content.strip().split("\n")
if len(lines) == 0:
raise PolarError("EMPTY_FILE")
# Parse header to get wind speeds
header_parts = re.split(r"\s+", lines[0].strip())
# Try to parse wind speeds (should be numeric)
try:
tws = [float(ws) for ws in header_parts[1:]]
except ValueError:
raise PolarError("WIND_SPEED_NOT_NUMERIC")
# Check for increasing wind speeds
if not all(tws[i] <= tws[i + 1] for i in range(len(tws) - 1)):
raise PolarError("WIND_SPEEDS_NOT_INCREASING")
# Check data rows
expected_columns = len(header_parts)
for i, line in enumerate(lines[1:], start=1):
parts = re.split(r"\s+", line.strip())
# Skip empty lines
if not parts or (len(parts) == 1 and not parts[0]):
raise PolarError("EMPTY_LINE")
# Check number of columns
if len(parts) != expected_columns:
raise PolarError("COLUMN_COUNT_MISMATCH")
# Check if TWA is in valid range
try:
twa = float(parts[0])
if twa < 0 or twa > 180:
raise PolarError("TWA_OUT_OF_RANGE")
except ValueError:
raise PolarError("TWA_NOT_NUMERIC")
# Check if boat speeds are non-negative
for j, speed in enumerate(parts[1:], start=1):
# Skip empty values or specific placeholders
if speed in ["", "-", "NaN", "NULL"]:
raise PolarError("EMPTY_VALUE")
try:
boat_speed = float(speed)
if boat_speed < 0:
raise PolarError("NEGATIVE_SPEED")
except ValueError:
raise PolarError("SPEED_NOT_NUMERIC")
# If we get here, the file is valid
return True
except PolarError:
# Re-raise PolarError exceptions
raise
except Exception as e:
# Wrap other exceptions in PolarError
raise PolarError("UNEXPECTED_ERROR", f"Error processing file: {str(e)}")