-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSampleAdNetwork.java
More file actions
1330 lines (1137 loc) · 47 KB
/
SampleAdNetwork.java
File metadata and controls
1330 lines (1137 loc) · 47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package ia;
//thist is aaa
//hangg
//haha
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import se.sics.isl.transport.Transportable;
import se.sics.tasim.aw.Agent;
import se.sics.tasim.aw.Message;
import se.sics.tasim.props.SimulationStatus;
import se.sics.tasim.props.StartInfo;
import tau.tac.adx.ads.properties.AdType;
import tau.tac.adx.demand.CampaignStats;
import tau.tac.adx.devices.Device;
import tau.tac.adx.props.AdxBidBundle;
import tau.tac.adx.props.AdxQuery;
import tau.tac.adx.props.PublisherCatalog;
import tau.tac.adx.props.PublisherCatalogEntry;
import tau.tac.adx.report.adn.AdNetworkKey;
import tau.tac.adx.report.adn.AdNetworkReport;
import tau.tac.adx.report.adn.AdNetworkReportEntry;
import tau.tac.adx.report.adn.MarketSegment;
import tau.tac.adx.report.demand.AdNetBidMessage;
import tau.tac.adx.report.demand.AdNetworkDailyNotification;
import tau.tac.adx.report.demand.CampaignOpportunityMessage;
import tau.tac.adx.report.demand.CampaignReport;
import tau.tac.adx.report.demand.CampaignReportEntry;
import tau.tac.adx.report.demand.CampaignReportKey;
import tau.tac.adx.report.demand.InitialCampaignMessage;
import tau.tac.adx.report.demand.campaign.auction.CampaignAuctionReport;
import tau.tac.adx.report.publisher.AdxPublisherReport;
import tau.tac.adx.report.publisher.AdxPublisherReportEntry;
import edu.umich.eecs.tac.props.Ad;
import edu.umich.eecs.tac.props.BankStatus;
/**
*
* @author Mariano Schain
* Test plug-in
*
*/
public class SampleAdNetwork extends Agent {
private final Logger log = Logger
.getLogger(SampleAdNetwork.class.getName());
/*
* Basic simulation information. An agent should receive the {@link
* StartInfo} at the beginning of the game or during recovery.
*/
@SuppressWarnings("unused")
private StartInfo startInfo;
/**
* Messages received:
*
* We keep all the {@link CampaignReport campaign reports} delivered to the
* agent. We also keep the initialization messages {@link PublisherCatalog}
* and {@link InitialCampaignMessage} and the most recent messages and
* reports {@link CampaignOpportunityMessage}, {@link CampaignReport}, and
* {@link AdNetworkDailyNotification}.
*/
private final Map<Integer, CampaignReport> campaignReports;
private final Map<Integer, AdNetworkReport> adNetworkReports;
private PublisherCatalog publisherCatalog;
private InitialCampaignMessage initialCampaignMessage;
private AdNetworkDailyNotification adNetworkDailyNotification;
private final Map<Integer, AdNetworkDailyNotification> notifications;
private final Queue<CampaignData> allCampaign;
/*
* The addresses of server entities to which the agent should send the daily
* bids data
*/
private String demandAgentAddress;
private String adxAgentAddress;
/*
* we maintain a list of queries - each characterized by the web site (the
* publisher), the device type, the ad type, and the user market segment
*/
private AdxQuery[] queries;
/**
* Information regarding the latest campaign opportunity announced
*/
private CampaignData pendingCampaign;
/**
* We maintain a collection (mapped by the campaign id) of the campaigns won
* by our agent.
*/
private Map<Integer, CampaignData> myCampaigns;
private Map<Integer, Long> myCampaignsBid;
/*
* the bidBundle to be sent daily to the AdX
*/
private AdxBidBundle bidBundle;
/*
* The current bid level for the user classification service
*/
double ucsBid;
/*
* The targeted service level for the user classification service
*/
double ucsTargetLevel;
private boolean haveCampaignOppotunityl;
/*
* current day of simulation
*/
private int day;
private String[] publisherNames;
private CampaignData currCampaign;
private double midPrice;
private double maxPrice;
private void computeUcsTargetLevel () {
}
public SampleAdNetwork() {
campaignReports = new HashMap<Integer, CampaignReport>();
allCampaign = new LinkedList<CampaignData>();
adNetworkReports = new HashMap<Integer, AdNetworkReport>();
notifications = new HashMap<Integer, AdNetworkDailyNotification>();
myCampaignsBid = new HashMap<Integer, Long>();
}
@Override
protected void messageReceived(Message message) {
try {
Transportable content = message.getContent();
// log.fine(message.getContent().getClass().toString());
if (content instanceof InitialCampaignMessage) {
handleInitialCampaignMessage((InitialCampaignMessage) content);
} else if (content instanceof CampaignOpportunityMessage) {
handleICampaignOpportunityMessage((CampaignOpportunityMessage) content);
} else if (content instanceof CampaignReport) {
handleCampaignReport((CampaignReport) content);
} else if (content instanceof AdNetworkDailyNotification) {
handleAdNetworkDailyNotification((AdNetworkDailyNotification) content);
} else if (content instanceof AdxPublisherReport) {
handleAdxPublisherReport((AdxPublisherReport) content);
} else if (content instanceof SimulationStatus) {
handleSimulationStatus((SimulationStatus) content);
} else if (content instanceof PublisherCatalog) {
handlePublisherCatalog((PublisherCatalog) content);
} else if (content instanceof AdNetworkReport) {
handleAdNetworkReport((AdNetworkReport) content);
} else if (content instanceof StartInfo) {
handleStartInfo((StartInfo) content);
} else if (content instanceof BankStatus) {
handleBankStatus((BankStatus) content);
} else if(content instanceof CampaignAuctionReport) {
hadnleCampaignAuctionReport((CampaignAuctionReport) content);
}
else {
System.out.println("[messageReceived] UNKNOWN Message Received: " + content);
}
} catch (NullPointerException e) {
this.log.log(Level.SEVERE,
"Exception thrown while trying to parse message." + e);
return;
}
}
private void hadnleCampaignAuctionReport(CampaignAuctionReport content) {
// System.out.println("[hadnleCampaignAuctionReport] "+day+" :"+ content.toMyString());
// ingoring
}
private void handleBankStatus(BankStatus content) {
System.out.println("[handleBankStatus] Day " + day + " :" + content.toString());
if(haveCampaignOppotunityl == false){
System.out.println(" [handleBankStatus] Day " + day + " : bid for ucs without campaign oppotunity");
ucsBid = getUCSbid(getUCSDemandlevel(getReachLevel(day+2), getTakeReachLevel(day+2)));
AdNetBidMessage bids = new AdNetBidMessage(ucsBid, 0, (long)0);
sendMessage(demandAgentAddress, bids);
}
}
/**
* Processes the start information.
*
* @param startInfo
* the start information.
*/
protected void handleStartInfo(StartInfo startInfo) {
this.startInfo = startInfo;
// System.out.println("[handleStartInfo] Day " + day + " :" + startInfo.toString());
}
/**
* Process the reported set of publishers
*
* @param publisherCatalog
*/
private void handlePublisherCatalog(PublisherCatalog publisherCatalog) {
this.publisherCatalog = publisherCatalog;
generateAdxQuerySpace();
getPublishersNames();
// System.out.println("[handlePublisherCatalog] Day " + day + " :" + publisherCatalog.toString());
}
/**
* On day 0, a campaign (the "initial campaign") is allocated to each
* competing agent. The campaign starts on day 1. The address of the
* server's AdxAgent (to which bid bundles are sent) and DemandAgent (to
* which bids regarding campaign opportunities may be sent in subsequent
* days) are also reported in the initial campaign message
*/
private void handleInitialCampaignMessage(
InitialCampaignMessage campaignMessage) {
System.out.println("[handleInitialCampaignMessage] "+campaignMessage.toString());
day = 0;
initialCampaignMessage = campaignMessage;
demandAgentAddress = campaignMessage.getDemandAgentAddress();
adxAgentAddress = campaignMessage.getAdxAgentAddress();
CampaignData campaignData = new CampaignData(initialCampaignMessage);
campaignData.setBudget(initialCampaignMessage.getBudgetMillis()/1000.0);
currCampaign = campaignData;
genCampaignQueries(currCampaign);
midPrice = 0.2*campaignData.budget/((campaignData.dayEnd-campaignData.dayStart+1)*1.0);
maxPrice = midPrice *1.3;
System.out.println(" [handleInitialCampaignMessage] Initial midPrice "+midPrice +" campaignData.budget "+campaignData.budget);
allCampaign.add(campaignData);
/*
* The initial campaign is already allocated to our agent so we add it
* to our allocated-campaigns list.
*/
System.out.println("[handleInitialCampaignMessage] Day " + day + ": Allocated campaign - " + campaignData);
myCampaigns.put(initialCampaignMessage.getId(), campaignData);
}
/**
* On day n ( > 0) a campaign opportunity is announced to the competing
* agents. The campaign starts on day n + 2 or later and the agents may send
* (on day n) related bids (attempting to win the campaign). The allocation
* (the winner) is announced to the competing agents during day n + 1.
*/
private void handleICampaignOpportunityMessage(
CampaignOpportunityMessage com) {
day = com.getDay();
haveCampaignOppotunityl = true;
pendingCampaign = new CampaignData(com);
System.out.println("[handleICampaignOpportunityMessage] Day " + day + ": Campaign opportunity - " + pendingCampaign);
if(day == 0){
ucsBid = getUCSbid(1.0);
}else{
ucsBid = getUCSbid(getUCSDemandlevel(getReachLevel(day+2), getTakeReachLevel(day+2)));
}
System.out.println(" [handleICampaignOpportunityMessage] Day " + day + " ucsBid = "+ ucsBid);
double bid = 1000*this.computeCampaignBid(pendingCampaign);
allCampaign.add(pendingCampaign);
/*
* The campaign requires com.getReachImps() impressions. The competing
* Ad Networks bid for the total campaign Budget (that is, the ad
* network that offers the lowest budget gets the campaign allocated).
* The advertiser is willing to pay the AdNetwork at most 1$ CPM,
* therefore the total number of impressions may be treated as a reserve
* (upper bound) price for the auction.
*/
showAllCampaign();
Random random = new Random();
long cmpimps = com.getReachImps();
long cmpBidMillis = random.nextInt((int)cmpimps);
System.out.println("[handleICampaignOpportunityMessage] Day " + day + ": Campaign total budget bid (millis): " + cmpBidMillis);
//getDayOtherCampaign(day);
//getDayMyCampaign(day);
// System.out.println(" [getReachLevel] Day " + day + " ReachLevel: " +getReachLevel(day));
// System.out.println(" [getTakeReachLevel] Day " + day + " ReachTakeLevel: " +getTakeReachLevel(day));
// System.out.println(" [getUCSDemandlevel] Day " + day + " UCSDemandlevel: "+ getUCSDemandlevel(getReachLevel(day), getTakeReachLevel(day)));
/*
* Adjust ucs bid s.t. target level is achieved. Note: The bid for the
* user classification service is piggybacked
*/
// if (adNetworkDailyNotification != null) {
// double ucsLevel = adNetworkDailyNotification.getServiceLevel();
// ucsBid = 0.1 + random.nextDouble()/10.0;
// System.out.println("[handleICampaignOpportunityMessage] Day " + day + ": ucs level reported: " + ucsLevel);
// } else {
// System.out.println("[handleICampaignOpportunityMessage] Day " + day + ": Initial ucs bid is " + ucsBid);
// }
myCampaignsBid.put(pendingCampaign.id,(long)(bid));
System.out.println(" [handleICampaignOpportunityMessage] Day " + day + ": Campaign bid is " + (0.15*cmpimps));
/* Note: Campaign bid is in millis */
AdNetBidMessage bids = new AdNetBidMessage(ucsBid, pendingCampaign.id,(long)(bid) /*(long)(0.15*cmpimps)*/);
sendMessage(demandAgentAddress, bids);
}
/**
* On day n ( > 0), the result of the UserClassificationService and Campaign
* auctions (for which the competing agents sent bids during day n -1) are
* reported. The reported Campaign starts in day n+1 or later and the user
* classification service level is applicable starting from day n+1.
*/
private void handleAdNetworkDailyNotification(
AdNetworkDailyNotification notificationMessage) {
adNetworkDailyNotification = notificationMessage;
System.out.println("[handleAdNetworkDailyNotification] Day " + day + ": Daily notification for campaign "
+ adNetworkDailyNotification.getCampaignId());
String campaignAllocatedTo = " allocated to "
+ notificationMessage.getWinner();
if ((pendingCampaign.id == adNetworkDailyNotification.getCampaignId())
&& (notificationMessage.getCostMillis() != 0)) {
/* add campaign to list of won campaigns */
pendingCampaign.setBudget(notificationMessage.getCostMillis()/1000.0);
currCampaign = pendingCampaign;
genCampaignQueries(currCampaign);
myCampaigns.put(pendingCampaign.id, pendingCampaign);
campaignAllocatedTo = " WON at cost (Millis)"
+ notificationMessage.getCostMillis();
}
notifications.put(day+1, notificationMessage);
System.out.println("[PutNotification](day:"+(day+1)+") (EffectDay:" + notificationMessage.getEffectiveDay()+")");
System.out.println("[handleAdNetworkDailyNotification] Day " + day + ": " + campaignAllocatedTo
+ ". UCS Level set to " + notificationMessage.getServiceLevel()
+ " at price " + notificationMessage.getPrice()
+ " Quality Score is: " + notificationMessage.getQualityScore());
setMidPrice(notificationMessage.getPrice(),notificationMessage.getServiceLevel());
double avr = setMaxPrice()+midPrice;
maxPrice = avr>(midPrice*2)?avr:(midPrice*2);
System.out.println(" [setMaxPrice] Day: "+ day +" MaxPrice = " + maxPrice);
// if(day>58){
// AdNetBidMessage bids = new AdNetBidMessage(0.1 + new Random().nextDouble()/10.0, pendingCampaign.id, (long)100);
// sendMessage(demandAgentAddress, bids);
// }
}
/**
* The SimulationStatus message received on day n indicates that the
* calculation time is up and the agent is requested to send its bid bundle
* to the AdX.
*/
private void handleSimulationStatus(SimulationStatus simulationStatus) {
System.out.println("[handleSimulationStatus] Day " + day + " : Simulation Status Received");
sendBidAndAds();
haveCampaignOppotunityl = false;
System.out.println("[handleSimulationStatus] Day " + day + " ended. Starting next day");
++day;
}
/**
*
*/
protected void sendBidAndAds() {
bidBundle = new AdxBidBundle();
/*
*
*/
int dayBiddingFor = day + 1;
/* A fixed random bid, for all queries of the campaign */
/*
* Note: bidding per 1000 imps (CPM) - no more than average budget
* revenue per imp
*/
//double maxBid = 10000.0;
/*
* add bid entries w.r.t. each active campaign with remaining contracted
* impressions.
*
* for now, a single entry per active campaign is added for queries of
* matching target segment.
*/
//Bid for all my active campaigns
Iterator it = myCampaigns.entrySet().iterator();
while(it.hasNext()){
Map.Entry entry = (Map.Entry)it.next();
CampaignData campaign = (CampaignData)entry.getValue();
//active campaign
if((dayBiddingFor >= campaign.dayStart)
&& (dayBiddingFor <= campaign.dayEnd)){
for(AdxQuery query : campaign.campaignQueries) {
// maxBid not exceed budget per imp
double maxBid = 1000000 * campaign.budget/campaign.reachImps;
// default coef = 1 (text, pc)
double coef = 1;
double impsCoef = 1;
double ucsCoef = 1;
double impsRatio = this.getImpsTogoDayRatio(day, campaign);
//more impression to do ratio, bid more.
if(impsRatio > 1){
impsCoef = 3;
} else if(impsRatio > 0.8){
impsCoef = 2;
} else if(impsRatio > 0.6){
impsCoef = 1.5;
} else if(impsRatio < 0.3) {
impsCoef = 0.8;
}
double ucs = this.getDayUcsLevel(dayBiddingFor);
// higher ucs level, lower bid.
ucsCoef = 0.6/ucs;
// weight set to impressionToGo ratio.
// more need, more weight.
/*int weight = (int)((impsRatio+0.2)*100);
if(campaign.impsTogo()==0 && this.numMyCampOnSeg(query.getMarketSegments(), dayBiddingFor)>0)
weight = 1;*/
int weight = 10;
// if reach imps, lower weight
if(campaign.impsTogo() == 0){
weight = 2;
}
// if is mobile or video, add 1.2 of corresponding coef
if(query.getDevice() == Device.mobile)
coef *= (1 + (campaign.mobileCoef-1)*1.2);
if(query.getAdType() == AdType.video)
coef *= (1 + (campaign.videoCoef-1)*1.2);
double n=0.8;
if(dayBiddingFor < 6)
n = 2.0;
double basicBid = n*maxBid*coef*impsCoef*ucsCoef;
//is unknown user
if(query.getMarketSegments().size() ==0){
String publisher = query.getPublisher();
double ratio = this.getCampaignPopRatio(campaign);
//System.out.println("[PopRatio]" + ratio);
bidBundle.addQuery(query, (basicBid*ratio)/2, new Ad(null),
campaign.id, weight);
}
// have competition, bid
else if(haveCompetitor(query.getMarketSegments(), dayBiddingFor)) {
bidBundle.addQuery(query, basicBid, new Ad(null),
campaign.id, weight);
}
// no competitor, 0.1 * bid
else {
bidBundle.addQuery(query, basicBid*0.5, new Ad(null), campaign.id, weight);
}
System.out.println("[Bid] seg:"+ query.getMarketSegments() + " basicBid:"+basicBid);
}
}
//set limit
bidBundle.setCampaignTotalLimit(campaign.id, (int)(campaign.reachImps*1.5), campaign.budget*5);
}
if (bidBundle != null) {
System.out.println("[sendBidAndAds] Day " + day + ": Sending BidBundle");
sendMessage(adxAgentAddress, bidBundle);
}
/*if ((dayBiddingFor >= currCampaign.dayStart)
&& (dayBiddingFor <= currCampaign.dayEnd)) {
int entCount = 0;
for (AdxQuery query : currCampaign.campaignQueries) {
if (currCampaign.impsTogo() - entCount > 0) {
/*
* among matching entries with the same campaign id, the AdX
* randomly chooses an entry according to the designated
* weight. by setting a constant weight 1, we create a
* uniform probability over active campaigns(irrelevant because we are bidding only on one campaign)
*
if (query.getDevice() == Device.pc) {
if (query.getAdType() == AdType.text) {
entCount++;
} else {
entCount += currCampaign.videoCoef;
}
} else {
if (query.getAdType() == AdType.text) {
entCount+=currCampaign.mobileCoef;
} else {
entCount += currCampaign.videoCoef + currCampaign.mobileCoef;
}
}
bidBundle.addQuery(query, rbid, new Ad(null),
currCampaign.id, 1);
}
}
double impressionLimit = currCampaign.impsTogo();
double budgetLimit = currCampaign.budget;
bidBundle.setCampaignDailyLimit(currCampaign.id,
(int) impressionLimit, budgetLimit);
System.out.println("[sendBidAndAds] Day " + day + ": Updated " + entCount
+ " Bid Bundle entries for Campaign id " + currCampaign.id);
}*/
}
/**
* Campaigns performance w.r.t. each allocated campaign
*/
private void handleCampaignReport(CampaignReport campaignReport) {
if(campaignReport.size()>0){
this.campaignReports.put(day, campaignReport);
}
/*
* for each campaign, the accumulated statistics from day 1 up to day
* n-1 are reported
*/
for (CampaignReportKey campaignKey : campaignReport.keys()) {
int cmpId = campaignKey.getCampaignId();
CampaignStats cstats = campaignReport.getCampaignReportEntry(
campaignKey).getCampaignStats();
myCampaigns.get(cmpId).setStats(cstats);
System.out.println("[handleCampaignReport] Day " + day + ": Updating campaign " + cmpId + " stats: "
+ cstats.getTargetedImps() + " tgtImps "
+ cstats.getOtherImps() + " nonTgtImps. Cost of imps is "
+ cstats.getCost());
}
}
/**
* Users and Publishers statistics: popularity and ad type orientation
*/
private void handleAdxPublisherReport(AdxPublisherReport adxPublisherReport) {
System.out.println("[handleAdxPublisherReport] Publishers Report: ");
for (PublisherCatalogEntry publisherKey : adxPublisherReport.keys()) {
AdxPublisherReportEntry entry = adxPublisherReport
.getEntry(publisherKey);
System.out.println("[handleAdxPublisherReport] "+entry.toString());
}
}
/**
*
* @param AdNetworkReport
*/
private void handleAdNetworkReport(AdNetworkReport adnetReport) {
this.adNetworkReports.put(day, adnetReport);
//System.out.println("[handleAdNetworkReport] Day " + day + " : AdNetworkReport");
for (AdNetworkKey adnetKey : adnetReport.keys()) {
double rnd = Math.random(); if (rnd > 0.95) { AdNetworkReportEntry
entry = adnetReport .getAdNetworkReportEntry(adnetKey);
//System.out.println(adnetKey + " " + entry);
}
}
}
@Override
protected void simulationSetup() {
day = 0;
bidBundle = new AdxBidBundle();
haveCampaignOppotunityl = false;
/* initial bid between 0.1 and 0.2 */
ucsBid = 0.2;
myCampaigns = new HashMap<Integer, CampaignData>();
log.fine("AdNet " + getName() + " simulationSetup");
System.out.println("[simulationSetup] Day " + day + " : ----------------------------------------------------");
}
@Override
protected void simulationFinished() {
campaignReports.clear();
allCampaign.clear();
adNetworkReports.clear();
notifications.clear();
bidBundle = null;
System.out.println("[simulationFinished] Day " + day + " : ----------------------------------------------------");
// System.exit(-1);
}
/**
* A user visit to a publisher's web-site results in an impression
* opportunity (a query) that is characterized by the the publisher, the
* market segment the user may belongs to, the device used (mobile or
* desktop) and the ad type (text or video).
*
* An array of all possible queries is generated here, based on the
* publisher names reported at game initialization in the publishers catalog
* message
*/
private void generateAdxQuerySpace() {
if (publisherCatalog != null && queries == null) {
Set<AdxQuery> querySet = new HashSet<AdxQuery>();
/*
* for each web site (publisher) we generate all possible variations
* of device type, ad type, and user market segment
*/
for (PublisherCatalogEntry publisherCatalogEntry : publisherCatalog) {
String publishersName = publisherCatalogEntry
.getPublisherName();
for (MarketSegment userSegment : MarketSegment.values()) {
Set<MarketSegment> singleMarketSegment = new HashSet<MarketSegment>();
singleMarketSegment.add(userSegment);
querySet.add(new AdxQuery(publishersName,
singleMarketSegment, Device.mobile, AdType.text));
querySet.add(new AdxQuery(publishersName,
singleMarketSegment, Device.pc, AdType.text));
querySet.add(new AdxQuery(publishersName,
singleMarketSegment, Device.mobile, AdType.video));
querySet.add(new AdxQuery(publishersName,
singleMarketSegment, Device.pc, AdType.video));
}
/**
* An empty segments set is used to indicate the "UNKNOWN"
* segment such queries are matched when the UCS fails to
* recover the user's segments.
*/
querySet.add(new AdxQuery(publishersName,
new HashSet<MarketSegment>(), Device.mobile,
AdType.video));
querySet.add(new AdxQuery(publishersName,
new HashSet<MarketSegment>(), Device.mobile,
AdType.text));
querySet.add(new AdxQuery(publishersName,
new HashSet<MarketSegment>(), Device.pc, AdType.video));
querySet.add(new AdxQuery(publishersName,
new HashSet<MarketSegment>(), Device.pc, AdType.text));
}
queries = new AdxQuery[querySet.size()];
querySet.toArray(queries);
}
}
/*genarates an array of the publishers names
* */
private void getPublishersNames() {
if (null == publisherNames && publisherCatalog != null) {
ArrayList<String> names = new ArrayList<String>();
for (PublisherCatalogEntry pce : publisherCatalog) {
names.add(pce.getPublisherName());
}
publisherNames = new String[names.size()];
names.toArray(publisherNames);
}
}
/*
* genarates the campaign queries relevant for the specific campaign, and assign them as the campaigns campaignQueries field
*/
private void genCampaignQueries(CampaignData campaignData) {
Set<AdxQuery> campaignQueriesSet = new HashSet<AdxQuery>();
for (String PublisherName : publisherNames) {
for (Set<MarketSegment> subSegment : campaignData.subTargetSegment){
campaignQueriesSet.add(new AdxQuery(PublisherName,
subSegment, Device.mobile, AdType.text));
campaignQueriesSet.add(new AdxQuery(PublisherName,
subSegment, Device.mobile, AdType.video));
campaignQueriesSet.add(new AdxQuery(PublisherName,
subSegment, Device.pc, AdType.text));
campaignQueriesSet.add(new AdxQuery(PublisherName,
subSegment, Device.pc, AdType.video));
}
//add unknown segment
campaignQueriesSet.add(new AdxQuery(PublisherName,
new HashSet<MarketSegment>(), Device.mobile,
AdType.video));
campaignQueriesSet.add(new AdxQuery(PublisherName,
new HashSet<MarketSegment>(), Device.mobile,
AdType.text));
campaignQueriesSet.add(new AdxQuery(PublisherName,
new HashSet<MarketSegment>(), Device.pc, AdType.video));
campaignQueriesSet.add(new AdxQuery(PublisherName,
new HashSet<MarketSegment>(), Device.pc, AdType.text));
/*test
campaignQueriesSet.add(new AdxQuery(PublisherName,
campaignData.targetSegment, Device.mobile, AdType.text));
campaignQueriesSet.add(new AdxQuery(PublisherName,
campaignData.targetSegment, Device.mobile, AdType.video));
campaignQueriesSet.add(new AdxQuery(PublisherName,
campaignData.targetSegment, Device.pc, AdType.text));
campaignQueriesSet.add(new AdxQuery(PublisherName,
campaignData.targetSegment, Device.pc, AdType.video));*/
}
campaignData.campaignQueries = new AdxQuery[campaignQueriesSet.size()];
campaignQueriesSet.toArray(campaignData.campaignQueries);
System.out.println("[genCampaignQueries] !!!!!!!!!!!!!!!!!!!!!!"+Arrays.toString(campaignData.campaignQueries)+"!!!!!!!!!!!!!!!!");
}
private void showAllCampaign(){
int count = 1;
for (CampaignData d: allCampaign){
//System.out.println(" [showAllCampaign] "+"("+count+") "+d);
count++;
}
}
private Queue<CampaignData> getDayOtherCampaign(int _day){
Queue<CampaignData> dayOtherCampaign;
dayOtherCampaign = new LinkedList<CampaignData>();
for (CampaignData d: allCampaign){
if(d.dayStart <= _day && d.dayEnd >= _day && myCampaigns.get(d.id) == null){
dayOtherCampaign.add(d);
//System.out.println(" [getDayOtherCampaign] (day: " + _day +") " + d);
}
}
return dayOtherCampaign;
}
private Queue<CampaignData> getDayMyCampaign(int _day){
Queue<CampaignData> dayMyCampaign;
dayMyCampaign = new LinkedList<CampaignData>();
for(CampaignData camp : myCampaigns.values()){
if(camp.dayStart <= _day && camp.dayEnd >= _day){
dayMyCampaign.add(camp);
System.out.println(" [getDayMyCampaign] (day: " + _day +") " + camp);
}
}
return dayMyCampaign;
}
private void setMidPrice(double ucsPrice, double ucsLevel){
if(midPrice == ucsPrice && ucsLevel < 0.48){midPrice = midPrice*2;}
if(midPrice == ucsPrice && ucsLevel >= 0.48 && ucsLevel < 0.53){midPrice = midPrice*1.1;}
if(midPrice == ucsPrice && ucsLevel >= 0.53 && ucsLevel < 0.73){midPrice = midPrice;}
if(midPrice == ucsPrice && ucsLevel >= 0.73 && ucsLevel < 1){midPrice = midPrice*0.9;}
if(midPrice == ucsPrice && ucsLevel ==1){midPrice = midPrice*0.5;}
System.out.println(" [setMidPrice] Day: "+ day +" MidPrice = " + midPrice);
}
private double setMaxPrice(){
double averImpCost = 0.0;
Queue<CampaignData> dayMyCampaign = getDayMyCampaign(day);
for(CampaignData d : dayMyCampaign){
if(myCampaignsBid.get(d.id) == null) continue;
averImpCost += (d.budget-myCampaignsBid.get(d.id))/((d.dayEnd-d.dayStart+1)*1.0);
}
return averImpCost/2;
}
private double getUCSbid(double ucsDemandLevel){
double _ucsBid = 0.0;
System.out.println(" [getUCSbid] Day: "+ day +" ucsDemandLevel = " + ucsDemandLevel);
if (ucsDemandLevel<0.4){_ucsBid = maxPrice>0.0005?0.0005:maxPrice;}
if (ucsDemandLevel>=0.4 && ucsDemandLevel<=0.7){_ucsBid = maxPrice>midPrice?midPrice:maxPrice;}
if (ucsDemandLevel>0.7){_ucsBid = maxPrice;}
return _ucsBid;
}
private double getUCSDemandlevel(Map<Set<MarketSegment>,Double> reachLevel, Map<Set<MarketSegment>,Double> takeLevel){
double ucsPrecidion = 0.0;
double cs = 0.0;
System.out.println(" [getUCSDemandlevel] Day: "+ day +" reachLevel = " + reachLevel);
System.out.println(" [getUCSDemandlevel] Day: "+ day+ " takeLevel = "+ takeLevel);
for(Set<MarketSegment> s: reachLevel.keySet()){
if(reachLevel.get(s)>0){
ucsPrecidion += (reachLevel.get(s)*MarketSegment.marketSegmentSize(s)/(1-takeLevel.get(s)));
cs += MarketSegment.marketSegmentSize(s);
}
}
if(cs == 0) return 0.0;
return ucsPrecidion/cs;
}
// Judge whether Others have campaign on a subSegment
private Map<Set<MarketSegment>,Double> getReachLevel(int _day){
Queue<CampaignData> dayMyCampaign = getDayMyCampaign(_day);
Map<Set<MarketSegment>,Double> reachLevel = genLevelMap();
double singleReachlevel = 0.0;
for(CampaignData d : dayMyCampaign){
// System.out.println(" [getReachLevel] d.subTargetSegment = " + d.subTargetSegment );
for(Set<MarketSegment> s: d.subTargetSegment){
if(day>0){
if(day>d.dayStart){
singleReachlevel = reachLevel.get(s)+((d.reachImps - d.stats.getTargetedImps())>0?
(d.reachImps - d.stats.getTargetedImps()):0)/(1.0*MarketSegment.marketSegmentSize(d.targetSegment)*(d.dayEnd-day+1));
}else{
singleReachlevel = reachLevel.get(s)+d.reachImps/(1.0*MarketSegment.marketSegmentSize(d.targetSegment)*(d.dayEnd-d.dayStart+1));
}
}
else{
singleReachlevel = reachLevel.get(s)+d.reachImps/(1.0*MarketSegment.marketSegmentSize(d.targetSegment)*(d.dayEnd-(day>d.dayStart?day:d.dayStart)+1));
}
reachLevel.put(s, singleReachlevel>1?1:singleReachlevel);
}
}
return reachLevel;
}
private Map<Set<MarketSegment>,Double> genLevelMap(){
Map<Set<MarketSegment>,Double> reachLevel = new HashMap<Set<MarketSegment>,Double>();
for(int i=18; i<26; i++){
reachLevel.put(MarketSegment.marketSegments().get(i), 0.0);
}
return reachLevel;
}
private Map<Set<MarketSegment>,Double> getTakeReachLevel(int _day){
Queue<CampaignData> dayOtherCampaign = getDayOtherCampaign(_day);
Map<Set<MarketSegment>,Double> takeLevel = genLevelMap();
double takeLevDou = 0.0;
for(CampaignData d : dayOtherCampaign){
// System.out.println(" [getTakeReachLevel] d.subTargetSegment = " + d.subTargetSegment );
for(Set<MarketSegment> s: d.subTargetSegment){
takeLevDou = d.reachImps/((MarketSegment.marketSegmentSize(d.targetSegment))*(d.dayEnd-d.dayStart+1)*1.0);
// System.out.println(" [getTakeReachLevel] takeLevDou = " + takeLevDou );
takeLevel.put(s, takeLevel.get(s)>takeLevDou?takeLevel.get(s):takeLevDou);
}
}
return takeLevel;
}
//start----------------ImpressionAuction----------------
private boolean haveCompetitor(Set<MarketSegment> seg, int day){
if(day <= 5) {
//System.out.println("[haveCompetitor] (day: " + day + ")" + "(segment:" + seg + ") false : First 5 days, cannot judge.");
return true;
}
for (CampaignData d: allCampaign){
// active campaign && not my campaign && contain this segment ---> competitor
if((d.dayStart <= day && d.dayEnd >= day) &&
(!myCampaigns.containsKey(d.id)) &&
(d.subTargetSegment.contains(seg))) {
//System.out.println("[haveCompetitor] (day: " + day +") " + "(segment:" + seg + ") true :" + d);
return true;
}
}
//System.out.println("[haveCompetitor] (day: " + day +") " + "(segment:" + seg + ")" + "false");
return false;
}
//Get how much Campaign I have on a subSegment
private int numMyCampOnSeg(Set<MarketSegment> seg, int day) {
int num = 0;
for(CampaignData d : myCampaigns.values()){
if((d.dayStart <= day && d.dayEnd >= day) &&
(d.subTargetSegment.contains(seg))) {
num++;
}
}
//System.out.println("[numMyCampaign] (day: " + day +") " + "(segment:" + seg + "):" + num);
return num;
}
// Get competitionRatio for a Campaign (weighted average of all subSegs)
private double getCompetitionRatio(CampaignData camp, int day) {
double total = MarketSegment.marketSegmentSize(camp.targetSegment);
double competeTotal = 0;
for(Set<MarketSegment> subseg : camp.subTargetSegment){
double subTotal = MarketSegment.marketSegmentSize(subseg);
// other competitor -> competitor
if(haveCompetitor(subseg, day)){
competeTotal += subTotal/2;
} else {
double numMy = numMyCampOnSeg(subseg, day);
System.out.println("[MyCampOnSeg]"+numMy);
// my other camp -> not fully compete.
if(numMy > 0){
competeTotal += (subTotal * (double)(numMy-1)/(double)numMy);
}
}
}
return competeTotal/total;
}
private double getCompeteRatioDuration(CampaignData camp){
double compete = 0;
for(long i = camp.dayStart; i<=camp.dayEnd;i++){
compete += this.getCompetitionRatio(camp, (int)i);
System.out.println("[DayCompete]:(day:"+(int)i+")"+this.getCompetitionRatio(camp, (int)i));
}
return compete/(double)camp.duration;
}
private double getSegmentPopRatio(Set<MarketSegment> seg){
double segPop = MarketSegment.marketSegmentSize(seg);
double allPop = MarketSegment.marketSegmentSize(MarketSegment.compundMarketSegment1(MarketSegment.MALE))
+ MarketSegment.marketSegmentSize(MarketSegment.compundMarketSegment1(MarketSegment.FEMALE));
double ratio = segPop/allPop;
//System.out.println("[getSegmentPopRatio] (totalPop: " + allPop
// + ") (segPop: " + segPop + ") ( ratio: "+ ratio );
return ratio;
}
private double getCampaignPopRatio(CampaignData camp){
double ratio = 0;
for(Set<MarketSegment> subseg : camp.subTargetSegment){
ratio += getSegmentPopRatio(subseg);
}
return ratio;
}
private double getDayUcsLevel(int day) {
if(day==0){
return 0.9;
}
if(notifications.get(day) != null){
double ucs = notifications.get(day).getServiceLevel();
//System.out.println("[getDayUcsLevel][day:" + day +"]" + ucs);
return ucs;
}
double ucs = 0.6;
//System.out.println("[getDayUcsLevel][day:" + day +"] (not found)" + ucs);
return ucs;
}
private double getDayQuality(int day) {
if(notifications.get(day) != null){
double quality = notifications.get(day).getQualityScore();
System.out.println("[getDayQuality][day:" + day +"]" + quality);
return quality;
}else{