1# imo.py - functions for handling IMO numbers 2# coding: utf-8 3# 4# Copyright (C) 2015 Arthur de Jong 5# 6# This library is free software; you can redistribute it and/or 7# modify it under the terms of the GNU Lesser General Public 8# License as published by the Free Software Foundation; either 9# version 2.1 of the License, or (at your option) any later version. 10# 11# This library is distributed in the hope that it will be useful, 12# but WITHOUT ANY WARRANTY; without even the implied warranty of 13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 14# Lesser General Public License for more details. 15# 16# You should have received a copy of the GNU Lesser General Public 17# License along with this library; if not, write to the Free Software 18# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 19# 02110-1301 USA 20 21"""IMO number (International Maritime Organization number). 22 23A number used to uniquely identify ships (the hull) for purposes of 24registering owners and management companies. The ship identification number 25consists of a six-digit sequentially assigned number and a check digit. The 26number is usually prefixed with "IMO". 27 28Note that there seem to be a large number of ships with an IMO that does not 29have a valid check digit or even have a different length. 30 31>>> validate('IMO 9319466') 32'9319466' 33>>> validate('IMO 8814275') 34'8814275' 35>>> validate('8814274') 36Traceback (most recent call last): 37 ... 38InvalidChecksum: ... 39>>> format('8814275') 40'IMO 8814275' 41""" 42 43from stdnum.exceptions import * 44from stdnum.util import clean, isdigits 45 46 47def compact(number): 48 """Convert the number to the minimal representation. This strips the 49 number of any valid separators and removes surrounding whitespace.""" 50 number = clean(number, ' ').upper().strip() 51 if number.startswith('IMO'): 52 number = number[3:] 53 return number 54 55 56def calc_check_digit(number): 57 """Calculate the check digits for the number.""" 58 return str(sum(int(n) * (7 - i) for i, n in enumerate(number[:6])) % 10) 59 60 61def validate(number): 62 """Check if the number provided is valid. This checks the length and 63 check digit.""" 64 number = compact(number) 65 if not isdigits(number): 66 raise InvalidFormat() 67 if len(number) != 7: 68 raise InvalidLength() 69 if calc_check_digit(number[:-1]) != number[-1]: 70 raise InvalidChecksum() 71 return number 72 73 74def is_valid(number): 75 """Check if the number provided is valid. This checks the length and 76 check digit.""" 77 try: 78 return bool(validate(number)) 79 except ValidationError: 80 return False 81 82 83def format(number): 84 """Reformat the number to the standard presentation format.""" 85 return 'IMO ' + compact(number) 86