Hybrid MOTOR_VORFLOP_FLOP_QUELLE=sharingan auf der Live-Konfiguration c18e20de (aus claude/motor-pruef6-3b22d4 2bf49fe0 + 85e831af)
Vorflop/Flop von SHARINGAN B-local-2e10 (Grundstrategie ohne Suche, Dienst sharingan-hybrid), Turn/River Motor mit SHARINGAN-gefuehrten Ranges vor dem Turn; angreifer_bewerten mit ANGREIFER_OPFER=hybrid. Standard aus. Aus: 72/72 bitgleich zur Live-Exe ae942a40 (b1 Saat 55, 4 Blaetter, Lauf-Schalter von flopsuche, Tafel 200q400 + sechs100-q.bin). An: 51/51 Entscheidungen vor dem Turn von SHARINGAN, act 6 ms, range max 696 ms, 0 Fehler. LICENSE und NOTICE (Apache-2.0) in entscheiden/motor/fremd/sharingan/. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
# SHARINGAN im Hybrid-Motor
|
||||
|
||||
Schalter `MOTOR_VORFLOP_FLOP_QUELLE=sharingan` (Standard aus; Brücke `entscheiden/motor/src/sharingan.rs`).
|
||||
|
||||
- Herkunft: SHARINGAN von Marko Kraemer, https://github.com/markokraemer/poker-sharingan, Stand 6a11d9b4 (7.11.2026).
|
||||
Gewichte: Fassung B-local-2e10 (`B-local-2e10.plcp`, MODEL_CARD: `license: apache-2.0`).
|
||||
- Lizenz: Apache License 2.0, Text in `LICENSE`, Hinweise des Urhebers in `NOTICE` (beide unverändert übernommen).
|
||||
- Unsere Änderung: `sharingan-hybrid.rs` ist ein neues Programm in seinem Baum (`sharingan-1/serve/src/bin/`), das seinen
|
||||
`Core::decide` aufruft (Grundstrategie ohne Suche, nur 127.0.0.1, kein Netz, kein Arena-Client). Sein Code und seine Gewichte
|
||||
sind sonst unverändert. Die Datei hier ist eine Kopie zum Nachvollziehen; gebaut wird sie in seinem Baum unter D:/pokerfreak-fremd.
|
||||
- Nichts davon wird weitergegeben; Code und Gewichte bleiben auf diesem Rechner.
|
||||
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2026 Marko Kraemer
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,37 @@
|
||||
SHARINGAN
|
||||
Copyright 2026 Marko Kraemer
|
||||
Licensed under the Apache License, Version 2.0.
|
||||
|
||||
This product includes or derives from the following third-party work:
|
||||
|
||||
* engine/iso is a Rust port of the hand-isomorphism indexer by Kevin Waugh
|
||||
(https://github.com/kdub0/hand-isomorphism, `hand_index.c`; K. Waugh, "A Fast and
|
||||
Optimal Hand Isomorphism Algorithm", 2013), distributed under this notice:
|
||||
|
||||
Copyright (c) 2013 Kevin Waugh (waugh@cs.cmu.edu).
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms are permitted
|
||||
provided that the above copyright notice and this paragraph are
|
||||
duplicated in all such forms and that any documentation,
|
||||
advertising materials, and other materials related to such
|
||||
distribution and use acknowledge that the software was developed
|
||||
by the <organization>. The name of the
|
||||
<organization> may not be used to endorse or promote products derived
|
||||
from this software without specific prior written permission.
|
||||
THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
|
||||
IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
|
||||
|
||||
The hand-isomorphism indexer was developed by Kevin Waugh.
|
||||
|
||||
External tools that are used as opponents or data but are NOT redistributed here:
|
||||
* RLCard (https://github.com/datamllab/rlcard, MIT): arena/adapters/rlcard_*.py are our own
|
||||
bridge/training scripts that import it at runtime.
|
||||
* PokerBench (HF `RZ412/PokerBench`, Apache-2.0 per its dataset card): download it separately.
|
||||
* SvanBot (https://github.com/SvanLabs/SvanBot, Apache-2.0): arena/adapters/svan/extbridge.rs is our own
|
||||
glue code that links against SvanBot's crates at build time; SvanBot's source is not included.
|
||||
* Open Poker (openpoker.ai) and Slumbot (slumbot.com): public services used through their APIs.
|
||||
|
||||
The Pluribus paper and supplement (Brown & Sandholm, Science 2019) are copyrighted by
|
||||
their publisher and are not included.
|
||||
@@ -0,0 +1,198 @@
|
||||
//! pokerfreak-Zusatz (29.11.): SHARINGAN-Grundstrategie als geteilter Dienst fuer den Hybrid-Motor (MOTOR_VORFLOP_FLOP_QUELLE=sharingan).
|
||||
//! Nur 127.0.0.1, kein Auth-Abruf, keine Suche (Aufruf mit --no-search). Ein Prozess fuer alle Tische eines Laufs.
|
||||
//! Zeilen-JSON ueber TCP, je Verbindung ein Faden:
|
||||
//! {"op":"act","req":<ActRequest>} -> {"ok":true,"response":<ActResponse>}
|
||||
//! {"op":"range","req":<ActRequest>,"act":{"type":..,"to":..}}
|
||||
//! -> {"ok":true,"p":[1326 Wahrscheinlichkeiten]}: je Lochkartenpaar (Reihenfolge a<b, Karten 0..51 = Rang*4+Farbe, Farben c d h s)
|
||||
//! die Wahrscheinlichkeit, mit der die Grundstrategie am Punkt `req` (hero_seat = wer zieht) den echten Zug `act` waehlt.
|
||||
//! Erhoehungen: Masse des Eintrags mit dem naechsten `to` (Verhaeltnis); mit "alle":true die Summe aller Erhoehungen. -1 = Paar kollidiert mit dem Brett,
|
||||
//! -2 = Punkt nicht in seinem Baum (fallback/desync), dann keine Information.
|
||||
//! {"op":"probs","req":<ActRequest>} -> {"ok":true,"source":..,"probs":[{"type","to","p"}]}: ganze Verteilung, ohne Ziehen
|
||||
//! (fuer die Angreifer-Probe gegen den Hybrid, angreifer_bewerten mit ANGREIFER_OPFER=hybrid)
|
||||
//! {"op":"ping"} -> {"ok":true}
|
||||
//! HYBRID_LEERLAUF_S (Standard 900): ohne offene Verbindung so lange still -> beenden (gibt den Speicher frei).
|
||||
use rayon::prelude::*;
|
||||
use serde_json::{json, Value};
|
||||
use sharingan_serve::api::ActRequest;
|
||||
use sharingan_serve::config::Config;
|
||||
use sharingan_serve::decide::Core;
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
static OFFEN: AtomicUsize = AtomicUsize::new(0);
|
||||
static ZULETZT: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
fn jetzt() -> u64 {
|
||||
SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs())
|
||||
}
|
||||
|
||||
const RANG: &[u8] = b"23456789TJQKA";
|
||||
const FARBE: &[u8] = b"cdhs";
|
||||
|
||||
fn name(k: usize) -> String {
|
||||
format!("{}{}", RANG[k / 4] as char, FARBE[k % 4] as char)
|
||||
}
|
||||
|
||||
fn range(core: &Core, pool: &rayon::ThreadPool, v: &Value) -> Value {
|
||||
let Ok(mut req) = serde_json::from_value::<ActRequest>(v["req"].clone()) else {
|
||||
return json!({"ok": false, "error": "bad_request"});
|
||||
};
|
||||
req.options.include_probs = true;
|
||||
req.options.search = false;
|
||||
req.options.sample = false;
|
||||
req.options.seed = Some(1);
|
||||
let kind = v["act"]["type"].as_str().unwrap_or("").to_string();
|
||||
let to = v["act"]["to"].as_i64();
|
||||
let alle = v["act"]["alle"] == true;
|
||||
let brett: Vec<String> = req.board.clone();
|
||||
let paare: Vec<(usize, usize)> = (0..52).flat_map(|a| (a + 1..52).map(move |b| (a, b))).collect();
|
||||
let p: Vec<f64> = pool.install(|| {
|
||||
paare
|
||||
.par_iter()
|
||||
.map(|&(a, b)| {
|
||||
let (na, nb) = (name(a), name(b));
|
||||
if brett.iter().any(|c| c.eq_ignore_ascii_case(&na) || c.eq_ignore_ascii_case(&nb)) {
|
||||
return -1.0;
|
||||
}
|
||||
let mut r = req.clone();
|
||||
r.hole_cards = vec![na, nb];
|
||||
let Ok(o) = core.decide(&r, String::new()) else { return -2.0 };
|
||||
if o.source != "blueprint" {
|
||||
return -2.0;
|
||||
}
|
||||
let probs = o.probs.unwrap_or_default();
|
||||
let erh = |k: &str| k == "raise" || k == "bet" || k == "all_in";
|
||||
if erh(&kind) && alle {
|
||||
probs.iter().filter(|x| x.kind == "raise").map(|x| x.p).sum()
|
||||
} else if erh(&kind) {
|
||||
let ziel = to.unwrap_or(0).max(1) as f64;
|
||||
probs
|
||||
.iter()
|
||||
.filter(|x| x.kind == "raise")
|
||||
.min_by(|x, y| {
|
||||
let d = |t: Option<i64>| (t.unwrap_or(1).max(1) as f64 / ziel).ln().abs();
|
||||
d(x.to).total_cmp(&d(y.to))
|
||||
})
|
||||
.map_or(0.0, |x| x.p)
|
||||
} else {
|
||||
// check und call fallen in seiner Ausgabe je nach Lage auf "check"/"call"; fold ohne Einsatz gibt es nicht
|
||||
let passiv = |k: &str| k == "check" || k == "call";
|
||||
probs.iter().filter(|x| if passiv(&kind) { passiv(x.kind) } else { x.kind == kind }).map(|x| x.p).sum()
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
json!({"ok": true, "p": p})
|
||||
}
|
||||
|
||||
fn bediene(core: Arc<Core>, pool: Arc<rayon::ThreadPool>, s: TcpStream) {
|
||||
OFFEN.fetch_add(1, Ordering::SeqCst);
|
||||
bediene_innen(core, pool, s);
|
||||
ZULETZT.store(jetzt(), Ordering::SeqCst);
|
||||
OFFEN.fetch_sub(1, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
fn bediene_innen(core: Arc<Core>, pool: Arc<rayon::ThreadPool>, s: TcpStream) {
|
||||
let _ = s.set_nodelay(true);
|
||||
let mut aus = match s.try_clone() {
|
||||
Ok(x) => x,
|
||||
Err(_) => return,
|
||||
};
|
||||
for line in BufReader::new(s).lines() {
|
||||
let Ok(line) = line else { break };
|
||||
if line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let v: Value = serde_json::from_str(&line).unwrap_or(Value::Null);
|
||||
let r = match v["op"].as_str() {
|
||||
Some("ping") => json!({"ok": true}),
|
||||
Some("act") => match serde_json::from_value::<ActRequest>(v["req"].clone()) {
|
||||
Err(e) => json!({"ok": false, "error": e.to_string()}),
|
||||
Ok(mut req) => {
|
||||
req.options.search = false;
|
||||
req.options.include_probs = false;
|
||||
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| core.decide(&req, core.next_request_id()))) {
|
||||
Ok(Ok(a)) => json!({"ok": true, "response": a}),
|
||||
Ok(Err(e)) => json!({"ok": false, "error": e.body()}),
|
||||
Err(_) => json!({"ok": false, "error": "panic"}),
|
||||
}
|
||||
}
|
||||
},
|
||||
Some("probs") => match serde_json::from_value::<ActRequest>(v["req"].clone()) {
|
||||
Err(e) => json!({"ok": false, "error": e.to_string()}),
|
||||
Ok(mut req) => {
|
||||
req.options.search = false;
|
||||
req.options.include_probs = true;
|
||||
req.options.sample = false;
|
||||
req.options.seed = Some(1);
|
||||
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| core.decide(&req, String::new()))) {
|
||||
Ok(Ok(a)) => json!({"ok": true, "source": a.source, "probs": a.probs.unwrap_or_default()}),
|
||||
Ok(Err(e)) => json!({"ok": false, "error": e.body()}),
|
||||
Err(_) => json!({"ok": false, "error": "panic"}),
|
||||
}
|
||||
}
|
||||
},
|
||||
Some("range") => std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| range(&core, &pool, &v))).unwrap_or_else(|_| json!({"ok": false, "error": "panic"})),
|
||||
_ => json!({"ok": false, "error": "op"}),
|
||||
};
|
||||
if writeln!(aus, "{r}").and_then(|_| aus.flush()).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let mut args: Vec<String> = std::env::args().skip(1).collect();
|
||||
// --port <n> ist unser Schalter; der Rest geht an seine Config
|
||||
let mut port = 47123u16;
|
||||
if let Some(i) = args.iter().position(|a| a == "--port") {
|
||||
port = args.get(i + 1).and_then(|x| x.parse().ok()).unwrap_or(port);
|
||||
args.drain(i..(i + 2).min(args.len()));
|
||||
}
|
||||
if !args.iter().any(|a| a == "--no-auth") {
|
||||
args.push("--no-auth".into());
|
||||
}
|
||||
if !args.iter().any(|a| a == "--no-search") {
|
||||
args.push("--no-search".into());
|
||||
}
|
||||
let mut cfg = match Config::parse(&|k| std::env::var(k).ok(), &args) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
eprintln!("{e}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
cfg.arena_auth_url = None;
|
||||
sharingan_serve::log::set_enabled(false);
|
||||
// erst binden: laeuft schon einer, sofort beenden (kein zweites Laden der Tabelle)
|
||||
let l = match TcpListener::bind(("127.0.0.1", port)) {
|
||||
Ok(l) => l,
|
||||
Err(e) => {
|
||||
eprintln!("sharingan-hybrid: Port {port} belegt ({e}), beende");
|
||||
std::process::exit(3);
|
||||
}
|
||||
};
|
||||
let core = Arc::new(Core::new(&cfg).unwrap_or_else(|e| {
|
||||
eprintln!("error: {e}");
|
||||
std::process::exit(1)
|
||||
}));
|
||||
let faeden = std::env::var("HYBRID_FAEDEN").ok().and_then(|x| x.parse().ok()).unwrap_or(2);
|
||||
let pool = Arc::new(rayon::ThreadPoolBuilder::new().num_threads(faeden).build().unwrap());
|
||||
eprintln!("sharingan-hybrid bereit auf 127.0.0.1:{port}");
|
||||
let leer = std::env::var("HYBRID_LEERLAUF_S").ok().and_then(|x| x.parse::<u64>().ok()).unwrap_or(900);
|
||||
ZULETZT.store(jetzt(), Ordering::SeqCst);
|
||||
std::thread::spawn(move || loop {
|
||||
std::thread::sleep(std::time::Duration::from_secs(5));
|
||||
if OFFEN.load(Ordering::SeqCst) == 0 && jetzt().saturating_sub(ZULETZT.load(Ordering::SeqCst)) > leer {
|
||||
eprintln!("sharingan-hybrid: {leer} s ohne Verbindung, beende");
|
||||
std::process::exit(0);
|
||||
}
|
||||
});
|
||||
for s in l.incoming().flatten() {
|
||||
let (c, p) = (core.clone(), pool.clone());
|
||||
std::thread::spawn(move || bediene(c, p, s));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,450 @@
|
||||
//! Trainierter Angreifer: External-Sampling-MCCFR nur fuer einen Platz gegen eine feste Strategie (Motor eingefroren).
|
||||
//! Karte: messung/motor/angreifer/KARTE.md.
|
||||
//!
|
||||
//! Training: wie lernen::Lauf, aber nur der Angreifer hat eine Tabelle; an Motor-Punkten wird der Zug aus der festen
|
||||
//! Verteilung (gegenprobe::Grund) gezogen. Mittelstrategie mit der eigenen Reichweite gewichtet (der Angreifer wird voll
|
||||
//! aufgefaltet, also muss die Reichweite mitlaufen).
|
||||
//!
|
||||
//! Auswertung (Duplikat): je Deal und Sitz Hand A = Angreifer (Mittelstrategie) gegen Motor, Hand B = Motor gegen Motor,
|
||||
//! dieselben Karten. Delta = A - B. Zellen: Leistungsdifferenz V(pi') - V(pi) = E_{Spur ~ pi'} Summe A^pi(s, a): an jeder
|
||||
//! Angreifer-Entscheidung zwei Fortsetzungen, in denen beide Plaetze den Motor spielen (gewaehlter Zug gegen Motor-Zug).
|
||||
//! Bei festem Deal gibt es keinen Zufall der Karten mehr, die Identitaet gilt je Deal; die Summe der Zellen schaetzt also
|
||||
//! dasselbe Delta wie A - B (eingebaute Probe).
|
||||
use crate::gegenprobe::Grund;
|
||||
use crate::karten::*;
|
||||
use crate::lernen::*;
|
||||
use crate::spiel::*;
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::Write;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::*};
|
||||
use std::time::Instant;
|
||||
|
||||
struct Lauf<'a> {
|
||||
s: &'a Spiel,
|
||||
l: &'a Lager,
|
||||
ta: &'a Tabellen,
|
||||
m: &'a Grund,
|
||||
rng: Rng,
|
||||
schnitt: f32,
|
||||
besuche: u64,
|
||||
}
|
||||
|
||||
impl Lauf<'_> {
|
||||
/// Wert fuer Platz p unter der laufenden Strategie des Angreifers; w = eigene Reichweite des Angreifers.
|
||||
fn lauf(&mut self, z: &Zustand, da: &mut Deal, dm: &mut Deal, p: usize, w: f32) -> f32 {
|
||||
if !z.lebt(p) {
|
||||
return -z.gesamt[p] as f32 / 100.0;
|
||||
}
|
||||
if z.ende {
|
||||
let mut aus = [0.0; MAXN];
|
||||
z.auszahlung(self.s, &dm.wert, &mut aus);
|
||||
return aus[p];
|
||||
}
|
||||
let me = z.menue(self.s);
|
||||
let a = me.n;
|
||||
if a == 1 {
|
||||
let mut y = *z;
|
||||
y.zieh(me.z[0].code, me.z[0].ziel);
|
||||
return self.lauf(&y, da, dm, p, w);
|
||||
}
|
||||
if z.dran as usize == p {
|
||||
self.besuche += 1;
|
||||
let (kl, k) = da.klasse(self.ta, z);
|
||||
let kn = self.l.hole(z.schluessel(&me), k, a);
|
||||
let o = kn.ab + kl * 2 * a;
|
||||
let mut s = [0f32; MAXA];
|
||||
abgleich(self.l, o, a, &mut s);
|
||||
let mut v = [0f32; MAXA];
|
||||
let mut ohne = [false; MAXA];
|
||||
let mut ev = 0.0;
|
||||
for i in 0..a {
|
||||
if self.schnitt > 0.0 && s[i] == 0.0 && self.l.lies(o + i) < -self.schnitt {
|
||||
ohne[i] = true;
|
||||
continue;
|
||||
}
|
||||
let mut y = *z;
|
||||
y.zieh(me.z[i].code, me.z[i].ziel);
|
||||
v[i] = self.lauf(&y, da, dm, p, w * s[i]);
|
||||
ev += s[i] * v[i];
|
||||
}
|
||||
for i in 0..a {
|
||||
if !ohne[i] {
|
||||
self.l.plus(o + i, v[i] - ev, &mut self.rng);
|
||||
}
|
||||
if w * s[i] > 0.0 {
|
||||
self.l.plus(o + a + i, w * s[i], &mut self.rng);
|
||||
}
|
||||
}
|
||||
ev
|
||||
} else {
|
||||
let (kl, _) = dm.klasse(&self.m.t, z);
|
||||
let v = self.m.zug(z, &me, kl);
|
||||
let i = waehle(&mut self.rng, &v[..a]);
|
||||
let mut y = *z;
|
||||
y.zieh(me.z[i].code, me.z[i].ziel);
|
||||
self.lauf(&y, da, dm, p, w)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Zelle einer Angreifer-Entscheidung (heads-up): Strasse, Position, Topfart (Vorflop-Raises), Lage (Raises dieser Strasse).
|
||||
fn zelle(z: &Zustand, vor_r: u8) -> String {
|
||||
const ST: [&str; 4] = ["vorflop", "flop", "turn", "river"];
|
||||
let d = z.dran as usize;
|
||||
let pos = if z.n > 2 { "" } else if z.strasse == 0 { ["SB", "BB"][d] } else { ["IP", "OOP"][d] };
|
||||
let topf = match (z.strasse, vor_r) {
|
||||
(0, _) => "",
|
||||
(_, 0) => " gelimpt",
|
||||
(_, 1) => " erhoeht",
|
||||
_ => " 3bet+",
|
||||
};
|
||||
let lage = match z.r {
|
||||
0 => "frei",
|
||||
1 => "gegen Einsatz",
|
||||
_ => "gegen Erhoehung",
|
||||
};
|
||||
if z.n > 2 {
|
||||
// 6-max: Sitzname statt IP/OOP, dazu zu zweit / mehrere im Topf
|
||||
const SITZ: [&str; MAXN] = ["SB", "BB", "UTG", "HJ", "CO", "BTN"];
|
||||
let sitz = SITZ[d]; // 6 Sitze: 0 SB, 1 BB, 2 UTG ... 5 BTN
|
||||
let weg = if z.strasse == 0 { "" } else if z.lebende() > 2 { " mehrere" } else { " zu zweit" };
|
||||
return format!("{} {}{}{} {}", ST[z.strasse as usize], sitz, weg, topf, lage);
|
||||
}
|
||||
format!("{} {}{} {}", ST[z.strasse as usize], pos, topf, lage)
|
||||
}
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
struct Summe {
|
||||
n: f64,
|
||||
s: f64,
|
||||
q: f64,
|
||||
}
|
||||
impl Summe {
|
||||
fn dazu(&mut self, x: f64) {
|
||||
self.n += 1.0;
|
||||
self.s += x;
|
||||
self.q += x * x;
|
||||
}
|
||||
fn plus(&mut self, o: &Summe) {
|
||||
self.n += o.n;
|
||||
self.s += o.s;
|
||||
self.q += o.q;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Auswertung {
|
||||
/// je Deal (beide Sitze zusammen, halbiert = je Hand): A, B, A - B, Summe der Zellen
|
||||
a: Summe,
|
||||
b: Summe,
|
||||
d: Summe,
|
||||
zs: Summe,
|
||||
/// Zellen: Summe der Vorteile je Deal-Sitz (n = Entscheidungen)
|
||||
zellen: BTreeMap<String, Summe>,
|
||||
unbekannt_angreifer: u64,
|
||||
entscheidungen: u64,
|
||||
}
|
||||
|
||||
struct Spieler<'a> {
|
||||
s: &'a Spiel,
|
||||
l: &'a Lager,
|
||||
ta: &'a Tabellen,
|
||||
m: &'a Grund,
|
||||
/// eingefrorener Angreifer aus einer Datei (angreifer_bewerten) statt der Mittelstrategie im Lager
|
||||
fest: Option<&'a crate::dienst::Strategie>,
|
||||
/// ANGREIFER_OPFER=hybrid (nur angreifer_bewerten): an Opfer-Punkten vor dem Turn spielt SHARINGAN (src/sharingan.rs)
|
||||
hybrid: bool,
|
||||
}
|
||||
|
||||
type Spur = Vec<serde_json::Value>;
|
||||
|
||||
impl Spieler<'_> {
|
||||
fn motor_zug(&self, z: &Zustand, me: &Menue, dm: &mut Deal, h: &Spur) -> [f32; MAXA] {
|
||||
if self.hybrid && z.strasse <= 1 {
|
||||
if let Some(v) = crate::sharingan::opfer_zug(z, me, h, dm.karten[z.dran as usize], &dm.brett) {
|
||||
return v;
|
||||
}
|
||||
}
|
||||
let (kl, _) = dm.klasse(&self.m.t, z);
|
||||
self.m.zug(z, me, kl)
|
||||
}
|
||||
/// Mittelstrategie des Angreifers; nie gesehen = Motor-Zug (der Angreifer folgt dort der Grundstrategie).
|
||||
fn angreifer_zug(&self, z: &Zustand, me: &Menue, da: &mut Deal, dm: &mut Deal, unb: &mut u64, h: &Spur) -> [f32; MAXA] {
|
||||
let (kl, _) = da.klasse(self.ta, z);
|
||||
if let Some(st) = self.fest {
|
||||
if let Some(v) = st.hole(z.schluessel(me), kl, me.n) {
|
||||
return v;
|
||||
}
|
||||
*unb += 1;
|
||||
return self.motor_zug(z, me, dm, h);
|
||||
}
|
||||
if let Some(kn) = self.l.suche(z.schluessel(me)) {
|
||||
if kn.a == me.n && kl < kn.k {
|
||||
if let Some(v) = mittel(self.l, &kn, kl) {
|
||||
return v;
|
||||
}
|
||||
}
|
||||
}
|
||||
*unb += 1;
|
||||
self.motor_zug(z, me, dm, h)
|
||||
}
|
||||
/// Beide Plaetze Motor bis zum Ende; Wert fuer p.
|
||||
fn ausspielen(&self, z: &Zustand, dm: &mut Deal, p: usize, rng: &mut Rng, h: &Spur) -> f64 {
|
||||
let mut z = *z;
|
||||
let mut h = h.clone();
|
||||
loop {
|
||||
if !z.lebt(p) {
|
||||
return -z.gesamt[p] as f64 / 100.0;
|
||||
}
|
||||
if z.ende {
|
||||
let mut aus = [0.0; MAXN];
|
||||
z.auszahlung(self.s, &dm.wert, &mut aus);
|
||||
return aus[p] as f64;
|
||||
}
|
||||
let me = z.menue(self.s);
|
||||
let i = if me.n == 1 { 0 } else { waehle(rng, &self.motor_zug(&z, &me, dm, &h)[..me.n]) };
|
||||
if self.hybrid {
|
||||
crate::sharingan::spur_zug(&mut h, &z, me.z[i].code, me.z[i].ziel);
|
||||
}
|
||||
z.zieh(me.z[i].code, me.z[i].ziel);
|
||||
}
|
||||
}
|
||||
/// Eine Hand; mit `angreifer` spielt Platz p die Mittelstrategie und die Zellen werden gefuellt.
|
||||
fn hand(&self, da: &mut Deal, dm: &mut Deal, p: usize, angreifer: bool, rng: &mut Rng, aw: &mut Auswertung) -> (f64, f64) {
|
||||
let mut z = Zustand::start(self.s);
|
||||
let mut h: Spur = if self.hybrid { crate::sharingan::spur_start() } else { Vec::new() };
|
||||
let mut vor_r = 0u8;
|
||||
let mut zsum = 0.0;
|
||||
loop {
|
||||
if !z.lebt(p) {
|
||||
return (-z.gesamt[p] as f64 / 100.0, zsum);
|
||||
}
|
||||
if z.ende {
|
||||
let mut aus = [0.0; MAXN];
|
||||
z.auszahlung(self.s, &dm.wert, &mut aus);
|
||||
return (aus[p] as f64, zsum);
|
||||
}
|
||||
let me = z.menue(self.s);
|
||||
let mut i = 0;
|
||||
if me.n > 1 {
|
||||
if z.dran as usize == p && angreifer {
|
||||
let v = self.angreifer_zug(&z, &me, da, dm, &mut aw.unbekannt_angreifer, &h);
|
||||
i = waehle(rng, &v[..me.n]);
|
||||
aw.entscheidungen += 1;
|
||||
// Vorteil des gewaehlten Zugs gegen einen Motor-Zug, Fortsetzung beide Motor, dieselben Karten
|
||||
let mv = self.motor_zug(&z, &me, dm, &h);
|
||||
let j = waehle(rng, &mv[..me.n]);
|
||||
let wert = |k: usize, rng: &mut Rng, dm: &mut Deal| {
|
||||
let mut y = z;
|
||||
let mut hk = h.clone();
|
||||
if self.hybrid {
|
||||
crate::sharingan::spur_zug(&mut hk, &z, me.z[k].code, me.z[k].ziel);
|
||||
}
|
||||
y.zieh(me.z[k].code, me.z[k].ziel);
|
||||
self.ausspielen(&y, dm, p, rng, &hk)
|
||||
};
|
||||
let adv = if i == j { 0.0 } else { wert(i, rng, dm) - wert(j, rng, dm) };
|
||||
aw.zellen.entry(zelle(&z, vor_r)).or_default().dazu(adv);
|
||||
zsum += adv;
|
||||
} else {
|
||||
i = waehle(rng, &self.motor_zug(&z, &me, dm, &h)[..me.n]);
|
||||
}
|
||||
}
|
||||
if z.strasse == 0 && me.z[i].code >= 2 {
|
||||
vor_r += 1;
|
||||
}
|
||||
if self.hybrid {
|
||||
crate::sharingan::spur_zug(&mut h, &z, me.z[i].code, me.z[i].ziel);
|
||||
}
|
||||
z.zieh(me.z[i].code, me.z[i].ziel);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// getrennt: Deals aus eigener Saat (gleich in allen Armen eines Vergleichs, auch wenn die Zuege auseinanderlaufen)
|
||||
fn auswerten(sp: &Spieler, deals: u64, faeden: usize, saat: u64, getrennt: bool) -> Auswertung {
|
||||
let teil = deals.div_ceil(faeden as u64);
|
||||
let teile: Vec<Auswertung> = std::thread::scope(|sc| {
|
||||
let h: Vec<_> = (0..faeden)
|
||||
.map(|f| {
|
||||
sc.spawn(move || {
|
||||
let mut aw = Auswertung::default();
|
||||
let mut rng = Rng(misch(saat, f as u64 + 77) | 1);
|
||||
let mut rng_deal = Rng(misch(saat, f as u64 + 177) | 1);
|
||||
for _ in 0..teil {
|
||||
let da0 = Deal::gib(if getrennt { &mut rng_deal } else { &mut rng }, sp.s.n);
|
||||
let (mut sa, mut sb, mut sz) = (0.0, 0.0, 0.0);
|
||||
for p in 0..sp.s.n {
|
||||
let mut da = Deal::aus(da0.karten, da0.brett, sp.s.n);
|
||||
let mut dm = Deal::aus(da0.karten, da0.brett, sp.s.n);
|
||||
let (x, zs) = sp.hand(&mut da, &mut dm, p, true, &mut rng, &mut aw);
|
||||
let (y, _) = sp.hand(&mut da, &mut dm, p, false, &mut rng, &mut aw);
|
||||
sa += x;
|
||||
sb += y;
|
||||
sz += zs;
|
||||
}
|
||||
let n = sp.s.n as f64;
|
||||
aw.a.dazu(sa / n);
|
||||
aw.b.dazu(sb / n);
|
||||
aw.d.dazu((sa - sb) / n);
|
||||
aw.zs.dazu(sz / n);
|
||||
}
|
||||
aw
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
h.into_iter().map(|x| x.join().unwrap()).collect()
|
||||
});
|
||||
let mut g = Auswertung::default();
|
||||
for t in teile {
|
||||
g.a.plus(&t.a);
|
||||
g.b.plus(&t.b);
|
||||
g.d.plus(&t.d);
|
||||
g.zs.plus(&t.zs);
|
||||
for (k, v) in t.zellen {
|
||||
g.zellen.entry(k).or_default().plus(&v);
|
||||
}
|
||||
g.unbekannt_angreifer += t.unbekannt_angreifer;
|
||||
g.entscheidungen += t.entscheidungen;
|
||||
}
|
||||
g
|
||||
}
|
||||
|
||||
/// Mittel und halbe Breite des 95-%-Intervalls in bb/100 (je Hand).
|
||||
fn bb100(x: &Summe, n: f64) -> (f64, f64) {
|
||||
let m = x.s / n;
|
||||
let v = (x.q / n - m * m).max(0.0);
|
||||
(m * 100.0, 1.96 * (v / n).sqrt() * 100.0)
|
||||
}
|
||||
|
||||
fn bericht(aw: &Auswertung, sitze: f64, kopf: &str, datei: &str) -> String {
|
||||
let n = aw.d.n;
|
||||
let (d, dc) = bb100(&aw.d, n);
|
||||
let (a, ac) = bb100(&aw.a, n);
|
||||
let (b, bc) = bb100(&aw.b, n);
|
||||
let (z, zc) = bb100(&aw.zs, n);
|
||||
let zeile = format!(
|
||||
"{kopf} | Delta {d:+.2} ±{dc:.2} bb/100 (A {a:+.2} ±{ac:.2}, B {b:+.2} ±{bc:.2}) | Zellensumme {z:+.2} ±{zc:.2} | Angreifer-Punkte ohne Tabelle {:.2} %",
|
||||
100.0 * aw.unbekannt_angreifer as f64 / aw.entscheidungen.max(1) as f64
|
||||
);
|
||||
if !datei.is_empty() {
|
||||
let mut f = std::fs::File::create(datei).unwrap();
|
||||
writeln!(f, "{zeile}").unwrap();
|
||||
writeln!(f, "Zelle\tEntscheidungen\tAnteil bb/100\t±95%\tje Entscheidung bb").unwrap();
|
||||
let mut v: Vec<_> = aw.zellen.iter().collect();
|
||||
v.sort_by(|x, y| y.1.s.partial_cmp(&x.1.s).unwrap());
|
||||
for (k, s) in v {
|
||||
// Anteil an Delta je Hand: Summe der Vorteile / (Deals * Sitze); Intervall aus der Streuung je Entscheidung
|
||||
let haende = n * sitze;
|
||||
let m = s.s / s.n.max(1.0);
|
||||
let var = (s.q / s.n.max(1.0) - m * m).max(0.0);
|
||||
let anteil = s.s / haende * 100.0;
|
||||
let ci = 1.96 * (var * s.n).sqrt() / haende * 100.0;
|
||||
writeln!(f, "{k}\t{}\t{anteil:+.3}\t{ci:.3}\t{m:+.4}", s.n as u64).unwrap();
|
||||
}
|
||||
}
|
||||
zeile
|
||||
}
|
||||
|
||||
/// angreifer <spiel> <ordner> <k2> <km> <motordatei> <k-angreifer> <minuten,..> <faeden> <deals> <eps> <aus-praefix>
|
||||
pub fn lauf(a: &[String]) {
|
||||
let kl = |k: &str| crate::klassen::Klassen::lade(&format!("{}/klassen-{k}.bin", a[1]));
|
||||
let s = Spiel::neu(&a[0]);
|
||||
let m = Grund { s: s.clone(), t: Tabellen { bretter: crate::klassen::Bretter::neu(), kl: [kl(&a[2]), kl(&a[3])] }, st: crate::dienst::Strategie::lade(&a[4]), schwelle: 0.0, eps: a[9].parse().unwrap() };
|
||||
let ta = Tabellen { bretter: crate::klassen::Bretter::neu(), kl: [kl(&a[5]), kl(&a[3])] };
|
||||
let punkte: Vec<f64> = a[6].split(',').map(|x| x.parse().unwrap()).collect();
|
||||
let faeden: usize = a[7].parse().unwrap();
|
||||
let deals: u64 = a[8].parse().unwrap();
|
||||
let aus = &a[10];
|
||||
let l = if s.n > 2 { Lager::neu(24, 20.0) } else { Lager::neu(20, 2.0) };
|
||||
let sp = Spieler { s: &s, l: &l, ta: &ta, m: &m, fest: None, hybrid: false };
|
||||
let protokoll = |x: &str| {
|
||||
println!("{x}");
|
||||
std::io::stdout().flush().unwrap();
|
||||
let mut f = std::fs::OpenOptions::new().create(true).append(true).open(format!("{aus}-kurve.txt")).unwrap();
|
||||
writeln!(f, "{x}").unwrap();
|
||||
};
|
||||
// Punkt 0: ohne Training (Angreifer folgt ueberall dem Motor) -> Delta = 0 bis auf Rauschen
|
||||
let aw = auswerten(&sp, deals, faeden, 1, false);
|
||||
protokoll(&bericht(&aw, s.n as f64, "0.0 min Training, 0 Mio Laeufe", &format!("{aus}-zellen-0.txt")));
|
||||
let runde_s = 20.0f64;
|
||||
let mut trainiert = 0.0f64;
|
||||
let (mut laeufe, mut r) = (0u64, 0u32);
|
||||
let wurzel = Zustand::start(&s);
|
||||
for (pi, &ziel) in punkte.iter().enumerate() {
|
||||
let online: [AtomicU64; MAXN] = std::array::from_fn(|_| AtomicU64::new(0));
|
||||
let mut online_n = 0u64;
|
||||
while trainiert < ziel * 60.0 - 1e-6 {
|
||||
r += 1;
|
||||
let dauer = runde_s.min(ziel * 60.0 - trainiert);
|
||||
let start = Instant::now();
|
||||
let fertig = AtomicBool::new(false);
|
||||
let zahl = AtomicU64::new(0);
|
||||
std::thread::scope(|sc| {
|
||||
for f in 0..faeden {
|
||||
let (s, l, ta, m, fertig, zahl, online, wurzel) = (&s, &l, &ta, &m, &fertig, &zahl, &online, &wurzel);
|
||||
sc.spawn(move || {
|
||||
let mut la = Lauf { s, l, ta, m, rng: Rng(misch(r as u64 * 1000 + f as u64, 0xA11) | 1), schnitt: 0.0, besuche: 0 };
|
||||
let (mut n, mut o) = (0u64, [0f64; MAXN]);
|
||||
while !fertig.load(Relaxed) {
|
||||
for _ in 0..64 {
|
||||
la.schnitt = if r > 5 && la.rng.f() < 0.95 { 3000.0 } else { 0.0 };
|
||||
for p in 0..s.n {
|
||||
let da0 = Deal::gib(&mut la.rng, s.n);
|
||||
let mut da = Deal::aus(da0.karten, da0.brett, s.n);
|
||||
let mut dm = Deal::aus(da0.karten, da0.brett, s.n);
|
||||
o[p] += la.lauf(wurzel, &mut da, &mut dm, p, 1.0) as f64;
|
||||
}
|
||||
n += 1;
|
||||
}
|
||||
if start.elapsed().as_secs_f64() > dauer {
|
||||
fertig.store(true, Relaxed);
|
||||
}
|
||||
}
|
||||
zahl.fetch_add(n, Relaxed);
|
||||
for p in 0..s.n {
|
||||
online[p].fetch_add((o[p] * 1e3) as i64 as u64, Relaxed);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
// hoechstens Rundenzeit + 1 s je Runde: ein angehaltener Prozess (Halter, Waechter) springt sonst um die ganze Haltezeit (hu160, 29.11.)
|
||||
trainiert += start.elapsed().as_secs_f64().min(dauer + 1.0);
|
||||
let n = zahl.load(Relaxed);
|
||||
laeufe += n;
|
||||
online_n += n;
|
||||
l.daempfe(r as f32 / (r + 1) as f32, faeden);
|
||||
}
|
||||
let on: f64 = online.iter().map(|x| x.load(Relaxed) as i64 as f64 / 1e3).sum::<f64>() / s.n as f64 / online_n.max(1) as f64 * 100.0;
|
||||
let aw = auswerten(&sp, deals, faeden, 1000 + pi as u64, false);
|
||||
let kopf = format!("{:.1} min Training, {:.1} Mio Laeufe, {} Knoten, laufende Strategie {on:+.1} bb/100", trainiert / 60.0, laeufe as f64 / 1e6, l.knoten.load(Relaxed));
|
||||
protokoll(&bericht(&aw, s.n as f64, &kopf, &format!("{aus}-zellen-{ziel}.txt")));
|
||||
l.speichere(&format!("{aus}-angreifer.bin"));
|
||||
}
|
||||
}
|
||||
|
||||
/// angreifer_bewerten <spiel> <ordner> <k2> <km> <motordatei> <k-angreifer> <angreiferdatei> <faeden> <deals> <aus-praefix>
|
||||
/// Eingefrorener Angreifer (gespeicherte Mittelstrategie) gegen die Tafel, ohne Training; Deals mit fester eigener Saat,
|
||||
/// damit Arme mit anderen Tafel-Faktoren (MOTOR_FLOP_XR, MOTOR_VORFLOP_4BET) dieselben Karten sehen (messung/motor/angreifer/faktor_probe).
|
||||
/// ANGREIFER_OPFER=hybrid: das Opfer spielt vor dem Turn SHARINGAN B-local-2e10 (Dienst sharingan-hybrid), Turn/River die Tafel
|
||||
/// (ohne Nachrechnung). Training gegen den Hybrid gibt es nicht (ueber die Leitung zu langsam); gemessen wird, was ein
|
||||
/// gegen die Tafel trainierter Angreifer gegen den Hybrid behaelt (messung/motor/pruef6/sharingan/hybrid/KARTE.md).
|
||||
pub fn bewerten(a: &[String]) {
|
||||
let kl = |k: &str| crate::klassen::Klassen::lade(&format!("{}/klassen-{k}.bin", a[1]));
|
||||
let s = Spiel::neu(&a[0]);
|
||||
let m = Grund { s: s.clone(), t: Tabellen { bretter: crate::klassen::Bretter::neu(), kl: [kl(&a[2]), kl(&a[3])] }, st: crate::dienst::Strategie::lade(&a[4]), schwelle: 0.0, eps: 0.0 };
|
||||
let ta = Tabellen { bretter: crate::klassen::Bretter::neu(), kl: [kl(&a[5]), kl(&a[3])] };
|
||||
let fest = crate::dienst::Strategie::lade(&a[6]);
|
||||
let faeden: usize = a[7].parse().unwrap();
|
||||
let deals: u64 = a[8].parse().unwrap();
|
||||
let aus = &a[9];
|
||||
let l = Lager::neu(4, 1e-6);
|
||||
let hybrid = std::env::var("ANGREIFER_OPFER").is_ok_and(|x| x == "hybrid");
|
||||
let sp = Spieler { s: &s, l: &l, ta: &ta, m: &m, fest: Some(&fest), hybrid };
|
||||
let aw = auswerten(&sp, deals, faeden, 4242, true);
|
||||
let schalter: Vec<String> = ["MOTOR_FLOP_XR", "MOTOR_VORFLOP_4BET", "ANGREIFER_OPFER"].iter().filter_map(|k| std::env::var(k).ok().map(|v| format!("{k}={v}"))).collect();
|
||||
let oz: Vec<u64> = crate::sharingan::OPFER_ZAHL.iter().map(|x| x.load(Relaxed)).collect();
|
||||
let opfer = if hybrid { format!(", SHARINGAN-Punkte Speicher {} Dienst {} ohne Antwort {}", oz[0], oz[1], oz[2]) } else { String::new() };
|
||||
let kopf = format!("eingefroren {} gegen Tafel, Schalter [{}]{opfer}", a[6], schalter.join(" "));
|
||||
println!("{}", bericht(&aw, s.n as f64, &kopf, &format!("{aus}-zellen.txt")));
|
||||
}
|
||||
@@ -444,7 +444,21 @@ impl Motor {
|
||||
a
|
||||
}
|
||||
|
||||
/// Hybrid (MOTOR_VORFLOP_FLOP_QUELLE=sharingan): nur der 6-max-Hauptmotor ohne Straddle, Splash und Antes
|
||||
fn hybrid(&self, q: &Value) -> bool {
|
||||
crate::sharingan::an() && self.s.n == 6 && !self.s.straddle && self.s.splash == 0 && !self.s.ante && self.s.art != crate::spiel::Art::PushFold
|
||||
&& Self::splash_tot(q) == 0.0 && Self::ante_tot(q) == 0.0 && !Self::ist_straddle(q) && q.get("eigen").is_none() && q.get("probeHand").is_none()
|
||||
}
|
||||
|
||||
fn versuche(&self, q: &Value) -> Result<Value, String> {
|
||||
let _hybrid = if crate::sharingan::an() { Some(crate::sharingan::Wache::setze(self.hybrid(q).then(|| crate::sharingan::Kontext::aus(q)).flatten())) } else { None };
|
||||
if let Some(k) = _hybrid.as_ref().and_then(|_| crate::sharingan::kontext()) {
|
||||
if matches!(q["street"].as_str(), Some("PREFLOP" | "FLOP")) {
|
||||
if let Some(a) = crate::sharingan::zug(q, &k) {
|
||||
return Ok(a);
|
||||
}
|
||||
}
|
||||
}
|
||||
let f = |k: &str| q[k].as_f64();
|
||||
let bb = f("bigBlind").ok_or("bigBlind")?;
|
||||
let geld = |x: f64| (x / bb * 100.0) as f32;
|
||||
@@ -889,13 +903,15 @@ impl Motor {
|
||||
// nie gespielte Wege (Limper, Nachposter): die gelernte Strategie ist dort kaum trainiert, ihre Deutung zaehlt wenig
|
||||
let duenn = |z: &Zustand, code: u8| z.strasse == 0 && z.hoch == 100 && code == CALL && z.dran >= 2;
|
||||
let limper = l.gepostet[p] || l.pfad.iter().any(|(z, c)| z.dran as usize == p && duenn(z, *c));
|
||||
for (z, code) in &l.pfad {
|
||||
for (k, (z, code)) in l.pfad.iter().enumerate() {
|
||||
if z.dran as usize != p || z.strasse >= bis {
|
||||
continue;
|
||||
}
|
||||
if l.gepostet[p] && z.strasse == 0 && z.hoch == 100 && *code == CALL {
|
||||
continue;
|
||||
}
|
||||
// Hybrid: vor dem Turn fuehrt seine Strategie die Range (None, wenn aus)
|
||||
let fremd_v = if crate::sharingan::an() { crate::sharingan::range_fuer(k, z.strasse, z.dran, fremd) } else { None };
|
||||
let m = z.menue(&self.s);
|
||||
let Some(i) = m.liste().iter().position(|x| x.code == *code) else { continue };
|
||||
let st = z.strasse as usize;
|
||||
@@ -912,6 +928,10 @@ impl Motor {
|
||||
None => vorflop(a, b),
|
||||
Some(t) => self.t.kl[g].klasse(st, t, (a, b)),
|
||||
};
|
||||
if let Some(fv) = &fremd_v {
|
||||
v[h] = fv[h].max(0.0);
|
||||
continue;
|
||||
}
|
||||
let alle = fremd && *code >= 2;
|
||||
v[h] = self.st.hole(key, kl, m.n).map_or(1.0 / m.n as f32, |mut v| {
|
||||
if !fremd {
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
mod angreifer;
|
||||
mod ausbeuten;
|
||||
mod rakezaehler;
|
||||
mod dienst;
|
||||
mod gedaechtnis;
|
||||
mod gegenprobe;
|
||||
mod schiedsrichter;
|
||||
mod sharingan;
|
||||
mod nachprobe;
|
||||
mod gegner;
|
||||
mod flopwert;
|
||||
@@ -144,6 +146,9 @@ fn main() {
|
||||
let f: Vec<(String, [usize; 3])> = a[4..].iter().map(|k| (format!("{}/klassen-{k}.bin", a[2]), { let v: Vec<usize> = k.split('-').map(|x| x.parse().unwrap()).collect(); [v[0], v[v.len() / 2], v[v.len() - 1]] })).collect();
|
||||
klassen::baue(&f, a[3].parse().unwrap());
|
||||
}
|
||||
// angreifer <spiel> <ordner> <k2> <km> <motordatei> <k-angreifer> <minuten,..> <faeden> <deals> <eps> <aus-praefix>
|
||||
"angreifer" => angreifer::lauf(&a[2..]),
|
||||
"angreifer_bewerten" => angreifer::bewerten(&a[2..]),
|
||||
"glueck" => glueck::werte(&a[2..]),
|
||||
// lbr6 <spiel> <ordner> <k2> <km> <strategie> <blaetter> <faeden> <saat> <fehler> <vorflop: grund|lbr> <welten> <aus>
|
||||
"lbr6" => lbr6::lauf(&a[2..]),
|
||||
|
||||
@@ -0,0 +1,489 @@
|
||||
//! Hybrid (29.11.): Vorflop und Flop spielt die SHARINGAN-Grundstrategie B-local-2e10 ohne Suche, Turn und River rechnet der Motor.
|
||||
//! Schalter MOTOR_VORFLOP_FLOP_QUELLE=sharingan, Standard aus (dann laeuft kein Code dieses Moduls ausser dem Schalter-Lesen).
|
||||
//!
|
||||
//! SHARINGAN (markokraemer/poker-sharingan) steht unter Apache-2.0: Code und Gewichte; LICENSE und NOTICE liegen in
|
||||
//! `entscheiden/motor/fremd/sharingan/`. Gerufen wird unser Dienst `sharingan-hybrid` (ein Zusatz in seinem Baum,
|
||||
//! sharingan-1/serve/src/bin/sharingan-hybrid.rs), ein Prozess fuer alle Tische, nur 127.0.0.1, ohne Netz.
|
||||
//!
|
||||
//! Zwei Dinge kommen von ihm:
|
||||
//! 1. der eigene Zug vor dem Flop und auf dem Flop (`zug`), danach greifen NL2-Regeln und Ausbeute wie sonst;
|
||||
//! 2. in der Range-Fuehrung (`ranges_mit`) die Wahrscheinlichkeit je Hand, mit der seine Strategie den echten Zug gewaehlt
|
||||
//! haette (`range_fuer`), fuer jeden Zug vor dem Flop und auf dem Flop. Uebersetzung wie in seiner TRANSLATION.md:
|
||||
//! Erhoehungen auf den naechsten Eintrag seines Menues (Verhaeltnis der Ziele), beim Gegner die Masse aller Erhoehungen
|
||||
//! zusammen (wie unsere eigene Fuehrung); Check und Call sind ein passiver Zug. Liegt ein Punkt nicht in seinem Baum
|
||||
//! (fallback), bleibt fuer diesen Zug unsere eigene Strategie.
|
||||
//! Umgebung: MOTOR_SHARINGAN_ADRESSE (127.0.0.1:47123), MOTOR_SHARINGAN_EXE, MOTOR_SHARINGAN_ARGS (Start, falls keiner laeuft),
|
||||
//! MOTOR_SHARINGAN_WARTEN (s, Laden abwarten, Standard 900), MOTOR_SHARINGAN_PROTOKOLL=<datei>: je Frage `op ms ok` anhaengen.
|
||||
use serde_json::{json, Value};
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::TcpStream;
|
||||
use std::rc::Rc;
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::karten::{paar, HAENDE};
|
||||
|
||||
pub fn an() -> bool {
|
||||
static AN: OnceLock<bool> = OnceLock::new();
|
||||
*AN.get_or_init(|| std::env::var("MOTOR_VORFLOP_FLOP_QUELLE").is_ok_and(|x| x == "sharingan"))
|
||||
}
|
||||
|
||||
const RANG: &[u8] = b"23456789TJQKA";
|
||||
const FARBE: &[u8] = b"cdhs";
|
||||
|
||||
fn karte(v: &Value) -> Option<String> {
|
||||
const R: [&str; 13] = ["TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "TEN", "JACK", "QUEEN", "KING", "ACE"];
|
||||
const F: [&str; 4] = ["CLUBS", "DIAMONDS", "HEARTS", "SPADES"];
|
||||
let r = R.iter().position(|x| Some(*x) == v["rank"].as_str())?;
|
||||
let f = F.iter().position(|x| Some(*x) == v["suit"].as_str())?;
|
||||
Some(format!("{}{}", RANG[r] as char, FARBE[f] as char))
|
||||
}
|
||||
|
||||
/// Ein echter Zug nach Vertrag, in seinen Begriffen
|
||||
struct Zug {
|
||||
strasse: u8,
|
||||
/// Platz im Motor (ab SB)
|
||||
sitz: u8,
|
||||
/// Index in `hist`
|
||||
j: usize,
|
||||
/// fold / call / raise (ALL_IN unter dem Hoechsteinsatz = call)
|
||||
art: &'static str,
|
||||
to: Option<i64>,
|
||||
}
|
||||
|
||||
pub struct Kontext {
|
||||
basis: Value,
|
||||
hist: Vec<Value>,
|
||||
brett: Vec<String>,
|
||||
zuege: Vec<Zug>,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static JETZT: RefCell<Option<Rc<Kontext>>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Setzt den Kontext der laufenden Anfrage, stellt beim Verlassen den vorigen wieder her.
|
||||
pub struct Wache(Option<Rc<Kontext>>);
|
||||
|
||||
impl Wache {
|
||||
pub fn setze(k: Option<Kontext>) -> Wache {
|
||||
Wache(JETZT.with(|j| j.replace(k.map(Rc::new))))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Wache {
|
||||
fn drop(&mut self) {
|
||||
let alt = self.0.take();
|
||||
JETZT.with(|j| *j.borrow_mut() = alt);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn kontext() -> Option<Rc<Kontext>> {
|
||||
JETZT.with(|j| j.borrow().clone())
|
||||
}
|
||||
|
||||
impl Kontext {
|
||||
/// Vertrag -> seine ActRequest (BB = 100 Chips, Sitze 0..5 in Tischreihenfolge, `to` = Einsatz dieser Strasse,
|
||||
/// stack_start = Stapel jetzt + eingezahlt). Nur volle sechs Plaetze, keine Antes; sonst None (dann spielt der Motor).
|
||||
pub fn aus(q: &Value) -> Option<Kontext> {
|
||||
let bb = q["bigBlind"].as_f64()?;
|
||||
let c = |x: f64| (x / bb * 100.0).round() as i64;
|
||||
let hist_q = q["history"].as_array()?;
|
||||
let held = q["heroSeat"].as_i64()?;
|
||||
let mut sitze: Vec<i64> = q["villains"].as_array()?.iter().filter_map(|v| v["seat"].as_i64()).collect();
|
||||
sitze.push(held);
|
||||
sitze.extend(hist_q.iter().filter_map(|h| h["seat"].as_i64()));
|
||||
sitze.sort_unstable();
|
||||
sitze.dedup();
|
||||
if sitze.len() != 6 {
|
||||
return None;
|
||||
}
|
||||
let pos = |s: i64| sitze.iter().position(|&x| x == s);
|
||||
let sb = pos(hist_q.iter().find(|h| h["action"] == "POST_SB")?["seat"].as_i64()?)?;
|
||||
let bbs = pos(hist_q.iter().find(|h| h["action"] == "POST_BB")?["seat"].as_i64()?)?;
|
||||
if bbs != (sb + 1) % 6 || hist_q.iter().filter(|h| h["action"] == "POST_BB").count() != 1 {
|
||||
return None;
|
||||
}
|
||||
let strasse_nr = |s: &str| ["PREFLOP", "FLOP", "TURN", "RIVER"].iter().position(|x| *x == s).map(|x| x as u8);
|
||||
let (mut hist, mut zuege, mut drin) = (Vec::new(), Vec::new(), [0i64; 6]);
|
||||
let (mut st, mut auf, mut hoch) = (0u8, [0i64; 6], 0i64);
|
||||
for h in hist_q {
|
||||
let x = h["action"].as_str()?;
|
||||
let s = pos(h["seat"].as_i64()?)?;
|
||||
let strasse = strasse_nr(h["street"].as_str().unwrap_or("PREFLOP"))?;
|
||||
if strasse != st {
|
||||
(st, auf, hoch) = (strasse, [0; 6], 0);
|
||||
}
|
||||
let typ = match x {
|
||||
"POST_SB" => "post_sb",
|
||||
"POST_BB" => "post_bb",
|
||||
"FOLD" => "fold",
|
||||
"CHECK" => "check",
|
||||
"CALL" => "call",
|
||||
"BET" => "bet",
|
||||
"RAISE" => "raise",
|
||||
"ALL_IN" => "all_in",
|
||||
_ => return None,
|
||||
};
|
||||
let mut e = json!({"seat": s, "type": typ});
|
||||
let mut to = None;
|
||||
if matches!(x, "POST_SB" | "POST_BB" | "BET" | "RAISE" | "ALL_IN" | "CALL") {
|
||||
if let Some(a) = h["amount"].as_f64() {
|
||||
let t = c(a);
|
||||
drin[s] += t - auf[s];
|
||||
auf[s] = t;
|
||||
if x != "CALL" {
|
||||
e["to"] = json!(t);
|
||||
to = Some(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
if !x.starts_with("POST") {
|
||||
let art = match x {
|
||||
"FOLD" => "fold",
|
||||
"CHECK" | "CALL" => "call",
|
||||
_ if to.unwrap_or(0) <= hoch => "call",
|
||||
_ => "raise",
|
||||
};
|
||||
zuege.push(Zug { strasse, sitz: ((s + 6 - sb) % 6) as u8, j: hist.len(), art, to });
|
||||
}
|
||||
if let Some(t) = to {
|
||||
hoch = hoch.max(t);
|
||||
}
|
||||
hist.push(e);
|
||||
}
|
||||
let mut stand = [None; 6];
|
||||
stand[pos(held)?] = q["heroStack"].as_f64().map(c);
|
||||
for v in q["villains"].as_array()? {
|
||||
if let (Some(s), Some(x)) = (v["seat"].as_i64().and_then(pos), v["stack"].as_f64()) {
|
||||
stand[s] = Some(c(x));
|
||||
}
|
||||
}
|
||||
let mut spieler = Vec::new();
|
||||
for s in 0..6 {
|
||||
spieler.push(json!({"seat": s, "stack_start": stand[s]? + drin[s]}));
|
||||
}
|
||||
let brett: Vec<String> = ["FLOP", "TURN", "RIVER"].iter().flat_map(|s| q["board"][*s].as_array().into_iter().flatten().filter_map(karte)).collect();
|
||||
let loch: Vec<String> = q["heroCards"].as_array()?.iter().filter_map(karte).collect();
|
||||
let seed = q["seed"].as_u64().unwrap_or(1);
|
||||
let basis = json!({"small_blind": 50, "big_blind": 100, "button_seat": (sb + 5) % 6, "hero_seat": pos(held)?, "hole_cards": loch,
|
||||
"board": brett, "players": spieler, "history": hist, "options": {"seed": seed, "include_probs": false}});
|
||||
Some(Kontext { basis, hist, brett, zuege })
|
||||
}
|
||||
}
|
||||
|
||||
struct Leitung {
|
||||
lesen: BufReader<TcpStream>,
|
||||
schreiben: TcpStream,
|
||||
}
|
||||
|
||||
static LEITUNG: Mutex<Option<Leitung>> = Mutex::new(None);
|
||||
|
||||
fn adresse() -> String {
|
||||
std::env::var("MOTOR_SHARINGAN_ADRESSE").unwrap_or_else(|_| "127.0.0.1:47123".into())
|
||||
}
|
||||
|
||||
fn verbinde() -> std::io::Result<Leitung> {
|
||||
let a: std::net::SocketAddr = adresse().parse().map_err(|_| std::io::Error::other("Adresse"))?;
|
||||
let s = TcpStream::connect_timeout(&a, Duration::from_millis(500))?;
|
||||
s.set_nodelay(true)?;
|
||||
s.set_read_timeout(Some(Duration::from_secs(120)))?;
|
||||
Ok(Leitung { lesen: BufReader::new(s.try_clone()?), schreiben: s })
|
||||
}
|
||||
|
||||
/// Laeuft kein Dienst: einen starten (losgeloest, BelowNormal, ohne Fenster) und das Laden abwarten. Starten mehrere Motoren
|
||||
/// zugleich, beendet sich jeder spaetere Dienst sofort (Port belegt), bevor er die Tabelle laedt.
|
||||
fn starte_und_warte() -> std::io::Result<Leitung> {
|
||||
let frist = std::env::var("MOTOR_SHARINGAN_WARTEN").ok().and_then(|x| x.parse().ok()).unwrap_or(900u64);
|
||||
// der Dienst bindet vor dem Laden: Verbindung steht sofort, die erste Antwort erst nach dem Laden
|
||||
let bereit = |mut l: Leitung| -> std::io::Result<Leitung> {
|
||||
l.schreiben.set_read_timeout(Some(Duration::from_secs(frist)))?;
|
||||
writeln!(l.schreiben, "{{\"op\":\"ping\"}}")?;
|
||||
let mut z = String::new();
|
||||
l.lesen.read_line(&mut z)?;
|
||||
l.schreiben.set_read_timeout(Some(Duration::from_secs(120)))?;
|
||||
if z.contains("true") { Ok(l) } else { Err(std::io::Error::other("ping")) }
|
||||
};
|
||||
if let Ok(l) = verbinde() {
|
||||
return bereit(l);
|
||||
}
|
||||
static GESTARTET: OnceLock<()> = OnceLock::new();
|
||||
GESTARTET.get_or_init(|| {
|
||||
const F: &str = "D:/pokerfreak-fremd/sharingan";
|
||||
let exe = std::env::var("MOTOR_SHARINGAN_EXE").unwrap_or_else(|_| format!("{F}/code/target/serve/pokerbench-pruef6-hybrid.exe"));
|
||||
let args = std::env::var("MOTOR_SHARINGAN_ARGS")
|
||||
.unwrap_or_else(|_| format!("--blueprint {F}/weights/B-local-2e10.plcp --buckets {F}/data/buckets-200 --sizing local"));
|
||||
let mut c = std::process::Command::new(exe);
|
||||
c.args(args.split_whitespace()).stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null());
|
||||
if let Some(port) = adresse().rsplit(':').next() {
|
||||
c.args(["--port", port]);
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
// DETACHED_PROCESS | CREATE_NO_WINDOW | BELOW_NORMAL_PRIORITY_CLASS | CREATE_BREAKAWAY_FROM_JOB
|
||||
c.creation_flags(0x8 | 0x0800_0000 | 0x4000 | 0x0100_0000);
|
||||
if c.spawn().is_err() {
|
||||
c.creation_flags(0x8 | 0x0800_0000 | 0x4000);
|
||||
let _ = c.spawn();
|
||||
}
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
let _ = c.spawn();
|
||||
});
|
||||
let t0 = Instant::now();
|
||||
loop {
|
||||
match verbinde() {
|
||||
Ok(l) => return bereit(l),
|
||||
Err(e) if t0.elapsed().as_secs() > frist => return Err(e),
|
||||
Err(_) => std::thread::sleep(Duration::from_millis(500)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn protokoll(op: &str, t0: Instant, ok: bool) {
|
||||
if let Ok(p) = std::env::var("MOTOR_SHARINGAN_PROTOKOLL") {
|
||||
if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(p) {
|
||||
let _ = writeln!(f, "{op} {:.0} {}", t0.elapsed().as_secs_f64() * 1000.0, ok as u8);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Eine Frage an den Dienst (mit Protokoll)
|
||||
fn frage(v: &Value) -> Option<Value> {
|
||||
let t0 = Instant::now();
|
||||
let r = frage_roh(v);
|
||||
protokoll(v["op"].as_str().unwrap_or("?"), t0, r.is_some());
|
||||
r
|
||||
}
|
||||
|
||||
/// Eine Frage an den Dienst; bei kaputter Leitung einmal neu verbinden.
|
||||
fn frage_roh(v: &Value) -> Option<Value> {
|
||||
let mut g = LEITUNG.lock().unwrap_or_else(|e| e.into_inner());
|
||||
for _ in 0..2 {
|
||||
if g.is_none() {
|
||||
*g = Some(starte_und_warte().ok()?);
|
||||
}
|
||||
let l = g.as_mut()?;
|
||||
let mut zeile = String::new();
|
||||
let ok = writeln!(l.schreiben, "{v}").and_then(|_| l.schreiben.flush()).and_then(|_| l.lesen.read_line(&mut zeile)).is_ok_and(|n| n > 0);
|
||||
if ok {
|
||||
if let Ok(r) = serde_json::from_str::<Value>(&zeile) {
|
||||
return (r["ok"] == true).then_some(r);
|
||||
}
|
||||
}
|
||||
*g = None;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Der eigene Zug von SHARINGAN, als Vertragsantwort. None: er weiss keinen (dann spielt der Motor).
|
||||
pub fn zug(q: &Value, k: &Kontext) -> Option<Value> {
|
||||
let r = frage(&json!({"op": "act", "req": k.basis}))?;
|
||||
let o = &r["response"];
|
||||
let a = &o["action"];
|
||||
let bb = q["bigBlind"].as_f64()?;
|
||||
let f = |x: &str| q[x].as_f64();
|
||||
let legal = |x: &str| q["legalActions"].as_array().is_some_and(|l| l.iter().any(|y| y == x));
|
||||
let offen = f("toCall").unwrap_or(0.0);
|
||||
let (mut akt, mut groesse) = match a["type"].as_str()? {
|
||||
"fold" => (if offen > 0.0 { "FOLD" } else { "CHECK" }, None),
|
||||
"check" => ("CHECK", None),
|
||||
"call" => (if offen > 0.0 { "CALL" } else { "CHECK" }, None),
|
||||
"raise" | "bet" | "all_in" => {
|
||||
let (min, max) = (f("minRaiseTo").unwrap_or(0.0), f("maxRaiseTo").unwrap_or(f64::MAX));
|
||||
let ziel = a["to"].as_f64().map_or(max, |t| t * bb / 100.0);
|
||||
("RAISE", Some(((ziel.clamp(min.min(max), max)) / bb * 100.0).round() / 100.0 * bb))
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
if akt == "RAISE" && !legal("RAISE") {
|
||||
(akt, groesse) = (if offen > 0.0 { "CALL" } else { "CHECK" }, None);
|
||||
}
|
||||
if let (Some(g), Some(erlaubt)) = (groesse, q["allowedSizes"].as_array()) {
|
||||
groesse = erlaubt.iter().filter_map(|x| x.as_f64()).min_by(|a, b| (a - g).abs().total_cmp(&(b - g).abs())).or(groesse);
|
||||
}
|
||||
if !legal(akt) {
|
||||
akt = if legal("CHECK") { "CHECK" } else if legal("CALL") && akt != "FOLD" { "CALL" } else { "FOLD" };
|
||||
groesse = None;
|
||||
}
|
||||
Some(json!({"action": akt, "size": groesse, "confidence": 1,
|
||||
"reason": format!("sharingan {} ({})", o["source"].as_str().unwrap_or("?"), o["street"].as_str().unwrap_or("?"))}))
|
||||
}
|
||||
|
||||
type Vektor = Arc<Vec<f32>>;
|
||||
|
||||
static SPEICHER: OnceLock<Mutex<HashMap<String, Vektor>>> = OnceLock::new();
|
||||
|
||||
/// Seine Reihenfolge (a<b ueber 0..51) -> unsere (paar)
|
||||
fn umordnung() -> &'static Vec<usize> {
|
||||
static U: OnceLock<Vec<usize>> = OnceLock::new();
|
||||
U.get_or_init(|| (0..52u8).flat_map(|a| (a + 1..52).map(move |b| paar(b, a))).collect())
|
||||
}
|
||||
|
||||
/// Fuer Schritt `k` des Pfads (Zug k des echten Verlaufs): je Hand (unsere Reihenfolge) die Wahrscheinlichkeit seines
|
||||
/// Zugs; < 0 = kollidiert mit dem Brett. None: aus, nicht vor dem Turn, Verlauf passt nicht, oder er weiss es nicht.
|
||||
pub fn range_fuer(k: usize, strasse: u8, sitz: u8, alle: bool) -> Option<Vektor> {
|
||||
let kx = kontext()?;
|
||||
let z = kx.zuege.get(k)?;
|
||||
if strasse > 1 || z.strasse != strasse || z.sitz != sitz {
|
||||
return None;
|
||||
}
|
||||
let mut req = kx.basis.clone();
|
||||
req["history"] = Value::Array(kx.hist[..z.j].to_vec());
|
||||
req["board"] = json!(kx.brett[..if strasse == 0 { 0 } else { 3.min(kx.brett.len()) }]);
|
||||
req["hero_seat"] = kx.hist[z.j]["seat"].clone();
|
||||
req["hole_cards"] = json!(["2c", "2d"]);
|
||||
let mut act = json!({"type": z.art, "to": z.to});
|
||||
if alle && z.art == "raise" {
|
||||
act["alle"] = json!(true);
|
||||
}
|
||||
let frage_v = json!({"op": "range", "req": req, "act": act});
|
||||
let schluessel = frage_v.to_string();
|
||||
let sp = SPEICHER.get_or_init(Default::default);
|
||||
if let Some(v) = sp.lock().unwrap_or_else(|e| e.into_inner()).get(&schluessel) {
|
||||
return Some(v.clone());
|
||||
}
|
||||
let r = frage(&frage_v)?;
|
||||
let p = r["p"].as_array()?;
|
||||
if p.len() != HAENDE || p.iter().any(|x| x.as_f64() == Some(-2.0)) {
|
||||
return None;
|
||||
}
|
||||
let mut v = vec![0f32; HAENDE];
|
||||
for (i, x) in p.iter().enumerate() {
|
||||
v[umordnung()[i]] = x.as_f64().unwrap_or(-1.0) as f32;
|
||||
}
|
||||
let v = Arc::new(v);
|
||||
let mut g = sp.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if g.len() > 20000 {
|
||||
g.clear();
|
||||
}
|
||||
g.insert(schluessel, v.clone());
|
||||
Some(v)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------------------------------
|
||||
// Opfer fuer die Angreifer-Probe (angreifer_bewerten mit ANGREIFER_OPFER=hybrid): an Opfer-Punkten vor dem Turn spielt
|
||||
// SHARINGANs Grundstrategie im Baum des Motors. Der Verlauf wird als seine Geschichte mitgefuehrt (Sitz 0 = SB, Knopf = letzter
|
||||
// Platz, Chips wie im Baum: BB = 100), seine ganze Verteilung (op probs, ohne Ziehen) wird auf unser Menue gelegt:
|
||||
// fold -> FOLD (ohne Einsatz: Check), check/call -> CALL, Erhoehung -> naechste Erhoehung des Menues (Verhaeltnis der Ziele).
|
||||
|
||||
use crate::lernen::MAXA;
|
||||
use crate::spiel::{Menue, Zustand, ALLIN, CALL, FOLD};
|
||||
|
||||
thread_local! {
|
||||
static FADEN_LEITUNG: RefCell<Option<Leitung>> = const { RefCell::new(None) };
|
||||
static OPFER_SPEICHER: RefCell<HashMap<(String, u8, u8), [f32; MAXA]>> = RefCell::new(HashMap::new());
|
||||
}
|
||||
|
||||
/// Eine Frage ueber die Leitung dieses Fadens (der Dienst bedient jede Verbindung in einem eigenen Faden).
|
||||
fn frage_faden(v: &Value) -> Option<Value> {
|
||||
FADEN_LEITUNG.with(|c| {
|
||||
let mut g = c.borrow_mut();
|
||||
for _ in 0..2 {
|
||||
if g.is_none() {
|
||||
*g = Some(starte_und_warte().ok()?);
|
||||
}
|
||||
let l = g.as_mut()?;
|
||||
let mut zeile = String::new();
|
||||
let ok = writeln!(l.schreiben, "{v}").and_then(|_| l.schreiben.flush()).and_then(|_| l.lesen.read_line(&mut zeile)).is_ok_and(|n| n > 0);
|
||||
if ok {
|
||||
if let Ok(r) = serde_json::from_str::<Value>(&zeile) {
|
||||
return (r["ok"] == true).then_some(r);
|
||||
}
|
||||
}
|
||||
*g = None;
|
||||
}
|
||||
None
|
||||
})
|
||||
}
|
||||
|
||||
fn name(k: u8) -> String {
|
||||
format!("{}{}", RANG[k as usize / 4] as char, FARBE[k as usize % 4] as char)
|
||||
}
|
||||
|
||||
/// Geschichte zu Handbeginn: die Blinds
|
||||
pub fn spur_start() -> Vec<Value> {
|
||||
vec![json!({"seat": 0, "type": "post_sb", "to": 50}), json!({"seat": 1, "type": "post_bb", "to": 100})]
|
||||
}
|
||||
|
||||
/// Zug `code` mit `ziel` im Zustand `z` (vor dem Zug) an die Geschichte haengen
|
||||
pub fn spur_zug(h: &mut Vec<Value>, z: &Zustand, code: u8, ziel: i32) {
|
||||
let d = z.dran as usize;
|
||||
let offen = z.hoch - z.einsatz[d];
|
||||
let to = z.einsatz[d] + (ziel - z.einsatz[d]).clamp(0, z.stack[d]);
|
||||
let e = match code {
|
||||
FOLD if offen > 0 => json!({"seat": d, "type": "fold"}),
|
||||
FOLD => json!({"seat": d, "type": "check"}),
|
||||
CALL if offen > 0 => json!({"seat": d, "type": "call"}),
|
||||
CALL => json!({"seat": d, "type": "check"}),
|
||||
_ if to <= z.hoch => json!({"seat": d, "type": "call"}),
|
||||
_ if to - z.einsatz[d] >= z.stack[d] || code == ALLIN => json!({"seat": d, "type": "all_in", "to": to}),
|
||||
_ if z.hoch == 0 => json!({"seat": d, "type": "bet", "to": to}),
|
||||
_ => json!({"seat": d, "type": "raise", "to": to}),
|
||||
};
|
||||
h.push(e);
|
||||
}
|
||||
|
||||
/// Zaehler der Opfer-Punkte vor dem Turn: [aus dem Speicher, vom Dienst, ohne Antwort (Tafel)]
|
||||
pub static OPFER_ZAHL: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
|
||||
|
||||
/// Seine Verteilung am Punkt `z` auf unserem Menue; None: aus seinem Baum gefallen (dann spielt die Tafel).
|
||||
pub fn opfer_zug(z: &Zustand, me: &Menue, h: &[Value], hand: (u8, u8), brett: &[u8; 5]) -> Option<[f32; MAXA]> {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
if z.strasse > 1 {
|
||||
return None;
|
||||
}
|
||||
let r = opfer_zug_innen(z, me, h, hand, brett);
|
||||
OPFER_ZAHL[match r { Some((_, true)) => 0, Some(_) => 1, None => 2 }].fetch_add(1, Relaxed);
|
||||
r.map(|x| x.0)
|
||||
}
|
||||
|
||||
fn opfer_zug_innen(z: &Zustand, me: &Menue, h: &[Value], hand: (u8, u8), brett: &[u8; 5]) -> Option<([f32; MAXA], bool)> {
|
||||
let n = z.n as usize;
|
||||
let schluessel = (serde_json::to_string(h).ok()?, hand.0.min(hand.1), hand.0.max(hand.1));
|
||||
if let Some(v) = OPFER_SPEICHER.with(|s| s.borrow().get(&schluessel).copied()) {
|
||||
return Some((v, true));
|
||||
}
|
||||
let spieler: Vec<Value> = (0..n).map(|i| json!({"seat": i, "stack_start": z.stack[i] + z.gesamt[i]})).collect();
|
||||
let b: Vec<String> = brett[..if z.strasse == 1 { 3 } else { 0 }].iter().map(|&k| name(k)).collect();
|
||||
let req = json!({"small_blind": 50, "big_blind": 100, "button_seat": if n == 2 { 0 } else { n - 1 }, "hero_seat": z.dran,
|
||||
"hole_cards": [name(hand.0), name(hand.1)], "board": b, "players": spieler, "history": h});
|
||||
let r = frage_faden(&json!({"op": "probs", "req": req}))?;
|
||||
if r["source"] != "blueprint" {
|
||||
return None;
|
||||
}
|
||||
let d = z.dran as usize;
|
||||
let offen = z.hoch - z.einsatz[d];
|
||||
let finde = |c: u8| me.z[..me.n].iter().position(|x| x.code == c);
|
||||
let erh: Vec<(usize, i32)> = (0..me.n).filter(|&i| me.z[i].code >= 2).map(|i| (i, z.einsatz[d] + (me.z[i].ziel - z.einsatz[d]).clamp(0, z.stack[d]))).collect();
|
||||
let passiv = finde(CALL);
|
||||
let mut v = [0f32; MAXA];
|
||||
for x in r["probs"].as_array()? {
|
||||
let p = x["p"].as_f64().unwrap_or(0.0) as f32;
|
||||
let i = match x["type"].as_str().unwrap_or("") {
|
||||
"fold" if offen > 0 => finde(FOLD).or(passiv),
|
||||
"fold" | "check" | "call" => passiv,
|
||||
_ => {
|
||||
let t = x["to"].as_f64().unwrap_or(0.0).max(1.0);
|
||||
erh.iter().min_by(|a, b| (a.1.max(1) as f64 / t).ln().abs().total_cmp(&(b.1.max(1) as f64 / t).ln().abs())).map(|e| e.0).or(passiv)
|
||||
}
|
||||
};
|
||||
v[i?] += p;
|
||||
}
|
||||
let s: f32 = v.iter().sum();
|
||||
if s <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
v.iter_mut().for_each(|x| *x /= s);
|
||||
OPFER_SPEICHER.with(|c| {
|
||||
let mut c = c.borrow_mut();
|
||||
if c.len() > 400_000 {
|
||||
c.clear();
|
||||
}
|
||||
c.insert(schluessel, v);
|
||||
});
|
||||
Some((v, false))
|
||||
}
|
||||
Reference in New Issue
Block a user