Sei sulla pagina 1di 9

1/8/2017

Cyclesinfamilytreesoftware

Cyclesinfamilytreesoftware
[+1596][18]PartickHse
[2011052818:39:28]
[c++graphcycleassertionsfamilytree]
[http://stackoverflow.com/questions/6163683/cyclesinfamilytreesoftware]

Iamthedeveloperofsomefamilytreesoftware(writteninC++andQt).Ihadnoproblemsuntiloneofmy
customers mailed me a bug report. The problem is that the customer has two children with their own
daughter,and,asaresult,hecan'tusemysoftwarebecauseoferrors.
Thoseerrorsaretheresultofmyvariousassertionsandinvariantsaboutthefamilygraphbeingprocessed(for
example,afterwalkingacycle,theprogramstatesthatXcan'tbebothfatherandgrandfatherofY).
HowcanIresolvethoseerrorswithoutremovingalldataassertions?
(202)Soundslikeyoushouldlimitthesaleofthesoftwaretothosethatavoidgettingintotrickyfamilysituations!Howdoesonehave
childrenwithhisowndaughterIhopeyou'retalkingabouthisdaughterinlaw!WillA
(220)YoushouldobviouslywriteyoursoftwarewithRayStevens'songinmind.PeterK.
(5)@PeterKtopnotch,+1forwhathastobeoneofthemostpertinentcommentsofalltime.WillA
(162)This might be one of those cases where you need to ask yourself: Do I really want to make business with that guy? Another
solution would be to press criminal charges against him. Incest is forbidden in most of the world, after all. Finally, your software is
brokenanyway,becauseyoucan(legally)havecyclesinafamilytree:cousinsareallowedtomarryinmost(all?)westerncountries.sbi
(30)Ifyoutraceyourfamilytreebackwardsfarenough,youwillhitthisproblemfarmoreoftenthanyouwouldlike.Abandoningthe
treerepresentationmaybepainfulbutwouldultimatelybemorecorrect.Thomas
(55)Youshouldn'taddassertionsforunlikelythings,onlyimpossiblethings.Cyclesaretheobviousthingsthataren'tpossibleinafamily
treegraph...noonecanbehisownancestorviaanymethod.Theseotherassertionsarejustbogusandshouldberemoved.pgod
(60)Maybenexttimeyou'lltryamoreabstractexample.Peopleherecan'toverlooktheincestpartandjustcloseit,evenifitisavalid
questionregardingtherepresentationoftreelikedata.stesch
(9)@pgodinsteadoffailingontheseassertions,Ithinkit'shelpfultoreportunlikelythingstotheusertoletthemknowtheymayhave
madeamistakebutprovideaneasyandnonpatronisingmethodtoproceedanyway.thomasrutter
(5)The only thing that this question might possibly lack is pseudo code, but I really don't see why any is necessary. I agree with the
decisionthatthecommunitymadetoreopenthis.TimPost
(3)Iwonderwhoaskedthatquestion..youtube.com/watch?v=VFl1m7MPBgg?Nils
(7)Well,evennotthinkingaboutcriminals,youmightthinkaboutthecasewherepeoplemaketheirfamilytreeupahighernumberof
generationstheremighthavebeentimeswhenthiskindofincestuoussituationswasnotthatuncommon(think"starvingpeople"+
"war" + "the need to have boys to make the crops / legate stuff to"). So this might not be such a useless use case, depending on the
expectedcustomerbase..phtrivier
(44)Thisisnotatallasillyquestionintheworldofpetbreeding.Daughtertofather,mothertoson,sistertobrother,grandchildrento
grandparentsisstandardtechniquethere,andpetbreedersneedfamilytreesoftwaretoo."Purebred"my%#&.kaleissin
(14)Thisquestionisagreatillustrationaboutassumptionsthatsoftwareengineersmakewhenproducingcode.Assertionshavenoplace
inproductioncodeforsituationsthatcouldhappen.Johnsyweb
(9)@PeterKRayStevenswasapiker.ForatrulycyclicalfamilytreeyouneedtoreadHeinlein'sAllYouZombies.DanNeely
(30)Areyouguysseriously trying to close this as subjective and argumentative? The question is totally clear to me, it's asking for a
solutiontocyclesinatree/graph.Xeo
@DanNeely:Agreed.ButHeinlein'sdoesn'ttranslatenearlysowelltoaYouTubevideo.:)PeterK.
(5)Doyougetthesamecycleerrorifcousinsmarried,forinstanceachildofcousinsthatmarriedwouldalsobeachildoftheparentbut
alsoacousinoftheparent.Thisisacommonscenario.RebeccaChernoff
(31)MarryingfirstcousinswasverycommoninVictorianEngland,especiallyamongtheupperclasses(itwasanexcellentwaytokeep
moneywithinthefamily).CharlesDarwin,forinstance,marriedhisfirstcousin,EmmaWedgwood.Anyfamilytreesoftwareneedsto
supportsituationslikethis.rtperson
(3)FYI,gotlinkedherefromRedditbgw
(1)@PeterK.I'mnotsureifit'savailableasarecording,butAtlantaRadioTheaterCompanyhasdoneAllYouZombiesanditcouldbe
uploadedtoYoutubeeasilyenoughifitexisted.DanNeely
@DanNeely:Nowyou'veremindedmeofbad80'smusic!Butinagoodway.PeterK.
(12)Thethingis,it'snottechnicallyatreeanymore,inthemathematicalsense.Assoonasyouintroduce(incestuous)cycles,itbecomes
afullyfledgedgraph.Sotellthecustomertogobuya"familygraph"programtailoredforincestuoushicks.:)Noldorin
(11)Oneofthoserarecaseswherethecrashreportshouldgotothepolicenotthedeveloper.MrK
(1)It'snotrelevantthathedoeshavekidswithhisdaughter,inlegalsense.Therelevantthingisratherwherehehadsexwithherasa
prosecutoryouhavetoprovethatthesexualacthappenedinsidestateborders.Skynet
(4)@pgod: If a person marries the mother of a man who marries his mother, then he's his own grandpa. Being your own ancestor
geneticallyisimpossible,butsociallyit'snot.Andmostfamilytreesoftwaretracksboth.MooingDuck
@Iterator:thatwasthe"earlierfunnierones"referenceamindfv
http://www.stackprinter.com/export?question=6163683&service=stackoverflow

1/9

1/8/2017

Cyclesinfamilytreesoftware

On 20130207 I made a suggestion. Maybe it will yet be helpful to someone. If necessary, one may compromise with the difficult
constraintsofGEDCOMbyenteringa"person"thatincorporatesagroupofpeoplewhohaveunsupportedrelationships.Toillustratethe
point,Icalledmyexample"DaddyDaughterInc."Iopenlyadmitthatthisisunpleasanttowardpeopleandfailstocapturesomefactsin
machinereadableform.Technically,doesitnotpatchoveralocalproblemintheGEDCOMrepresentationofafamily?Ohwell.Itwas
downvotedto3withoutcomment,soIdeleteditfromtheanswers.minopret
(3)Thisiswhyit'sgoodtochallengeassertionsstronglywhengatheringrequirements."Xdoesn'thappen".Ok,butdoesthatmeanthat
"Xdoesn'tnormallyhappen",that"Xwill"never"happen",orthat"Xcannotpossiblyhappen"?Sahuagin
(4)Nofamilytree(outsideoftimetravelfiction)hascycles,buttheproblemhereisthatyourprogramdoesn'tsupportdirectedacyclic
graphs,whereonenodecanserveasmorethanonetypeofancestortoanother.Suchgraphsmaybeundesirableeithermorally,socially,
orlegally,buttheyarenotbiologicallyimpossible.chepner
Iwonderhowcanbedescribedthesituationhere:youtube.com/watch?v=eYlJH81dSiwVasilPopov

[+731][2011060108:25:09]BertGoethals[

ACCEPTED]

Itseemsyou(and/oryourcompany)haveafundamentalmisunderstandingofwhatafamilytreeissupposedtobe.
Letmeclarify,Ialsoworkforacompanythathas(asoneofitsproducts)afamilytreeinitsportfolio,andwehavebeen
strugglingwithsimilarproblems.
The problem, in our case, and I assume your case as well, comes from the GEDCOM [1] format that is extremely
opinionated about what a family should be. However this format contains some severe misconceptions about what a
familytreereallylookslike.
GEDCOM has many issues, such as incompatibility with same sex relations, incest, etc... Which in real life happens
moreoftenthanyou'dimagine(especiallywhengoingbackintimetothe17001800).
Wehavemodeledourfamilytreetowhathappensintherealworld:Events(forexample,births,weddings,engagement,
unions, deaths, adoptions, etc.). We do not put any restrictions on these, except for logically impossible ones (for
example,onecan'tbeone'sownparent,relationsneedtwoindividuals,etc...)
Thelackofvalidationsgivesusamore"realworld",simplerandmoreflexiblesolution.
Asforthisspecificcase,Iwouldsuggestremovingtheassertionsastheydonotholduniversally.
Fordisplayingissues(thatwillarise)Iwouldsuggestdrawingthesamenodeasmanytimesasneeded,hintingatthe
duplicationbylightingupallthecopiesonselectingoneofthem.
[1]http://en.wikipedia.org/wiki/GEDCOM
(32)Thislooksliketherightapproach,andit'seasyenoughtoextendtodetectmorecomplexproblems.Youcanworkoutasetof"A
happenedbeforeB"relationshipsbetweenevents.Forexample,thatapersonwasbornbeforeanyothereventsinvolvingthem.Thisisa
directedgraph.Youcouldthencheckthatthegraphcontainsnocycles.SeethisquestiononStackOverflow.Thisshouldbeokuntiltime
travelisinvented.PaulHarrison
(41)@paulharrisonIfitwhereonlythatsimple.Inolderrecords(evennewones)therearedateinconsistencies.Baptismbeforebirth,
multiplebirthrecordsetc...Sotoanextent,inofficialrecords,thereistimetravel.Weallowthisinconsistentdata.Weallowusersto
indicate what the application should consider "the" birth record in case of duplicates. And we'll indicate broken timelines if found.
BertGoethals
(38)@benvoigtGEDCOMisaformatcreatedbytheTheChurchofJesusChristofLatterdaySaints.Thespecificationclearlystates
thatmarriage(MARR)istobebetweenmenandwomen.ForsamesexmarriageorincesttheASSOtagshouldbeused(ASSOCIATES),
alsousedtoindicatefriendshiporbeingneighbours.Itisclearthesamesexmarriageissecondclassrelationwithinthisspec.Amore
neutralspecwouldnotdemandmalefemalerelations.BertGoethals
(1) @Bert Goethals: You are confusing GEDCOM with certain programs that do not support samesex marriage (PAF, Legacy).
GEDCOMdoesnotprecludeconstructssuchas"0@F1@FAM/1HUSB@I1@/1HUSB@I2@",andthussupportssamesexmarriagesif
yoursoftwarechoosesto.Pierre
(1)@Pierre You can cheat the system indeed. This is directly from the 5.5.1 docs: "MARR {MARRIAGE}: = A legal, commonlaw, or
customary event of creating a family unit of a man and a woman as husband and wife."
(homepages.rootsweb.ancestry.com/~pmcbride/gedcom/55gcappa.htm)Asyoucansee,nosamesexmarriagehere.BertGoethals
(1)@BertGoethals:Hereisatestwhichyoucaneasilyperformyourself:[1]CreateasamesexmarriageinaFamilyTreeMakerfile
[2]exporttoGEDCOM[3]ImporttheGEDCOMfileintoRootsMagic.Thesamesexmarriageispreserved(vg.bothpartnersarestill
male).Howdidthathappen?Don'tconfusewhatthespec.recommends,versuswhatisactuallypossible.Pierre
(1)"relationsneedtwoindividuals"nope!MarkAmery
@MarkAmeryProbablysafetosayhewasimplying"atleast".TylerH
@TylerH I did mean at least. Also any "relation" could be expressed as a multiple of pairs. Eg: a threesome can be expressed as 2
relationsperindividual.BertGoethals
@Pierre My post is about the Spec not about what other applications try to achieve by breaking the spec. A spec "specifies" not
recommends.Thefactthatimplementersarebreakingthespecindicatesthatthespecisindeedflawed.BertGoethals
1

http://www.stackprinter.com/export?question=6163683&service=stackoverflow

2/9

1/8/2017

Cyclesinfamilytreesoftware

[+565][2011052819:20:12]BenVoigt
Relaxyourassertions.
Not by changing the rules, which are mostly likely very helpful to 99.9% of your customers in catching mistakes in
enteringtheirdata.
Instead,changeitfromanerror"can'taddrelationship"toawarningwithan"addanyway".
(143)Whenencounteringaveryunlikelysituation,thatis,onewhereauserwouldusuallyonlydoitbymistake,itisagoodideato
showtheuserawarning.That'sgoodfeedback.Butthenlettheusergoaheadiftheyarereallysuretheywantto.SoIthinkthisisa
goodanswer,evenifitdoesn'tgetintothenutsandboltsofhow.thomasrutter
(15)Goodanswer!Ijustwonder,howthiskindofsoftwarewillhandle"Iammyowngrandpa"(youtube.com/watch?v=eYlJH81dSiw)
situation?ZaurNasibov
(4)Thisisnotreallyananswer,becauseIthinktheproblemcomesfromactuallytraversingthetree?However,itisagoodsuggestion.
bdwakefield
(3)@bdwakefield:Thequestionwas"HowdoIresolvetheseerrors,withoutremovingalldataassertions?"IbelieveI'veansweredthat.
BenVoigt
(2)@BenItdependsonwhattheassertionsarefor.Iftheypreventinfiniteloopsorfatalerrorsfromhappening,thenyouareeffectively
suggestingtoremovetheassertions.Iftheyarejusttheretowarnauserofapotentialmistake,thenyouranswerisagoodone.rm999
@rm999:Thequestionisprettyclearthattheassertionsareenforcedaftertraversingthedatastructure.BenVoigt
(1)@Ben I think we are reading the question differently. I interpret "cycle" to mean a cycle in the graph (which would mean during
traversal). This makes sense in the context of the question: OP assumes a tree structure, and a child having the same father and
grandfather is a loop and hence not a tree. Many tree traversal algorithms would fail on a graph with loops, so if my reading of the
questioniscorrectbdwakefieldhasanentirelylegitimatepoint.rm999
2

[+224][2011060109:58:15]exDM69
Here'stheproblemwithfamilytrees:theyarenottrees.TheyaredirectedacyclicgraphsorDAGs.IfIunderstandthe
principlesofthebiologyofhumanreproductioncorrectly,therewillnotbeanycycles.
AsfarasIknow,eventheChristiansacceptmarriages(andthuschildren)betweencousins,whichwillturnthefamily
treeintoafamilyDAG.
Themoralofthestoryis:choosetherightdatastructures.
(7)Itwouldneedafurtherrestrictionofeverynodehaving1or2maximumnodespointingtoitforinvitroandsexualreproduction.
Although to be more true to real life, you might allow multiple dashed lines for uncertain descendancy on the father side (it's always
clear who the mother is, but only DNA testing can insure who the father is, and that's rarely done even today), or even for both is
adoptionistakenintoaccount.manixrock
(7)@manixrock since this question is about rare cases, i would like to assert that is not always clear who the mother is. adoptions,
abandonedbabies,surrogatemoms,etccanallcomplicatematters.PeterRecore
(9)It'snotnecessarilyacyclic,isit?Manmarriesgrandmother.EdRopple
(13)Manmarryinghisongrandmotherwillnotmakehimselfhisowngrandfatherandaddingacycle.Iftheyhavechildren,itwillbea
noncyclingregulargraphedge.exDM69
(11)It'sactuallyTWOADGs.Thereistheparentagegraphandthelegalrelationshipgraph.Usuallythesame,butdivergentmorethan
onemightexpect.JSacksteder
(1)Generally speaking there will be cycles. Just not cycles of the "parent of" type of relationship. There can very well be cycles in
relationshipsgenerally,suchas"marriedto",especiallywhenyouconsiderthattheserelationshipschangeovertime.Agrajag
(2)Assumingperfectknowledgeandbiology,therewon'tbeanycyclesinbiologicalancestry,butintherealworldgenealogyisfullof
"perhaps"links.manxrockabove,forexample,assertsthatit'salwaysclearwhothemotheris.Whichisnottrueintherealworld.Yes,
todayDNAtestingcananswerthatquestion,buthowareyougoingtogetyourrelativefrom5generationsbackDNAtested?Agrajag
3

[+115][2011052818:50:16]EduardThamm
Iguessthatyouhavesomevaluethatuniquelyidentifiesapersononwhichyoucanbaseyourchecks.
Thisisatrickyone.Assumingyouwanttokeepthestructureatree,Isuggestthis:
Assumethis:Ahaskidswithhisowndaughter.
AaddshimselftotheprogramasAandasB.Onceintheroleoffather,let'scallitboyfriend.

http://www.stackprinter.com/export?question=6163683&service=stackoverflow

3/9

1/8/2017

Cyclesinfamilytreesoftware

Addais_same_for_out() function which tells the output generating part of your program that all links going to B
internallyshouldbegoingtoAonpresentationofdata.
Thiswillmakesomeextraworkfortheuser,butIguessITwouldberelativelyeasytoimplementandmaintain.
Buildingfromthat,youcouldworkoncodesynchingAandBtoavoidinconsistencies.
Thissolutionissurelynotperfect,butisafirstapproach.
(9)Probablysuch"proxy"nodesareindeedsuitablesolution.HoweverIhavenoideahowcanthosebeputinuserinterfacewithout
offendinguser.Icantellyouthatwritingsoftwarethatdealswithrealpeople(especiallyyourcustomers)isnoteasy.PartickHse
(6)ItneverendsB'snewsonwillbehisownuncle.Iwouldconsiderafullrefundfortheprogram!BoPersson
(2)Jupitisakindofmessedupsituation.IsinlineprologpossibleinC++?EduardThamm
(3)@WillA:Andthenrealizesheisalsohisownmother,andrecruitshisyoungerselfintothetimeagency?NullSet
@EduardThamm,maybe:swiprolog.org/contrib/CPP.htmlIdon'tunderstandhalfofit.Prof.Falken
(2)Duplication (and syncing) of data within one system is bad practice. It indicates that the solution is sub optimal and should be
reconsidered.Ifcreatingextra(duplicate)nodeswouldbeneeded,indicateitasaproxyanddelegatethedatareadsandwritestothe
originalnode.BertGoethals
(1)What portion of your customers does this scenario represent? Is it worthwhile to add it? I hope this doesn't represent your target
market.OscarRyz
@AmigableClarkKantThisactuallylooksgood.EduardThamm
4

[+84][2011060108:51:56]christopheml
You should focus on whatreallymakesvalueforyoursoftware. Is the time spent on making it work for ONE
consumerworththepriceofthelicense?Likelynot.
Iadviseyoutoapologizetothiscustomer,tellhimthathissituationisoutofscopeforyoursoftwareandissuehima
refund.
(3)Verytrue.Butalsoweighotherpotentialproblemswithsimilartroublesothershavebroughtup.Prof.Falken
(2)Ofcourse.Thereasoningis:ifit'sarareedgecaseonanoncriticalapplication,youarenotrequiretofixorimplementanything.If
it'sreallyhurtingyourusers,there'svalueinworkingonit.christopheml
(10)Probablyeverybodyhassomecaseofincestsomewhereinhis/herancestry.Soyou'llhitthatbumpifonedigsfamilyhistory(too)
deep.datenwolf
(1)Makinggenealogytreeofsomeweirdsituation(inbreedroyalty,Fritzletc)isvaliduseofsoftware.Bulwersator
(1)Afamilytreesoftwarethatwon'tallowsecondcousinstomarryisuseless.Nearlyallfamilieshasatleastonecaseofthis.Whichis
whyIthinktheoriginalexampleismadeupforeffect.Fuzzy76
5

[+79][2011060116:10:42]user779752
YoushouldhavesetuptheAtreides [1]family(eithermodern,Dune [2],orancient,OedipusRex)asatestingcase.You
don'tfindbugsbyusingsanitizeddataasatestcase.
[1]http://en.wikipedia.org/wiki/House_Atreides
[2]http://en.wikipedia.org/wiki/House_Atreides
(2)Sadly,waytoomanypeoplefirstthinkof'ok'datainsteadoftheedgecasesthatbreaktheirsystems.sjas
6

[+59][2011060106:10:44]TimPost
This is one of the reasons why languages like "Go" do not have assertions. They are used to handle cases that you
probably didn't think about, all too often. You should only assert the impossible, not simply the unlikely.
Doingthelatteriswhatgivesassertionsabadreputation.Everytimeyoutypeassert(,walkawayfortenminutesand
reallythinkaboutit.
Inyourparticularlydisturbingcase,itisbothconceivableandappallingthatsuchanassertionwouldbebogusunder
rarebutpossiblecircumstances.Hence,handleitinyourapp,ifonlytosay"Thissoftwarewasnotdesignedtohandle
thescenariothatyoupresented".
Assertingthatyourgreat,great,greatgrandfatherbeingyourfatherasimpossibleisareasonablethingtodo.

http://www.stackprinter.com/export?question=6163683&service=stackoverflow

4/9

1/8/2017

Cyclesinfamilytreesoftware

If I was working for a testing company that was hired to test your software, of course I would have presented that
scenario.Why?Everyjuvenileyetintelligent'user'isgoingtodotheexactsamethingandrelishintheresulting'bug
report'.
(48)Dont'forgetfrozensperm...Prof.Falken
(5)Agreewith'whentouseassertions'argumentdon'tseehowitrelatesto'somelanguageshaveasserts,Godoesn't.'phooji
@TimPostIfyouknowit'simpossible,thenwhybotherassertingit?Arlen
(2) @Red Hue sometimes compilers make the impossible ... possible. Some versions of gcc think 10 == 10 in the abs()
implementation.TimPost
@AmigableClarkKantDon'tforgetmaintainers:)TimPost
(2)@RedHue:Thewholepointofassertionsistodocumentandtestconditionsthatshouldalwaysbetrue(orfalse).Ithelpskeepyou
(andothers)from"fixing"thingsinsuchawaythatthoseimpossiblecasesarise,asthenthey'dexplicitly(ratherthansubtly)breakthe
app.Ifthere'savalidreasonforan"impossible"casetoappear,thenyou'veassertedtoomuch.cHao
(1)@cHao@TimPostI'mjusttryingtounderstandwhyGonothavingassertionsisagoodthingsincemostofyouagreethatassertion
isimportanttohave.Arlen
(1) @Red Hue: I imagine that point of view is based on cases like the original question, where assertions are being a bit abused.
Assertingtoomuch(ortoolittle)ismorecommonthanmanypeoplewillrealize,becausepeoplerarelylearntouseassertionsproperly.
It'salsoadevtimething,whichoftenwon'tbetestedinproductionanyway,sosomewouldconcludethatthebestwaytohandleitisto
getridofassertionsaltogether.Idisagree,buthavesomesympathyforthereasoningbehindit.cHao
(1)Ifalanguagehasassertionsornotbuiltinwillhardlymuchimpactonifdeveloperswilluseanassertionpattern,ornot,intheircode.
ManyIamsureevendoitwithoutknowingthatit'scalledanassertion...Prof.Falken
(5)Havingassertions(orassertionlikecode)isirrelevant.CodeinlanguageslikeGocanandwillmakeassumptionsaboutthestructure
of data it just can't document and enforce those assumptions with assertions. Bottom line: the application has a bug. Tommy
McGuire
Thisquestionhasnothingtodowithlanguagefeatures.gvd
7

[+41][2011052818:55:14]Sean
Ihatecommentingonsuchascrewedupsituation,buttheeasiestwaytonotrejiggerallofyourinvariantsistocreatea
phantomvertexinyourgraphthatactsasaproxybacktotheincestuousdad.
8

[+37][2011060118:39:33]tfinniga
So,I'vedonesomeworkonfamilytreesoftware.Ithinktheproblemyou'retryingtosolveisthatyouneedtobeableto
walkthetreewithoutgettingininfiniteloopsinotherwords,thetreeneedstobeacyclical.
However,itlookslikeyou'reassertingthatthereisonlyonepathbetweenapersonandoneoftheirancestors.Thatwill
guarantee that there are no cycles, but is too strict. Biologically speaking, descendancy is a directed acyclic graph [1]
(DAG).Thecaseyouhaveiscertainlyadegeneratecase,butthattypeofthinghappensallthetimeonlargertrees.
Forexample,ifyoulookatthe2^nancestorsyouhaveatgenerationn,iftherewasnooverlap,thenyou'dhavemore
ancestorsin1000ADthantherewerepeoplealive.So,there'sgottobeoverlap.
However,youalsodotendtogetcyclesthatareinvalid,justbaddata.Ifyou'retraversingthetree,thencyclesmustbe
dealtwith.Youcandothisineachindividualalgorithm,oronload.Ididitonload.
Findingtruecyclesinatreecanbedoneinafewways.Thewrongwayistomarkeveryancestorfromagivenindividual,
and when traversing, if the person you're going to step to next is already marked, then cut the link. This will sever
potentiallyaccuraterelationships.Thecorrectwaytodoitistostartfromeachindividual,andmarkeachancestorwith
the path to that individual. If the new path contains the current path as a subpath, then it's a cycle, and should be
broken.Youcanstorepathsasvector<bool>(MFMF,MFFFMF,etc.)whichmakesthecomparisonandstorageveryfast.
There are a few other ways to detect cycles, such as sending out two iterators and seeing if they ever collide with the
subsettest,butIendedupusingthelocalstoragemethod.
Alsonotethatyoudon'tneedtoactuallyseverthelink,youcanjustchangeitfromanormallinktoa'weak'link,which
isn'tfollowedbysomeofyouralgorithms.Youwillalsowanttotakecarewhenchoosingwhichlinktomarkasweak
sometimesyoucanfigureoutwherethecycleshouldbebrokenbylookingatbirthdateinformation,butoftenyoucan't
figureoutanythingbecausesomuchdataismissing.
[1]http://en.wikipedia.org/wiki/Directed_acyclic_graph

http://www.stackprinter.com/export?question=6163683&service=stackoverflow

5/9

1/8/2017

Cyclesinfamilytreesoftware

Carefulaboutthoseassumptionsonemaleandonefemaleparentisn'tagivenwhenpeopleadapt,orlesibanswhoconsiderthemselves
asparents,inthenearfuturetheymayevenbeabletoreallybebiologicallytheparents,atleastofgirls.Forthatmatter,ifweapplydolly
tohumans,eventheassumption"apersonhastwodistinctparents"isout.Agrajag
(1)@Agrajag,yesthat'swhyIspecified"biologicallyspeaking"forthecycledetection.Evenbiologically,therearelotsofpossibleissues,
like surrogate mothers and artificial insemination. If you also allow adoptions and other nonbiological methods for defining parents,
thenit'spossibletohaveavalidtruecycleinatreeforexample,maybesomeoneadoptstheirgrandparentwhentheygetoldandare
no longer able to take care of themselves. Making assumptions about people's family life is always complicated. But when writing
softwareyouneedtomakesomeassumptions..tfinniga
9

[+36][2011060114:12:54]clvrmnky
Anothermockseriousanswerforasillyquestion:
Therealansweris,useanappropriatedatastructure.Humangenealogycannotfullybeexpressedusingapuretreewith
nocycles.Youshouldusesomesortofgraph.Also,talktoananthropologistbeforegoinganyfurtherwiththis,because
thereareplentyofotherplacessimilarerrorscouldbemadetryingtomodelgenealogy,eveninthemostsimplecaseof
"Westernpatriarchalmonogamousmarriage."
Evenifwewanttoignorelocallytaboorelationshipsasdiscussedhere,thereareplentyofperfectlylegalandcompletely
unexpectedwaystointroducecyclesintoafamilytree.
Forexample:http://en.wikipedia.org/wiki/Cousin_marriage
Basically, cousin marriage is not only common and expected, it is the reason humans have gone from thousands of
smallfamilygroupstoaworldwidepopulationof6billion.Itcan'tworkanyotherway.
Therereallyareveryfewuniversalswhenitcomestogenealogy,familyandlineage.Almostanystrictassumptionabout
norms suggesting who an aunt can be, or who can marry who, or how children are legitimized for the purpose of
inheritance,canbeupsetbysomeexceptionsomewhereintheworldorhistory.
(9)Yourcommentmademethinkofpolygamy.Genealogysoftwarethatonlymodelssexualreproductionmayrequireanameattached
tothespermandtheeggbutbroaderdefinitionsoffamilystructuredonot.SteveKalemkiewicz
Genealogy software will often allow more than one spouse in the model. How you display the model in the view varies widely, even
withinoneprogram,dependingonthe"mode"thathasbeenprovided.ToddHopkinson
10

[+20][2011052818:49:45]WillA
Potentiallegalimplicationsaside,itcertainlyseemsthatyouneedtotreata'node'onafamilytreeasapredecessor
personratherthanassumingthatthenodecanbetheoneandonlyperson.
Havethetreenodeincludeapersonaswellasthesuccessorsandthenyoucanhaveanothernodedeeperdownthetree
thatincludesthesamepersonwithdifferentsuccessors.
11

[+13][2011060119:55:59]kerkeslager
Afewanswershaveshownwaystokeeptheassertions/invariants,butthisseemslikeamisuseofassertions/invariant.
Assertions are to make sure something that should be true is true, and invariants are to make sure something that
shouldn'tchangedoesn'tchange.
Whatyou'reassertinghereisthatincestuousrelationshipsdon'texist.Clearlytheydoexist,soyourassertionisinvalid.
Youcanworkaroundthisassertion,buttherealbugisintheassertionitself.Theassertionshouldberemoved.
12

[+8][2011060112:22:18]PatrickCornelissen
Yourfamilytreeshouldusedirectedrelations.Thiswayyouwon'thaveacycle.
13

[+5][2012121219:08:20]TylerDurden
http://www.stackprinter.com/export?question=6163683&service=stackoverflow

6/9

1/8/2017

Cyclesinfamilytreesoftware

Genealogicaldataiscyclicanddoesnotfitintoanacyclicgraph,soifyouhaveassertionsagainstcyclesyoushould
removethem.
Thewaytohandlethisinaviewwithoutcreatingacustomviewistotreatthecyclicparentasa"ghost"parent.Inother
words, when a person is both a father and a grandfather to the same person, then the grandfather node is shown
normally,butthefathernodeisrenderedasa"ghost"nodethathasasimplelabellike("seegrandfather")andpointsto
thegrandfather.
Inordertodocalculationsyoumayneedtoimproveyourlogictohandlecyclicgraphssothatanodeisnotvisitedmore
thanonceifthereisacycle.
14

[+4][2011060606:12:48]NasserHadjloo
Themostimportantthingistoavoid creating a problem,soIbelievethatyoushoulduseadirectrelation to
avoidhavingacycle.
As@markmywordssaid,#include"fritzl.h".
Finally I have to say recheck your data structure. Maybe something is going wrong over there (maybe a
bidirectionallinkedlistsolvesyourproblem).
15

[+4][2015012614:17:42]stefan.schwetschke

Assertionsdon'tsurvivereality
Usuallyassertionsdon'tsurvivethecontactwithrealworlddata.It'sapartoftheprocessofsoftwareengineeringto
decide,withwhichdatayouwanttodealandwhichareoutofscope.

Cyclicfamilygraphs
Regardingfamily"trees"(infactitarefullblowngraphs,includingcycles),thereisaniceanecdote:
Imarriedawidowwhohadagrowndaughter.Myfather,whooftenvisitedus,fellinlovewithmystep
daughterandmarriedher.Asaresult,myfatherbecamemyson,andmydaughterbecamemymother.
Sometimelater,Igavemywifeason,whowasthebrotherofmyfather,andmyuncle.Myfather'swife
(whoisalsomydaughterandmymother)gotason.Asaresult,Igotabrotherandagrandsoninthesame
person.Mywifeisnowmygrandmother,becausesheismymother'smother.SoIamthehusbandofmy
wife,andatthesametimethestepgrandsonofmywife.Inotherwords,I'mmyowngrandpa.
Thingsgetevenmorestrange,whenyoutakesurrogates[1]or"fuzzyfatherhood"intoaccount.

Howtodealwiththat
Definecyclesasoutofscope
Youcoulddecidethatyoursoftwareshouldnotdealwithsuchrarecases.Ifsuchacaseoccurs,theusershouldusea
different product. This makes dealing with the more common cases much more robust, because you can keep more
assertionsandasimplerdatamodel.
Inthiscase,addsomegoodimportandexportfeaturestoyoursoftware,sotheusercaneasilymigratetoadifferent
productwhennecessary.

Allowmanualrelations
http://www.stackprinter.com/export?question=6163683&service=stackoverflow

7/9

1/8/2017

Cyclesinfamilytreesoftware

You could allow the user to add manual relations. These relations are not "firstclass citizens", i.e. the software takes
themasis,doesn'tcheckthemanddoesn'thandletheminthemaindatamodel.
The user can then handle rare cases by hand. Your data model will still stay quite simple and your assertions will
survive.
Becarefulwithmanualrelations.Thereisatemptationtomakethemcompletelyconfigurableandhencecreateafully
configurabledatamodel.Thiswillnotwork:Yoursoftwarewillnotscale,youwillgetstrangebugsandfinallytheuser
interfacewillbecomeunusable.Thisantipatterniscalled"softcoding"[2],and"ThedailyWTF"[3]isfullofexamplesfor
that.

Makeyourdatamodelmoreflexible,skipassertions,testinvariants
Thelastresortwouldbemakingyourdatamodelmoreflexible.Youwouldhavetoskipnearlyallassertionsandbase
yourdatamodelonafullblowngraph.Astheaboveexampleshows,itiseasilypossibletobeyourowngrandfather,so
youcanevenhavecycles.
Inthiscase,youshouldextensivelytestyoursoftware.Youhadtoskipnearlyallassertions,sothereisagoodchancefor
additionalbugs.
Useatestdatageneratortocheckunusualtestcases.TherearequickchecklibrariesforHaskell[4],Erlang[5]orC [6].For
Java / Scala there are ScalaCheck [7] and Nyaya [8]. One test idea would be to simulate a random population, let it
interbreedatrandom,thenletyoursoftwarefirstimportandthenexporttheresult.Theexpectationwouldbe,thatall
connectionsintheoutputarealsointheinputandviceverse.
Acase,whereapropertystaysthesameiscalledaninvariant.Inthiscase,theinvariantisthesetof"romanticrelations"
between the individuals in the simulated population. Try to find as much invariants as possible and test them with
randomlygenerateddata.Invariantscanbefunctional,e.g.:
anunclestaysanuncle,evenwhenyouaddmore"romanticrelations"
everychildhasaparent
apopulationwithtwogenerationshasatleastonegrandparent
Ortheycanbetechnical:
Yoursoftwarewillnotcrashonagraphupto10billionmembers(nomatterhowmanyinterconnections)
YoursoftwarescaleswithO(numberofnodes)andO(numberofedges^2)
Yoursoftwarecansaveandreloadeveryfamilygraphupto10billionmembers
Byrunningthesimulatedtests,youwillfindlotsofstrangecornercases.Fixingthemwilltakealotoftime.Alsoyou
willlosealotofoptimizations,yoursoftwarewillrunmuchslower.Youhavetodecide,ifitisworthitandifthisisin
thescopeofyoursoftware.
[1]http://en.wikipedia.org/wiki/Surrogacy
[2]http://thedailywtf.com/articles/Soft_Coding
[3]http://www.thedailywtf.com/
[4]https://wiki.haskell.org/Introduction_to_QuickCheck1
[5]http://www.quviq.com/products/erlangquickcheck/
[6]http://www.quviq.com/products/quickcheckforc/
[7]http://scalacheck.org/
[8]https://github.com/japgolly/nyaya
16

[+3][2011120210:19:49]ctype.h
Instead of removing all assertions, you should still check for things like a person being his/her own parent or other
impossiblesituationsandpresentanerror.Maybeissueawarningifitisunlikelysotheusercanstilldetectcommon
inputerrors,butitwillworkifeverythingiscorrect.
Iwouldstorethedatainavectorwithapermanentintegerforeachpersonandstoretheparentsandchildreninperson
objectswherethesaidintistheindexofthevector.Thiswouldbeprettyfasttogobetweengenerations(butslowfor
thingslikenamesearches).Theobjectswouldbeinorderofwhentheywerecreated.
17

http://www.stackprinter.com/export?question=6163683&service=stackoverflow

8/9

1/8/2017

Cyclesinfamilytreesoftware

[3][2012011304:39:52]numeric
Duplicatethefather(orusesymlink/reference).
Forexample,ifyouareusinghierarchicaldatabase:
$#eachpersonnodehastwonodesrepresentingitsparents.
$mkdirFamily
$mkdirFamily/Son
$mkdirFamily/Son/Daughter
$mkdirFamily/Son/Father
$mkdirFamily/Son/Daughter/Father
$lnsFamily/Son/Daughter/FatherFamily/Son/Father
$mkdirFamily/Son/Daughter/Wife
$treeFamily
Family
Son
Daughter
Father
Wife
Father>Family/Son/Daughter/Father
4directories,1file

(3) The ln s command doesn't work that way the resolution of the link Family/Son/Father will look for
Family/Son/Daughter/FatherfromunderFamily/Son,wherethelinkresides,notfrom.whereyouissuedthelnscommand.
musiphil
(48)cloningisprohibitedbythegenevaconventionsMikeIsrael
18

http://www.stackprinter.com/export?question=6163683&service=stackoverflow

9/9

Potrebbero piacerti anche