• Aucun résultat trouvé

A Generic Lazy Evaluation Scheme for Exact Geometric Computations

N/A
N/A
Protected

Academic year: 2021

Partager "A Generic Lazy Evaluation Scheme for Exact Geometric Computations"

Copied!
24
0
0

Texte intégral

(1)

HAL Id: inria-00089229

https://hal.inria.fr/inria-00089229v2

Submitted on 18 Aug 2006

HAL is a multi-disciplinary open access archive for the deposit and dissemination of sci- entific research documents, whether they are pub-

L’archive ouverte pluridisciplinaire HAL, est destinée au dépôt et à la diffusion de documents scientifiques de niveau recherche, publiés ou non,

Computations

Sylvain Pion, Andreas Fabri

To cite this version:

Sylvain Pion, Andreas Fabri. A Generic Lazy Evaluation Scheme for Exact Geometric Computations.

[Research Report] RR-5966, INRIA. 2006, pp.23. �inria-00089229v2�

(2)

inria-00089229, version 2 - 18 Aug 2006

a p p o r t

d e r e c h e r c h e

9-6399ISRNINRIA/RR--5966--FR+ENG

Thème SYM

A Generic Lazy Evaluation Scheme for Exact Geometric Computations

Sylvain Pion — Andreas Fabri

N° 5966

August 2006

(3)
(4)

SylvainPion

, Andreas Fabri

ThèmeSYMSystèmessymboliques

ProjetsGeometria

Rapportdereherhe 5966August200620pages

Abstrat: We present a generi C++ design to perform eient and exat geometri

omputations using lazy evaluations. Exat geometri omputations are ritial for the

robustnessof geometri algorithms. Their eieny is also ritial for most appliations,

hene the need for delaying the exat omputations at run time until they are atually

needed. Ourapproahis generiand extensible in the sense that it ispossibleto makeit

alibrary whih usersan extend to theirown geometri objetsorprimitives. It involves

tehniquessuhasgenerifuntoradaptors,dynamipolymorphism,refereneountingfor

themanagementofdiretedayligraphsandexeptionhandlingfordetetingaseswhere

exat omputations are needed. It also relies on multiple preision arithmeti as well as

intervalarithmeti. WeapplyourapproahtothewholegeometrikernelofCGAL.

Key-words: omputationalgeometry,exatgeometriomputation,numerialrobustness,

intervalarithmeti,lazyevaluation,generiprogramming,C++, CGAL

ProjetGeometria,INRIASophia-Antipolis,Sylvain.Pionsophia.inri a.f r

GeometryFatory,Grasse,Frane,andreas.fabrigeometryf ato ry. om

(5)

Résumé: Nousprésentonsunearhiteturegénériquepoureetuerdesalulsgéométriques

exatset eaes en utilisantune évaluation paresseuse. Les aluls géométriques exats

sontritiquespourlarobustessedesalgorithmesgéométriques.Leureaitéestégalement

ritiquepourlaplupartdesappliations,d'où lebesoinpourrepousserlesalulsexatsle

plustard possibleà l'exéution, jusqu'au point ils sont absolument néessaires. Notre

approheestgénériqueetextensibledanslesensilestpossibled'enfaireunebibliothèque

queles utilisateurspeuventétendre àleur propresobjetsgéométriqueset primitives. Elle

faitappelàdestehniquesommelesadaptateursgénériquesdefonteurs,lepolymorphisme

dynamique, leomptage deréférenes pourla gestiondes graphes ayliques dirigéset la

gestion d'exeptions pour signaler les as les aluls exats sont requis. Elle s'appuie

également sur le alul arithmétique multipréision et l'arithmétique d'intervalles. Nous

appliquonsnotreapproheaunoyaugéométriquedeCGALenentier.

Mots-lés : géométrie algorithmique, alul géométrique exat, robustesse numérique,

arithmétiqued'intervalles,évaluationparesseuse,programmationgénérique,C++, CGAL

(6)

1 Introdution

Non-robustnessissuesduetonumerialapproximationsarewellknowningeometriompu-

tations,espeiallyintheomputationalgeometryliterature. ThedevelopmentoftheCgal

library,alargeolletionofgeometrialgorithmsimplementedinC++,expressedtheneed

forageneriandeienttreatmentofthese problems.

Typialsolutionsto solvethese problemsinvolveexatarithmeti omputations. How-

ever, due to eieny issues,good implementations makeuse of arithmeti lteringteh-

niquestobenetfromthespeedofertiedoating-pointapproximationslikeintervalarith-

meti,heneallingtheostlymultipreisionroutinesrarely.

One eient approah is toperform lazy exatomputations at thelevelof geometri

objets. It is mentionedin [13℄ and animplementation is desribedin [7℄. Unfortunately,

thisimplementationdoesnotusethegeneriprogrammingparadigm,althoughtheapproah

isgeneral. Thisisexatlythenoveltyofthispaper.

Inthispaper,wedeviseageneridesigntoprovidethemostgenerallyappliablemethods

toalargenumberofgeometriprimitives. Ourdesignmakesiteasytoapplytotheomplete

geometrykernelofCgal,andisextensibletotheuser'snewgeometriobjetsandgeometri

primitives.

Our designthus implementslazy evaluation of theexat geometri objets. The om-

putationis delayed until apoint where the approximationwith interval arithmeti is not

preiseenoughto deidesafelyomparisons,whih mayhopefullyneverbeneeded.

Setion 2desribesin moredetailthe ontextand motivationin geometri omputing,

as well as the basis of a generi geometri kernel parameterized by the arithmeti, and

whatanbedoneat thislevel. Then, Setion3disussesourdesignin detail,namelyhow

geometriprediates, onstrutionsandobjetsareadapted. Setion4illustrates how our

shemeanbeappliedtotheusers'sowngeometriobjetsandprimitives. Wethenprovide

in Setion 5somebenhmarksthat onrmthe benet ofourdesign andimplementation.

Finally, we listafewopen questions relatedto ourdesignin Setion 6, andonludewith

ideasforfuture work.

2 Exat geometri omputations and the CGAL kernel

2.1 Exat Geometri Computations

Many geometri algorithms suh as onvex hull omputations, Delaunay triangulations,

meshgenerators,arenotoriouslypronetorobustnessissuesduetotheapproximate nature

ofoating-pointomputations. Thisisdue tothedual natureof geometrialgorithms: on

onesidenumerialdataisused,suhasoordinatesofpoints,andontheothersidedisrete

struturesarebuilt,suhasthegraphrepresentingamesh.

ThebridgesbetweenthenumerialdataandtheBooleandeisionswhihallowtobuilda

disretestruture,arealledthegeometriprediates. Thesearefuntionstakinggeometri

objetssuh aspoints asinput and returninga Boolean orenumeratedvalue. Internally,

(7)

thesefuntionstypiallyperformomparisonsofnumerialvaluesomputedfromtheinput.

Alassialexampleistheorientationprediateofthreepointsintheplane,whihreturnsif

thethreepointsaredoingaleftturn,arightturn,oriftheyareollinear(seeFigure1). Using

Cartesianoordinatesforthepoints,theorientationisthesign(asathree-valuedfuntion:

-1,0,1)ofthefollowing3-dimensionaldeterminantwhihreduestoa2-dimensionalone:

1 1 1

p.x() q.x() r.x()

p.y() q.y() r.y()

= q.x()p.x() r.x()p.x() q.y()p.y() r.y()p.y()

Figure1: Theorientationprediatesof3pointsintheplane.

Manyprediatesarebuiltontopofsignsofpolynomialexpressionsovertheoordinates

of theinput points. Evaluating suh afuntion with oating-point arithmeti is going to

introdueroundoerrors,whihanhaveforonsequenethatthesignoftheapproximate

valuediersfromthesignof theexatvalue. Theimpat ofwrongsignsonthegeometri

algorithms whih all theprediates an bedisastrous, as for example it anbreak some

invariants like planarity of a graph, or make the algorithm loop. Didati examples of

onsequenesanbefoundin[12℄aswellasin theomputationalgeometryliterature.

Operations building new geometri objets, like the point at the intersetion of two

lines, the irumenter of three non-ollinear points, or the midpoint of two points, are

alledgeometrionstrutions. Wewill usethetermgeometriprimitives whenreferingto

eitherprediatesoronstrutions.

Inorderto taklethesenon-robustnessissues,manysolutionshavebeenproposed. We

fous hereon the exat geometri omputation paradigm [16℄, asit is a general solution.

Thisparadigmstatesthat,in orderto ensuretheorretexeution ofthealgorithms, itis

enoughthat all deisionsbased onprediates are taken orretly. Conretely, this means

thatallomparisonsofnumerialvaluesneedtobeperformedexatly.

Anaturalwaytoperformtheexatevaluationofprediatesistoevaluatethenumerial

expressions using exat arithmeti. For example, sine most omputations are signs of

(8)

polynomials, it is enough to use multipreision rational arithmeti whih is provided by

libraries suh as Gmp [8℄. Note that exat arithmeti is also available for all algebrai

omputations using libraries suh as Core [10℄ or Leda [5℄, whih is useful when doing

geometryoverurvedobjets. Thissolutionworkswell,butittendstobeveryslow.

2.2 The Geometry Kernel of CGAL

Cgal[1℄isalargeolletionof omputationalgeometryalgorithms. These algorithmsare

parameterizedbythegeometrytheyapplyto. Thegeometrytakestheformofakernel [9,4℄

regroupingthetypesofthegeometriobjetssuh aspoints,segments,lines, ... aswellas

thebasiprimitivesoperatingonthem,in theformoffuntors. TheCgalkernelprovides

over100prediatesand150onstrutions,heneuniformityand generiityisruial when

treatingthem, fromamaintenanepointofview.

Cgal provides several models of kernels. The basi families are the template lasses

CartesianandHomogeneouswhihareparameterizedbythetyperepresentingtheoordi-

nates of the points. Theyrespetively useCartesian and homogeneousrepresentations of

theoordinates,andtheirimplementationlooksasfollows:

template < lass NT >

strut Cartesian {

// Geometri objets

typedef ... Point_2;

typedef ... Point_3;

typedef ... Segment_2;

...

// Funtors for prediates

typedef ... Compare_x_2;

typedef ... Orientation_2;

...

// Funtors for onstrutions

typedef ... Construt_midpoint_2;

typedef ... Construt_irumenter_2;

...

};

These simple template models already allow to use double arithmeti or multipreision

rational arithmeti for example. Cgal therefore providesa hierarhyof oneptsfor the

numbertypes,whihdesribetherequirementsfortypestobepluggableinto thesekernels,

suhasaddition,multipliation,omparisons... Thefuntorsareimplementedinthefollow-

ingway(herethereturntypeoftheprediateisathree-valuedenumeratedtype,moreover

sometypenamekeywordsareremovedforlarity):

template < lass Kernel >

lass Orientation_2 {

(9)

typedef Kernel::Point_2 Point;

typedef Kernel::FT FT;

publi:

typedef CGAL::Orientation result_type;

result_type

operator()(Point p, Point q, Point r) onst

{

FT det = (q.x() - p.x()) * (r.y() - p.y())

- (r.x() - p.x()) * (q.y() - p.y());

if (det > 0) return POSITIVE;

if (det < 0) return NEGATIVE;

return ZERO;

}

};

template < lass Kernel >

lass Construt_midpoint_2 {

typedef Kernel::Point_2 Point;

publi:

typedef Point result_type;

result_type

operator()(Point p, Point q) onst

{

return Point( (p.x() + q.x()) / 2,

(p.y() + q.y()) / 2 );

}

};

Asmuh asonversionsbetweennumbertypesareuseful,Cgalalsoprovidestoolstoon-

vertgeometriobjetsbetweendierentkernels. Weshortlypresentthese hereastheywill

bereferedtointhesequel. Akernelonverterisafuntorwhose funtionoperatorisover-

loaded for eah objetof thesoure kerneland whih returns theorresponding objetof

thetargetkernel. Suhonversionsmaydependonthedetails ofrepresentationofthegeo-

metriobjets,suhashomogeneousversusCartesianrepresentation. Cgalprovidessuh

onvertersparameterizedby onverters betweennumber types, for example the onverter

betweenkernelsoftheCartesianfamily:

template < lass K1, lass K2, lass NT_onv =

Default_onv<K1::FT, K2::FT> >

strut Cartesian_onverter {

NT_onv v;

(10)

K2::Point_2

operator()(K1::Point_2 p) onst

{

return K2::Point_2( v(p.x()), v(p.y()) );

}

...

};

Relatedto this, Cgalalso providesawayto ndoutthetypeof ageometri objet(say,

a3D segment)in agiven kernel, given its type in another kernel and this seond kernel.

Thisisinpratiethereturntypeofthefuntionoperatorofthekernelonverterdesribed

above.

template < lass O1, lass K1, lass K2 >

strut Type_mapper {

typedef ... type;

};

The urrent implementation works by speializing on all known kernel objet types like

K1::Point_2,K1::Segment_3. A moreextensible approahouldbesought,althoughthis

isnotthemainpointofthispaper.

2.3 A Generi Lazy Exat Number Type

Inordertospeeduptheexatevaluationofprediates,peoplehaveobservedthat,giventhat

theoating-pointevaluationgivestherightanswerinmostases,itshouldbeenoughtoadd

awaytodetettheaseswhereitanhangethesign,andrelyontheostlymultipreision

arithmetionlyinthoseases. Thesetehniquesareusuallyreferedtoasarithmetiltering.

There are many variants of arithmeti lters, but we are going to fous on onewhih

appliesnielyinageneriontext,andisbasedonintervalarithmeti[3℄,awellknowntool

to ontrol roundoerrors in oating-pointomputations. The idea is that we implement

anewnumbertype whih forwardsitsoperations to anintervalarithmeti type,and also

remembers the way it was onstruted by storing the history of operations in a direted

ayligraph(Dag)[2℄. Figure2illustrates thehistoryDagoftheexpression

x+y px+y+ 2xy.

When aomparison is performed on this numbertype and the intervals overlap, then

the Dag is used to reompute the valueswith an exatmultipreision type, hene giving

the exatresult. Cgal providessuh a lazy numbertype alled Lazy_exat_nt<NT>pa-

rameterizedbytheexattypeused toperformtheexatomputationswhen needed(suh

asarationalnumbertype). Somehow,thisanbeseenasawrapperontopofitstemplate

parameter,whihdelaystheomputationsuntiltheyareneeded,ashopefullytheywon'tbe

neededatall.

Thissolutionworksverywell. Itanhoweverbefurtherimprovedintermsofeieny.

Indeedwenotethatthereareseveraloverheadswhihanbeoptimized. First,anodeofthe

(11)

Figure2: ExampleDag:

x+y

px+y+ 2xy.

Dagisreatedforeaharithmetioperation,soitwouldbenietobeabletoregroupthem

in order to diminishthe number of memory alloations as well asthe memory footprint.

Seond, rounding mode hanges for interval arithmeti omputations are made for eah

arithmetioperation,soagain,itwouldbenietobeabletoregroupthemtooptimizeaway

thesemodehanges.

These remark have lead to a new sheme mentioned in [13℄, and the desription of

an implementation has also beenproposed in [7℄. Theidea is to introdue a Dag at the

geometrilevel,byonsideringgeometriprimitivesforthenodes. Thenextsetiondesribes

suhanoptimizedsetup. Ourdesigndiersfromtheonein[7℄inthatwefollowedthegeneri

programmingparadigm and extensive use of templates to makeit aseasily extensible as

possible.

3 Design of the Lazy Exat Computation Framework

The previouslydesribed design of lazy omputation is based only on generiity overthe

numbertype. Inthissetion,wemakeuseofthegeneriityatthehigherlevelofgeometri

primitives,in orderto provideamoreeientsolution. Werstdesribehowtolterthe

(12)

prediates. Thenweextendthepreviousideaof Lazy_exat_ntto geometri objetsand

onstrutions.

3.1 Filtered Prediates

Performingalteredprediatemeansrstevaluatingtheprediatewithintervalarithmeti.

If it fails, the prediate is evaluated again, this time with an exat numbertype. As all

prediatesof aCgalkernelarefuntorsweanusethefollowingadaptor:

template<lass EP,lassAP, lassC2E, lassC2A>

lassFiltered_prediate

{

typedefAP Approximate_prediate;

typedefEP Exat_prediate;

typedefC2E To_exat_onverter;

typedefC2A To_approximate_onverter;

EP ep;

AP ap;

C2E2e;

C2A2a;

publi:

typedefEP::result_type result_type;

template<lass A1,lass A2>

result_type

operator()(onstA1 &a1, onstA2 &a2) onst

{

try{

Protet_FPU_roundingP(FE_TOINFTY);

return ap(2a(a1), 2a(a2));

}ath (Interval_nt_advaned::unsafe_omparison){

Protet_FPU_roundingP(FE_TONEAREST);

return ep(2e(a1), 2e(a2));

}

}

};

Funtionoperatorswith anyarityshould beprovided. This isurrentlydoneby hand

uptillaxedarity,andwillbereplaedwhenvariaditemplatesbeomeavailableinC++.

Note that Protet_FPU_roundinghanges the urrent rounding mode of the FPU to

theonespeiedas argumentto the onstrutor, andsavestheold onein the objet. Its

destrutorrestoresthesavedmode,whihhappensatthereturnofthefuntionorwhenan

exeptionisthrown.

ThelassFiltered_kernelisheneobtainedfromakernelKbyadaptingallprediates

of K. This is urrently done with the preproessor. The geometri objets as well asthe

onstrutionsremainunhanged.

template<lassK>

strut Filtered_kernel{

// Thevariouskernels

typedefCartesian<double> CK;

(13)

typedefCartesian<Interval_nt> AK;

typedefCartesian<Gmpq> EK;

// Kernel onverters

typedefCartesian_onverter<CK, AK> C2A;

typedefCartesian_onverter<CK, EK> C2E;

// Geometriobjets

typedefCK::Point_2 Point_2;

...

// Funtorsforprediates

typedefFiltered_prediate<AK::Compare_x_2,

EK::Compare_x_2,

C2E, C2A> Compare_x_2;

...

};

3.2 Lazy Exat Objets

Performinglazyexatonstrutionsmeansperformingonstrutionswithintervalapproxi-

mations,andstoringthesequeneofonstrutionsteps. Whenlateraprediateapplied to

theseapproximationsannotreturnaresultthatisguaranteedtobeorret,thesequeneof

onstrutionstepsisperformedagain,thistimewithanexatarithmeti. Nowtheprediate

anbeevaluatedorretly.

The sequene of onstrution steps is stored in a Dag. Eah node of the Dag stores

(i)an approximation, (ii) theexat versionof the funtion that wasused to omputethe

approximation, (iii) and the lazy objets that were arguments to the funtion. So the

outdegreeofanodeis thearityofthefuntion.

Figure 3: TheDagrepresentsthe midpoint of anintersetion point and thevertialpro-

jetionofapointonaline. Testingwhether a,m,andbareollinearhasagoodhaneto

triggeranexatonstrution.

(14)

The example illustrates that lazy objets anbe of the same type, without being the

resultof the same sequeneof onstrutions. a, m, and b are allpoint-ish. Therefore we

haveatemplatedhandle lass,with apointerto anodeoftheDag. Inourexample,only

thelatterareofdierenttypes.

Figure4: ThelasshierarhyforthenodesoftheDag.

WewillnowexplainsomeofthelassesinFigure 4inmoredetail.

Lazy_exat is the handle lass. It also doesreferene ounting with a design similar

to theonedesribedin [11℄. It hasLazy_exat_ntassublass, whihprovidesarithmeti

operations. Notethatthisframeworkhandlesarithmetiandgeometriobjetsinaunied

way. Forexampleadistane bewteengeometri objetsyields alazyexatnumber,and a

lazyexatnumberanbeometheoordinateofapoint.

ThelassConstrutionisanabstratbaselass. Itstorestheapproximation,andholds

apointertotheexatvalue. Initially,thispointerissettoNULL,anditisthevirtualmember

funtionupdate_exatwhihlatermayomputetheexatvalueandthenaheit.

ThesublassConstrution_2isused forbinaryfuntions. Similarlassesexistforthe

otherarities. Theselassesstoretheargumentsand theexatversionofthefuntion. The

argumentsmay beof arbitrary types. In thease of lazy exatgeometri objets orlazy

exatnumberstheargumentsarehandlesasdesribedbefore.

template<lass AC,lassEC, lassLK,lassA1, lassA2>

lassConstrution_2

:publi Constrution<AC::result_type,EC::result_type,E2A>

,private EC

{

typedefAC Approximate_onstrution;

typedefEC Exat_onstrution;

typedefLK::C2E To_exat_onverter;

typedefLK::C2A To_approximate_onverter;

typedefLK::E2A Exat_to_approximate_onverter;

typedefAC::result_type AT;

(15)

typedefEC::result_type ET;

A1 m_a1;

A2 m_a2;

onstEC& e()onst {return *this; }

publi:

void

update_exat()

{

this->et=newET(e()(C2E()(m_a1),C2E()(m_a2)));

this->at=E2A()(*(this->et));

// Prunelazy dag

m_a1 =A1();

m_a2 =A2();

}

Constrution_2(onstAC&a,onst EC&e,

onstA1&a1, onstA2&a2)

:Constrution<AT,ET,E2A>(a(C2A()(a1),C2A()(a2)),

m_a1(a1),m_a2(a2)

{}

};

Theonstrutorstoresthetwoarguments. Itthentakestheirapproximationsandalls

theapproximateversionofthefuntor.

In ase the exat version of the onstrution is needed, this gets omputed in the

update_exatmethod. It fethes theexatversionsof thearguments, whih in turn may

triggertheirexatomputationiftheyarenotalreadyomputedandahed. Fromtheex-

atlazyobjetoneomputesagaintheapproximateobjet,astheobjetomputedwiththe

approximateversionofthefuntorhasagood hanetohaveaumulatedmorenumerial

error.

Finally,theDagispruned. AsthenodesoftheDagarerefereneounted,someofthem

may getdealloatedbythepruning. MostoftenA1and A2will belazyexatobjets. For

performanereasonstheirdefaultonstrutorsgeneratesahandletoasharedstatinodeof

theDag.

Also,weuseprivatederivationoftheexatonstrutionEC,insteadofstoringitasdata

member,in ordertobenetfrom theemptybaselassoptimization.

The otherderived lassesstorethe leavesof the Dag. There is ageneralpurposeleaf

lass,andmorespeializedones,forexampleforreatingalazyexatnumberfromanint.

Theyarethere forperformanereasons.

3.3 The Funtor Adaptor

Sofarwehaveonlyexplainedhowlazyonstrutionsarestored,butnothownewnodesof

theDagaregenerated.

Thefollowingfuntor adaptoris appliedto alltheonstrutionswewantto makelazy.

Ithasfuntionoperatorsforotherarities.

template<lass LK,lassAC, lassEC>

Références

Documents relatifs

(2) a scheduled next event date is expired and the new scheduled synchronous event E, provided by the music controller M, is passed to the output con- troller to be fired at time

Recent studies that tie slip on thrust faults to glacial unloading [Turpeinen et al., 2008] prompt us to examine whether rapid changes in erosion and ice loads in an area located in

This visibility data allows to solve efficiently and exactly the visibility of an area light source for each point to be shaded, taking advantage of the visibility coherence

In this paper, we present a new high quality soft shadow algorithm based on exact visibility computed from the area light source.. Our method relies on an equivalence relation

However, as the signal-to-background (in the sample of J/ψ candidates) is worse in the J/ψγγ sample, we use the same dimuon mass criteria for both J/ψπ − π + and J/ψγγ

It has been suggested that the dynamics of attention are primarily temporal in nature, rather than being driven by the sequential presentation of targets and distractors (Nieuwenhuis

by Florence Le Ber (Université de Strasbourg, ENGEES), Jean Lieber (Université de Lorraine, Inria) and Marc Benoît (INRA). A farmer’s decision to plant new perennial biomass crops is

The primary scientific aim of this project is to model the constraints integrated by the planner in order to propose valid delivery rounds from financial, environmental and