Skip to content
Vector2D.py 12.4 KiB
Newer Older
####################################################################################################
#
# PyValentina - A Python implementation of Valentina Pattern Drafting Software
Fabrice Salvaire's avatar
Fabrice Salvaire committed
# Copyright (C) 2017 Fabrice Salvaire
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 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
#
# 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.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
####################################################################################################

####################################################################################################

import math

import numpy as np

####################################################################################################

from Valentina.Math.Functions import sign, trignometric_clamp #, is_in_trignometric_range

####################################################################################################

class Vector2DBase(object):

    __data_type__ = None

    #######################################

    def __init__(self, *args):

        """
        Example of usage::

          Vector(1, 3)
          Vector((1, 3))
          Vector([1, 3])
          Vector(iterable)
          Vector(vector)

        """

        array = self._check_arguments(args)

        # Fixme: self._v
        # call __getitem__ once
        self.v = np.array(array[:2], dtype=self.__data_type__)

    ##############################################

    def _check_arguments(self, args):

        size = len(args)
        if size == 1:
            array = args[0]
        elif size == 2:
            array = args
        else:
            raise ValueError("More than 2 arguments where given")

        if not (np.iterable(array) and len(array) == 2):
            raise ValueError("Argument must be iterable and of length 2")

        return array

    #######################################

    @property
    def x(self):
        return self.__data_type__(self.v[0])

    @property
    def y(self):
        return self.__data_type__(self.v[1])

    @x.setter
    def set_x(self, x):
        self.v[0] = x

    @y.setter
    def set_y(self, y):
        self.v[1] = y

    #######################################

    def copy(self):

        """ Return a copy of self """

        return self.__class__(self.v)

    #######################################

    def __repr__(self):

        # return str(self.__class__) + ' ' + str(self.v)
        return 'Vector ' + str(self.v)

    #######################################

    def __nonzero__(self):

        return bool(self.v.any())

    #######################################

    def __len__(self):

        return 2

    #######################################

    def __iter__(self):

        return iter(self.v)

    #######################################

    def __getitem__(self, a_slice):

        return self.v[a_slice]

    #######################################

    def __setitem__(self, index, value):

        self.v[index] = value

    #######################################

    def __eq__(v1, v2):

        """ self == other """

        # return v1.v == v2.v
        return v1.x == v2.x and v1.y == v2.y

    #######################################

    def __add__(self, other):

        """ Return a new vector equal to the addition of self and other """

        return self.__class__(self.v + other.v)

    #######################################

    def __iadd__(self, other):

        """ Add other to self """

        self.v += other.v

        return self

    #######################################

    def __sub__(self, other):

        """ Return a new vector """

        return self.__class__(self.v - other.v)

    #######################################

    def __isub__(self, other):

        """ Return a new vector equal to the subtraction of self and other """

        self.v -= other.v

        return self

    ##############################################

    def to_int_list(self):

        return [int(x) for x in self.v]

####################################################################################################

class Vector2DInt(Vector2DBase):

    __data_type__ = np.int

####################################################################################################

class Vector2DFloatBase(Vector2DBase):

    __data_type__ = np.float

    #######################################

    def almost_equal(v1, v2, n=7):

        """ self ~= other """

        espilon = 10**(-n)

        return v1.x - v1.x < espilon and v2.y - v2.y < espilon

    #######################################

    def magnitude_square(self):

        """ Return the square of the magnitude of the vector """

        return np.dot(self.v, self.v)

    #######################################

    def magnitude(self):

        """ Return the magnitude of the vector """

        return math.sqrt(self.magnitude_square())

    #######################################

    def orientation(self):

        """ Return the orientation in degree """

        #
        # 2 | 1
        # - + -
        # 4 | 3
        #
        #       | 1    | 2         | 3    | 4         |
        # x     | +    | -         | +    | -         |
        # y     | +    | +         | -    | -         |
        # tan   | +    | -         | -    | +         |
        # atan  | +    | -         | -    | +         |
        # theta | atan | atan + pi | atan | atan - pi |
        #

        if not bool(self):
            raise NameError("Null Vector")
        if self.x == 0:
            return math.copysign(90, self.y)
        elif self.y == 0:
            return 0 if self.x >= 0 else 180
        else:
            orientation = math.degrees(math.atan(self.tan()))
            if self.x < 0:
                if self.y > 0:
                    orientation += 180
                else:
                    orientation -= 180
            return orientation

    #######################################

    def rotate_counter_clockwise(self, angle):

        """ Return a new vector equal to self rotated of angle degree in the counter clockwise
        direction
        """

        radians = math.radians(angle)
        c = math.cos(radians)
        s = math.sin(radians)

        # Fixme: np matrice
        xp = c * self.v[0] -s * self.v[1]
        yp = s * self.v[0] +c * self.v[1]

        return self.__class__((xp, yp))

    #######################################

    def rotate_counter_clockwise_90(self):

        """ Return a new vector equal to self rotated of 90 degree in the counter clockwise
        direction
        """

        xp = -self.v[1]
        yp =  self.v[0]

        return self.__class__((xp, yp))

    #######################################

    def rotate_clockwise_90(self):

        """ Return a new vector equal to self rotated of 90 degree in the clockwise direction
        """

        xp =  self.v[1]
        yp = -self.v[0]

        return self.__class__((xp, yp))

    #######################################

    def rotate_180(self):

        """ Return a new vector equal to self rotated of 180 degree
        """

        # parity
        xp = -self.v[0]
        yp = -self.v[1]

        return self.__class__((xp, yp))

    #######################################

    def tan(self):

        """ Return the tangent """

        # RuntimeWarning: divide by zero encountered in double_scalars
        return self.y / self.x

    #######################################

    def inverse_tan(self):

        """ Return the inverse tangent """

        return self.x / self.y

    #######################################

    def dot(self, other):

        """ Return the dot product of self with other """

        return float(np.dot(self.v, other.v))

    #######################################

    def cross(self, other):

        """ Return the cross product of self with other """

        return float(np.cross(self.v, other.v))

    #######################################

    def is_parallel(self, other):

        """ Self is parallel with other """

        return round(self.cross(other), 7) == 0

    #######################################

    def is_orthogonal(self, other):

        """ Self is orthogonal with other """

        return round(self.dot(other), 7) == 0

    #######################################

    def cos_with(self, direction):

        """ Return the cosinus of self with direction """

        cos = direction.dot(self) / (direction.magnitude() * self.magnitude())

        return trignometric_clamp(cos)

    #######################################

    def projection_on(self, direction):

        """ Return the projection of self on direction """

        return direction.dot(self) / direction.magnitude()

    #######################################

    def sin_with(self, direction):

        """ Return the sinus of self with other """

        # turn from direction to self
        sin = direction.cross(self) / (direction.magnitude() * self.magnitude())

        return trignometric_clamp(sin)

    #######################################

    def deviation_with(self, direction):

        """ Return the deviation of self with other """

        return direction.cross(self) / direction.magnitude()

    #######################################

    def orientation_with(self, direction):

        # Fixme: check all cases
        # -> angle_with

        """ Return the angle of self on direction """

        angle = math.acos(self.cos_with(direction))
        angle_sign = sign(self.sin_with(direction))

        return angle_sign * math.degrees(angle)

####################################################################################################

class Vector2D(Vector2DFloatBase):

    """ 2D Vector """

    #######################################

    @staticmethod
    def from_angle(angle):

        """ Create the unitary vector (cos(angle), sin(angle)).  The *angle* is in degree. """

        rad = math.radians(angle)

        return Vector2D((math.cos(rad), math.sin(rad)))

    #######################################

    @staticmethod
    def middle(p0, p1):

        """ Return the middle point. """

        return Vector2D(p0 + p1) * .5

    #######################################

    def __mul__(self, scale):

        """ Return a new vector equal to the self scaled by scale """

        return self.__class__(scale * self.v)

    #######################################

    def __imul__(self, scale):

        """ Scale self by scale """

        self.v *= scale

        return self

    #######################################

    def __truediv__(self, scale):

        """ Return a new vector equal to the self dvivided by scale """

        return self.__class__(self.v / scale)

    #######################################

    def __itruediv__(self, scale):

        """ Scale self by 1/scale """

        self.v /= scale

        return self

    #######################################

    def normalise(self):

        """ Normalise the vector """

        self.v /= self.magnitude()

    #######################################

    def to_normalised(self):

        """ Return a normalised vector """

        return NormalisedVector2D(self.v / self.magnitude())

    #######################################

    def rint(self):

        return Vector2DInt(np.rint(self.v))

####################################################################################################

class NormalisedVector2D(Vector2DFloatBase):

    """ 2D Normalised Vector """

    #######################################

    def __init__(self, *args):

        super(NormalisedVector2D, self).__init__(*args)

        #! if self.magnitude() != 1.:
        #!     raise ValueError("Magnitude != 1")

        # if not (is_in_trignometric_range(self.x) and
        #         is_in_trignometric_range(self.y)):
        #     raise ValueError("Values must be in trignometric range")

    #######################################

    def __mul__(self, scale):

        """ Return a new vector equal to the self scaled by scale """

        return Vector2D(scale * self.v)