using System.Text.Json;
using EARSystem.Core;
namespace EARSystem.Tests;
// A repeatable teaching experiment. These labels are authored synthetic preferences, not human study results.
public class EvaluationTests
{
[Fact, Trait("Category","Evaluation")]
public void CompareThreeRankingsOnIdenticalSyntheticCandidates() {
var rng=new Random(42);
double[][] vectors=[[3,4,1,3,4,1],[4,5,2,2,3,4],[4,4,5,2,2,2],[5,4,2,1,1,5],[4,4,2,2,2,3],[1,4,1,5,5,1]];
var places=Enumerable.Range(0,60).Select(i=>{
var category=i/10;
return new PlaceCandidate((i+1).ToString("D3"),Guid.Parse((i+1).ToString("X32")),"合成地点 "+i,"合成示例",
(PlaceCategory)category,120.155+(rng.NextDouble()-.5)*.045,30.274+(rng.NextDouble()-.5)*.036,
i%9==0?null:20m+i%8*7,Math.Round(3.6+rng.NextDouble()*1.3,1),true,vectors[category],15,"Demo","演示数据");
}).ToArray();
// Column order: Dining, Cafe, Park, Bookstore, Gallery, Entertainment.
Dictionary<RecommendationGoal,int[]> relevance=new() {
[RecommendationGoal.Relax]=[0,3,3,2,1,0],
[RecommendationGoal.Focus]=[0,3,0,3,1,0],
[RecommendationGoal.Social]=[3,2,0,0,1,3],
[RecommendationGoal.Explore]=[2,1,3,1,3,1]
};
var records=new List<object>();
var summary=new Dictionary<string,List<(double Precision,double Ndcg,int Coverage,double Satisfaction)>> {
["Distance"]=[],["Rating"]=[],["MultiDimensional"]=[]
};
foreach(var goal in Enum.GetValues<RecommendationGoal>())
for(var offset=-2;offset<=2;offset++) {
var profile=new EmotionProfile(3,goal==RecommendationGoal.Relax?2:3,3,1,[]);
var query=new RecommendationQuery{Location=new(120.155+offset*.003,30.274+offset*.002),Goal=goal};
var context=new RankingContext(profile,goal,query,[PlaceCategory.Cafe,PlaceCategory.Park],[],[],[],new());
// Eligibility is identical for all three baselines; only their ranking changes.
var candidates=places.Where(p=>RecommendationScorer.Score(p,context)!=null).ToArray();
Dictionary<string,PlaceCandidate[]> lists=new() {
["Distance"]=candidates.OrderBy(p=>RecommendationScorer.Distance(query.Location,p.Longitude,p.Latitude)).ThenBy(p=>p.Id).Take(5).ToArray(),
["Rating"]=candidates.OrderByDescending(p=>p.Rating??3).ThenBy(p=>p.Id).Take(5).ToArray(),
["MultiDimensional"]=RecommendationScorer.Rank(candidates,context,out _).Take(5).Select(x=>x.Place).ToArray()
};
double Gain(PlaceCandidate p)=>Math.Pow(2,relevance[goal][(int)p.Category])-1;
double Dcg(IEnumerable<PlaceCandidate> items)=>items.Select((p,i)=>Gain(p)/Math.Log2(i+2)).Sum();
var ideal=Dcg(candidates.OrderByDescending(Gain).Take(5));
foreach(var (name,list) in lists) {
var precision=list.Count(p=>relevance[goal][(int)p.Category]>=2)/5.0;
var ndcg=ideal==0?0:Dcg(list)/ideal;
var coverage=list.Select(p=>p.Category).Distinct().Count();
// A declared simulation model; this number cannot be presented as observed satisfaction.
var satisfaction=list.Average(p=>Math.Clamp(1+relevance[goal][(int)p.Category]*4/3.0
-Math.Min(.8,RecommendationScorer.Distance(query.Location,p.Longitude,p.Latitude)/4000),1,5));
Assert.InRange(ndcg,0,1.000001);Assert.InRange(satisfaction,1,5);
summary[name].Add((precision,ndcg,coverage,satisfaction));
records.Add(new{goal=goal.ToString(),offset,method=name,candidateCount=candidates.Length,
ids=list.Select(p=>p.Id),precisionAt5=precision,ndcgAt5=ndcg,categoryCoverageAt5=coverage,simulatedSatisfaction=satisfaction});
}
}
var report=new {
measuredAt=DateTimeOffset.UtcNow,
data="60 fictional places; 4 goals x 5 query centers; manually authored category relevance",
limitation="Synthetic behavior illustration only. Real relevance and satisfaction require a separate consenting user study.",
methods=summary.Select(kv=>new{method=kv.Key,scenarios=kv.Value.Count,
precisionAt5=Math.Round(kv.Value.Average(x=>x.Precision),4),
ndcgAt5=Math.Round(kv.Value.Average(x=>x.Ndcg),4),
categoryCoverageAt5=Math.Round(kv.Value.Average(x=>x.Coverage),2),
simulatedSatisfaction=Math.Round(kv.Value.Average(x=>x.Satisfaction),2)}),
scenarios=records
};
var path=Environment.GetEnvironmentVariable("EAR_EVALUATION_OUTPUT")
??Path.GetFullPath("../../../../../artifacts/evaluation.json",AppContext.BaseDirectory);
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllText(path,JsonSerializer.Serialize(report,new JsonSerializerOptions{WriteIndented=true}));
Assert.All(summary.Values,values=>Assert.Equal(20,values.Count));
}
}
using System.Text.Json;
using EARSystem.Core;
namespace EARSystem.Tests;
// A repeatable teaching experiment. These labels are authored synthetic preferences, not human study results.
public class EvaluationTests
{
[Fact, Trait("Category","Evaluation")]
public void CompareThreeRankingsOnIdenticalSyntheticCandidates() {
var rng=new Random(42);
double[][] vectors=[[3,4,1,3,4,1],[4,5,2,2,3,4],[4,4,5,2,2,2],[5,4,2,1,1,5],[4,4,2,2,2,3],[1,4,1,5,5,1]];
var places=Enumerable.Range(0,60).Select(i=>{
var category=i/10;
return new PlaceCandidate((i+1).ToString("D3"),Guid.Parse((i+1).ToString("X32")),"合成地点 "+i,"合成示例",
(PlaceCategory)category,120.155+(rng.NextDouble()-.5)*.045,30.274+(rng.NextDouble()-.5)*.036,
i%9==0?null:20m+i%8*7,Math.Round(3.6+rng.NextDouble()*1.3,1),true,vectors[category],15,"Demo","演示数据");
}).ToArray();
// Column order: Dining, Cafe, Park, Bookstore, Gallery, Entertainment.
Dictionary<RecommendationGoal,int[]> relevance=new() {
[RecommendationGoal.Relax]=[0,3,3,2,1,0],
[RecommendationGoal.Focus]=[0,3,0,3,1,0],
[RecommendationGoal.Social]=[3,2,0,0,1,3],
[RecommendationGoal.Explore]=[2,1,3,1,3,1]
};
var records=new List<object>();
var summary=new Dictionary<string,List<(double Precision,double Ndcg,int Coverage,double Satisfaction)>> {
["Distance"]=[],["Rating"]=[],["MultiDimensional"]=[]
};
foreach(var goal in Enum.GetValues<RecommendationGoal>())
for(var offset=-2;offset<=2;offset++) {
var profile=new EmotionProfile(3,goal==RecommendationGoal.Relax?2:3,3,1,[]);
var query=new RecommendationQuery{Location=new(120.155+offset*.003,30.274+offset*.002),Goal=goal};
var context=new RankingContext(profile,goal,query,[PlaceCategory.Cafe,PlaceCategory.Park],[],[],[],new());
// Eligibility is identical for all three baselines; only their ranking changes.
var candidates=places.Where(p=>RecommendationScorer.Score(p,context)!=null).ToArray();
Dictionary<string,PlaceCandidate[]> lists=new() {
["Distance"]=candidates.OrderBy(p=>RecommendationScorer.Distance(query.Location,p.Longitude,p.Latitude)).ThenBy(p=>p.Id).Take(5).ToArray(),
["Rating"]=candidates.OrderByDescending(p=>p.Rating??3).ThenBy(p=>p.Id).Take(5).ToArray(),
["MultiDimensional"]=RecommendationScorer.Rank(candidates,context,out _).Take(5).Select(x=>x.Place).ToArray()
};
double Gain(PlaceCandidate p)=>Math.Pow(2,relevance[goal][(int)p.Category])-1;
double Dcg(IEnumerable<PlaceCandidate> items)=>items.Select((p,i)=>Gain(p)/Math.Log2(i+2)).Sum();
var ideal=Dcg(candidates.OrderByDescending(Gain).Take(5));
foreach(var (name,list) in lists) {
var precision=list.Count(p=>relevance[goal][(int)p.Category]>=2)/5.0;
var ndcg=ideal==0?0:Dcg(list)/ideal;
var coverage=list.Select(p=>p.Category).Distinct().Count();
// A declared simulation model; this number cannot be presented as observed satisfaction.
var satisfaction=list.Average(p=>Math.Clamp(1+relevance[goal][(int)p.Category]*4/3.0
-Math.Min(.8,RecommendationScorer.Distance(query.Location,p.Longitude,p.Latitude)/4000),1,5));
Assert.InRange(ndcg,0,1.000001);Assert.InRange(satisfaction,1,5);
summary[name].Add((precision,ndcg,coverage,satisfaction));
records.Add(new{goal=goal.ToString(),offset,method=name,candidateCount=candidates.Length,
ids=list.Select(p=>p.Id),precisionAt5=precision,ndcgAt5=ndcg,categoryCoverageAt5=coverage,simulatedSatisfaction=satisfaction});
}
}
var report=new {
measuredAt=DateTimeOffset.UtcNow,
data="60 fictional places; 4 goals x 5 query centers; manually authored category relevance",
limitation="Synthetic behavior illustration only. Real relevance and satisfaction require a separate consenting user study.",
methods=summary.Select(kv=>new{method=kv.Key,scenarios=kv.Value.Count,
precisionAt5=Math.Round(kv.Value.Average(x=>x.Precision),4),
ndcgAt5=Math.Round(kv.Value.Average(x=>x.Ndcg),4),
categoryCoverageAt5=Math.Round(kv.Value.Average(x=>x.Coverage),2),
simulatedSatisfaction=Math.Round(kv.Value.Average(x=>x.Satisfaction),2)}),
scenarios=records
};
var path=Environment.GetEnvironmentVariable("EAR_EVALUATION_OUTPUT")
??Path.GetFullPath("../../../../../artifacts/evaluation.json",AppContext.BaseDirectory);
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllText(path,JsonSerializer.Serialize(report,new JsonSerializerOptions{WriteIndented=true}));
Assert.All(summary.Values,values=>Assert.Equal(20,values.Count));
}
}