Source code for pref_voting.social_welfare_function
''' File: social_welfare_function.py Author: Wes Holliday (wesholliday@berkeley.edu) and Eric Pacuit (epacuit@umd.edu) Date: February 6, 2024 The SWF class and helper functions for social welfare functions'''importfunctools
[docs]classSocialWelfareFunction(object):""" A class to add functionality to social welfare functions Args: swf (function): An implementation of a voting method. The function should accept any type of profile, and a keyword parameter ``curr_cands`` to find the winner after restricting to ``curr_cands``. name (string): The Human-readable name of the social welfare function. Returns: A ranking (Ranking) of the candidates. """def__init__(self,swf,name=None):self.swf=swfself.name=namefunctools.update_wrapper(self,swf)def__call__(self,edata,curr_cands=None,**kwargs):if(curr_candsisnotNoneandlen(curr_cands)==0)orlen(edata.candidates)==0:return[]returnself.swf(edata,curr_cands=curr_cands,**kwargs)
[docs]defwinners(self,edata,curr_cands=None,**kwargs):"""Return a sorted list of the first place candidates."""returnsorted(self.swf(edata,curr_cands=curr_cands,**kwargs).first())
[docs]defdisplay(self,edata,curr_cands=None,**kwargs):"""Display the result of the social welfare function."""ranking=self.swf(edata,curr_cands=curr_cands,**kwargs)print(f"{self.name} ranking is {ranking}")
[docs]defset_name(self,new_name):"""Set the name of the social welfare function."""self.name=new_name
def__str__(self):returnf"{self.name}"
[docs]defswf(name=None):""" A decorator used when creating a social welfare function. """defwrapper(f):returnSocialWelfareFunction(f,name=name)returnwrapper