Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • wilsonba/polling-server-ia-04
  • gvandevi/ia04binome2a
2 results
Show changes
Commits on Source (68)
Showing with 929 additions and 187 deletions
# IA04binôme2A
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://gitlab.utc.fr/gvandevi/ia04binome2a.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://gitlab.utc.fr/gvandevi/ia04binome2a/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
package ballotagent
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"sync"
"time"
rad "gitlab.utc.fr/gvandevi/ia04binome2a" // à remplacer par le nom du dossier actuel
)
type BallotServerAgent struct {
sync.Mutex
id string
reqCount int
addr string
ballots map[rad.Ballot]BallotInfo
}
func NewBallotServerAgent(addr string) *BallotServerAgent {
return &BallotServerAgent{id: addr, addr: addr}
}
// Test de la méthode
func (rsa *BallotServerAgent) checkMethod(method string, w http.ResponseWriter, r *http.Request) bool {
if r.Method != method {
w.WriteHeader(http.StatusMethodNotAllowed)
fmt.Fprintf(w, "method %q not allowed", r.Method)
return false
}
return true
}
func decodeRequest[Req rad.Request](r *http.Request) (req Req, err error) {
buf := new(bytes.Buffer)
buf.ReadFrom(r.Body)
err = json.Unmarshal(buf.Bytes(), &req)
return
}
func (rsa *BallotServerAgent) doReqcount(w http.ResponseWriter, r *http.Request) {
if !rsa.checkMethod("GET", w, r) {
return
}
w.WriteHeader(http.StatusOK)
rsa.Lock()
defer rsa.Unlock()
serial, _ := json.Marshal(rsa.reqCount)
w.Write(serial)
}
func (rsa *BallotServerAgent) Start() {
// création du multiplexer
mux := http.NewServeMux()
mux.HandleFunc("/new_ballot", rsa.createBallot)
mux.HandleFunc("/vote", rsa.receiveVote)
mux.HandleFunc("/result", rsa.sendResults)
rsa.ballots = make(map[rad.Ballot]BallotInfo)
// création du serveur http
s := &http.Server{
Addr: rsa.addr,
Handler: mux,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20}
// lancement du serveur
log.Println("Listening on", rsa.addr)
go log.Fatal(s.ListenAndServe())
}
package ballotagent
import (
"encoding/json"
"fmt"
"net/http"
"time"
rad "gitlab.utc.fr/gvandevi/ia04binome2a"
cs "gitlab.utc.fr/gvandevi/ia04binome2a/comsoc"
)
type BallotInfo struct {
profile cs.Profile
options [][]int
votersId []string
nbAlts int
isOpen bool
results rad.ResultResponse
}
func (rsa *BallotServerAgent) createBallot(w http.ResponseWriter, r *http.Request) {
// mise à jour du nombre de requêtes
rsa.Lock()
defer rsa.Unlock()
rsa.reqCount++
// vérification de la méthode de la requête
if !rsa.checkMethod("POST", w, r) {
return
}
// décodage de la requête
req, err := decodeRequest[rad.BallotRequest](r)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, err.Error())
return
}
// Check for valid deadline formatting
deadline, errTime := time.Parse(time.RFC3339, req.Deadline)
if errTime != nil {
w.WriteHeader(http.StatusBadRequest)
msg := fmt.Sprintf("'%s' n'utilise pas le bon format, merci d'utiliser RFC3339 ", req.Deadline)
w.Write([]byte(msg))
return
}
// Check if the deadline is in the future
if deadline.Before(time.Now()) {
w.WriteHeader(http.StatusBadRequest)
msg := fmt.Sprintf("'%s' est déjà passé ", req.Deadline)
w.Write([]byte(msg))
return
}
// traitement de la requête
var resp rad.Ballot
resp.BallotID = fmt.Sprintf("scrutin%d", len(rsa.ballots)+1)
rsa.ballots[resp] = BallotInfo{
profile: make(cs.Profile, 0),
options: make([][]int, 0),
votersId: req.VotersID,
nbAlts: req.NbAlts,
isOpen: true,
results: rad.ResultResponse{}}
tb := make([]cs.Alternative, 0)
for _, alt := range req.TieBreak {
tb = append(tb, cs.Alternative(alt))
}
switch req.Rule {
case "majority":
go rsa.handleBallot(resp, cs.MajoritySWF, cs.MajoritySCF, tb, deadline)
case "borda":
go rsa.handleBallot(resp, cs.BordaSWF, cs.BordaSCF, tb, deadline)
case "approval":
go rsa.handleBallotWithSingleOption(resp, cs.ApprovalSWF, cs.ApprovalSCF, tb, deadline)
case "copeland":
go rsa.handleBallot(resp, cs.CopelandSWF, cs.CopelandSCF, tb, deadline)
case "stv":
go rsa.handleBallot(resp, cs.STV_SWF, cs.STV_SCF, tb, deadline)
default:
w.WriteHeader(http.StatusNotImplemented)
msg := fmt.Sprintf("Unkonwn rule '%s'", req.Rule)
w.Write([]byte(msg))
return
}
w.WriteHeader(http.StatusOK)
serial, _ := json.Marshal(resp)
w.Write(serial)
}
func (rsa *BallotServerAgent) handleBallot(
ballot rad.Ballot,
swf func(cs.Profile) (cs.Count, error),
scf func(cs.Profile) ([]cs.Alternative, error),
orderedTBAlts []cs.Alternative,
deadline time.Time,
) {
time.Sleep(time.Until(deadline))
targetBallot := rsa.ballots[ballot]
profile := targetBallot.profile
// If profile is empty, set winner as 0 and ranking as empty list
if len(profile) == 0 {
targetBallot.results = rad.ResultResponse{Winner: 0, Ranking: make([]int, 0)}
fmt.Println(ballot.BallotID, "n'a pas reçu de votes.")
return
}
tb := cs.TieBreakFactory(orderedTBAlts)
ballotSWF := cs.SWFFactory(swf, tb)
ballotSCF := cs.SCFFactory(scf, tb)
ranking, _ := ballotSWF(profile)
winner, err := ballotSCF(profile)
if err != nil {
fmt.Println(err)
return
}
intRanking := make([]int, 0)
for _, alt := range ranking {
intRanking = append(intRanking, int(alt))
}
rsa.ballots[ballot] = BallotInfo{
profile: profile,
options: targetBallot.options,
votersId: targetBallot.votersId,
nbAlts: targetBallot.nbAlts,
isOpen: false,
results: rad.ResultResponse{Winner: int(winner), Ranking: intRanking},
}
}
func (rsa *BallotServerAgent) handleBallotWithSingleOption(
ballot rad.Ballot,
swf func(cs.Profile, []int) (cs.Count, error),
scf func(cs.Profile, []int) ([]cs.Alternative, error),
orderedTBAlts []cs.Alternative,
deadline time.Time,
) {
time.Sleep(time.Until(deadline))
targetBallot := rsa.ballots[ballot]
targetBallot.isOpen = false
profile := targetBallot.profile
options := targetBallot.options
// If profile is empty, set winner as 0 and ranking as empty list
if len(profile) == 0 {
targetBallot.results = rad.ResultResponse{Winner: 0, Ranking: make([]int, 0)}
fmt.Println(ballot.BallotID, "n'a pas reçu de votes.")
return
}
// Only the fist element of the agents' options is filled/matters
singleOptions := make([]int, len(options))
for i, option := range options {
singleOptions[i] = option[0]
}
tb := cs.TieBreakFactory(orderedTBAlts)
ballotSWF := cs.SWFFactoryWithOptions(swf, tb)
ballotSCF := cs.SCFFactoryWithOptions(scf, tb)
ranking, _ := ballotSWF(profile, singleOptions)
winner, err := ballotSCF(profile, singleOptions)
if err != nil {
fmt.Println(err)
return
}
intRanking := make([]int, 0)
for _, alt := range ranking {
intRanking = append(intRanking, int(alt))
}
rsa.ballots[ballot] = BallotInfo{
profile: profile,
options: targetBallot.options,
votersId: targetBallot.votersId,
nbAlts: targetBallot.nbAlts,
isOpen: false,
results: rad.ResultResponse{Winner: int(winner), Ranking: intRanking},
}
}
package ballotagent
import (
"encoding/json"
"fmt"
"net/http"
rad "gitlab.utc.fr/gvandevi/ia04binome2a"
)
func (rsa *BallotServerAgent) sendResults(w http.ResponseWriter, r *http.Request) {
// mise à jour du nombre de requêtes
rsa.Lock()
defer rsa.Unlock()
rsa.reqCount++
// vérification de la méthode de la requête
if !rsa.checkMethod("POST", w, r) {
return
}
// décodage de la requête
req, err := decodeRequest[rad.Ballot](r)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, err.Error())
return
}
// recupération des infos
scrutin := req.BallotID
voteBallot := rad.Ballot{BallotID: scrutin}
ballots := make([]rad.Ballot, len(rsa.ballots))
// Check if ballot exists
i := 0
for k := range rsa.ballots {
ballots[i] = k
i++
}
if !contains[rad.Ballot](ballots, voteBallot) {
w.WriteHeader(http.StatusNotFound)
msg := fmt.Sprintf("The ballot '%s' does not exist", scrutin)
w.Write([]byte(msg))
return
}
ballot := rsa.ballots[voteBallot]
// Check que la deadline n'est pas déjà passée
if ballot.isOpen {
w.WriteHeader(http.StatusTooEarly)
msg := fmt.Sprintf("The ballot '%s' is not closed yet.", scrutin)
w.Write([]byte(msg))
return
}
w.WriteHeader(http.StatusOK)
serial, _ := json.Marshal(rsa.ballots[voteBallot].results)
w.Write(serial)
}
package ballotagent
import (
"fmt"
"net/http"
rad "gitlab.utc.fr/gvandevi/ia04binome2a"
cs "gitlab.utc.fr/gvandevi/ia04binome2a/comsoc"
)
func contains[S string | rad.Ballot](s []S, e S) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
func intToAlt(s []int) []cs.Alternative {
res := make([]cs.Alternative, len(s))
for i, v := range s {
res[i] = cs.Alternative(v)
}
return res
}
func removeFromSlice(slice []string, elem string) []string {
res := make([]string, 0)
i := 0
for _, el := range slice {
if el != elem {
res = append(res, el)
i++
}
}
return res
}
func (rsa *BallotServerAgent) receiveVote(w http.ResponseWriter, r *http.Request) {
// mise à jour du nombre de requêtes
rsa.Lock()
defer rsa.Unlock()
rsa.reqCount++
// vérification de la méthode de la requête
if !rsa.checkMethod("POST", w, r) {
return
}
// décodage de la requête
req, err := decodeRequest[rad.Vote](r)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, err.Error())
return
}
// recupération des infos
scrutin := req.BallotID
voteBallot := rad.Ballot{BallotID: scrutin}
ballots := make([]rad.Ballot, len(rsa.ballots))
// Check if ballot exists
i := 0
for k := range rsa.ballots {
ballots[i] = k
i++
}
if !contains[rad.Ballot](ballots, voteBallot) {
w.WriteHeader(http.StatusBadRequest)
msg := fmt.Sprintf("The ballot '%s' does not exist", scrutin)
w.Write([]byte(msg))
return
}
ballot := rsa.ballots[voteBallot]
// Check que la deadline n'est pas déjà passée
if !ballot.isOpen {
w.WriteHeader(http.StatusServiceUnavailable)
msg := fmt.Sprintf("The deadline has passed, the ballot '%s' is therefore closed.", scrutin)
w.Write([]byte(msg))
return
}
// Check que l'agent fait bien partie des votants
if !contains(ballot.votersId, req.AgentID) {
w.WriteHeader(http.StatusForbidden)
msg := fmt.Sprintf("The user '%s' has either already voted or cannot vote", req.AgentID)
w.Write([]byte(msg))
return
}
// Check if vote is valid beforehand (don't want to register a vote that could break the results' calculation)
tempProf := make(cs.Profile, 1)
tempProf[0] = intToAlt(req.Prefs)
_, errPrefs := cs.MajoritySWF(tempProf)
if errPrefs != nil || len(req.Prefs) != ballot.nbAlts {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, errPrefs.Error())
return
}
// Register the vote
rsa.ballots[voteBallot] = BallotInfo{
profile: append(ballot.profile, intToAlt(req.Prefs)), // add preferences to profile
options: append(ballot.options, req.Options), // add options to all options
votersId: removeFromSlice(rsa.ballots[voteBallot].votersId, req.AgentID), // remove voter from the list of voters
nbAlts: rsa.ballots[voteBallot].nbAlts,
isOpen: true,
results: rad.ResultResponse{},
}
}
package voteragent
import (
"bytes"
"encoding/json"
"fmt"
"log"
"math/rand"
"net/http"
rad "gitlab.utc.fr/gvandevi/ia04binome2a"
cs "gitlab.utc.fr/gvandevi/ia04binome2a/comsoc"
)
type RestClientAgent struct {
id string
url string
scrutin string
nbAlts int
prefs []int
options []int
}
func NewRestClientAgent(id string, url string, scrutin string, nbAlts int, prefs []int, options []int) *RestClientAgent {
return &RestClientAgent{id, url, scrutin, nbAlts, prefs, options}
}
func (rca *RestClientAgent) vote() (err error) {
req := rad.Vote{
AgentID: rca.id,
BallotID: rca.scrutin,
Prefs: rca.prefs,
Options: rca.options,
}
// sérialisation de la requête
url := rca.url + "/vote"
data, _ := json.Marshal(req)
// envoi de la requête
resp, err := http.Post(url, "application/json", bytes.NewBuffer(data))
// traitement de la réponse
if err != nil {
return
}
if resp.StatusCode != http.StatusOK {
err = fmt.Errorf("[%d] %s", resp.StatusCode, resp.Status)
return
}
return
}
func (rca *RestClientAgent) Start() {
log.Printf("démarrage de %s", rca.id)
prefs := make([]cs.Alternative, 0)
if len(rca.prefs) == 0 {
prefs = cs.GenerateProfile(1, rca.nbAlts)[0]
rca.prefs = make([]int, len(prefs))
for i, pref := range prefs {
rca.prefs[i] = int(pref)
}
}
if len(rca.options) == 0 {
rca.options = []int{1 + rand.Intn(rca.nbAlts-1)}
}
err := rca.vote()
if err != nil {
log.Fatal(rca.id, "error:", err.Error())
} else {
log.Printf("[%s] voted in %s\n", rca.id, rca.scrutin)
}
}
package main
import (
"fmt"
ba "gitlab.utc.fr/gvandevi/ia04binome2a/agt/ballotagent"
)
func main() {
server := ba.NewBallotServerAgent(":8080")
server.Start()
fmt.Scanln()
}
package main
import (
"fmt"
va "gitlab.utc.fr/gvandevi/ia04binome2a/agt/voteragent"
)
func main() {
ag := va.NewRestClientAgent("ag1", "http://localhost:8080", "scrutin1", 3, make([]int, 0), make([]int, 0))
ag.Start()
fmt.Scanln()
}
......@@ -10,5 +10,7 @@ func main() {
//comsoc.Test_maxCount()
//comsoc.Test_checkProfile()
//comsoc.Test_checkProfileAlternative()
comsoc.Test_MajoritySWF()
//comsoc.Test_MajoritySWF()
//comsoc.Test_sWFFactory()
comsoc.Test_majority()
}
......@@ -4,18 +4,29 @@ package comsoc
// thresholds est un slice d'entiers strictement positifs
func ApprovalSWF(p Profile, thresholds []int) (count Count, err error) {
count = make(Count)
for _, pref := range p {
for index, alt := range pref {
count[alt] += thresholds[len(thresholds)-1-index]
err = checkProfileFromProfile(p)
if err != nil {
return nil, err
}
//initialisation de la map : comptes à 0
count = make(Count)
for _,alt := range p[0]{
count[alt]=0
}
//actualisation du compte à l'aide du scrutin
for index, alt := range p {
for i := 0; i < thresholds[index]; i++ {
count[alt[i]] += 1
}
}
return count, nil
return
}
func ApprovalSCF(p Profile, thresholds []int) (bestAlts []Alternative, err error) {
count, err := ApprovalSWF(p, thresholds)
alts, err := ApprovalSWF(p, thresholds)
if err != nil {
return nil, err
}
return maxCount(count), nil
bestAlts = maxCount(alts)
return
}
package comsoc
import("fmt")
func BordaSWF(p Profile) (count Count, err error){
import (
"fmt"
)
func BordaSWF(p Profile) (count Count, err error) {
count = make(Count)
nAlts := len(p[0])
for _, row := range p{
for i:=0; i<nAlts;i++{
count[row[i]]+=nAlts-1-i
err = checkProfileFromProfile(p)
if err != nil {
return nil, err
}
nAlts := len(p[0])
for _, row := range p {
for i := 0; i < nAlts; i++ {
count[row[i]] += nAlts - 1 - i
}
}
return count,nil
return
}
func BordaSCF(p Profile) (bestAlts []Alternative, err error) {
......@@ -17,14 +24,14 @@ func BordaSCF(p Profile) (bestAlts []Alternative, err error) {
if err != nil {
return nil, err
}
return maxCount(count), nil
}
return maxCount(count), err
}
func Test_borda(){
profil := GenerateProfile(3,5)
func Test_borda() {
profil := GenerateProfile(3, 5)
fmt.Println("Profil :", profil)
count,_ := BordaSWF(profil)
count, _ := BordaSWF(profil)
fmt.Println("Décompte :", count)
winners,_ := BordaSCF(profil)
winners, _ := BordaSCF(profil)
fmt.Println("Vainqueur(s) :", winners)
}
\ No newline at end of file
}
package comsoc
import "errors"
// Gagnant de condorcet, retourne un slice vide ou de 1 élément
// A vérifier avec plus d'exemples
func CondorcetWinner(p Profile) (bestAlts []Alternative, err error) {
......@@ -25,5 +27,5 @@ func CondorcetWinner(p Profile) (bestAlts []Alternative, err error) {
return []Alternative{alt1}, nil
}
}
return []Alternative{}, nil
return nil, errors.New("pas de gagnant de Condorcet")
}
package comsoc
\ No newline at end of file
package comsoc
func CopelandSWF(p Profile) (count Count, err error) {
count = make(Count)
alts := make([]Alternative, 0)
for i := 1; i <= len(p[0]); i++ {
alts = append(alts, Alternative(i))
}
err = checkProfileAlternative(p, alts)
if err != nil {
return nil, err
}
for alt1 := 1; alt1 <= len(alts); alt1++ {
for alt2 := alt1 + 1; alt2 <= len(alts); alt2++ {
score1, score2 := 0, 0
for _, pref := range p {
if isPref(Alternative(alt1), Alternative(alt2), pref) {
score1++
} else {
score2++
}
}
if score1 > score2 {
count[Alternative(alt1)]++
count[Alternative(alt2)]--
} else if score2 > score1 {
count[Alternative(alt1)]--
count[Alternative(alt2)]++
}
}
}
return
}
func CopelandSCF(p Profile) (bestAlts []Alternative, err error) {
count, err := CopelandSWF(p)
if err != nil {
return nil, err
}
return maxCount(count), err
}
......@@ -5,7 +5,6 @@ import (
"fmt"
)
// cours TODO
func plusN(n int) func(i int) int {
f := func(i int) int {
return (i + n)
......@@ -71,13 +70,22 @@ func Test_maxCount() {
func checkProfile(prefs []Alternative, alts []Alternative) error {
//vérifier
if len(prefs) < len(alts) {
return errors.New("Il manque des alternatives")
return errors.New("préférences non complètes")
} else if len(prefs) > len(alts) {
return errors.New("Il y a des alternatives en trop.")
return errors.New("alternatives en trop")
} else { //vérifier complet
for _, element := range alts {
if rank(element, prefs) == -1 {
return errors.New("au moins une alternative est absente des préférences")
return errors.New("une des alternatives est absente des préférences")
}
nApp := 0
for _, pref := range prefs {
if element == pref {
nApp += 1
}
}
if nApp != 1 {
return errors.New("une alternative apparait plusieurs fois")
}
}
}
......@@ -95,15 +103,21 @@ func Test_checkProfile() {
// vérifie le profil donné, par ex. qu'ils sont tous complets
// et que chaque alternative de alts apparaît exactement une fois par préférences
func checkProfileAlternative(prefs Profile, alts []Alternative) error {
for _, row := range prefs {
e := checkProfile(row, alts)
if e != nil {
return e
}
for _, pref := range prefs {
return checkProfile(pref, alts)
}
return nil
}
func checkProfileFromProfile(prof Profile) (err error) {
alts := make([]Alternative, 0)
for i := 1; i <= len(prof[0]); i++ {
alts = append(alts, Alternative(i))
}
err = checkProfileAlternative(prof, alts)
return
}
func Test_checkProfileAlternative() {
alts := []Alternative{1, 2, 3, 4, 5}
pref1 := []Alternative{5, 3, 1, 4, 2}
......
package comsoc
import ("fmt")
//majorité simple
// fonctions de bien-être social (social welfare function, SWF) :
// retournent un décompte à partir d'un profil
// En utilisation la méthode de la majorité simple
// Majorité simple
func MajoritySWF(p Profile) (count Count, err error) {
err = checkProfileFromProfile(p)
if err != nil {
return nil, err
}
//initialisation de la map : comptes à 0
count = make(Count)
for _,alt := range p[0]{
count[alt]=0
}
//actualisation du compte à l'aide du scrutin
for _, pref := range p {
count[pref[0]]++
}
return count, nil
return
}
func MajoritySCF(p Profile) (bestAlts []Alternative, err error) {
......@@ -17,5 +24,14 @@ func MajoritySCF(p Profile) (bestAlts []Alternative, err error) {
if err != nil {
return nil, err
}
return maxCount(count), nil
return maxCount(count), err
}
func Test_majority() {
profil := GenerateProfile(3, 5)
fmt.Println("Profil :", profil)
count, _ := MajoritySWF(profil)
fmt.Println("Décompte :", count)
//winners, _ := MajoritySCF(profil)
//fmt.Println("Vainqueur(s) :", winners)
}
\ No newline at end of file
package comsoc
\ No newline at end of file
package comsoc
func getRandomKey(count Count) Alternative {
for k := range count {
return k
}
return 0 // should never happen
}
func countContains(count Count, alt Alternative) bool {
for k := range count {
if alt == k {
return true
}
}
return false
}
// renvoie une des pires alternatives pour un décompte donné
func minCount(count Count, alts []Alternative) (worstAlt Alternative) {
for _, alt := range alts {
if !countContains(count, alt) {
return alt
}
}
worstAlt = getRandomKey(count)
minPoints := count[worstAlt]
for i, points := range count {
if points < minPoints {
worstAlt = i
minPoints = points
}
}
return worstAlt
}
func STV_SWF(p Profile) (count Count, err error) {
count = make(Count)
alts := make([]Alternative, 0)
for i := 1; i <= len(p[0]); i++ {
alts = append(alts, Alternative(i))
}
err = checkProfileAlternative(p, alts)
if err != nil {
return nil, err
}
nbRounds := len(alts)
for round := 0; round < nbRounds; round++ {
majorityRes := make(Count)
for _, pref := range p {
majorityRes[pref[0]]++
}
worstAlt := minCount(majorityRes, alts)
count[worstAlt] = round
// On enlève la pire alt des alts
alts[rank(worstAlt, alts)] = alts[len(alts)-1]
alts = alts[:len(alts)-1]
// on enlève la pire alt de chacunes des preferences
for i, pref := range p {
pref[rank(worstAlt, pref)] = pref[len(pref)-1]
pref = pref[:len(pref)-1]
p[i] = pref
}
}
return
}
func STV_SCF(p Profile) (bestAlts []Alternative, err error) {
count, err := STV_SWF(p)
if err != nil {
return nil, err
}
return maxCount(count), err
}
package comsoc
import("fmt")
func TieBreakFactory(orderedAlts []Alternative) (func ([]Alternative) (Alternative, error)){
return func (bestAlts []Alternative) (Alternative, error) {
bestAlt := bestAlts[0]
for _,alt:= range bestAlts[1:]{
if isPref(alt,bestAlt,orderedAlts){
bestAlt = alt
}
import "fmt"
func TieBreakFactory(orderedAlts []Alternative) func([]Alternative) (Alternative, error) {
return func(bestAlts []Alternative) (Alternative, error) {
bestAlt := bestAlts[0]
for _, alt := range bestAlts[1:] {
if isPref(alt, bestAlt, orderedAlts) {
bestAlt = alt
}
return bestAlt, nil
}
return bestAlt, nil
}
}
func Test_tieBreakFactory(){
orderedAlts := []Alternative{8,9,6,1,3,2}
func Test_tieBreakFactory() {
orderedAlts := []Alternative{8, 9, 6, 1, 3, 2}
fmt.Println("Ordre strict :", orderedAlts)
lambda:=TieBreakFactory(orderedAlts)
bestAlts := []Alternative{3,6}
lambda := TieBreakFactory(orderedAlts)
bestAlts := []Alternative{3, 6}
fmt.Println("Premières alternatives, à départager :", bestAlts)
bestAlt,_ := lambda(bestAlts)
bestAlt, _ := lambda(bestAlts)
fmt.Println("Première alternative :", bestAlt)
}
func SWFFactory(swf func (Profile) (Count, error), tb func([]Alternative) (Alternative, error)) (func(Profile) ([]Alternative, error)){
return func(p Profile) ([]Alternative, error){
func SWFFactory(swf func(Profile) (Count, error), tb func([]Alternative) (Alternative, error)) func(Profile) ([]Alternative, error) {
return func(p Profile) ([]Alternative, error) {
//récupération du décompte
count,_ := swf(p)
count, errSWF := swf(p)
if errSWF != nil {
return nil, errSWF
}
//préparation de la sortie
var sorted_alts []Alternative
var sortedAlts []Alternative
//PARCOURS DU DECOMPTE
for len(count) > 0{
for len(count) > 0 {
//On prend les meilleures alternatives (avant tie break)
bestAlts := maxCount(count)
//On supprime les meilleures alternatives du décompte
for alt := range bestAlts{
delete(count, Alternative(alt))
for alt := range bestAlts {
delete(count, Alternative(alt))
}
//Départage
for len(bestAlts) > 0{
bestAlt,_ := tb(bestAlts)
//Départage
for len(bestAlts) > 0 {
bestAlt, errTB := tb(bestAlts)
if errTB != nil {
return nil, errTB
}
//ajout de la meilleure alternative post-tie break
sorted_alts = append(sorted_alts, bestAlt)
sortedAlts = append(sortedAlts, bestAlt)
//suppression de l'alternative dans bestAlts
indice := rank(bestAlt, bestAlts)
bestAlts=append(bestAlts[:indice], bestAlts[indice+1:]...)
//suppression de l'alternativ dans le compte
bestAlts = append(bestAlts[:indice], bestAlts[indice+1:]...)
//suppression de l'alternativ dans le compte
delete(count, Alternative(bestAlt))
}
}
return sorted_alts,nil
}
return sortedAlts, nil
}
}
func Test_sWFFactory(){
func Test_sWFFactory() {
//Définition de l'Ordre strict
orderedAlts := []Alternative{8,9,6,1,3,2}
orderedAlts := []Alternative{8, 9, 6, 1, 3, 2}
fmt.Println("Ordre strict :", orderedAlts)
//Construction d'un profil avec alternatives ex aequo
profil := make([][]Alternative, 2)
profil[0] = []Alternative{1, 2, 3,4,5,6}
profil[1] = []Alternative{3, 2, 1,4,5,6}
profil[0] = []Alternative{1, 2, 3, 4, 5, 6}
profil[1] = []Alternative{3, 2, 1, 4, 5, 6}
fmt.Println("Profil :", profil)
//Construction de la fonction Tie Break
lambda:=TieBreakFactory(orderedAlts)
lambda := TieBreakFactory(orderedAlts)
//Construction de la Social Welfare Factory à partir de la fonction swf + la fonction de TieBreak
mu := SWFFactory(BordaSWF,lambda)
//Construction d'une fonction
sorted_alts,_ := mu(profil)
mu := SWFFactory(MajoritySWF, lambda)
// mu := SWFFactory(BordaSWF, lambda)
//Construction d'une fonction
sorted_alts, _ := mu(profil)
fmt.Println("Alternatives strictement ordonnées selon la méthode de Borda :", sorted_alts)
}
func SCFFactory(scf func (p Profile) ([]Alternative, error),tb func ([]Alternative) (Alternative, error)) (func(Profile) (Alternative, error)){
return func(p Profile) (Alternative, error){
//récupération des meilleures alternatives
bestAlts,_ := scf(p)
//récupération de la meilleure alternative
bestAlt,_ := tb(bestAlts)
return bestAlt,nil
func SWFFactoryWithOptions(
swf func(Profile, []int) (Count, error),
tb func([]Alternative) (Alternative, error),
) func(Profile, []int) ([]Alternative, error) {
return func(p Profile, o []int) ([]Alternative, error) {
//récupération du décompte
count, errSWF := swf(p, o)
if errSWF != nil {
return nil, errSWF
}
//préparation de la sortie
var sortedAlts []Alternative
//PARCOURS DU DECOMPTE
for len(count) > 0 {
//On prend les meilleures alternatives (avant tie break)
bestAlts := maxCount(count)
//On supprime les meilleures alternatives du décompte
for alt := range bestAlts {
delete(count, Alternative(alt))
}
//Départage
for len(bestAlts) > 0 {
bestAlt, errTB := tb(bestAlts)
if errTB != nil {
return nil, errTB
}
//ajout de la meilleure alternative post-tie break
sortedAlts = append(sortedAlts, bestAlt)
//suppression de l'alternative dans bestAlts
indice := rank(bestAlt, bestAlts)
bestAlts = append(bestAlts[:indice], bestAlts[indice+1:]...)
//suppression de l'alternativ dans le compte
delete(count, Alternative(bestAlt))
}
}
return sortedAlts, nil
}
}
func SCFFactoryWithOptions(
scf func(Profile, []int) ([]Alternative, error),
tb func([]Alternative) (Alternative, error),
) func(Profile, []int) (Alternative, error) {
return func(p Profile, o []int) (Alternative, error) {
//récupération des meilleures alternatives
bestAlts, errSCF := scf(p, o)
if errSCF != nil {
return Alternative(0), errSCF
}
//récupération de la meilleure alternative
bestAlt, errTB := tb(bestAlts)
return bestAlt, errTB
}
}
func SCFFactory(scf func(p Profile) ([]Alternative, error), tb func([]Alternative) (Alternative, error)) func(Profile) (Alternative, error) {
return func(p Profile) (Alternative, error) {
//récupération des meilleures alternatives
bestAlts, errSCF := scf(p)
if errSCF != nil {
return Alternative(0), errSCF
}
//récupération de la meilleure alternative
bestAlt, errTB := tb(bestAlts)
return bestAlt, errTB
}
}
func Test_sCFFactory(){
func Test_sCFFactory() {
//Définition de l'Ordre strict
orderedAlts := []Alternative{8,9,6,1,3,2}
orderedAlts := []Alternative{8, 9, 6, 1, 3, 2}
fmt.Println("Ordre strict :", orderedAlts)
//Construction d'un profil avec alternatives ex aequo
profil := make([][]Alternative, 2)
profil[0] = []Alternative{1, 2, 3,4,5,6}
profil[1] = []Alternative{3, 2, 1,4,5,6}
profil[0] = []Alternative{1, 2, 3, 4, 5, 6}
profil[1] = []Alternative{3, 2, 1, 4, 5, 6}
fmt.Println("Profil :", profil)
//Construction de la fonction Tie Break
lambda:=TieBreakFactory(orderedAlts)
mu := SCFFactory(BordaSCF,lambda)
//Construction d'une fonction
best_Alt,_ := mu(profil)
lambda := TieBreakFactory(orderedAlts)
mu := SCFFactory(BordaSCF, lambda)
//Construction d'une fonction
best_Alt, _ := mu(profil)
fmt.Println("Meilleure alternative selon la méthode de Borda :", best_Alt)
}
\ No newline at end of file
}
# Serveur de vote Rest en Go
Le serveur permet de créer des scrutins suivants plusieures méthodes de vote.
Les votants peuvent faire des requêtes pour voter dans les scrutins qui le concernent
Toutes les requêtes doivent suivre la norme suivante : https://gitlab.utc.fr/lagruesy/ia04/-/blob/main/docs/sujets/activit%C3%A9s/serveur-vote/api.md
2 exécutables (indépendants) sont fournis :
* `launch-bagt` permet de lancer un agent de type serveur de vote
* `launch-vagt` permet de lancer un agent de type votant
Il est possible d'avoir accès à ces commandes en les installant ainsi :
`go install gitlab.utc.fr/gvandevi/ia04binome2a/cmd/launch-bagt`
Méthodes de vote implémentées :
* Majorité
* Approval
* Borda
* Copeland
* STV
Agents implémentés :
* Serveur
* Votants (paramètres à modifier en fonction du scrutin créé auprès du serveur)
\ No newline at end of file
package ia04binome2a
type BallotRequest struct {
Rule string `json:"rule"`
Deadline string `json:"deadline"`
VotersID []string `json:"voters-id"`
NbAlts int `json:"#alts"`
TieBreak []int `json:"tie-break"`
}
type Vote struct {
AgentID string `json:"agent-id"`
BallotID string `json:"ballot-id"`
Prefs []int `json:"prefs"`
Options []int `json:"options"`
}
type Ballot struct {
BallotID string `json:"ballot-id"`
}
type ResultResponse struct {
Winner int `json:"winner"`
Ranking []int `json:"ranking"`
}
type Request interface {
BallotRequest | Ballot | Vote
}