diff --git a/dat/Daring/righting_moment.json b/dat/Daring/righting_moment.json new file mode 100644 index 0000000..4faf95d --- /dev/null +++ b/dat/Daring/righting_moment.json @@ -0,0 +1,4 @@ +{ + "Heel": [0.0, 10.0, 20.0, 30.0, 40.0, 50.0, 60.0], + "GZ": [0.000, 0.120, 0.230, 0.310, 0.350, 0.330, 0.260] +} diff --git a/dat/orc/asym_cl_kite.dat b/dat/orc/asym_cl_kite.dat new file mode 100644 index 0000000..64d8303 --- /dev/null +++ b/dat/orc/asym_cl_kite.dat @@ -0,0 +1,5 @@ +# asymmetric spinnaker centerline tack lift and drag coefficients (ORC VPP). first row is awa +0.02639,,,,,,,,,,, +0.0000,28.000,41.000,50.000,60.000,67.000,75.000,100.000,115.000,130.000,150.000,180.000 +0.0000,0.19100,0.28000,0.36600,0.52300,0.44800,0.55600,0.75700,0.79000,0.77600,0.62000,0.40000 +0.0000,0.02600,1.01800,1.27700,1.47100,1.51300,1.44400,1.13700,0.82900,0.56000,0.25000,-0.12000 diff --git a/dat/orc/asym_pole_kite.dat b/dat/orc/asym_pole_kite.dat new file mode 100644 index 0000000..4a94b72 --- /dev/null +++ b/dat/orc/asym_pole_kite.dat @@ -0,0 +1,5 @@ +# asymmetric spinnaker pole tack lift and drag coefficients (ORC VPP). first row is awa +0.02639,,,,,,,,,,, +0.0000,28.000,41.000,50.000,60.000,67.000,75.000,100.000,115.000,130.000,150.000,180.000 +0.0000,0.17000,0.23800,0.30600,0.45900,0.39200,0.49300,0.79100,0.89400,0.93600,0.93600,0.93600 +0.0000,0.08500,1.11400,1.36000,1.51300,1.54800,1.47900,1.20700,0.95600,0.70600,0.42500,0.00000 diff --git a/dat/orc/jib.dat b/dat/orc/jib.dat new file mode 100644 index 0000000..1bd52b0 --- /dev/null +++ b/dat/orc/jib.dat @@ -0,0 +1,5 @@ +# jib lift drag and lift coefficient (high). first row is awa +0.016,,,,,,,,, +0.00000,7.0000,15.0000,20.0000,27.0000,50.0000,60.0000,100.0000,150.0000,180.0000 +0.003,0.05000,0.03200,0.03100,0.03700,0.25000,0.35000,0.73000,0.95000,0.90000 +0.00000,0.00000,1.10000,1.47500,1.50000,1.45000,1.25000,0.40000,0.00000,-0.10000 \ No newline at end of file diff --git a/dat/orc/jib_low.dat b/dat/orc/jib_low.dat new file mode 100644 index 0000000..b4b58a1 --- /dev/null +++ b/dat/orc/jib_low.dat @@ -0,0 +1,5 @@ +# jib lift drag and lift coefficient (low performance rig). first row is awa +0.016,,,,,,,,, +0.00000,7.0000,15.0000,20.0000,27.0000,50.0000,60.0000,100.0000,150.0000,180.0000 +0.003,0.05000,0.03200,0.03100,0.03700,0.25000,0.35000,0.73000,0.95000,0.90000 +0.00000,0.00000,1.00000,1.37500,1.45000,1.43000,1.25000,0.40000,0.00000,-0.10000 diff --git a/dat/orc/kite.dat b/dat/orc/kite.dat new file mode 100644 index 0000000..d8b6dc7 --- /dev/null +++ b/dat/orc/kite.dat @@ -0,0 +1,5 @@ +# kite lift drag and lift coefficient (high). first row is awa +0.02639,,,,,,,,,,,, +0.0000,28.000,41.000,50.000,60.000,67.000,75.000,100.000,115.000,130.000,150.000,170.000,180.000 +0.0000,0.19152,0.28152,0.35496,0.43920,0.48960,0.53280,0.61920,0.65880,0.67320,0.67320,0.67320,0.67320 +0.0000,-0.02484,0.69437,0.90677,1.04400,1.08000,1.08000,0.95760,0.81360,0.61200,0.32400,0.10800,0.00000 \ No newline at end of file diff --git a/dat/orc/main.dat b/dat/orc/main.dat new file mode 100644 index 0000000..12dc64e --- /dev/null +++ b/dat/orc/main.dat @@ -0,0 +1,5 @@ +# mainsail lift drag and lift coefficient (high). first row is awa +0.01379,,,,,,,,, +0.00000,7.0000,9.0000,12.0000,28.0000,60.0000,90.0000,120.0000,150.0000,180.000 +0.03448,0.01724,0.01466,0.01466,0.02586,0.11302,0.38250,0.96888,1.31578,1.34483 +0.00000,0.94828,1.13793,1.25000,1.42681,1.38319,1.26724,0.93103,0.38793,-0.11207 \ No newline at end of file diff --git a/dat/orc/main_low.dat b/dat/orc/main_low.dat new file mode 100644 index 0000000..2784d4f --- /dev/null +++ b/dat/orc/main_low.dat @@ -0,0 +1,5 @@ +# mainsail lift drag and lift coefficient (low performance rig). first row is awa +0.01379,,,,,,,,, +0.00000,7.0000,9.0000,12.0000,28.0000,60.0000,90.0000,120.0000,150.0000,180.000 +0.04300,0.02600,0.02300,0.02300,0.03300,0.11302,0.38250,0.96888,1.31578,1.34483 +0.00000,0.86200,1.05200,1.16400,1.34700,1.23900,1.12500,0.83800,0.29600,-0.11207 diff --git a/dat/orc/sym_kite.dat b/dat/orc/sym_kite.dat new file mode 100644 index 0000000..dd45e31 --- /dev/null +++ b/dat/orc/sym_kite.dat @@ -0,0 +1,5 @@ +# symmetric spinnaker lift and drag coefficients (ORC VPP). first row is awa +0.02639,,,,,,,,,,, +0.0000,28.000,41.000,50.000,60.000,67.000,75.000,100.000,115.000,130.000,150.000,180.000 +0.0000,0.21300,0.32100,0.42500,0.58700,0.59800,0.61900,0.85000,0.91100,0.93500,0.93500,0.93500 +0.0000,0.00000,0.97800,1.24100,1.45400,1.45600,1.43700,1.19000,0.95100,0.70600,0.42500,0.00000 diff --git a/src/SailMod.py b/src/SailMod.py index 0e286d2..95fa8d3 100644 --- a/src/SailMod.py +++ b/src/SailMod.py @@ -1,32 +1,118 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- -import numpy as np +__author__ = "Marin Lauber" +__copyright__ = "Copyright 2020, Marin Lauber" +__license__ = "GPL" +__version__ = "1.0.1" +__email__ = "M.Lauber@soton.ac.uk" + import matplotlib.pyplot as plt -from scipy.interpolate import Akima1DInterpolator +import numpy as np +from scipy import interpolate + + +SAIL_TYPES = { + "main": "main", + "main_low": "main_low", + "jib": "jib", + "jib_low": "jib_low", + "kite": "kite", + "sym_kite": "sym_kite", + "asym_cl_kite": "asym_cl_kite", + "asym_pole_kite": "asym_pole_kite", +} + class Sail(object): - def __init__(self, name, type, area, vce, up=True): + def __init__(self, name, type, area, vce, up=True, data_source="orc", + cl_data=None, cd_data=None, sail_type=None): + """ + Base sail class. + Parameters + ---------- + name : str + Sail identifier (e.g. "J1", "A2"). + type : str + Sail type, used to load coefficient data from ``dat/.dat``. + One of ``"main"``, ``"jib"``, or ``"kite"``. + area : float + Sail area (m^2). + vce : float + Vertical centre of effort above deck (m). + up : bool, optional + Whether this is an upwind sail. Default is True. + data_source : str, optional + Coefficient data source directory under ``dat/``. Default "orc". + cl_data : dict, optional + User-provided CL data: ``{"awa": [...], "values": [...]}``. + cd_data : dict, optional + User-provided CD data: ``{"awa": [...], "values": [...]}``. + sail_type : str, optional + Override for the coefficient data file name. E.g. ``"main_low"``, + ``"sym_kite"``, ``"asym_cl_kite"``, ``"asym_pole_kite"``. + If None, uses *type*. + """ self.name = name self.type = type self.area = area self.vce = vce + # Determine which data file to load + coeff_file = sail_type if sail_type is not None else self.type # get sails coefficients - self._build_interp_func(self.type) + if cl_data is not None and cd_data is not None: + self._build_interp_func(coeff_file, data_source=data_source) + self._build_interp_from_arrays(cl_data, cd_data) + else: + self._build_interp_func(coeff_file, data_source=data_source) self.bk = 1.0 # always valid for main, only AWA<135 for jib self.up = up # is that an upwind sail? - def _build_interp_func(self, fname): - """ - build interpolation function and returns it in a list + def _build_interp_func(self, fname, data_source="orc"): + """Build cubic B-spline interpolation functions for CL and CD. + + Falls back to linear (k=1) if fewer than 4 data points are available. + Tries ``dat/{data_source}/{fname}.dat`` first, then ``dat/{fname}.dat``. """ - a = np.genfromtxt("dat/" + fname + ".dat", delimiter=",", skip_header=1) + import os + path = os.path.join("dat", data_source, fname + ".dat") + if not os.path.exists(path): + path = os.path.join("dat", fname + ".dat") + a = np.genfromtxt(path, delimiter=",", skip_header=1) self.kp = a[0, 0] - # linear for now, this is not good, might need to polish data outside - self.interp_cd = Akima1DInterpolator(a[1, :], a[2, :]) - self.interp_cl = Akima1DInterpolator(a[1, :], a[3, :]) + # Filter NaN values (trailing commas in CSV create NaNs) + mask = ~(np.isnan(a[1, :]) | np.isnan(a[2, :]) | np.isnan(a[3, :])) + x = a[1, mask] + cd = a[2, mask] + cl = a[3, mask] + k = 3 if len(x) >= 4 else 1 + self.interp_cd = interpolate.make_interp_spline(x, cd, k=k) + self.interp_cd.extrapolate = True + self.interp_cl = interpolate.make_interp_spline(x, cl, k=k) + self.interp_cl.extrapolate = True + + def _build_interp_from_arrays(self, cl_data, cd_data): + """Build interpolation from user-provided coefficient arrays. + + Parameters + ---------- + cl_data : dict + {"awa": [...], "values": [...]} for lift coefficients. + cd_data : dict + {"awa": [...], "values": [...]} for drag coefficients. + """ + cl_awa = np.array(cl_data["awa"]) + cl_vals = np.array(cl_data["values"]) + cd_awa = np.array(cd_data["awa"]) + cd_vals = np.array(cd_data["values"]) + k_cl = 3 if len(cl_awa) >= 4 else 1 + k_cd = 3 if len(cd_awa) >= 4 else 1 + self.interp_cl = interpolate.make_interp_spline(cl_awa, cl_vals, k=k_cl) + self.interp_cl.extrapolate = True + self.interp_cd = interpolate.make_interp_spline(cd_awa, cd_vals, k=k_cd) + self.interp_cd.extrapolate = True def cl(self, awa): awa = max(0, min(awa, 180)) @@ -36,6 +122,9 @@ def cd(self, awa): awa = max(0, min(awa, 180)) return self.interp_cd(awa) + def measure(self, rfm, ftj): + """Update sail dimensions for current reef/furl state.""" + def debbug_coeffs(self, N=256): awa = np.linspace(0, 180, N) coeffs = np.empty((N, 2)) @@ -49,46 +138,31 @@ def debbug_coeffs(self, N=256): class Main(Sail): - def __init__(self, name, P, E, Roach, BAD): + def __init__(self, name, P, E, Roach, BAD, data_source="orc", + cl_data=None, cd_data=None, sail_type=None): """ - Initialize mainsail - - This function initializes an object of class Main which inherits the class Sail. - It calculates the area, the Vertical Center of Effort (vce), - sets CE = 1 and calls the super class constructor. + Initialize mainsail. Parameters ---------- - name : string - Of the sail - - P : Float - Height of the Mainsail in meters - - E: Float - Length (Foot) of the Mainsail in meters - - Roach: Float - Percentage by which the triangular area is increased in order to obtain the mainsail area. - This is area behind the line from clew to head. - To get this number you have to calculate Mainsail_area / (P*E/2) -1 - - BAD: Float - Boom Above Deck: Distance between boom and Deck in meters - - Returns - ------- - Main - Object of type Main( Sail ) - - See Also - -------- - Jib( Sail ) - - Examples - -------- - >>> Main("MN1", P=16.60, E=5.60, Roach=0.1, BAD=1.0) - + name : str + Sail identifier. + P : float + Height of the Mainsail in meters. + E : float + Length (Foot) of the Mainsail in meters. + Roach : float + Roach factor (Mainsail_area / (P*E/2) - 1). + BAD : float + Boom Above Deck in meters. + data_source : str, optional + Coefficient data source. Default "orc". + cl_data : dict, optional + User-provided CL data. + cd_data : dict, optional + User-provided CD data. + sail_type : str, optional + Coefficient variant: ``"main"`` (default) or ``"main_low"``. """ self.name = name self.type = "main" @@ -98,10 +172,23 @@ def __init__(self, name, P, E, Roach, BAD): self.BAD = BAD self.area0 = 0.5 * P * E * (1 + self.roach) self.vce = P / 3.0 * (1 + self.roach) + self.BAD - super().__init__(self.name, self.type, self.area0, self.vce) + super().__init__(self.name, self.type, self.area0, self.vce, + data_source=data_source, cl_data=cl_data, cd_data=cd_data, + sail_type=sail_type) self.measure() def measure(self, rfm=1, ftj=1): + """ + Update mainsail dimensions for reef state. + + Parameters + ---------- + rfm : float + Reef factor for mainsail (0 to 1). 1 = fully unreefed. + ftj : float + Furl factor for jib (unused for mainsail, present for interface + compatibility). + """ self.P_r = self.P*rfm self.vce = self.P_r / 3.0 * (1 + self.roach) + self.BAD self.area = self.area0*rfm**2 @@ -109,7 +196,32 @@ def measure(self, rfm=1, ftj=1): class Jib(Sail): - def __init__(self, name, I, J, LPG, HBI): + def __init__(self, name, I, J, LPG, HBI, data_source="orc", + cl_data=None, cd_data=None, sail_type=None): + """ + Headsail (jib/genoa). + + Parameters + ---------- + name : str + Sail identifier (e.g. "J1"). + I : float + Forestay height (m). + J : float + Base of the foretriangle (m). + LPG : float + Luff perpendicular (m). + HBI : float + Height of the jib tack above deck (m). + data_source : str, optional + Coefficient data source. Default "orc". + cl_data : dict, optional + User-provided CL data. + cd_data : dict, optional + User-provided CD data. + sail_type : str, optional + Coefficient variant: ``"jib"`` (default) or ``"jib_low"``. + """ self.name = name self.type = "jib" self.I = I @@ -119,27 +231,72 @@ def __init__(self, name, I, J, LPG, HBI): self.HBI = HBI self.area = 0.5 * I * max(J, LPG) self.vce = I / 3.0 + HBI - super().__init__(self.name, self.type, self.area, self.vce) + super().__init__(self.name, self.type, self.area, self.vce, + data_source=data_source, cl_data=cl_data, cd_data=cd_data, + sail_type=sail_type) self.measure() def measure(self, rfm=1, ftj=1): + """ + Update jib dimensions for furl state. + + Parameters + ---------- + rfm : float + Reef factor for mainsail (unused for jib, present for interface + compatibility). + ftj : float + Furl factor for jib (0 to 1). 0 = fully unfurled. + """ self.LPG_r = self.LPG*ftj self.IG_r = self.IG*ftj self.area = 0.5 * self.I * max(self.J, self.LPG_r) class Kite(Sail): - def __init__(self, name, area, vce): + def __init__(self, name, area, vce, data_source="orc", + cl_data=None, cd_data=None, sail_type=None): + """ + Spinnaker or asymmetric downwind sail. + + Parameters + ---------- + name : str + Sail identifier (e.g. "A2", "A5"). + area : float + Sail area (m^2). + vce : float + Vertical centre of effort above deck (m). + data_source : str, optional + Coefficient data source. Default "orc". + cl_data : dict, optional + User-provided CL data. + cd_data : dict, optional + User-provided CD data. + sail_type : str, optional + Coefficient variant: ``"kite"`` (default), ``"sym_kite"``, + ``"asym_cl_kite"``, or ``"asym_pole_kite"``. + """ self.name = name self.type = "kite" self.area = area self.min_area = self.area self.vce = vce - super().__init__(self.name, self.type, self.area, self.vce, up=False) + super().__init__(self.name, self.type, self.area, self.vce, up=False, + data_source=data_source, cl_data=cl_data, cd_data=cd_data, + sail_type=sail_type) self.measure() def measure(self, rfm=1, ftj=1): pass +# class Kite(Sail): +# def __init__(self, SLU, SLE, SFL, SHW, ISP, J, SPL): +# self.type = 'kite' +# area_d = 1.14*np.sqrt(ISP**2+J**2)*max(SPL,J) # only for symm kite +# self.area = max(area_d, 0.5*(SLU+SLE)*(SFL+4*SHW)/6.) +# self.vce = 0.565*ISP # above base of I +# super().__init__(self.type, self.area, self.vce, up=False) + if __name__=="__main__": pass diff --git a/src/YachtMod.py b/src/YachtMod.py index 0905d67..ac2ccc2 100644 --- a/src/YachtMod.py +++ b/src/YachtMod.py @@ -1,14 +1,43 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- +__author__ = "Marin Lauber" +__copyright__ = "Copyright 2020, Marin Lauber" +__license__ = "GPL" +__version__ = "1.0.1" +__email__ = "M.Lauber@soton.ac.uk" + import numpy as np -from src.UtilsMod import build_interp_func,json_read,json_write from scipy import interpolate +from src.UtilsMod import build_interp_func, json_read, json_write + + +def _zero_cr(fn): + """Zero residuary resistance (for appendages without Cr data).""" + return 0.0 + + class Appendage(object): def __init__(self, type, chord, area, span, vol, ce): """ - + Base class for underwater appendages (keels, rudders, bulbs). + + Parameters + ---------- + type : str + Appendage type (``"keel"``, ``"rudder"``, or ``"bulb"``). + Controls residuary resistance coefficient lookup. + chord : float + Mean chord length (m). + area : float + Planform (wetted) area (m^2). + span : float + Appendage span (m). Set to 0 for non-lifting bodies (bulbs). + vol : float + Displaced volume (m^3). Used for residuary resistance calculation. + ce : float + Centre of effort — depth below waterline (m, positive downward). """ self.type = type self.chord = chord @@ -24,15 +53,12 @@ def __init__(self, type, chord, area, span, vol, ce): self.cla = self.dclda * self.area self.teff = 1.8 * self.span # no residuary resistance - self._interp_cr = lambda fn: 0.0 + self._interp_cr = _zero_cr if self.type == "keel": self._interp_cr = build_interp_func("rrk") if self.type == "bulb": self._interp_cr = build_interp_func("rrk", i=2) - def _cl(self, leeway): - return self.dclda * np.radians(leeway) - def _cr(self, fn): return self._interp_cr(max(0.0, min(fn, 0.6))) @@ -50,6 +76,21 @@ def _print(self): class Keel(Appendage): def __init__(self, Cu=1, Cl=1, Span=0): + """ + Trapezoidal keel appendage. + + Computes area, mean chord, span, volume, and centre of effort from + the root and tip chord lengths assuming a trapezoidal planform. + + Parameters + ---------- + Cu : float, optional + Root (upper) chord length (m). Default is 1. + Cl : float, optional + Tip (lower) chord length (m). Default is 1. + Span : float, optional + Keel span (m). Default is 0. + """ self.type = "keel" self.cu = Cu self.cl = Cl @@ -64,6 +105,18 @@ def __init__(self, Cu=1, Cl=1, Span=0): class Rudder(Appendage): def __init__(self, Cu=1, Cl=1, Span=0): + """ + Trapezoidal rudder appendage. + + Parameters + ---------- + Cu : float, optional + Root (upper) chord length (m). Default is 1. + Cl : float, optional + Tip (lower) chord length (m). Default is 1. + Span : float, optional + Rudder span (m). Default is 0. + """ self.type = "rudder" self.cu = Cu self.cl = Cl @@ -82,6 +135,23 @@ def _Ksff(self, phi): class Bulb(Appendage): def __init__(self, Chord, area, vol, CG): + """ + Keel bulb appendage. + + A non-lifting body attached to the keel tip. Contributes wetted + surface area and residuary resistance but no side force. + + Parameters + ---------- + Chord : float + Bulb chord length (m). + area : float + Wetted surface area (m^2). + vol : float + Displaced volume (m^3). + CG : float + Centre of gravity depth below waterline (m). + """ self.type = "bulb" self.chord = Chord self.area = area @@ -91,20 +161,98 @@ def __init__(self, Chord, area, vol, CG): super().__init__(self.type, self.chord, self.area, 0.0, self.vol, self.ce) +class ShortKeel(Appendage): + def __init__(self, Length=1.0, Depth=0.5, Tc_ratio=0.15): + """ + Short/integrated keel appendage. + + For traditional or hull-integrated keels with low aspect ratio. + Uses the Jones low-AR lift formula instead of Prandtl correction, + higher form drag, and zero appendage residuary resistance (hull + resistance surfaces capture it). + + Parameters + ---------- + Length : float + Fore-aft keel length along hull bottom (m). + Depth : float + Keel depth below canoe body (m). + Tc_ratio : float + Average thickness-to-chord ratio. Default 0.15. + """ + self.type = "short_keel" + self.length = Length + self.depth = Depth + self.tc_ratio = Tc_ratio + self.span = Depth + self.chord = Length + self.area = Length * Depth + self.ce = -Depth / 2.0 + self.cof = 1.4 + 0.5 * Tc_ratio + self.vol = Length * Depth * Length * Tc_ratio * 0.7 + super().__init__(self.type, self.chord, self.area, self.span, self.vol, self.ce) + # Override Prandtl lift model with Jones low-AR formula + ar = self.Ar + self.dclda = np.pi * ar / 2.0 + self.cla = self.dclda * self.area + self.teff = 1.5 * self.span + + class Yacht(object): def __init__(self, Name, Lwl, Vol, Bwl, Tc, WSA, Tmax, - Amax, Mass, Loa, Boa, Ff, Fa, App=[], Sails=[]): + Amax, Mass, Loa, Boa, Ff, Fa, App=[], Sails=[], GZ=None, crew_weight=None, + roughness=150e-6, Hs=0.0, Ts=0.0, wave_direction=None): """ - Name : Name of particular design - Lwl : waterline length (m) - Vol : volume of canoe body (m^3) - Bwl : waterline beam (m) - Tc : Canoe body draft (m) - WSA : Wetted surface area (m^2) - Tmax : Maximum draft of yacht (m) - Amax : Max section area (m^2) - Mass : total mass of the yacht (kg) - App : appendages (Appendages object as list, i.e [Keel(...)] ) + Yacht hull and rig definition. + + Parameters + ---------- + Name : str + Name of the yacht design. + Lwl : float + Waterline length (m). + Vol : float + Displaced volume of the canoe body (m^3). + Bwl : float + Waterline beam (m). + Tc : float + Canoe body draft (m). + WSA : float + Wetted surface area of the canoe body (m^2). + Tmax : float + Maximum draft including keel (m). + Amax : float + Maximum cross-section area (m^2). + Mass : float + Total displacement mass including keel (kg). + Loa : float + Length overall (m). + Boa : float + Beam overall (m). + Ff : float + Freeboard height at the bow (m). + Fa : float + Freeboard height at the stern (m). + App : list of Appendage, optional + Underwater appendages (keels, rudders, bulbs). Default is []. + Sails : list of Sail, optional + Sail inventory. Default is []. + GZ : dict, optional + Righting arm curve as ``{"Heel": [...], "GZ": [...]}``. + Heel in degrees, GZ in metres. If *None*, loads from + ``righting_moment.json`` (backward compatible). + crew_weight : float, optional + Total crew weight (kg). If *None*, uses empirical formula + ``25.8 * Lwl ** 1.4262``. + roughness : float, optional + Mean hull roughness height (m). Default 150e-6 (150 μm, + new antifouling paint). Set to 0 for a smooth hull. + Hs : float, optional + Significant wave height (m). Default 0.0 (flat water). + Ts : float, optional + Modal wave period (s). Default 0.0. + wave_direction : float or None, optional + Wave direction (degrees). If None, waves align with wind. """ self.g = 9.81 self.Name = Name @@ -125,7 +273,7 @@ def __init__(self, Name, Lwl, Vol, Bwl, Tc, WSA, Tmax, self.Rm4 = 0.43 * self.tmax # standard crew weight - self.cw = 25.8 * self.l ** 1.4262 + self.cw = crew_weight if crew_weight is not None else 25.8 * self.l ** 1.4262 self.carm = 0.8 * self.bmax # must be average of rail where crew sits # rough estimate of projected area of the hull @@ -133,10 +281,19 @@ def __init__(self, Name, Lwl, Vol, Bwl, Tc, WSA, Tmax, self.cla = self.area_proj * 2 * np.pi / (1.0 + 0.5 * self.area_proj / self.tc) self.teff = 2.07 * self.tc + # hull roughness and wave parameters + self.roughness = roughness + self.Hs = Hs + self.Ts = Ts + self.wave_direction = wave_direction + # appendages object self.appendages = App self.sails = Sails + # GZ data (righting arm curve) + self._gz_data = GZ + # righting moment interpolation function self._interp_rm = self._build_rm_interp() @@ -145,7 +302,10 @@ def __init__(self, Name, Lwl, Vol, Bwl, Tc, WSA, Tmax, def _build_rm_interp(self): - a = json_read('righting_moment') + if self._gz_data is not None: + a = self._gz_data + else: + a = json_read('righting_moment') return interpolate.interp1d(np.array(a["Heel"]), np.array(a["GZ"]), kind="linear", fill_value="extrapolate") diff --git a/src/api.py b/src/api.py index 7d48b23..56a3867 100644 --- a/src/api.py +++ b/src/api.py @@ -13,7 +13,7 @@ sys.path.append(os.path.realpath(".")) from src.SailMod import Jib, Kite, Main from src.VPPMod import VPP -from src.YachtMod import Keel, Rudder, Yacht +from src.YachtMod import Keel, Rudder, ShortKeel, Yacht app = Flask(__name__) @@ -28,16 +28,34 @@ def ping(): def data_to_vpp(data: Dict[str, Any]) -> VPP: - keel = Keel( - Cu=float(data["keel"]["Cu"]), - Cl=float(data["keel"]["Cl"]), - Span=float(data["keel"]["Span"]) - ) + keel_data = data["keel"] + keel_type = keel_data.get("type", "fin") + # Also detect from keys if type is missing or inconsistent + if keel_type == "short" or "Length" in keel_data: + keel = ShortKeel( + Length=float(keel_data["Length"]), + Depth=float(keel_data["Depth"]), + Tc_ratio=float(keel_data.get("Tc_ratio", 0.15)), + ) + else: + keel = Keel( + Cu=float(keel_data["Cu"]), + Cl=float(keel_data["Cl"]), + Span=float(keel_data["Span"]), + ) rudder = Rudder( Cu=float(data["rudder"]["Cu"]), Cl=float(data["rudder"]["Cu"]), Span=float(data["rudder"]["Span"]) ) + # Environment parameters + roughness = float(data.get("roughness", 150e-6)) + Hs = float(data.get("Hs", 0.0)) + Ts = float(data.get("Ts", 0.0)) + wave_direction = data.get("wave_direction") + if wave_direction is not None: + wave_direction = float(wave_direction) + yacht = Yacht( Name=data["yacht"]["Name"], Lwl=float(data["yacht"]["Lwl"]), @@ -52,6 +70,10 @@ def data_to_vpp(data: Dict[str, Any]) -> VPP: Fa=float(data["yacht"]["Fa"]), Boa=float(data["yacht"]["Boa"]), Loa=float(data["yacht"]["Loa"]), + roughness=roughness, + Hs=Hs, + Ts=Ts, + wave_direction=wave_direction, App=[keel, rudder], Sails=[ Main( @@ -60,6 +82,10 @@ def data_to_vpp(data: Dict[str, Any]) -> VPP: E=float(data["main"]["E"]), Roach=float(data["main"]["Roach"]), BAD=float(data["main"]["BAD"]), + data_source=data.get("data_source", "orc"), + cl_data=data["main"].get("cl_data"), + cd_data=data["main"].get("cd_data"), + sail_type=data["main"].get("sail_type"), ), Jib( name=data["jib"]["Name"], @@ -67,11 +93,19 @@ def data_to_vpp(data: Dict[str, Any]) -> VPP: J=float(data["jib"]["J"]), LPG=float(data["jib"]["LPG"]), HBI=float(data["jib"]["HBI"]), + data_source=data.get("data_source", "orc"), + cl_data=data["jib"].get("cl_data"), + cd_data=data["jib"].get("cd_data"), + sail_type=data["jib"].get("sail_type"), ), Kite( name=data["kite"]["Name"], area=float(data["kite"]["area"]), vce=float(data["kite"]["vce"]), + data_source=data.get("data_source", "orc"), + cl_data=data["kite"].get("cl_data"), + cd_data=data["kite"].get("cd_data"), + sail_type=data["kite"].get("sail_type"), ), ], ) @@ -81,17 +115,26 @@ def data_to_vpp(data: Dict[str, Any]) -> VPP: tws_range=np.array(data["tws_range"]), twa_range=np.array(data["twa_range"]), ) - return vpp + return vpp, data.get("method", "iterative") + @app.route("/api/vpp/", methods=["POST"]) def makevppresults(): data = request.get_json() - - # TODO: Support multiple implementations of different sails: require API design - # TODO: Error handling incorrect ranges - - vpp = data_to_vpp(data) - vpp.run() + if data is None: + return jsonify({"error": "Request body must be valid JSON."}), 400 + + try: + vpp, method = data_to_vpp(data) + except (KeyError, TypeError, ValueError) as e: + logging.warning("Invalid VPP input: %s", e) + return jsonify({"error": f"Invalid input: {e}"}), 400 + + try: + vpp.run(verbose=True, method=method) + except Exception as e: + logging.exception("VPP simulation failed") + return jsonify({"error": f"Simulation failed: {e}"}), 500 return jsonify(vpp.results()) diff --git a/tests/test_api.py b/tests/test_api.py index 53aab60..f1e068a 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -4,6 +4,9 @@ from src.api import app +HEADERS = {"content-type": "application/json", "Accept-Charset": "UTF-8"} + + def test_ping_route(): client = app.test_client() response = client.get("/ping") @@ -11,29 +14,27 @@ def test_ping_route(): assert response.data.decode("utf-8") == "Pong! The server is up and running." -def make_yd41(): - yacht = dict( - { - "Name": "YD41", - "Lwl": 11.90, - "Vol": 6.05, - "Bwl": 3.18, - "Tc": 0.4, - "WSA": 28.20, - "Tmax": 2.30, - "Amax": 1.051, - "Mass": 6500, - "Ff": 1.5, - "Fa": 1.5, - "Boa": 4.2, - "Loa": 12.5, - } - ) - keel = dict({"Cu": 1.00, "Cl": 0.78, "Span": 1.90}) - rudder = dict({"Cu": 0.48, "Cl": 0.22, "Span": 1.15}) - main = dict({"Name": "MN1", "P": 16.60, "E": 5.60, "Roach": 0.1, "BAD": 1.0}) - jib = dict({"Name": "J1", "I": 16.20, "J": 5.10, "LPG": 5.40, "HBI": 1.8}) - kite = dict({"Name": "A2", "area": 150.0, "vce": 9.55}) +def make_yd41(**overrides): + yacht = { + "Name": "YD41", + "Lwl": 11.90, + "Vol": 6.05, + "Bwl": 3.18, + "Tc": 0.4, + "WSA": 28.20, + "Tmax": 2.30, + "Amax": 1.051, + "Mass": 6500, + "Ff": 1.5, + "Fa": 1.5, + "Boa": 4.2, + "Loa": 12.5, + } + keel = {"Cu": 1.00, "Cl": 0.78, "Span": 1.90} + rudder = {"Cu": 0.48, "Cl": 0.22, "Span": 1.15} + main = {"Name": "MN1", "P": 16.60, "E": 5.60, "Roach": 0.1, "BAD": 1.0} + jib = {"Name": "J1", "I": 16.20, "J": 5.10, "LPG": 5.40, "HBI": 1.8} + kite = {"Name": "A2", "area": 150.0, "vce": 9.55} tws_range = np.arange(4.0, 7.0, 2.0).tolist() twa_range = np.linspace(30.0, 180.0, 5).tolist() @@ -48,17 +49,156 @@ def make_yd41(): "tws_range": tws_range, "twa_range": twa_range, } + d.update(overrides) return d +def post_vpp(data): + client = app.test_client() + return client.post("/api/vpp/", data=json.dumps(data), headers=HEADERS) + + def test_vpp_simulation(): d = make_yd41() + response = post_vpp(d) + assert response.status_code == 200 + + +def test_empty_tws_range_returns_400(): + d = make_yd41(tws_range=[]) + response = post_vpp(d) + assert response.status_code == 400 + assert "empty" in response.json["error"].lower() + + +def test_empty_twa_range_returns_400(): + d = make_yd41(twa_range=[]) + response = post_vpp(d) + assert response.status_code == 400 + assert "empty" in response.json["error"].lower() + + +def test_tws_out_of_range_returns_400(): + d = make_yd41(tws_range=[1.0, 5.0]) + response = post_vpp(d) + assert response.status_code == 400 + assert "outside valid bounds" in response.json["error"] + - json_string = json.dumps(d) - headers = {"content-type": "application/json", "Accept-Charset": "UTF-8"} +def test_tws_above_range_returns_400(): + d = make_yd41(tws_range=[10.0, 40.0]) + response = post_vpp(d) + assert response.status_code == 400 + assert "outside valid bounds" in response.json["error"] + +def test_twa_out_of_range_returns_400(): + d = make_yd41(twa_range=[-10.0, 90.0]) + response = post_vpp(d) + assert response.status_code == 400 + assert "outside valid bounds" in response.json["error"] + + +def test_missing_field_returns_400(): + d = make_yd41() + del d["keel"] + response = post_vpp(d) + assert response.status_code == 400 + assert "error" in response.json + + +def test_invalid_json_returns_400(): client = app.test_client() - response = client.post("/api/vpp/", data=json_string, headers=headers) + response = client.post("/api/vpp/", data="not json", headers=HEADERS) + assert response.status_code == 400 + + +def test_short_keel_with_type_field(): + """Short keel payload with explicit type='short' should succeed.""" + d = make_yd41() + d["keel"] = {"type": "short", "Length": 1.2, "Depth": 0.90, "Tc_ratio": 0.15} + response = post_vpp(d) + assert response.status_code == 200 + + +def test_short_keel_without_type_field(): + """Short keel payload detected from keys alone (no type field).""" + d = make_yd41() + d["keel"] = {"Length": 1.2, "Depth": 0.90, "Tc_ratio": 0.15} + response = post_vpp(d) + assert response.status_code == 200 + + +def test_fin_keel_with_type_field(): + """Fin keel payload with explicit type='fin' should succeed.""" + d = make_yd41() + d["keel"] = {"type": "fin", "Cu": 1.00, "Cl": 0.78, "Span": 1.90} + response = post_vpp(d) + assert response.status_code == 200 + + +def test_api_5dof_method(): + """API accepts method='5dof' and returns results.""" + d = make_yd41() + d["method"] = "5dof" + response = post_vpp(d) + assert response.status_code == 200 + results = np.array(response.json["results"]) + assert np.any(results[:, :, :, 0] > 0), "5-DOF should produce non-zero speeds" + + +def test_api_data_source(): + """API accepts data_source parameter.""" + d = make_yd41() + d["data_source"] = "orc" + response = post_vpp(d) + assert response.status_code == 200 + + +def test_api_sail_type_sym_kite(): + """API accepts sail_type in kite section and produces results.""" + d = make_yd41() + d["kite"]["sail_type"] = "sym_kite" + response = post_vpp(d) + assert response.status_code == 200 + results = np.array(response.json["results"]) + assert np.any(results[:, :, :, 0] > 0) + + +def test_api_sail_type_low_performance(): + """API accepts low-performance sail_type for main and jib.""" + d = make_yd41() + d["main"]["sail_type"] = "main_low" + d["jib"]["sail_type"] = "jib_low" + response = post_vpp(d) + assert response.status_code == 200 + results = np.array(response.json["results"]) + assert np.any(results[:, :, :, 0] > 0) + + +def test_api_roughness(): + """API accepts roughness parameter and rough hull is slower.""" + d_smooth = make_yd41(roughness=0.0) + d_rough = make_yd41(roughness=500e-6) + r_smooth = post_vpp(d_smooth) + r_rough = post_vpp(d_rough) + assert r_smooth.status_code == 200 + assert r_rough.status_code == 200 + speeds_smooth = np.array(r_smooth.json["results"])[:, :, :, 0].max() + speeds_rough = np.array(r_rough.json["results"])[:, :, :, 0].max() + assert speeds_smooth > speeds_rough, "Rough hull should be slower" + + +def test_api_wave_params(): + """API accepts Hs and Ts parameters.""" + d = make_yd41(Hs=1.0, Ts=6.0) + response = post_vpp(d) + assert response.status_code == 200 + +def test_api_wave_direction(): + """API accepts wave_direction parameter.""" + d = make_yd41(Hs=1.0, Ts=6.0, wave_direction=45.0) + response = post_vpp(d) assert response.status_code == 200 diff --git a/tests/test_yacht.py b/tests/test_yacht.py new file mode 100644 index 0000000..dda3403 --- /dev/null +++ b/tests/test_yacht.py @@ -0,0 +1,79 @@ +import numpy as np +import pytest +from src.YachtMod import Yacht, Keel, Rudder, ShortKeel +from src.SailMod import Main, Jib + + +def _minimal_yacht(**overrides): + """Create a minimal Yacht for testing with sensible defaults.""" + defaults = dict( + Name="TestYacht", Lwl=7.01, Vol=1.95, Bwl=1.70, Tc=0.45, + WSA=11.5, Tmax=1.35, Amax=0.38, Mass=2000, Loa=9.90, Boa=1.98, + Ff=0.75, Fa=0.55, + App=[Keel(Cu=0.70, Cl=0.45, Span=0.90), Rudder(Cu=0.32, Cl=0.18, Span=0.75)], + Sails=[Main("MN1", P=10.80, E=3.30, Roach=0.1, BAD=0.80), + Jib("J1", I=8.50, J=2.70, LPG=2.70, HBI=0.50)], + ) + defaults.update(overrides) + return Yacht(**defaults) + + +def test_yacht_accepts_gz_parameter(): + """Yacht should accept an optional gz dict to override the global file.""" + gz = {"Heel": [0, 10, 20, 30], "GZ": [0.0, 0.12, 0.23, 0.31]} + yacht = _minimal_yacht(GZ=gz) + rm_10 = yacht._get_RmH(10.0) + expected = 0.12 * 2000 * 9.81 + assert abs(rm_10 - expected) < 1.0 + + +def test_yacht_falls_back_to_file_when_no_gz(): + """When no GZ parameter given, should still load from file (backward compat).""" + yacht = _minimal_yacht() + rm_10 = yacht._get_RmH(10.0) + assert rm_10 > 0 + + +def test_yacht_accepts_crew_weight(): + """Yacht should accept an optional crew_weight to override the empirical formula.""" + yacht = _minimal_yacht(crew_weight=240.0) + assert yacht.cw == 240.0 + + +def test_yacht_default_crew_weight(): + """Without crew_weight param, should use empirical formula.""" + yacht = _minimal_yacht() + expected = 25.8 * 7.01 ** 1.4262 + assert abs(yacht.cw - expected) < 0.1 + + +# --- ShortKeel-specific unit tests --- + +def test_short_keel_jones_lift_formula(): + """ShortKeel dclda should match Jones low-AR formula: pi*AR/2.""" + sk = ShortKeel(Length=1.2, Depth=0.90, Tc_ratio=0.15) + ar = sk.span / sk.area # = 0.90 / (1.2 * 0.90) + expected = np.pi * ar / 2.0 + assert abs(sk.dclda - expected) < 1e-10, f"dclda={sk.dclda}, expected={expected}" + + +def test_short_keel_no_appendage_residuary(): + """ShortKeel should return zero appendage residuary resistance.""" + sk = ShortKeel(Length=1.2, Depth=0.90, Tc_ratio=0.15) + for fn in [0.0, 0.2, 0.4, 0.6]: + assert sk._cr(fn) == 0.0, f"_cr({fn}) should be 0.0 for short_keel" + + +def test_short_keel_lower_lift_than_fin(): + """A ShortKeel with equivalent area should produce less lift than a fin Keel.""" + sk = ShortKeel(Length=1.2, Depth=0.90, Tc_ratio=0.15) + # Fin keel with similar area: chord ~0.575, span 0.90 -> area ~0.5175 + # Use root/tip that give similar area to short keel + fk = Keel(Cu=1.40, Cl=1.00, Span=0.90) # area = 1.08, same span + # At the same leeway, short keel should generate less lift coefficient + leeway_rad = np.radians(5.0) + cl_short = sk.dclda * leeway_rad + cl_fin = fk.dclda * leeway_rad + assert cl_short < cl_fin, ( + f"ShortKeel cl={cl_short:.4f} should be less than Keel cl={cl_fin:.4f}" + )