⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 agent.java

📁 在这个电脑中的虚拟市场中
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
      size=fcastList.size();      for ( int i=0;i<size;i++){          aForecast=(Forecast)fcastList.elementAt(i);	  if (aForecast.count >= 0){              weight=aForecast.strength;	      countsum += weight;              offset += aForecast.b*dividend + aForecast.c*weight;	      pdcoeff += aForecast.a*weight;              offset1+=aForecast.b*dividend + aForecast.c;              pdcoeff1+=aForecast.a;	    }	  forecastvar = variance;      }      if (countsum > 0.0){	      offset /= countsum;	      pdcoeff /= countsum;      }else{              countsum=size;              offset =0;//offset1/countsum;	      pdcoeff =0;//pdcoeff1/countsum;      }    }  //更新需求效用函数中的分母。  double addvar=privateParams.addvar;  divisor = privateParams.lambda*forecastvar+addvar;  //divisor=Math.sqrt(divisor);}/*"A forecast has a set of conditions it is watching. These are packedtight in a BitVector. We need the world data about the status of thoseconditions packed the same way, in order to make quick checks to findout if the world conditions are matched by the BitVector'sconditions. This method creates a BitVector to match the conditionsthat are being monitored by the agent's forecasts.  This requires theuse of the design assumption that all of an agent's forecasts have thesame bitlist."*/String collectWorldData(){//收集世界的信息及其编码  int i,n,nworldbits;  String world;  String myRealWorld=null;  world="";  nworldbits =worldForAgent.getNumWorldBits();  myRealWorld=worldForAgent.getRealWorld();  world=myRealWorld;  return world;}/*"This is the main inner loop over forecasts. Go through the list  of active forecasts, compare how they did against the world.  Notice  the switch that checks to see how big the bitvector (condwords) is  before proceeding.  At one time, this gave a significant  speedup. The original sfsm authors say 'Its ugly, but it  works. Don't mess with it!'  (pj: I've messed with it, and don't  notice much of a speed effect on modern computers with modern  compilers :> My alternative implementation is commented out inside  this method)"*/void updateActiveList(String worldvalues){  //根据世界当前的编码,更新激活规则链表  Forecast aForecast;  copyList(activeList,oldActiveList);  activeList.removeAllElements();  //作一份拷贝  int size=oldActiveList.size();  for( int i=0;i<size;i++){      aForecast=(Forecast)oldActiveList.elementAt(i);      aForecast.lforecast=aForecast.forecast;  }  //循环所有的规则  size=fcastList.size();  for( int i=0;i<size;i++){      aForecast=(Forecast)fcastList.elementAt(i);      boolean tmp=true;      //对所有的位进行循环,注意当前世界编码中的哑位不进行判断      for(int j=0;j<aForecast.condbits;j++){        int dumybits=worldForAgent.NWORLDBITS-aForecast.condbits;        char c1,c2;        c1=aForecast.conditions.charAt(j);        c2=worldvalues.charAt(j+dumybits);        //如果当前的规则的该位不适不在乎,并且与世界的数值不相等        if(c1!='2'&&c2!=c1){          tmp=false;        }      }      if(tmp){        //在激活列表中增加新的规则        activeList.addElement(aForecast);      }  }}double getDemandAndSlope(double slope[],double trialprice)  /*" Returns the agent's requested bid (if >0) or offer (if <0) using* best (or mean) linear forecast chosen by -prepareForTrading. The* forecast is given by   forecast = pdcoeff*(trialprice+dividend) + offset* where pdcoeff and offset are set by -prepareForTrading.A risk aversion computation gives a target holding, and itsderivative ("slope") with respect to price.  The slope is calculatedas the linear approximated response of a change in price on thetraders' demand at time t, based on the change in the forecastaccording to the currently active linear rule. "*/{  //得到需求和边界需求  //先得到预测的价格量  forecast = (trialprice + dividend)*pdcoeff + offset;  //根据公式x=(a(p+d)+b-p(1+r))/divisor计算需求量  if (forecast >= 0.0){      demand = -((trialprice*intratep1 - forecast)/divisor + position);      slope[0] = (pdcoeff-intratep1)/divisor;  }else{      forecast = 0.0;      demand = - (trialprice*intratep1/divisor + position);      slope[0] = -intratep1/divisor;    }  //限定需求量的范围。  // Clip bid or offer at "maxbid".  This is done to avoid problems when  // the variance of the forecast becomes very small, thought it's not clear  // that this is the best solution.  if (demand > privateParams.maxbid)    {      demand = privateParams.maxbid;      slope[0] = 0.0;    }  else if (demand < -privateParams.maxbid)    {      demand = -privateParams.maxbid;      slope[0] = 0.0;    }  constrainDemand(slope,trialprice);  return demand;}/*" Now update the variance and strength of all the forecasts that  were active in the previous period, since now we know how they  performed. This method causes an update of price/dividend  information from the world, then it measures how far off each  forecast was and puts the square of that "deviance" measure into the  forecast with the forecast's setVariance: method. Each forecast in  the active list is told to update its forecast.  It also updates the  instance variable variance, which is calculated here as an  exponentially weignted moving average of that forecast's  squared-error (variance).  Inside the code of updatePerformance,  there is a description of the strength formula that is used, and how  the formula now matches the formula used in the original sfsm,  rather than ASM-2.0. "*/void updatePerformance(){  //对规则的表现参数进行更新  //pj: register struct BF_fcast *fptr;  Forecast  aForecast;  double deviation, ftarget, tauv, a, b, c, av, bv, maxdev;  // Precompute things for speed  tauv = privateParams.tauv;  a = 1.0/tauv;  b = 1.0-a;  // special rates for variance  // We often want this to be different from tauv  // PARAM:  100. should be a parameter  BL  av = 0.7;//1.0/(double)100.0;  bv = 1.0-av;    /* fixed variance if tauv at max */  if (tauv == 100000)    {      a = 0.0;      b = 1.0;      av = 0.0;      bv = 1.0;    }    //最大的离差  maxdev = privateParams.maxdev;  double maxprice=local.asmModelParams.maxprice;// Update global mean (p+d) and our variance//预测目标如下计算  getPriceFromWorld();  ftarget = price + dividend;// Update global mean (p+d) and our variance  realDeviation = deviation = ftarget - lforecast;  if (Math.abs(deviation) > maxdev) deviation = maxdev;  //重新计算p+d的数值,采用加权平均的方式  global_mean = b*global_mean + a*ftarget;  // Use default for initial variances - for stability at startup  currentTime = getCurrentTime( );  if (currentTime < 1)    variance = privateParams.initvar;  else    variance = bv*variance + av*deviation*deviation*maxdev*maxdev/(maxprice*maxprice);//计算方差  int size=activeList.size();  for( int i=0;i<size;i++ ){      aForecast=(Forecast)activeList.elementAt(i);      aForecast.updateForecastPrice(price,dividend);  }  if (currentTime > 0){      size=oldActiveList.size();//index = [ activeList begin: [self getZone]];      for( int i=0;i<size;i++ ){        aForecast=(Forecast)oldActiveList.elementAt(i);	{	  double  lastForecast=aForecast.lforecast;	  deviation = (ftarget - lastForecast)*(ftarget - lastForecast)*maxdev*maxdev/(maxprice*maxprice);          //更新规则的预测方差,是一个加权平均,即上一期的方差与这期的离差的加权和	  if (deviation > maxdev) deviation = maxdev;	  if (aForecast.c> tauv)	    aForecast.variance = b*aForecast.variance + a*deviation;	  else{	      c = 1.0/(double) (1.0 +aForecast.count);  //??bfagent had no 1+ here ??	      aForecast.variance=(1.0 - c)*aForecast.variance + c*deviation;          }          //更新规则的强度	  aForecast.strength=privateParams.maxdev-aForecast.variance+aForecast.specfactor;	}    }  }}/*"Returns the absolute value of realDeviation"*/double getDeviation(){  return Math.abs(realDeviation);}int nbits(){  return privateParams.condbits;}int nrules(){  return privateParams.numfcasts;}int lastgatime(){  return lastgatime;}/*" Genetic algorithm. It relies on the following separate methods.(pj: 2001-11-25. I still see some room for improvement here, but theemphasis is to eliminate all global variables and explicitly passreturn values instead.  Any values needed for computations shouldeither be passed explicitly or taken from someplace safe)////  1. MakePool makes a list of the weakest forecasts://  rejectList. That is the "npool" weakest rules.////  2. "nnew" new rules are created. They are put into a Swarm list//  called newList. Their bit settings are taken from either crossover//  (using tournament selection to get parents), or mutation.//  "Tournament selection" means picking two candidates purely at//  random and then choosing the one with the higher strength.  See//  the Crossover and Mutate methods for more details about how they//  work.////  3. The nnew new rules replace weakest old ones found in step//  1. This is done by the method "TransferFcastsFrom:To:" It pays no//  attention to strength, but looks at similarity of the bitstrings//  -- rather like tournament selection, we pick two candidates from//  the rejectList at random and choose the one with the MORE similar//  bitstring to be replaced.  This maintains more diversity.////  4. Generalize looks for rules that haven't been triggered for//  "longtime" and generalizes them by changing a randomly chosen//  fraction "genfrac" of 0/1 bits to "don't care".  It does this//  independently of strength to all rules in the population.////  There are several private methods that take care of this//  work. They don't show up in the public interface, but here they//  are:-(BFCast *)  CopyRule:(BFCast *) to From: (BFCast *) from-(void) MakePool: rejects From: (id <Array>) list-(BOOL) Mutate: (BFCast *) new Status: (BOOL) changed-(BFCast *) Crossover:(BFCast *) newForecast Parent1: (BFCast *) parent1 Parent2: (BFCast *) parent2- (void) TransferFcastsFrom: newlist To:  forecastList Replace: rejects- (BFCast *)  GetMort: (BFCast *) new Rejects: (id <List>) rejects-(void) Generalize: (id) list AvgStrength: (double) avgstrength// Parameter list:_{npool	-- size of pool of weakest rules for possible relacement;		   specified as a fraction of numfcasts by "poolfrac"}_{nnew	-- number of new rules produced		   specified as a fraction of numfcasts by "newfrac"}_{ pcrossover -- probability of running Crossover.}_{plinear    -- linear combination "crossover" prob.}//  _{ prandom    -- random from each parent crossover prob.}//  _{ pmutation  -- per bit mutation prob.}//  _{ plong      -- long jump prob.}//   _{pshort     -- short (neighborhood) jump prob.}//  _{nhood      -- size of neighborhood.}//   _{longtime	-- generalize if rule unused for this length of time}//  _{ genfrac	-- fraction of 0/1 bits to make don't-care when generalising}"*/void performGA(){  //执行遗传算法  int f;  int new1;  Forecast parent1, parent2;  double ava,avb,avc,sumc;  double madv=0.0;  double meanv = 0.0;  double temp;  //for holding values needed shortly  //pj: previously declared as globals  //int bitlist[];  Vector newList=new Vector();//盛放新的规则  Vector rejectList=new Vector();//盛放淘汰掉的规则  int rejectIndex[];//淘汰规则的索引  rejectIndex=new int[privateParams.npool+1];  double avstrength;//规则的平均适应度static inside a method has a different effect than static in a class  ++gacount;//遗传算法运行的次数  currentTime = getCurrentTime();//当前的方针周期  lastgatime = currentTime;  //制作一个池子,成方那些被淘汰的规则列表  MakePool(rejectList,rejectIndex,fcastList);  local.localasm.setStatus("正在执行遗传算法:计算平均值");  // Compute average strength (for assignment to new rules)  avstrength = ava = avb = avc = sumc = 0.0;  minstrength = 1.0e20;  //计算平均系数a,b,c,平均方差,最小适应度  for (f=0; f < privateParams.numfcasts; f++){      Forecast aForecast =(Forecast)fcastList.elementAt(f);// [fcastList atOffset: f];      double varvalue = 0;      varvalue= aForecast.variance;      meanv += varvalue;      if ( aForecast.count >= 0){	  if ( varvalue !=0  ){	      avstrength += aForecast.strength;// atOffset: f] getStrength];	      sumc += 1.0/ varvalue ;	      ava +=  aForecast.a  / varvalue ;	      avb +=  aForecast.b / varvalue;	      avc +=  aForecast.c / varvalue ;	    }	  if( aForecast.strength < minstrength)	    minstrength = aForecast.strength;	}    }  meanv = meanv/ privateParams.numfcasts;

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -