Package: endplay
endplayendplayis a Python library providing a variety of different tools for generating, analysing, solving and scoring bridge deals. It is a collection of different tools based on Bo Haglund's famousdds library, Hans van Staveren'sdealer programand other personal projects which have been cobbled together into a compatible interface using a common type system based on the encodings defined in the dds library.If you find this useful and would like to contribute, or found it totally buggy and broken and want to fix it, then I am very open to contributions.Table of ContentsendplayBuilding and installingFrom PyPIFrom sourceFor developmentBuilding the documentationRunning the test suiteOverview of submodulesTutorialInspecting dealsEnumerated typesTheinteractmoduleGenerating handsThe main moduleEvaluating handsAssigning point values to handsEvaluating shapeDouble dummy analysisAnalyseDD TablesPar contract calculation and scoring contractsBids and auctions: an asideSolving for a player's handParsing to and from bridge file formats (PBN, LIN, JSON)Building and installingFrom PyPIBinary Python wheels are built and distributed onPyPIfor the following Python versions:ArchitectureWindowsLinuxMacOSx86N/AN/A3.7-3.11x643.7-3.113.7-3.113.7-3.11On these systemspython3 -m pip install endplaywill install these pre-built wheels, otherwise it will attempt to install from the source distribution which requires a C++ compiler on your system. Note thatendplayrequires Python 3.7+.The version of the library available on PyPI may be older than the current status of the repo, this is to ensure stability of these builds. For access to the latest bug fixes and preview features, you can install directly from the GitHub repo withpython3 -m pip install +git:https://github.com/dominicprice/endplayFrom sourceendplayusessetuptoolsto manage its build and can be installed withpip.# Clone repo and submodulesgitclone--recursivehttps://github.com/dominicprice/endplay.gitcdendplay
python3-mpipinstall.If you want to build the binary wheels for your system, you can use thebuildpackage. This will create an isolated environment when collecting packages so you do not need to perform this in a virtual environment.# Only build is required to start the build, other packages# are automatically fetchedpython3-mpipinstallbuild
python3-mbuild# generates dist/endplay-<VERSIONSUFFIX>.whlFor developmentIf you are trying to develop for the library, then it is recommended to do all your testing in a virtual environment:python3-mpipinstallvirtualenv
virtualenvvenvsourcevenv/bin/activate# on windows, `cmd venv\scripts\activate`python-mpipinstall.# installs into the created venvYou can then modify some files, and when you want to debug simply rerunpython -m pip install .and the old build will be overwritten. This also has the advantage of being able to reuse the cache from the previous install (including the CMake cache) which speeds up build time.If you are not planning on modifying the underlying C library, its packaging logic or the config file, then you can avoid having to reinstall each time by making an in-source build and symlinking this into your site packages. The simplest way to do this is to run the following from the root directory:mkdirbuild&&cdbuild
cmake-DCMAKE_INSTALL_PREFIX=../src..
cmake--build.--targetinstallcd../srcpwd>"$(python-msite--user-site)/endplay.pth"The last command will work on POSIX systems, on Windows you can get the site packages directory by runningpython -m site --user-siteand creating a fileendplay.pththere with a single line containing the absolute path to<ENDPLAY_ROOT>/src.The.gitignoreis set up to ignore the files CMake installs so no extra care needs to be taken when staging and committing your changes to git.Building the documentationThe documentation is semi-auto generated with sphinx. To build it, ensure thatendplayis installed and thencdinto the root directory and then runcddocs
makehtml# or latex, or whatever output format you wantThe documentation will be built in thebuilddirectory.Running the test suiteThe test suite is implemented with theunittestlibrary and can be run from the root directory withpython3-mpytestOverview of submodulesendplayis divided into six main components, each of which can interoperate with each other:endplay.typesis the basis for the whole library, providing the classes which are used by all the other modules for encapsulating the key objects in bridge. The 'master' class isDeal, whose state consists of the four hands in the deal, the cards played to the current trick,  a trump suit and the player to lead to the current trick. All the methods one would expect to  be defined on this are provided - accessing the hands, playing/unplaying cards from the current trick, importing and exporting from PBN format etc. From this class there is a hierarchy of typesDeal -> Hand -> SuitHolding -> Rankwhich allows introspection of the deal at any level wanted. Many other types, such as containers for holding results from double dummy analysis and storing contracts, are also provided here.endplay.dealerprovides functions for generating bridge hands. The main function isgenerate_dealswhich can accept a list of constraints (either  functions which accept aDealobject and returnTrue/False, or strings written indealer syntax) and generates a specified number of deals which satisfy the constraints. Thedealermodule can also be run as a main module withpython3 -m endplay.dealer(or simplyendplay-dealer) which works very similarly to the  Hans van Staverendealer program, but with some different output options and extra functionality.endplay.evaluateis the simplest component, consisting of a variety of functions which evaluate various properties of bridge hands, such as calculating high  card points, shape, losers, controls and other algorithms for estimating the quality of a hand.endplay.ddsis a high-level wrapper around Bo Haglund'sdds librarywhich takes care of converting between the different types and encodings it uses internally and providing sensible defaults for things such as the number of threads it uses. A lower level wrapperendplay._dds, which is little more than the basicctypesdeclarations, is also provided and is used internally by the dds functions when making library calls.endplay.parsersprovides tools for parsing common file types which are used as inputs and outputs for bridge software, this includes PBN and Dealer. These produce document tree representation of the input files and are used internally for many things, but can also be traversed manually to create programs which interact with other bridge software easily.endplay.interactprovides theCommandObjectclass which keeps an undo stack whenever its state is modified, making it easier to interact with the deal. The main purpose of the module is to provide a tool to create interactive deal programs, such as the main module (python3 -m endplay.interactorendplay-interact) which provides a a set of frontends analysing bridge deals.TutorialInspecting dealsTheDealobject is the class which is most frequently used inendplay. A deal can be constructed most simply by specifying it as a PBN string:>>>fromendplay.typesimportDeal>>>d=Deal("N:974.AJ3.63.AK963 K83.K9752.7.8752 AQJ5.T864.KJ94.4 T62.Q.AQT852.QJT")The PBN string starts with a letter representing the first hand and a colon, and then each of the four hands separated by a space, where each hand consists of the cards in spades, hearts, diamonds and clubs respectively separated by a dot. The__str__method of the deal returns the deal as a PBN string, but apprintmethod is provided to view the deal as a hand diagram:>>>print(d)N:974.AJ3.63.AK963K83.K9752.7.8752AQJ5.T864.KJ94.4T62.Q.AQT852.QJT>>>d.pprint()974AJ363AK963T62K83QK9752AQT8527QJT8752AQJ5T864KJ944The four hands can be viewed by using thenorth,east,southandwestproperties, by using the__getitem__operator or by iterating over the deal to loop over all four hands:>>>d.northHand("974.AJ3.63.AK963")>>>fromendplay.typesimportPlayer>>>w=d[Player.west]>>>w.pprint()♠T62♥Q♦AQT852♣QJT>>>forp,hind:...print(h)974.AJ3.63.AK963K83.K9752.7.8752AQJ5.T864.KJ94.4T62.Q.AQT852.QJTNote that iterating over the deal returns(Player, Hand)tuples. If your terminal doesn't handle the Unicode suit symbols, then you can tellendplayto use the letters SHDC instead:>>>fromendplayimportconfig>>>config.use_unicode=False>>>w.pprint()ST62HQDAQT852CQJTIf there is a particular section of code which you would like to turn off unicode suit symbols for, for example if you are trying to export to export to a certain file format or would just like a particular piece of output to be formatted in plaintext, then you can use thesuppress_unicodecontext manager:>>>config.use_unicode=True>>>fromendplay.configimportsuppress_unicode>>>print(Denom.spades.abbr)♠>>>withsuppress_unicode():...print(Denom.spades.abbr)S>>>print(Denom.spades.abbr)♠TheHandobject which is returned is bound to the data inside the deal, so any operations you perform on the hand will update the deal too; to get a copy of the hand which doesn't affect the deal object you should use thecopymethod.Dealalso overloads the__setitem__function and accepts aHandobject which is copied into the deal, or a PBN string which sets the cards in the hand to the specified cards:>>>fromendplay.typesimportHand>>>d=Deal()>>>h=Hand("AQ..T964.QJ975")>>>d.west=h>>>d.west="AQ..T964.QJ975"# equivalentModifying the contents of the hand can be done using theadd,extendandremovemethods.addandremovereturnTrueif the operation was successful: attempting to remove a card which isn't in a hand, or adding a card which is already there causes it to returnFalse.>>>h=Hand()>>>h.add("SQ")True>>>print(h)Q...>>>h.extend(["SQ","HA","CT"])2>>>h.remove("D2")Falseextendreturns the number of cards which were added to the hand. As well as specifying cards by strings, theCardclass which stores aRankandDenomobject can also be used:>>>fromendplay.typesimportCard,Rank,Denom>>>c=Card(suit=Denom.hearts,rank=Rank.R9)>>>cinh# or "H9" in hFalse>>>len(h)3>>>print(", ".join(str(c)forcinh))♠Q,♥A,♣TCardobjects are immutable, but should not be tested for equality using identity (i.e. use==notis). The individual suit holdings in the hand can be examined by using thespades,hearts,diamondsandclubsproperties or using the__getitem__operator. This returns aSuitHoldingobject which, like accessing hands of a deal, returns an object which is bound to the data in the hand. Many of the methods defined inHandare also defined inSuitHolding, but use theRankclass instead of theCardclass:>>>s=h.spades>>>s.add(Rank.R2)True>>>print(h)Q2.A..T>>>Rank.RQinsTrue>>>forrankins:...print(rank)Rank.RQRank.R2Holdings in a hand can be specified using the__setitem__operator too:>>>h.diamonds="9752"Moving back to theDealobject itself, as well as the four hands it also contains some other information such as the trump suit, player on lead and cards played to the current trick. Many functions in theendplaylibrary will ignore these values, but the double dummy solving algorithms in particular may rely on these to provide accurate results. The trump suit and player on lead can be set by setting thetrumpandfirstproperties respectively:>>>d=Deal("65..2. .A.AK. .J.97. 8..83.")>>>d.trump=Denom.hearts>>>d.first=Player.south# not so fun, must concede all tricks to E>>>d.first=Player.north# helicopter coup successfulTricks can be played by using theplaymethod, and picked up using theunplaymethod. By default,endplayattempts to take the card to be played from the hand who is currently on lead and will raise an error if they do not hold it.>>>d.play("S6")# north tries a coup-en-passant>>>d.pprint()5---2---8^♠6------A83AK---------J97--->>>d.play("DA")>>>d.unplay()# East picks back up the DA>>>d.play("HA")# try ruffing instead...>>>d.play("D9")>>>d.play("S8")>>>d.pprint()5---2---------------83AK---------J7--->>>d.first<Player.east:1>Notice how after the final card to the trick is played, the trick is cleared andd.firstis assigned the winner of the trick. By passingfromHand=Falsetoplay, you can cause a card to be added to the current trick without attempting to remove it from anybody's hand:>>>d.play("HA")# can't play the HA againTraceback(mostrecentcalllast):File"<stdin>",line1,in<module>File"endplay\types\deal.py",line124,inplayraiseRuntimeError("Trying to play card not in hand")RuntimeError:Tryingtoplaycardnotinhand>>>d.play("HA",fromHand=False)# let's hope N isn't paying too much attentionSimilarly,unplaycan be passedtoHand=Falseto not move the picked-up card back into somebody's hand. The contents of the current trick can be examined by looking at thecurtrickproperty which returns a list of cards played to the current trick, however this is a read-only object and attempting to modify it will not alter theDealobject.Enumerated typesendplayexposes five enumerated types:Denom,Penalty,Player,RankandVul. These all have a fairly consistent interface to make handling them as convenient as possible:They have a staticfindmethod which allows them to be constructed from a string, e.g.Denom.find("hearts"),Penalty.find("x")orVul.find("ew"). There are often multiple ways of expressing these objects as strings (suit-symbols vs letters,luvvsnonefor vulnerability etc.) and thefindmethod does its best to convert whatever string you give it into a value. This raises aValueErrorif the conversion failsAs well as thenameproperty inherited fromEnumwhich returns a lowercase string, they also have anabbrproperty which return a one or two character abbreviation for the object. This is used by e.g. theCardclass to construct a string representation of the card (the__str__method consists of the single linereturn f"{self.suit.abbr}{self.rank.abbr}")All enumerations can have their members iterated over using e.g.for x in Player, however many also provide functions which allow iterating over the elements in a different order or over a subset of the elements (e.g.Denom.suits(),Denom.bidorder()). A few other unique methods for the enumerated types includeDenom.is_major()/Denom.is_minor()/Denom.is_suit()Player.lho/Player.partner/Player.rho. Rotating a playernpositions left or right can be done withPlayer.next(n)andPlayer.prev(n)Vul.from_board(n)for determining vulnerability from board number.Rankhas a sister-classAlternateRankwhich is used internally by some double dummy routines, but should not be used outside of this context.A full list of the methods can be found in the API reference of the documentation.TheinteractmoduleOne of my main motivations for building up this library is that sometimes I just want a quick way to see how a hand would play in a particular contract, or step through a deal card by card checking to see if a particular play would work. Using an interactive Python environment this is relatively easy, but in the end I developed a separate module calledinteractwhich implements a variety of frontends for interacting with deals. they can be run by executingpython3 -m endplay.interact, and a specific frontend can be selected by using the-x FRONTENDflag:-x cmdThe default frontend, a simple REPL inside your terminal-x cursesA curses frontend which runs inside the terminal-x htmlAn HTML frontend which opens inside your web browser, with the python program acting as a local server.Both thecmdandcursesfrontends require you to enter shell-like commands such asshuffle,deal 'PBNSTRING'orplay SA. You can typehelpto get a list of all available commands, orhelp CMDNAMEto get a specific help message about a command. Thehtmlinterface allows you to click on cards and buttons to interact with it, which under the hood it turns into these commands which it sends back to the server.The interactive interface keeps account of all the actions which have taken place, allowing you to type commands such asundoandredoto go back and forth through the state (orrewindandfastforwardto go to either end of the history).Generating handsTheendplay.dealercan be used to generate deals satisfying some constraints. The most basic usage is as follows:>>>fromendplay.dealerimportgenerate_deal>>>generate_deal()Deal('N:Q6.A872.KT3.J974 KT7.53.A42.AKQ85 AJ9853.KQ.J87.63 42.JT964.Q965.T2')Constraints can be provided as functions which take aDealobject and returnTrueorFalsebased on some condition. The functions provided in theendplay.evaluatemodule are useful for specifying these. In the following example, we generate a list of 10 deals where north might open 2NT:>>>fromendplay.evaluateimporthcp,is_balanced>>>defnorth_2nt(deal):...return20<=hcp(deal.north)<=22andis_balanced(deal.north)...>>>d=generate_deal(north_2nt)>>>d.pprint()Q83AKQJ7A9KQ3AKJ7652862T9K75JT3A8754962T94543Q8642JTInstead of defining the named functionnorth_2nt, we can of course also just provide an anonymous lambda to do the same thing.generate_dealcan be passed an arbitrary number of constraints which must all be satisfied, so the above is equivalent to:>>>d=generate_deal(lambdadeal:20<=hcp(deal.north)<=22,lambdadeal:is_balanced(deal.north))Internally,generate_dealgenerates random deals and checks whether they satisfy the constraints until it finds one which does which it then returns. If many conditions are specified, or you wish to generate freak deals, then the number of deals which need to be generated might be very large.generate_dealwill throw an exception if it generates enough deals that it doesn't think it will find a matching deal (defaulting to 1,000,000). This can be altered by providing themax_attemptsparameter; if it is set to-1then it will never throw this exception.generate_dealalso accepts string constraints which contain expressions using thedealer syntaxwhich it will parse and evaluate on the deal, making the above condition for a north 2NT opening equivalent to the following:>>>d=generate_deal("hcp(north) >= 20 && hcp(north) <= 22 && shape(north, any 4333 + any 4432 + any 5332)")This is ok for experimenting, but there is a large overhead involved with parsing and evaluating the string as this is currently all implemented in non-optimised Python, so if you are looking to do stats over many thousands of hands it is recommended to create a function instead.If you need to generate more than one deal then the generator functiongenerate_dealsis supplied. It accepts the exact same parameters asgenerate_dealwith an extraproduceparameter which defaults to 40. The deals are yielded, so if you want to collect them into a list then this must be done manually withlist(generate_deals()), however iterating over the lists as they are generated can be done with the naturalfor deal in generate_deals():construct.The main moduleThedealermodule can also be run as a program by executingpython3 -m endplay.dealer. Without any arguments this will generate and print 40 random deals. The main usage of this script is to emulate the behaviour of thedealer programand so if it is passed a dealer script file then it will interpret and execute it, although the format of the output will not correspond 1:1 with original program. Dealer scripts allow simple as well as more advanced functions to be performed. A simple example of a dealer script is the followingstayman.dlwhich produces hands where west opens a strong notrump and east has a Stayman hand and prints the two hands, which is useful for practicing partnership bidding.produce 2 // Number of hands we want to output
west1n =
	hcp(west) >= 15 &&
	hcp(west) <= 17 &&
	shape(west, any 4333 + any 4432 + any 5332)
eastStayman =
	hcp(east) >= 10 &&
	(hearts(east) == 4 || spades(east) == 4) &&
	hearts(east) < 5 && spades(east) < 5
condition west1n && eastStayman
action printewRunningpython3 -m endplay.dealer -s 510 stayman.dloutputs (with some whitespace trimmed)AQ5                         KT76
Q54                         AKT8
AQ62                        JT
Q97                         T65


AJ                          96
J43                         AQ72
AJT7                        Q65
AT97                        K843The-sparameter specifies a seed for the random number generator allowing reproducible results. Another use for the dealer module is to gather statistics about different hand types. The following script namedoops_2nt.dlgenerates hands where north opens 2NT and finds south without any honours, and calculates the average number of tricks north can make double dummy playing the contract:produce 30 // producing more will make the statistics more accurate
north2n =
    hcp(north) >= 20 &&
    hcp(north) <= 22 &&
    shape(north, any 4333 + any 4432 + any 5332)
disappointingSouth = hcp(south) == 0
condition north2n && disappointingSouth
action average tricks(north, notrumps)Running this on my machine takes a few minutes, even with only 30 hands, as the hand type is quite rare. In order to get some progress updates you can pass the-mflag which will display a progress bar as the hands are generated. To speed up generation of these sorts of hands, one of the swapping options can be passed which perform rotations on each shuffle:-2swaps the EW hands, and-3produces all permutations of the east, south and west hands; by default the-0switch (no swapping) is used. As the shuffle is a relatively expensive operation this can improve performance, however it is not fully compatible with predealt hands. A (not particularly scientific) comparison of the three swapping algorithms is outlined here using thestayman.dlfile using the seed-s 1234and the number of hands to produce increased to 1000:Swapping methodFlagstayman.dlruntimePredeal compatibilityNo swapping-053sN✅ E✅ S✅ W✅2-way swapping (E, W)-246s (~13% faster)N✅ E❌ S✅ W❌3-way swapping (E, S, W)-333s (~38% faster)N✅ E❌ S❌ W❌Of course, had we set upstayman.dlto produce bidding patterns for north and south, 2-way swapping would be significantly worse as swapping the east west hands does not change the value of the predicate.Evaluating handsWhen constructing constraints for use with thegenerate_deal/generate_dealsfunctions, or performing statistics over deals, various metrics for evaluating the quality of various aspects of a hand are useful.endplaycomes with a variety of functions for evaluating hands in theendplay.evaluatesubmodule. A full list of the functions contained in this submodule can be found in the API documentation; the list here is merely representative of the sorts of things which can be done.Assigning point values to handsBy far the most well known and widely applied metric for calculating the quality of a hand is the traditional 'high card points' scale where we assign points to each of the face cards: 4 for an ace, 3 for a king, 2 for a queen and 1 for a jack. Thehcpfunction can be used to evaluate a hand or suit holding using this metric:>>>fromendplay.typesimportHand>>>fromendplay.evaluateimporthcp>>>hand=Hand("AQ963.J64.852.K2")>>>hcp(hand)10>>>hcp(hand.hearts)1Although the 4321 metric is the most widely applied, it is sometimes preferable to use a different scale. One such scale is theBergen scalewhich assigns 4.5/3/1.5/0.75/0.25 to the top 5 cards. This scale is built into endplay asbergen_hcp_scaleand thehcpcan be told to use it by passing it as the second parameter:>>>fromendplay.evaluateimportbergen_hcp_scale>>>hcp(hand,bergen_hcp_scale)9.75If you want to use your own custom scale, then you can pass a list of numbers containing the point values of the cards in the order A, K, Q, J, ..., 3, 2. If the list has less than 13 values, then it is assumed to be continued with zeroes:>>>custom_hcp_scale=[6,4,2,1]# A=6, K=4, Q=2, J=1, all other cards worth no points>>>hcp(hand,custom_hcp_scale)13Another quality of the hand which is often described in terms of points is the distribution. A common system is to assign 3 points for a void, 2 points for a singleton and a single point for a doubleton. This is the standard behaviour of thedist_pointsfunction:>>>fromendplay.evaluateimportdist_points>>>hand2=Hand("AK.JT98765..Q963")>>>dist_points(hand2)4>>>dist_points(hand2.diamonds)3As with the high card points scale, there are many different ways of counting points and so thedist_pointsfunction accepts ascaleparameter which defines the counting method.endplaycomes with five different scales built into theevalutemodule:shortage_nofit_dist_scale: The standard 3/2/1 scaleshortage_fit_dist_scale: A 5/3/1 scale, often applied to a hand once a trump fit has been foundlength_dist_scale: Assigns a point for every extra card in a suit longer than 4, e.g. a five card suit is worth 1 point and a seven card suit is worth 3.mixed_nofit_dist_scale: A combination ofshortage_nofit_dist_scaleandlength_dist_scalemixed_fit_dist_scale: A combination ofshortage_fit_dist_scaleandlength_dist_scaleCustom scales can be passed as lists where thenth element (zero-indexed) is the number of points awarded to a suit of lengthn, and as with thehcpfunction the list is assumed to be padded with zeroes if later elements are omitted. As an example, the following scale just counts the number of tripletons in a hand:>>>tripletons=[0,0,0,1]>>>dist_points(hand,tripletons)2>>>dist_points(hand2,tripletons)0If a trump suit is found, then it usually the case that shortage points are not included in the calculation of distribution points. To account for this,dist_pointsalso takes anexcludeparameter with a list of suits to exclude from the calculation. Note that this is ignored if the object is aSuitHoldinginstead of aHand:>>>dist_points(hand2,exclude=[Denom.spades])3>>>dist_points(hand2.diamonds,exclude=[Denom.diamonds])3High card points and distribution points are often combined into a scale known as 'total points'. In its most basic form, this is simply the sum of the two metrics:>>>fromendplay.evaluateimporttotal_points>>>total_points(hand2)# = hcp(hand2) + dist_points(hand2) = 10 + 414An optionaltrumpparameter can be provided with a suit which is added to theexcludelist ofdist_points:>>>total_points(hand2,trump=Denom.spades)13Unprotected honours, i.e. honours which will drop if the opponents play higher honours from the top, are often discounted from the total points calculation. This can be enabled by setting theprotect_honoursflag:>>>total_points(hand)# 10 HCP and 1 doubleton11>>>total_points(hand,protect_honours=True)#Jxx drops and the point is removed10A more advanced method of calculating the overall strength of a hand is theKaplan Four Csmethod which is implemented in theccccalgorithm:>>>fromendplay.evaluateimportcccc>>>cccc(hand)11.15>>>cccc(hand2)13.950000000000001Evaluating shapeThe shape of a hand can be evaluated using theshapeandexact_shapefunctions; the former returns the shape ordered from longest to shortest whilst the latter always returns the shape in the order spades, hearts, diamonds and clubs:>>>fromendplay.typesimportHand>>>fromendplay.evaluateimportshape,exact_shape>>>h=Hand("AK92.A3.Q9.AK762")>>>shape(h)[5,4,2,2]>>>exact_shape(h)[4,2,2,5]Various predicate functions are provided to query more generally the 'class' of the hand shape:>>>fromendplay.evaluateimportis_balanced,is_semibalanced,is_single_suited,is_two_suited>>>is_balanced(h)# 4333, 4432 or 5332False>>>is_semibalanced(h)# balanced or 5422True>>>is_single_suited(h)# 6 or more cards in one suitFalse>>>is_two_suited(h)# 10 cards in two suitsFalseThere are more variants on these and optional parameters to fine tune their definitions, which can be found in the API documentation.Double dummy analysisA particularly important feature ofendplayis the ability to call routines from theC++ dds library. The library is built and distributed withendplayso it is not necessary to have a copy of the library built on your machine.The double-dummy solving algorithms are split across four components:endplay.dds.analysecontains algorithms for analysing play sequences, calculating the maximum number of tricks which can be made after each card is playedendplay.dds.ddtablehas the functions for calculating double-dummy tables, showing the maximum number of tricks that each player could make in each contractendplay.dds.parprovides par contract calculation algorithmsendplay.dds.solveprovides functions for calculating the maximum number of tricks each card in a player's hand can makeNB: out of laziness, I will often refer to 'maximum number of tricks' instead of 'double-dummy maximum number of tricks', i.e. the number of tricks that can be made assuming everybody at the table has perfect knowledge of where all the cards are and makes optimal plays at each opportunity.Most algorithms come in two variants, one which calculates a result for a single deal and a second which accepts multiple deals. The multiple deal variant is trivial to use if you understand how the single-deal versions work, so will not be covered here, but if you need to do calculations for multiple deals it is always better to use versions as they use multithreading and can reuse internal data structures.AnalyseTheanalysemodule consists of two pairs of functions:analyse_play/analyse_all_playsandanalyse_start/analyse_all_starts.The analysis functions are useful when you have the play history of a deal and want to see how optimal each card played was. Takethe following four card ending:>>>fromendplay.typesimportDeal,Player>>>d=Deal("AJ.6.A. KQ..K8. 4.A.Q4. 7..T.Q5",first=Player.south)>>>d.pprint()AJ6A---7KQ------TK8Q5---4AQ4---The optimal play here is of course to unblock the ace of diamonds and then return to hand with a heart which squeezes east; the play history for this would be something like (depending on which losing option east goes for):>>>fromendplay.ddsimportanalyse_play>>>history=[..."D4","DT","DA","D8",..."H6","DK","HA","S7",..."DQ","C5","SJ","SQ",..."S4","CQ","SA","SK"]As everyone has played optimally (not that EW get much of a chance to make a mistake) runninganalyse_playwill show that at each point in the play history EW can make no tricks:>>>h_analysis=analyse_play(d,history)>>>print(", ".join(str(n)forninh_analysis))0,0,0,0,0,0,0,0,0,0,0,0,0Despite being on the surface being nothing more than a computationally expensive way of printing a load of zeroes, it is worth noting two interesting things here:The number of tricks is displayed from the perspective of the player to the right of player on lead. This is because it attempts to show declarers trick count, and in a full deal the declarer is to the right of the person on lead. In this case, as we have a four card ending with declarer on lead we can passdeclarer_is_first=Trueto perform the swap and print4, 4, 4, ...There are 16 cards in the play history, but only 13 cards in the output. Two things are going on here: a) the number of tricks before any card is played is appended to the front and b) as the last four cards are all forced and no-one can alter the outcome of the contract at this stage these are not calculated by the algorithm. Therefore the number of cards returned in this instance is 16 (cards in play history) + 1 (starting tricks) - 4 (remove final trick) = 13.We all know that partner will never find this line though, so lets see what the function does when we play bridge ping-pong:>>>history2=[..."HA","C5","H6","SK",..."S4","S7","SJ","SQ"]>>>h2_analysis=analyse_play(d,history2,declarer_is_first=True)>>>print(", ".join(str(n)forninh2_analysis))4,3,3,3,4,4,4,3,3We could find all the suboptimal plays by checking whether the number of tricks goes up or down after each card is played:>>>fromitertoolsimportpairwise# Python 3.10 upwards only>>>forcard,tricksinzip(history2,pairwise(h2_analysis)):...iftricks[0]!=tricks[1]:...print(Card(card))♥A♠K♠JCashing the ace at the start breaks up the squeeze, but when east incorrectly tosses a spade playing to the ace will drop the queen, however this leads to south finessing into east's now stiff queen.Because theanalyse_playfunction calculates the maximum tricks before any card is played, calling it with an empty play history is actually one of the most efficient ways of calculating the double dummy result of a deal. This is allanalyse_startis - a wrapper foranalyse_playwith an empty play history.DD TablesTheddtablemodule consists of two functions,calc_dd_tableand its multiple-deal variantcalc_all_tables. The slight naming inconsistency is in order to keep the naming convention consistent with the original DDS library.This is one of the simplest and most powerful functions in theddsmodule. Let's cast our minds back to 1975 withthis famous dealand remember just how thin the 7♣ contract really is:>>>fromendplay.typesimportDeal,Player,Denom>>>fromendplay.ddsimportcalc_dd_table>>>d=Deal("QJ8.AJ965.K82.AQ 43.QT87.QT64.754 AKT9..A97.J98632 7652.K432.J53.KT")>>>table=calc_dd_table(d)>>>table.pprint()♣♦♥♠NTN131091313S131091313E02400W02400Individual results are accessible through the overloaded__getitem__operator:>>>assert(table[Denom.clubs,Player.south]==13)# Filthy, but the assert passesIf, like me, you can never remember whether the table is indexed by strain or seat first, then luckily the operator is agnostic to which order you pass them:>>>assert(table[Player.south,Denom.clubs]==13)The multiple-deal variantcalc_all_tablesaccepts an extra argument not available tocalc_dd_tablewith a list of strains to be excluded from the calculation, if e.g. you want to calculate how a series of deals would play in notrumps and don't want to waste time calculating the table for the other strains. In this case, the results for all other strains will be set to 0. Theexcludeparameter can be any iterable, so[Denom.notrumps, Denom.hearts]would produce results for clubs, diamonds and spades, or in the example below we useDenom.suits()as a shorthand for excluding all the suits:>>>fromendplay.ddsimportcalc_all_tables>>>table,*_=calc_all_tables([d],exclude=Denom.suits())>>>table.pprint()♣♦♥♠NTN000013S000013E00000W00000(NB: If you don't understand howtable, *_ =works then don't worry, it is just a quick way to store the first element of the returned list intotableand the other elements, in this case an empty list as we only requested one table, into the variable_which we will throw away.)Par contract calculation and scoring contractsTheendplay.dds.parmodule contains only one function,par, which calculates the optimum contract on a deal, i.e. the lowest contract over which the opponents cannot bid any making contract and which sacrificing is too expensive. The par contracts are always returned as a list, as there are often multiple contracts which score the same (commonly the same contract played by either partner). As well as the deal (or double dummy table, as this is the only relevant information about the deal required) there are two more pieces of information which come into play:The vulnerability, as this affects the scoreThe dealer, as there are occasions where i.e. both sides can make 1NT, and so the par contract depends on who gets to bid it firstHere are some examples of how the par function can be used:>>>fromendplay.typesimportDeal,Vul,Player>>>fromendplay.ddsimportpar>>>d=Deal("N:AKQJ8..AT8632.43 T742.Q9543.J.QT8 63.AJT8.97.J7652 95.K762.KQ54.AK9")>>>forcontractinpar(d,Vul.none,Player.north):...print(contract)2♠N=2♠S=3♦N=3♦S=>>>forcontractinpar(d,Vul.ew,Player.north):...print(contract)1♠N+11♠S+12♦N+12♦S+1Notice that when EW become vulnerable, the level of the par contracts goes down as their possible sacrifice in hearts becomes too expensive. Note that if you have previously calculated the double dummy table for a board, then it is much more efficient to pass this instead of theDealobject:>>>fromendplay.ddsimportcalc_dd_table>>>table=calc_dd_table(d)>>>par(table,Vul.ew,Player.north)# saves `par` having to recalculate the DD tableThe score associated with the par contracts is a property of the list-type object which holds the list of contracts, as it is of course constant across all the contracts. In the following high-stakes deal, NS can sacrifice in seven clubs over EW's heart slam:>>>d=Deal("N:J976..762.KQJ982 K5.JT9843.AK93.A AT42.765.J84.T54 Q83.AKQ2.QT5.763")>>>parlist=par(d,Vul.ew,Player.north)>>>parlist.score-1100TheContractclass also has ascoremethod which calculates the score of a contract based on a given vulnerability:>>>forcontractinparlist:...print(contract.score(Vul.ew))-1100-1100You can calculate the score of an arbitrary contract by constructing aContractobject and scoring it:>>>fromendplay.typesimportContract>>>c=Contract("4HNx=")# construct from a string>>>c.score(Vul.none)590>>>fromendplayimportDenom,Penalty>>>c=Contract(# construct from values...level=4,...denom=Denom.hearts,...declarer=Player.north,...penalty=Penalty.doubled,...result=0# number of over/undertricks)>>>c.score(Vul.ns)790>>>c.result=-5>>>c.score(Vul.ns)-1400Bids and auctions: an asideWhile on the topic of contracts, it is worth mentioning theBidclass which represents a call in an auction.Bidobjects are very weird, as they fulfill a double purpose of being able to representpenalty actions, i.e. "Pass", "Double" and "Redoule", as well ascontract actionswhich name a strain and a level. These are represented by thePenaltyBidandContractBidclasses respectively, which derive fromBidbut define different member variables -PenaltyBid.penaltyvsContractBid.denomandContractBid.level. You can construct these directly using their__init__functions:fromendplay.typesimportPenaltyBid,ContractBid,Penalty,Denom>>>oneclub=ContractBid(1,Denom.clubs)>>>double=PenaltyBid(Penalty.double)or by using theBidconstructor to supply the name of the bid as a string:>>>twohearts=Bid("2H")>>>double=Bid("double")# Bid("x") also worksNotice however that the type you get is actually always one ofPenaltyBidorContractBid- theBidconstructor will always automatically downcast the class instance to the appropriate type:>>>type(twohearts)<class'endplay.types.bid.ContractBid'>>>>type(pass_)<class'endplay.types.bid.PenaltyBid'>All bid class constructors also accept optional booleanalertableand stringannouncementparameters, of which none, either or both can be defined to allow for the case where e.g. the point range of a notrump bid is announced but not alertable:>>>unusual2nt=Bid("2H",announcement="Weak")>>>forcing_pass=Bid("Pass",alertable=True,announcement="Forcing for one round")Thealertableandannouncementattributes can be assigned and altered after construction of theBidobject, but the other properties are immutable.An auction is simply a list of bid objects:>>>auction=[...oneclub,forcing_pass,two_hearts,double,...Bid("Pass"),Bid("Pass"),Bid("pass")]To calculate a contract from a given auction, you can use theContract.from_auctionmethod and provide the name of the first player to bid:>>>fromendplay.typesimportPlayer,Contract>>>Contract.from_auction(auction,Player.west)Contract("2♥Ex=")Any iterable ofBidobjects satisfying theReversibleinterface can be passed as an auction.Solving for a player's handThe final module,endplay.dds.solve, provides thesolve_board/solve_all_boardsfunction pair which returns the number of tricks each card in a player's hand can yield. Let's go back toa nice four card ending:>>>d=Deal("Q2..6.A 5.632.. A..A.Q8 K4...K9",first=Player.south)>>>d.pprint()Q2---6AK45---632------K9---A---AQ8Can you work out how to pull off this squeeze? We can see what the optimal play is usingsolve_board:>>>fromendplayimportsolve_board>>>forcard,tricksinsolve_board(d):...print(card,tricks)♦A4♠A3♣83♣Q3We can then see west's options after south plays the ♦A by playing this to the trick:>>>d.play("DA")>>>d.pprint()Q2---6AK45---632------K9v♦A---A------Q8>>>forcard,tricksinsolve_board(d):...print(card,tricks)♠40♣90♠K0♣K0Oops, out of luck! Notice how as opposed to theanalysefamily of functions,solve_boardalways returns the number of tricks the person playing the card can make.Parsing to and from bridge file formats (PBN, LIN, JSON)While not the primary aim of the library,endplaydoes support experimental parsing and writing of PBN and LIN file formats. These interfaces are in theendplay.parserssubmodule, and aim to provide an interface consistent with that of the standard library parsing libraries. Each of the parsing packagesendplay.parsers.pbn,endplay.parsers.linandendplay.parsers.jsonprovide four functions:load: Parse a file object into a list ofBoardobjectsloads: Parse a string into a list ofBoardobjectsdump: Write a list ofBoardobjects to a file objectdumpsWrite a list ofBoardobjects to a stringInternally, each module provides*Encoderand*Decoderclasses which do the heavy lifting. These can be used directly, but their interface may be unstable so cannot be recommended.The libraries store file information in lists ofendplay.types.Boardobjects, which wrap aDealas well as other information which is usually provided by these file formats. The full list of defined members can be found in the API reference as this is one of the bulkiest classes inendplay, in order to deal with the wealth of information that these file formats can store. We will present here a lighter introduction to the class by reading a PBN file and examining the result. We being by opening the sample PBN file in the examples directory and putting the first board into the variableboardA:>>>importendplay.parsers.pbnaspbn>>>withopen("examples/pbn_files/sample.pbn")asf:...boards=pbn.load(f)>>>boardA=boards[0]From here we can explore a lot of the basic information about the deal using the tools which we have already learned:The deal>>>boardA.deal.pprint()AT92J432A9863KJ8576432AQT85349KQK4QJT72QKJ976AT87655The auction>>>fromendplay.utils.ioimportpprint_auction>>>pprint_auction(boardA.dealer,boardA.auction,include_announcements=True)NESWPP1♥P1NT2♥*3♦4♠5♦PP5♠*XPPP2♥*:Spades&minor5♠*:♠The play history>>>fromendplay.ddsimportanalyse_play>>>analyse_play(boardA.deal,boards[0].play)<SolvedPlayobject;data=(8,9,9,9,9,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8)>Meta-information about the board. As this can store just about anything you might want it can get a bit messy, so although I have tried to keep it as basic as possible don't worry if the code samples below go in one ear and out the other>>>boardA.info.keys()dict_keys(['Event','Site','Date','West','North','East','South','Dealer','Scoring','Score','Table','HomeTeam','VisitTeam','ScoreIMP','DoubleDummyTricks','OptimumResultTable','OptimumScore','Competition'])>>>boardA.info.event# Dot access is case-insensitive'TestingPBN'>>>boardA.info["Site"]# Subscript access is case-sensitive'SampleTestSite'PBN tags ending inTable(but not equal toTable- that key is for the table number the board was played at) are tabular data, and entries in theBoard.infodictionary which end inTableare treated differently; instead of having string values they are dictionaries with keys for the column headings and the rows:>>>frompprintimportpprint>>>pprint(boardA.info.OptimumResultTable){'headers':['Declarer',{'alignment':'R','minwidth':'2','name':'Denomination','ordering':None},{'alignment':'R','minwidth':'2','name':'Result','ordering':None}],'rows':[['N','NT','7'],['N','S','4'],['N','H','6'],['N','D','11'],['N','C','5'],['W','NT','5'],['W','S','8'],['W','H','6'],['W','D','2'],['W','C','7']]}Theheaderskey is a list of the column names; they can either be strings or dictionaries specifying how the columns should be displayed (see the API reference for more information). Therowskey is a 2D list representing the rows of the table.In sample.pbn, the second board contains some fields with value "#" indicating that they should be copied over from the previous board, these are automatically resolved:>>>boardB=boards[1]>>>assertboardA.info.event==boardB.info.eventOn the second board, the hand was passed out. TheBoardobject is populated with an empty play history and aContractobject representing the pass:>>>boardB.play[]>>>boardB.contractContract("Pass")Using theendplay.parsers.linmodule, we can export these boards to LIN in order to use them on BBO:>>>importendplay.parsers.linaslin>>>l=lin.dumps(boards)>>>print(l)pn|JOHNSMITH,ARTHURSOMEBODY,JORDANPRESENTLY,EDWARDPEABODY|st||md|3S9TAH2D234JC3689A,S23467H4DQKC27TJQ,SQH679JKD5678TAC5,|rh||ah|Board17|sv|o|mb|p|mb|p|mb|1H|mb|p|mb|1N|mb|2H|an|Spades&minor|mb|3D|mb|4S|mb|5D|mb|p|mb|p|mb|5S|an|!S|mb|d|mb|p|mb|p|mb|p|pg||pc|H2|pc|H4|pc|HK|pc|HA|pg||pc|D9|pc|D2|pc|DQ|pc|DA|pg||pc|C5|pc|C4|pc|CA|pc|C2|pg||pc|C9|pc|C7|pc|SQ|pc|CK|pg||pc|H6|pc|H8|pc|S9|pc|CT|pg||pc|C8|pc|CJ|pc|D5|pc|H3|pg||pc|S2|pc|D6|pc|SK|pc|SA|pg||pc|ST|pc|S3|pc|D7|pc|SJ|pg||mc|8|pn|LOUISEFORWEES,JEANJEANY,MARTINEESPEREDO,BRENDACALLOUGHWAY|st||md|1S29JAH478D6TJC3QA,S3467H3TQD23C69JK,S8TKH69AD59AC2457,|rh||ah|Board11|sv|o|mb|p|mb|p|mb|p|mb|p|pg||Suit symbols are automatically escaped using the!S,!Hetc... names used by BBO. Of course, far less information is stored in a LIN file than a PBN file and so many of the fields in theinfodictionary of theBoardare lost during the conversion. We can of course alsoloada LIN file anddumpit into a PBN file, any keys which the PBN file expects which aren't provided by the LIN file can either be specified by appending to theBoard.infodictionary, or else they will be given the default value of?as specified by thePBN standard.Finally, for compatibility with projects which make use of other langauges or which need an easily parsable serialisation format, theendplay.parsers.jsonmodule provides the ability to parse to and from a JSON format definedby this schema. Note that this is not an officially recognised schema but has been developed for the specific purpose of providing a JSON format which translates naturally to PBN and, in particular, the data types whichendplayuses.