compas-dev / compas

Core packages of the COMPAS framework.
https://compas.dev/compas/
MIT License
305 stars 104 forks source link

[Discussion] Type-consistent through basic math operation #1345

Open xarthurx opened 2 months ago

xarthurx commented 2 months ago

Case 1: In the documentation: https://compas.dev/compas/latest/userguide/basics.geometry.points_and_vectors.html

We have: image

The different resulting types of + and - for Point looks quite strange to me at the beginning... It is understandable after a bit of thinking that - for point should result a "vector" as it means direction from p0 to p1.

However, as a basic geometry library, it is recommended to make types consistent across such basic math operations, rather than "interpret" it subjectively -- this may lead to unexpected errors and increase maintenance cost.

Case 2: Another scenario may happen is when I have a p0 from some computation, and would like to use the corresponding v0 so that I can use methods in the compas.Vector class.

Currently there is no provided method in compas for doing sth like v0 = Vector(p0) or v0 = p0.CastToVector().

Recommendation

Perhaps such cases are due to a legacy where "type" was not considered as a first-class citizen in Python development... I would however recommend to unify the types and make the computation more consistent.

For the math operations, following approach could be an option:

  1. Make computation within each type constant.
  2. Provide casting methods like v0 = p0.CastToVector(), or v0 = p0.CastToVector().
gonzalocasas commented 2 months ago

I was also tripped by this in the past, however, it's more common than expected. In particular, Rhino SDK behaves the same: image

And I think we discussed other libraries that also do the same, so it's not such an arbitrary decision.

Regarding the second point, it's already supported using list unpacking syntax (which could be claimed is more pythonic than cast_to_vector() which looks very much like C#/static-typing language):

from compas.geometry import Point, Vector

v0 = Vector(1.0, 0.0, 0.0)
p0 = Point(0.0, 1.0, 0.0)
print(v0)
print(p0)

v1 = Vector(*p0)
print(v1)
p1 = Point(*v0)
print(p1)

image

xarthurx commented 2 months ago
from compas.geometry import Point, Vector

v0 = Vector(1.0, 0.0, 0.0)
p0 = Point(0.0, 1.0, 0.0)
print(v0)
print(p0)

v1 = Vector(*p0)
print(v1)
p1 = Point(*v0)
print(p1)

image

This is good to know. Always learn sth from you every time we communicate. :)