コード例 #1
0
ファイル: IpIpoptData.cpp プロジェクト: AyMaN-GhOsT/simbody
  void IpoptData::SetTrialEqMultipliersFromStep(Number alpha,
      const Vector& delta_y_c,
      const Vector& delta_y_d)
  {
    DBG_ASSERT(have_prototypes_);

    SmartPtr<IteratesVector> newvec = trial()->MakeNewContainer();
    newvec->create_new_y_c();
    newvec->y_c_NonConst()->AddTwoVectors(1., *curr()->y_c(), alpha, delta_y_c, 0.);

    newvec->create_new_y_d();
    newvec->y_d_NonConst()->AddTwoVectors(1., *curr()->y_d(), alpha, delta_y_d, 0.);

    set_trial(newvec);
  }
コード例 #2
0
ファイル: LookupTables.cpp プロジェクト: JetBrains/jdk8u_jdk
U_NAMESPACE_BEGIN

/*
    These are the rolled-up versions of the uniform binary search.
    Someday, if we need more performance, we can un-roll them.

    Note: I put these in the base class, so they only have to
    be written once. Since the base class doesn't define the
    segment table, these routines assume that it's right after
    the binary search header.

    Another way to do this is to put each of these routines in one
    of the derived classes, and implement it in the others by casting
    the "this" pointer to the type that has the implementation.
*/
const LookupSegment *BinarySearchLookupTable::lookupSegment(const LETableReference &base, const LookupSegment *segments, LEGlyphID glyph, LEErrorCode &success) const
{

    le_int16  unity = SWAPW(unitSize);
    le_int16  probe = SWAPW(searchRange);
    le_int16  extra = SWAPW(rangeShift);
    TTGlyphID ttGlyph = (TTGlyphID) LE_GET_GLYPH(glyph);
    LEReferenceTo<LookupSegment> entry(base, success, segments);
    LEReferenceTo<LookupSegment> trial(entry, success, extra);

    if(LE_FAILURE(success)) return NULL;

    if (SWAPW(trial->lastGlyph) <= ttGlyph) {
        entry = trial;
    }

    while (probe > unity && LE_SUCCESS(success)) {
        probe >>= 1;
        trial = entry; // copy
        trial.addOffset(probe, success);

        if (SWAPW(trial->lastGlyph) <= ttGlyph) {
            entry = trial;
        }
    }

    if (SWAPW(entry->firstGlyph) <= ttGlyph) {
      return entry.getAlias();
    }

    return NULL;
}
コード例 #3
0
void
rename_if_collision(SymbolTableObject *sto, SymbolTable *new_st)
{
    LString orig = sto->get_name();
    if (orig == emptyLString || !new_st->has_lookup_table_member(orig))
      return;

    for (IInteger serial = 0; ; ++serial) {
      String suffix;
      serial.write(suffix, 10);
      LString trial(orig + suffix);
      if (!new_st->has_lookup_table_member(trial)) {
          sto->set_name(trial);
          return;
      }
    }
}
コード例 #4
0
ファイル: PDP.C プロジェクト: MadMaxPavlo/aima
void PDP::average(Function* target, int attempts, double rate)
{
   int successes = 0;
   int adjustments;
   double total = 0;

   for(int i = 0; i < attempts; i++) {
      adjustments = trial(target, 1, rate);
      if(adjustments != FAILURE) {
         successes++;
         total += adjustments;
      }
   }

   if(successes > 0)
      cout << "The average is " << total / successes << " for "
           << successes << " successes out of " << attempts
           << " attempts." << endl;
   else
      cout << "No successes out of " << attempts << " attempts." << endl;
}
コード例 #5
0
  void IpoptData::SetTrialBoundMultipliersFromStep(Number alpha,
      const Vector& delta_z_L,
      const Vector& delta_z_U,
      const Vector& delta_v_L,
      const Vector& delta_v_U)
  {
    DBG_ASSERT(have_prototypes_);

    SmartPtr<IteratesVector> newvec = trial()->MakeNewContainer();
    newvec->create_new_z_L();
    newvec->z_L_NonConst()->AddTwoVectors(1., *curr()->z_L(), alpha, delta_z_L, 0.);

    newvec->create_new_z_U();
    newvec->z_U_NonConst()->AddTwoVectors(1., *curr()->z_U(), alpha, delta_z_U, 0.);

    newvec->create_new_v_L();
    newvec->v_L_NonConst()->AddTwoVectors(1., *curr()->v_L(), alpha, delta_v_L, 0.);

    newvec->create_new_v_U();
    newvec->v_U_NonConst()->AddTwoVectors(1., *curr()->v_U(), alpha, delta_v_U, 0.);

    set_trial(newvec);
  }
コード例 #6
0
ファイル: utility.hpp プロジェクト: abhi12ravi/dcsxx-des
UIntT num_replications(RealT eps, UIntT r0, ::dcs::iterator::iterator_range< ::dcs::iterator::any_forward_iterator<RealT> > const& s0_range, RealT level=0.95, UIntT max_trials=::std::numeric_limits<UIntT>::max())
{
	if (r0 < 2)
	{
		return r0;
	}

	UIntT r_max(0);

	for (
		::dcs::iterator::any_forward_iterator<RealT> it = s0_range.begin();
		it != s0_range.end();
		++it
	) {
		RealT r(0);
		UIntT trial(0);

		do
		{
			++r0;

			::dcs::math::stats::students_t_distribution<RealT> dist(r0-1);

			RealT t = dist.quantile((1+level)/RealT(2));
			r = t*(*it)/eps;
			r *= r;

			++trial;
		}
		while (r0 < r && trial < max_trials);

		r_max = ::std::max(r0, r_max);
	}

	return r_max;
}
コード例 #7
0
ファイル: utility.hpp プロジェクト: abhi12ravi/dcsxx-des
UIntT num_replications(RealT eps, UIntT r0, RealT s0, RealT level=0.95, UIntT max_trials=::std::numeric_limits<UIntT>::max())
{
	if (r0 < 2)
	{
		return r0;
	}

	RealT r(0);
	UIntT trial(0);

	while (r0 < r && trial < max_trials)
	{
		::dcs::math::stats::students_t_distribution<RealT> dist(r0-1);

		RealT t = dist.quantile((1+level)/RealT(2));
		r = t*s0/eps;
		r *= r;

		++trial;
		++r0;
	}

	return r0;
}
コード例 #8
0
/* stress test the realloc routine */
static int stressTestRealloc( void )
{
  const size_t nmax = 256;
  int keep = lalDebugLevel;

  v = NULL;

  XLALClobberDebugLevel(lalDebugLevel | LALMEMDBGBIT | LALMEMPADBIT | LALMEMTRKBIT);
  XLALClobberDebugLevel(lalDebugLevel & ~LALMEMINFOBIT);

  /* ascending */
  for ( n = 1; n <= nmax; ++n )
  {
    size_t *u;
    trial( v = LALRealloc( v, n * sizeof( *v ) ), 0, "" );
    trial( u = v[n - 1] = LALRealloc( NULL, n * sizeof( **v ) ), 0, "" );
    for ( i = 0; i < n; ++i ) u[i] = n - 1;
    for ( i = 0; i < n; ++i )
    {
      trial( u = v[i] = LALRealloc( v[i], n * sizeof( *u ) ), 0, "" );
      for ( j = 0; j < n - 1; ++j )
        if ( u[j] != n - 1 ) die( wrong contents );
      for ( j = 0; j < n; ++j )
        u[j] = n;
    }
  }

  for ( n = 0; n < nmax; ++n )
  {
    trial( v[n] = LALRealloc( v[n], 0 ), 0, "" );
  }
  trial( v = LALRealloc( v, 0 ), 0, "" );

  trial( LALCheckMemoryLeaks(), 0, "" );
  XLALClobberDebugLevel(keep);
  return 0;
}
コード例 #9
0
/* does end of month actions */
void passmonth(char &clearformess,char canseethings)
{
   short oldlaw[LAWNUM];
   memmove(oldlaw,law,sizeof(short)*LAWNUM);
   int l, v, p;

   //TIME ADVANCE
   day=1;
   month++;
   if(month==13)
   {
      month=1;
      year++;
   }

   switch(endgamestate)
   {
   case ENDGAME_NONE:
      if(publicmood(-1)>60)
      {
         endgamestate=ENDGAME_CCS_APPEARANCE;
         attitude[VIEW_CONSERVATIVECRIMESQUAD]=0;
      }
      break;
   case ENDGAME_CCS_APPEARANCE:
      if(publicmood(-1)>80)
         endgamestate=ENDGAME_CCS_ATTACKS;
      break;
   case ENDGAME_CCS_ATTACKS:
      if(publicmood(-1)>90)
         endgamestate=ENDGAME_CCS_SIEGES;
      break;
   case ENDGAME_CCS_SIEGES:
   case ENDGAME_CCS_DEFEATED:
      //if(publicmood(-1)>85&&presparty!=LIBERAL_PARTY)
      //   endgamestate=ENDGAME_MARTIALLAW;
      break;
   }

   //CLEAR RENT EXEMPTIONS
   for(l=0;l<len(location);l++) location[l]->newrental=0;

   //YOUR PAPER AND PUBLIC OPINION AND STUFF
   vector<int> nploc;
   for(l=0;l<len(location);l++)
   {
      if((location[l]->compound_walls & COMPOUND_PRINTINGPRESS)&&
         !location[l]->siege.siege&&
          location[l]->renting!=RENTING_CCS) nploc.push_back(l);
   }

   // Check for game over
   endcheck(END_DEAD);
   dispersalcheck(clearformess);

   int guardianpower=0;
   if(len(nploc)&&!disbanding)
   {
      //DO SPECIAL EDITIONS
      int loottypeindex=choosespecialedition(clearformess);

      if(loottypeindex!=-1)
      {
         guardianpower+=10*len(nploc);
         printnews(loottypeindex,len(nploc));

         if(loottype[loottypeindex]->get_idname()=="LOOT_INTHQDISK"|| //For special edition xml file? -XML
            loottype[loottypeindex]->get_idname()=="LOOT_SECRETDOCUMENTS")
         {
            for(int l=0;l<len(nploc);l++)
               criminalizepool(LAWFLAG_TREASON,-1,nploc[l]);
         }
      }
   }

   int libpower[VIEWNUM]={0};

   //STORIES STALE EVEN IF NOT PRINTED
   for(v=0;v<VIEWNUM;v++)public_interest[v]/=2;

   int conspower=200-attitude[VIEW_AMRADIO]-attitude[VIEW_CABLENEWS];

   //HAVING SLEEPERS
   for(int pl=len(pool)-1;pl>0;pl--)
      if(pool[pl]->alive&&(pool[pl]->flag & CREATUREFLAG_SLEEPER))
         sleepereffect(*pool[pl],clearformess,canseethings,libpower);

   //Manage graffiti
   for(int l=0;l<len(location);l++) // Check each location
   {
      for(int c=len(location[l]->changes)-1;c>=0;c--) // Each change to the map
      {
         if(location[l]->changes[c].flag==SITEBLOCK_GRAFFITI||
            location[l]->changes[c].flag==SITEBLOCK_GRAFFITI_CCS||
            location[l]->changes[c].flag==SITEBLOCK_GRAFFITI_OTHER) // Find changes that refer specifically to graffiti
         {
            int power=0,align=0;

            if(location[l]->changes[c].flag==SITEBLOCK_GRAFFITI) align=1;
            if(location[l]->changes[c].flag==SITEBLOCK_GRAFFITI_CCS) align=-1;

            //Purge graffiti from more secure sites (or from non-secure
            //sites about once every five years), but these will
            //influence people more for the current month
            if(securityable(location[l]->type))
            {
               location[l]->changes.erase(location[l]->changes.begin()+c);
               power=5;
            }
            else
            {
               if(location[l]->renting==RENTING_CCS)
                  location[l]->changes[c].flag=SITEBLOCK_GRAFFITI_CCS; // Convert to CCS tags
               else if(location[l]->renting==RENTING_PERMANENT)
                  location[l]->changes[c].flag=SITEBLOCK_GRAFFITI; // Convert to LCS tags
               else
               {
                  power=1;
                  if(!LCSrandom(10))
                     location[l]->changes[c].flag=SITEBLOCK_GRAFFITI_OTHER; // Convert to other tags
                  if(!LCSrandom(10)&&endgamestate<ENDGAME_CCS_DEFEATED&&endgamestate>0)
                     location[l]->changes[c].flag=SITEBLOCK_GRAFFITI_CCS; // Convert to CCS tags
                  if(!LCSrandom(30))
                     location[l]->changes.erase(location[l]->changes.begin()+c); // Clean up
               }
            }
            if(align==1)
            {
               background_liberal_influence[VIEW_LIBERALCRIMESQUAD]+=power;
               background_liberal_influence[VIEW_CONSERVATIVECRIMESQUAD]+=power;
            }
            else if(align==-1)
            {
               background_liberal_influence[VIEW_LIBERALCRIMESQUAD]-=power;
               background_liberal_influence[VIEW_CONSERVATIVECRIMESQUAD]-=power;
            }
         }
      }
   }

   int mediabalance=0;
   int issuebalance[VIEWNUM-5];
   //int stimulus=0;
   //double cost=0;
   //double tax=0;

   //PUBLIC OPINION NATURAL MOVES
   for(v=0;v<VIEWNUM;v++)
   {
      // Liberal essays add their power to the effect of sleepers
      libpower[v]+=background_liberal_influence[v];
      background_liberal_influence[v]=static_cast<short>(background_liberal_influence[v]*0.66);

      if(v==VIEW_LIBERALCRIMESQUADPOS) continue;
      if(v==VIEW_LIBERALCRIMESQUAD) continue;
      //if(v==VIEW_POLITICALVIOLENCE)
      //{
      //   change_public_opinion(VIEW_POLITICALVIOLENCE,-1,0);
      //   continue;
      //}
      if(v==VIEW_CONSERVATIVECRIMESQUAD) continue;
      if(v!=VIEW_AMRADIO&&v!=VIEW_CABLENEWS)
      {
         issuebalance[v] = libpower[v] - conspower;
         mediabalance += issuebalance[v];

         // Heavy randomization -- balance of power just biases the roll
         int roll = issuebalance[v] + LCSrandom(400)-200;

         // If +/-50 to either side, that side wins the tug-of-war
         if(roll < -50)
            change_public_opinion(v,-1,0);
         else if(roll > 50)
            change_public_opinion(v,1,0);
         else // Else random movement
            change_public_opinion(v,LCSrandom(2)*2-1,0);
      }

      // AM Radio and Cable News popularity slowly shift to reflect public
      // opinion over time -- if left unchecked, their subtle influence
      // on society will become a self-perpetuating Conservative nightmare!
      else if(v==VIEW_AMRADIO||v==VIEW_CABLENEWS)
      {
         if(publicmood(-1)<attitude[v])change_public_opinion(v,-1);
         else change_public_opinion(v,1);
      }
   }

   // Temporary Stalinizing Code (TODO: Implement the Stalinist Comrade Squad for changing public opinion, then remove this)
   if(stalinmode) for(int v=0;v<VIEWNUM-3;v++)
   {
      if(stalinview(v,false)) { if((attitude[v]+=3)>100) attitude[v]=100; }
      else { if(--attitude[v]<0) attitude[v]=0; }
   }
   // End Temporary Stalinizing Code (TODO: Implement the Stalinist Comrade Squad for changing public opinion, then remove this)

   // Seduction monthly experience stipends for those liberals
   // who have been getting it on with their love slaves/masters
   // in the background
   for(int s=0;s<len(pool);s++)
   {
      pool[s]->train(SKILL_SEDUCTION,loveslaves(*pool[s])*5);
      if(pool[s]->flag & CREATUREFLAG_LOVESLAVE)
         pool[s]->train(SKILL_SEDUCTION,5);
   }

   /*******************************************************
   *                 INTELLIGENCE REPORT                  *
   *     ONLY IF SHOWMECHANICS OR SHOWWAIT IS DEFINED     *
   *        EYES ONLY - LCS PROPERTY - TOP SECRET         *
   *******************************************************/
   #if defined(SHOWMECHANICS) || defined(SHOWWAIT)
   if(canseethings)
   {
      music.play(MUSIC_ELECTIONS);
      erase();
      set_color(COLOR_WHITE,COLOR_BLACK,1);
      mvaddstr(0,23,"LCS MONTHLY INTELLIGENCE REPORT");
      mvaddstr(2,27,"CURRENT POLITICAL TRENDS");
      int numviews=(endgamestate>=ENDGAME_CCS_DEFEATED||newscherrybusted<2)?VIEWNUM-1:VIEWNUM;
      for(int v=-1-stalinmode,y=4,x=0,pip;v<numviews;v++)
      {
         if((y-4)*2>=numviews+1+stalinmode) y=4,x=40;
         for(pip=2;pip>=-2;pip--)
         {
            set_alignment_color(pip,true);
            if(pip==2) mvaddchar(y,x+22,'\x11');
            addstr("ÄÄÄ");
            if(pip==-2) addchar('\x10');
         }
         if(v>=0) pip=14-(attitude[v]*14)/100;
         else pip=14-(publicmood(v)*14)/100;
         set_alignment_color((14-pip)/3-2,true);
         mvaddstr(y,x,getview(v,false));
         mvaddchar(y++,x+23+pip,'O');
      }
      set_color(COLOR_GREEN,COLOR_BLACK,1);
      mvaddstr(23,0,"Elite Liberal ");
      set_color(COLOR_WHITE,COLOR_BLACK,0);
      addstr("-  ");
      set_color(COLOR_CYAN,COLOR_BLACK,1);
      addstr("Liberal  ");
      set_color(COLOR_WHITE,COLOR_BLACK,0);
      addstr("-  ");
      set_color(COLOR_YELLOW,COLOR_BLACK,1);
      addstr("moderate  ");
      set_color(COLOR_WHITE,COLOR_BLACK,0);
      addstr("-  ");
      set_color(COLOR_MAGENTA,COLOR_BLACK,1);
      addstr("Conservative  ");
      set_color(COLOR_WHITE,COLOR_BLACK,0);
      addstr("-  ");
      set_color(COLOR_RED,COLOR_BLACK,1);
      addstr("Arch-Conservative");
      set_color(COLOR_WHITE,COLOR_BLACK,0);
      mvaddstr(24,0,"Press any key to reflect on these poll numbers.");
      clearformess=1;

      getkey();
   }
   #endif
   /*******************************************************
   *                                                      *
   *               END INTELLIGENCE REPORT                *
   *                                                      *
   *******************************************************/

   //ELECTIONS
   if(month==11){elections(clearformess,canseethings);clearformess=1;}

   //SUPREME COURT
   if(month==6){supremecourt(clearformess,canseethings);clearformess=1;}

   //CONGRESS
   congress(clearformess,canseethings);clearformess=1;

   //DID YOU WIN?
   if(wincheck())
   {
      liberalagenda(1);
      savehighscore(END_WON);
      reset(savefile_name);
      viewhighscores();
      end_game();
   }

   //CONTROL LONG DISBANDS
   if(disbanding&&year-disbandtime>=50)
   {
      music.play(MUSIC_DEFEAT);
      set_color(COLOR_WHITE,COLOR_BLACK,1);

      erase();
      move(12,10);
      addstr("The Liberal Crime Squad is now just a memory.", gamelog);
      gamelog.newline();

      getkey();

      set_color(COLOR_WHITE,COLOR_BLACK,0);
      erase();
      move(12,12);
      addstr("The last LCS members have all been hunted down.", gamelog);
      gamelog.newline();

      getkey();

      set_color(COLOR_BLACK,COLOR_BLACK,1);
      erase();
      move(12,14);
      addstr("They will never see the utopia they dreamed of...", gamelog);
      gamelog.newline();
      gamelog.nextMessage();

      getkey();

      savehighscore(END_DISBANDLOSS);
      reset(savefile_name);
      viewhighscores();
      end_game();
   }

   //UPDATE THE WORLD IN CASE THE LAWS HAVE CHANGED
   updateworld_laws(law,oldlaw);

   //THE SYSTEM!
   for(p=len(pool)-1;p>=0;p--)
   {
      if(disbanding) break;

      if(!pool[p]->alive) continue;
      if(pool[p]->flag & CREATUREFLAG_SLEEPER) continue;
      if(pool[p]->location==-1) continue;

      if(location[pool[p]->location]->type==SITE_GOVERNMENT_POLICESTATION)
      {
         if(clearformess) erase();
         else makedelimiter();

         if(pool[p]->flag & CREATUREFLAG_MISSING)
         {
            set_color(COLOR_MAGENTA,COLOR_BLACK,1);
            move(8,1);
            addstr("Cops re-polluted ", gamelog);
            addstr(pool[p]->name, gamelog);
            addstr("'s mind with Conservatism!", gamelog);
            gamelog.nextMessage();

            getkey();

            removesquadinfo(*pool[p]);
            delete_and_remove(pool,p);
            continue;
         }
         else if(pool[p]->flag & CREATUREFLAG_ILLEGALALIEN && law[LAW_IMMIGRATION]!=2)
         {
            set_color(COLOR_MAGENTA,COLOR_BLACK,1);
            move(8,1);
            addstr(pool[p]->name, gamelog);
            addstr(" has been shipped out to the INS to face ", gamelog);
            if(law[LAW_IMMIGRATION]==-2 && law[LAW_DEATHPENALTY]==-2)
               addstr("execution.", gamelog);
            else addstr("deportation.", gamelog);
            gamelog.newline();

            getkey();

            removesquadinfo(*pool[p]);
            delete_and_remove(pool,p);
            continue;
         }
         else
         {
            //TRY TO GET RACKETEERING CHARGE
            int copstrength=100;
            if(law[LAW_POLICEBEHAVIOR]==-2) copstrength=200;
            if(law[LAW_POLICEBEHAVIOR]==-1) copstrength=150;
            if(law[LAW_POLICEBEHAVIOR]==1) copstrength=75;
            if(law[LAW_POLICEBEHAVIOR]==2) copstrength=50;

            copstrength=(copstrength*pool[p]->heat)/4;
            if(copstrength>200)copstrength=200;

            //Confession check
            if(LCSrandom(copstrength)>pool[p]->juice  +  pool[p]->get_attribute(ATTRIBUTE_HEART,true)*5  -
                                      pool[p]->get_attribute(ATTRIBUTE_WISDOM,true)*5  +  pool[p]->get_skill(SKILL_PSYCHOLOGY)*5
                                      /*+ pool[p]->get_skill(SKILL_SURVIVAL)*5*/  &&  pool[p]->hireid!=-1)
            {
               int nullify=0;
               int p2=getpoolcreature(pool[p]->hireid);

               if(pool[p2]->alive && (pool[p2]->location==-1 || location[pool[p2]->location]->type!=SITE_GOVERNMENT_PRISON))
               {  //Charge the boss with racketeering!
                  criminalize(*pool[p2],LAWFLAG_RACKETEERING);
                  //Rack up testimonies against the boss in court!
                  pool[p2]->confessions++;
               }
               if(!nullify)
               {  //Issue a raid on this guy's base!
                  if(pool[p]->base>=0)location[pool[p]->base]->heat+=300;

                  set_color(COLOR_WHITE,COLOR_BLACK,1);
                  move(8,1);
                  addstr(pool[p]->name, gamelog);
                  addstr(" has broken under the pressure and ratted you out!", gamelog);
                  gamelog.newline();

                  getkey();

                  set_color(COLOR_WHITE,COLOR_BLACK,1);
                  move(9,1);
                  addstr("The traitor will testify in court, and safehouses may be compromised.", gamelog);
                  gamelog.nextMessage();

                  getkey();

                  removesquadinfo(*pool[p]);

                  delete_and_remove(pool,p);
                  continue; //no trial for this person; skip to next person
               }
               //else continue to trial
            }

            set_color(COLOR_WHITE,COLOR_BLACK,1);
            move(8,1);
            addstr(pool[p]->name, gamelog);
            addstr(" is moved to the courthouse for trial.", gamelog);
            gamelog.nextMessage();

            getkey();

            pool[p]->location=find_courthouse(*pool[p]);
            Armor prisoner(*armortype[getarmortype("ARMOR_PRISONER")]);
            pool[p]->give_armor(prisoner,NULL);
         }
      }
      else if(location[pool[p]->location]->type==SITE_GOVERNMENT_COURTHOUSE)
      { trial(*pool[p]); clearformess=1; }
      else if(location[pool[p]->location]->type==SITE_GOVERNMENT_PRISON)
         if(prison(*pool[p])) clearformess=1;
   }

   //NUKE EXECUTION VICTIMS
   for(p=len(pool)-1;p>=0;p--)
   {
      if(pool[p]->location==-1) continue;

      if(location[pool[p]->location]->type==SITE_GOVERNMENT_PRISON&&!pool[p]->alive)
      {
         removesquadinfo(*pool[p]);
         pool[p]->die();
         pool[p]->location=-1;
      }
   }

   //MUST DO AN END OF GAME CHECK HERE BECAUSE OF EXECUTIONS
   endcheck(END_EXECUTED);

   //DISPERSAL CHECK
   dispersalcheck(clearformess);

   //FUND REPORTS
   if(canseethings)fundreport(clearformess);
   ledger.resetMonthlyAmounts();
   if(clearformess) erase();

   //HEAL CLINIC PEOPLE
   for(p=0;p<len(pool);p++)
   {
      if(disbanding) break;
      if(!(pool[p]->alive)) continue;

      if(pool[p]->clinic>0)
      {
         pool[p]->clinic--;

         for(int w=0;w<BODYPARTNUM;w++)
         {
            if((pool[p]->wound[w]&WOUND_NASTYOFF)||(pool[p]->wound[w]&WOUND_CLEANOFF))
               pool[p]->wound[w]=(char)WOUND_CLEANOFF;
            else pool[p]->wound[w]=0;
         }

         int healthdamage = 0;

         if(pool[p]->special[SPECIALWOUND_RIGHTLUNG]!=1)
         {
            pool[p]->special[SPECIALWOUND_RIGHTLUNG]=1;
            if(LCSrandom(2)) healthdamage++;
         }
         if(pool[p]->special[SPECIALWOUND_LEFTLUNG]!=1)
         {
            pool[p]->special[SPECIALWOUND_LEFTLUNG]=1;
            if(LCSrandom(2)) healthdamage++;
         }
         if(pool[p]->special[SPECIALWOUND_HEART]!=1)
         {
            pool[p]->special[SPECIALWOUND_HEART]=1;
            if(LCSrandom(3)) healthdamage++;
         }
         pool[p]->special[SPECIALWOUND_LIVER]=1;
         pool[p]->special[SPECIALWOUND_STOMACH]=1;
         pool[p]->special[SPECIALWOUND_RIGHTKIDNEY]=1;
         pool[p]->special[SPECIALWOUND_LEFTKIDNEY]=1;
         pool[p]->special[SPECIALWOUND_SPLEEN]=1;
         pool[p]->special[SPECIALWOUND_RIBS]=RIBNUM;

         if(!pool[p]->special[SPECIALWOUND_NECK])
            pool[p]->special[SPECIALWOUND_NECK]=2;
         if(!pool[p]->special[SPECIALWOUND_UPPERSPINE])
            pool[p]->special[SPECIALWOUND_UPPERSPINE]=2;
         if(!pool[p]->special[SPECIALWOUND_LOWERSPINE])
            pool[p]->special[SPECIALWOUND_LOWERSPINE]=2;

         // Inflict permanent health damage
         pool[p]->set_attribute(ATTRIBUTE_HEALTH,pool[p]->get_attribute(ATTRIBUTE_HEALTH,0)-healthdamage);
         if(pool[p]->get_attribute(ATTRIBUTE_HEALTH,0)<=0)
            pool[p]->set_attribute(ATTRIBUTE_HEALTH,1);

         if(pool[p]->blood<=20&&pool[p]->clinic<=2)pool[p]->blood=50;
         if(pool[p]->blood<=50&&pool[p]->clinic<=1)pool[p]->blood=75;

         // If at clinic and in critical condition, transfer to university hospital
         if(pool[p]->clinic > 2 &&
            pool[p]->location > -1 &&
            location[pool[p]->location]->type==SITE_HOSPITAL_CLINIC)
         {
            int hospital=find_hospital(*pool[p]);
            if(hospital!=-1)
            {
               pool[p]->location=hospital;
               set_color(COLOR_WHITE,COLOR_BLACK,1);
               move(8,1);
               addstr(pool[p]->name, gamelog);
               addstr(" has been transferred to ", gamelog);
               addstr(location[hospital]->name, gamelog);
               addstr(".", gamelog);
               gamelog.nextMessage();

               getkey();
            }
         }

         // End treatment
         if(pool[p]->clinic==0)
         {
            pool[p]->blood=100;
            if(clearformess) erase();
            else makedelimiter();

            set_color(COLOR_WHITE,COLOR_BLACK,1);
            move(8,1);
            addstr(pool[p]->name, gamelog);
            addstr(" has left ", gamelog);
            addstr(location[pool[p]->location]->name, gamelog);
            addstr(".", gamelog);
            gamelog.nextMessage();

            int hs=find_homeless_shelter(*pool[p]);
            if(hs==-1) hs=0; //TODO: Error unable to find location

            if(location[pool[p]->base]->siege.siege||
               location[pool[p]->base]->renting==RENTING_NOCONTROL)
               pool[p]->base=hs;

            pool[p]->location=pool[p]->base;

            getkey();
         }
      }
   }
}
コード例 #10
0
void GetP3Responses(ap::template_2d_array<float,true>& signal, 
                    ap::template_1d_array<short int,true>& trialnr,
                    ap::template_1d_array<double,true>& windowlen, 
                    ap::template_1d_array<unsigned short int, true>& stimulusCode,
                    ap::template_1d_array<unsigned short int, true>& stimulusType,
                    const ap::template_1d_array<unsigned char, true>& Flashing,
                    const ap::template_1d_array<double, true>& channels,
                    const int MAfilter,
                    const int DecFact)
{
////////////////////////////////////////////////////////////////////////////
// Section:  Define variables
int bound_min, bound_max, row, col, row_windowlen,
    row_channels, numchannels, lenflash, sig_ds_len, siglen;
double val_temp;
ap::template_1d_array<float, true> vect;
ap::template_1d_array<float, true> vect_r;
ap::template_1d_array<float, true> a; //variable to store filter coefficients
ap::template_1d_array<float, true> b; //Variable to store filter coefficients
ap::template_2d_array<float, true> sig; //filtered and downsampled signal
ap::template_1d_array<float, true> y_downsampled;
ap::template_1d_array<unsigned short int, true> Code;
ap::template_1d_array<unsigned short int, true> Type;
ap::template_1d_array<short int, true> trial;
vector<int> tmp;
////////////////////////////////////////////////////////////////////////////
// Section:  Get dimensions
row = signal.gethighbound(1)+1;
col = signal.gethighbound(0)+1;
row_windowlen = windowlen.gethighbound(1)+1;
row_channels = channels.gethighbound(1)+1;
numchannels = col;
lenflash = row;
////////////////////////////////////////////////////////////////////////////
// Section:  Check if windowlen has only one value (e.g. windlen = 800)
if (row_windowlen == 1)
{
  val_temp = windowlen(0);
  windowlen.setbounds(0, row_windowlen);
  windowlen(0) = 0;
  windowlen(1) = val_temp;
}
////////////////////////////////////////////////////////////////////////////
// Section:  Identify changes in Flashing 
for (int i=1; i<lenflash; i++)
{
  if (Flashing(i-1) == 0 && Flashing(i) ==1)
  {
    if((i+windowlen(1)-2)<lenflash)
      tmp.push_back(i);
  }
}
Code.setbounds(0,static_cast<int>(tmp.size())-1);
Type.setbounds(0,static_cast<int>(tmp.size())-1);
trial.setbounds(0, static_cast<int>(tmp.size())-1);
////////////////////////////////////////////////////////////////////////////
// Section:  Filter and downsample the signal 
sig_ds_len = ap::iceil((windowlen(1)-windowlen(0))/DecFact); 
siglen = sig_ds_len * numchannels; 
sig.setbounds(0,static_cast<int>(tmp.size())-1,0, siglen-1);
y_downsampled.setbounds(0, sig_ds_len-1);

// Define filter coefficients (Moving Average Filter) 
a.setbounds(0, MAfilter-1);
b.setbounds(0, MAfilter-1);
for (int i=0; i<MAfilter; i++)
{
  a(i) = (float) 1;
  b(i) = (float) 1/MAfilter;
}
// Extract the signal according to the specified window
// then downsample and filtering it.
for(int j=0; j<static_cast<int>(tmp.size()); j++)
{
  bound_min = static_cast<int>( tmp[j] + windowlen(0) - 1 );
  bound_max = static_cast<int>( tmp[j] + windowlen(1) - 2 );
  vect.setbounds(0, bound_max-bound_min);
  vect_r.setbounds(0, bound_max-bound_min);

  for (int i=0; i<col; i++)
  {
    ap::vmove(vect.getvector(0, bound_max-bound_min), signal.getcolumn(i, bound_min, bound_max));
    filter(MAfilter-1, a, b, bound_max-bound_min, vect, vect_r);
    downsampling(vect_r, DecFact, y_downsampled);
    ap::vmove(sig.getrow(j, i*sig_ds_len, ((i+1)*sig_ds_len)-1), y_downsampled.getvector(0, sig_ds_len-1));
  }
  Code(j) = stimulusCode(tmp[j]);
  Type(j) = stimulusType(tmp[j]);
  trial(j) = trialnr(tmp[j]);
}
// Overwrite signal and states
signal.setbounds(0,static_cast<int>(tmp.size())-1,0, siglen-1);
stimulusCode.setbounds(0, static_cast<int>(tmp.size())-1);
stimulusType.setbounds(0, static_cast<int>(tmp.size())-1);
trialnr.setbounds(0, static_cast<int>(tmp.size())-1);

signal = sig;
stimulusCode = Code;
stimulusType = Type;
trialnr = trial;
}
コード例 #11
0
    void run ()
    {
        mask.allowed_data_types = INT_MASK;

        // Main program =========================================================
        params.V1.read(fn1);
        params.V1().setXmippOrigin();
        params.V2.read(fn2);
        params.V2().setXmippOrigin();

        // Initialize best_fit
        double best_fit = 1e38;
        Matrix1D<double> best_align(8);
        bool first = true;

        // Generate mask
        if (mask_enabled)
        {
            mask.generate_mask(params.V1());
            params.mask_ptr = &(mask.get_binary_mask());
        }
        else
            params.mask_ptr = NULL;

        // Exhaustive search
        if (!usePowell && !useFRM)
        {
            // Count number of iterations
            int times = 1;
            if (!tell)
            {
                if (grey_scale0 != grey_scaleF)
                    times *= FLOOR(1 + (grey_scaleF - grey_scale0) / step_grey);
                if (grey_shift0 != grey_shiftF)
                    times *= FLOOR(1 + (grey_shiftF - grey_shift0) / step_grey_shift);
                if (rot0 != rotF)
                    times *= FLOOR(1 + (rotF - rot0) / step_rot);
                if (tilt0 != tiltF)
                    times *= FLOOR(1 + (tiltF - tilt0) / step_tilt);
                if (psi0 != psiF)
                    times *= FLOOR(1 + (psiF - psi0) / step_psi);
                if (scale0 != scaleF)
                    times *= FLOOR(1 + (scaleF - scale0) / step_scale);
                if (z0 != zF)
                    times *= FLOOR(1 + (zF - z0) / step_z);
                if (y0 != yF)
                    times *= FLOOR(1 + (yF - y0) / step_y);
                if (x0 != xF)
                    times *= FLOOR(1 + (xF - x0) / step_x);
                init_progress_bar(times);
            }
            else
                std::cout << "#grey_factor rot tilt psi scale z y x fitness\n";

            // Iterate
            int itime = 0;
            int step_time = CEIL((double)times / 60.0);
            Matrix1D<double> r(3);
            Matrix1D<double> trial(9);
            for (double grey_scale = grey_scale0; grey_scale <= grey_scaleF ; grey_scale += step_grey)
                for (double grey_shift = grey_shift0; grey_shift <= grey_shiftF ; grey_shift += step_grey_shift)
                    for (double rot = rot0; rot <= rotF ; rot += step_rot)
                        for (double tilt = tilt0; tilt <= tiltF ; tilt += step_tilt)
                            for (double psi = psi0; psi <= psiF ; psi += step_psi)
                                for (double scale = scale0; scale <= scaleF ; scale += step_scale)
                                    for (ZZ(r) = z0; ZZ(r) <= zF ; ZZ(r) += step_z)
                                        for (YY(r) = y0; YY(r) <= yF ; YY(r) += step_y)
                                            for (XX(r) = x0; XX(r) <= xF ; XX(r) += step_x)
                                            {
                                                // Form trial vector
                                                trial(0) = grey_scale;
                                                trial(1) = grey_shift;
                                                trial(2) = rot;
                                                trial(3) = tilt;
                                                trial(4) = psi;
                                                trial(5) = scale;
                                                trial(6) = ZZ(r);
                                                trial(7) = YY(r);
                                                trial(8) = XX(r);

                                                // Evaluate
                                                double fit = fitness(MATRIX1D_ARRAY(trial));

                                                // The best?
                                                if (fit < best_fit || first)
                                                {
                                                    best_fit = fit;
                                                    best_align = trial;
                                                    first = false;
                                                    if (tell)
                                                    	std::cout << "Best so far\n";
                                                }

                                                // Show fit
                                                if (tell)
                                                    std::cout << trial << " " << fit << std::endl;
                                                else
                                                    if (++itime % step_time == 0)
                                                        progress_bar(itime);
                                            }
            if (!tell)
                progress_bar(times);
        }
        else if (usePowell)
        {
            // Use Powell optimization
            Matrix1D<double> x(9), steps(9);
            double fitness;
            int iter;
            steps.initConstant(1);
            if (onlyShift)
                steps(0)=steps(1)=steps(2)=steps(3)=steps(4)=steps(5)=0;
            if (params.alignment_method == COVARIANCE)
                steps(0)=steps(1)=0;
            x(0)=grey_scale0;
            x(1)=grey_shift0;
            x(2)=rot0;
            x(3)=tilt0;
            x(4)=psi0;
            x(5)=scale0;
            x(6)=z0;
            x(7)=y0;
            x(8)=x0;

            powellOptimizer(x,1,9,&wrapperFitness,NULL,0.01,fitness,iter,steps,true);
            best_align=x;
            best_fit=fitness;
            first=false;
        }
        else if (useFRM)
        {
    		String scipionPython;
    		initializeScipionPython(scipionPython);
    		PyObject * pFunc = getPointerToPythonFRMFunction();
    		double rot,tilt,psi,x,y,z,score;
    		Matrix2D<double> A;
    		alignVolumesFRM(pFunc, params.V1(), params.V2(), Py_None, rot,tilt,psi,x,y,z,score,A,maxShift,maxFreq,params.mask_ptr);
    		best_align.initZeros(9);
    		best_align(0)=1; // Gray scale
    		best_align(1)=0; // Gray shift
    		best_align(2)=rot;
    		best_align(3)=tilt;
    		best_align(4)=psi;
    		best_align(5)=1; // Scale
    		best_align(6)=z;
    		best_align(7)=y;
    		best_align(8)=x;
    		best_fit=-score;
        }

        if (!first)
            std::cout << "The best correlation is for\n"
            << "Scale                  : " << best_align(5) << std::endl
            << "Translation (X,Y,Z)    : " << best_align(8)
            << " " << best_align(7) << " " << best_align(6)
            << std::endl
            << "Rotation (rot,tilt,psi): "
            << best_align(2) << " " << best_align(3) << " "
            << best_align(4) << std::endl
            << "Best grey scale       : " << best_align(0) << std::endl
            << "Best grey shift       : " << best_align(1) << std::endl
            << "Fitness value         : " << best_fit << std::endl;
        Matrix1D<double> r(3);
        XX(r)            = best_align(8);
        YY(r)            = best_align(7);
        ZZ(r)            = best_align(6);
        Matrix2D<double> A,Aaux;
        Euler_angles2matrix(best_align(2), best_align(3), best_align(4),
                            A, true);
        translation3DMatrix(r,Aaux);
        A = A * Aaux;
        scale3DMatrix(vectorR3(best_align(5), best_align(5), best_align(5)),Aaux);
        A = A * Aaux;
        if (verbose!=0)
			std::cout << "xmipp_transform_geometry will require the following values"
					  << "\n   Angles: " << best_align(2) << " "
					  << best_align(3) << " " << best_align(4)
					  << "\n   Shifts: " << A(0,3) << " " << A(1,3) << " " << A(2,3)
					  << std::endl;
        if (apply)
        {
            applyTransformation(params.V2(),params.Vaux(),MATRIX1D_ARRAY(best_align));
            params.V2()=params.Vaux();
            params.V2.write(fnOut);
        }
    }
コード例 #12
0
/* test to make sure padding does what it's supposed to do */
static int testPadding( void )
{
  int keep = lalDebugLevel;

  XLALClobberDebugLevel(lalDebugLevel | LALMEMDBGBIT | LALMEMPADBIT);
  XLALClobberDebugLevel(lalDebugLevel & ~LALMEMTRKBIT);

  /* try to free NULL pointer */
  /* changed behaviour: LALFree is a no-op when passed NULL */
  // trial( LALFree( NULL ), SIGSEGV, "error: tried to free NULL pointer" );

  /* double free */
  /* actually, this cannot be done robustly -- system can change values
   * in unallocated space at will */
  //trial( p = LALMalloc( 2 * sizeof( *p ) ), 0, "" );
  //trial( LALFree( p ), 0, "" );
  //trial( LALFree( p ), SIGSEGV, "error: tried to free a freed pointer" );
  //trial( LALCheckMemoryLeaks(), 0, "" );

  /* wrong magic */
  trial( p = LALMalloc( 2 * sizeof( *p ) ), 0, "" );
  p[-1] = 4;
  trial( LALFree( p ), SIGSEGV, "error: wrong magic" );
  p[-1] = 0xABadCafe;
  trial( LALFree( p ), 0, "" );
  trial( LALCheckMemoryLeaks(), 0, "" );

  /* corrupt size */
  trial( p = LALMalloc( 4 * sizeof( *p ) ), 0, "");
  n = p[-2];
  p[-2] = -2;
  trial( LALFree( p ), SIGSEGV, "error: corrupt size descriptor" );
  p[-2] = n;
  trial( LALFree( p ), 0, "" );
  trial( LALCheckMemoryLeaks(), 0, "" );

  /* overwritten array bounds */
  trial( p = LALMalloc( 8 * sizeof( *p ) ), 0, "" );
  n = p[8];
  p[8] = 0;
  trial( LALFree( p ), SIGSEGV, "error: array bounds overwritten" );
  p[8] = n;
  trial( LALFree( p ), 0, "" );
  trial( LALCheckMemoryLeaks(), 0, "" );

  /* free too much memory */
  q = malloc( 4 * sizeof( *p ) );
  trial( p = LALMalloc( sizeof( *p ) ), 0, "" );
  memcpy( q, p - 2, 4 * sizeof( *p ) );
  trial( LALFree( p ), 0, "" );
  trial( LALFree( q + 2 ), SIGSEGV, "error: lalMallocTotal too small" );
  free( q );
  trial( LALCheckMemoryLeaks(), 0, "" );

  XLALClobberDebugLevel(keep);
  return 0;
}
コード例 #13
0
ファイル: RESULT.CPP プロジェクト: amirna2/fingerprints
void Network::test_from_file (
   char *dataname ,  // Input file name
   char *outname,     // Output file name
   int   netmod
   )
{
   int i, maxlin, did_any, best,name=0,win1,win2,win3 ;
   float *inputs, *iptr, maxi1,maxi2,maxi3 ;
   char msg[81], *line, *lptr, *tab[20];
   FILE *fp_in, *fp_out, *fname;


/*
   Open the file which contains the data to be classified
*/
   if ((fp_in = fopen ( dataname , "rt" )) == NULL) {
      strcpy ( msg , "Cannot open input data file " ) ;
      strcat ( msg , dataname ) ;
      error_message ( msg ) ;
      return ;
      }

/*
   Open the file to which outputs will be written.
   If it already exists, write a newline at its end.
*/

   fp_out = fopen ( outname , "rt" ) ;
   if (fp_out != NULL) {
      did_any = 1 ;
      fclose ( fp_out ) ;
      }
   else
      did_any = 0 ;

   if ((fp_out = fopen ( outname , "at" )) == NULL) {
      strcpy ( msg , "Cannot open output file " ) ;
      strcat ( msg , outname ) ;
      error_message ( msg ) ;
      fclose ( fp_in ) ;
      return ;
      }

   if (did_any)
   {
      fprintf ( fp_out , "\n" ) ;
   }

/*
   Allocate for the file lines as read. Conservatively guess length.
   Also allocate for network input vector.
*/

   maxlin = nin * 20 + 100 ;
   if (maxlin < 1024)
      maxlin = 1024 ;

   MEMTEXT ( "EXECUTE:line, inputs" ) ;
   line = (char *) MALLOC ( maxlin ) ;

   inputs = (float *) MALLOC ( nin * sizeof(float) ) ;

   if ((line == NULL)  ||  (inputs == NULL)) {
      memory_message ( "to execute" ) ;
      fclose ( fp_in ) ;
      fclose ( fp_out ) ;
      if (line != NULL)
	 FREE ( line ) ;
      if (inputs != NULL)
	 FREE ( inputs ) ;
      return ;
      }

/*
   Read and process the file.
*/

   did_any = 0 ;  /* If file runs out on first try, ERROR! */
   int e=0;
   for (;;) {  // Endless loop reads until file exhausted

      if ((fgets ( line , maxlin , fp_in ) == NULL) || (strlen ( line ) < 2)) {
	 if ((! did_any)  ||  ferror ( fp_in )) {
	    strcpy ( msg , "Problem reading file " ) ;
	    strcat ( msg , dataname ) ;
	    error_message ( msg ) ;
	    }
	 break ;
	 }

      lptr = line ;           // Parse the data from this line
      iptr = inputs ;         // This will be the network inputs
      for (i=0 ; i<nin ; i++)
	 *iptr++ = ParseDouble ( &lptr ) ;

      if (did_any)            // Start each new case on new line
	 fprintf ( fp_out , "\n" ) ;

      did_any = 1 ;           // Flag that at least one found
      trial ( inputs ) ;      // Compute network's outputs
      maxi1=maxi2=maxi3=0.0;
      win1=win2=win3=0;
      // Saving maximun activation and the winner of the output vector
      if (netmod==NETMOD_KOH)
      {
	// First maximum
	for (i=0 ; i<nout ; i++)
	{
	   if (out[i]>maxi1)
	   {
	     maxi1=out[i];
	     win1=i;
	   }
	}
	// 2nd Maximum
	for (i=0 ; i<nout ; i++)
	{
	   if ( (out[i]>maxi2) && (out[i]<maxi1) )
	   {
	     maxi2=out[i];
	     win2=i;
	   }
	}
	// 3rd Maximum
	for (i=0 ; i<nout ; i++)
	{
	   if ( (out[i]>maxi3) && (out[i]<maxi2) )
	   {
	     maxi3=out[i];
	     win3=i;
	   }
	}

      }

      if (netmod==NETMOD_KOH)
      {
	fprintf (fp_out,"%d %3.2lf\n",win1,maxi1*100.0);
	fprintf (fp_out,"%d %3.2lf\n",win2,maxi2*100.0);
	fprintf (fp_out,"%d %3.2lf",win3,maxi3*100.0);
      }
      else
	for (i=0 ; i<nout ; i++)
	{
	   fprintf ( fp_out , "%.4lf ",out[i]);
	}

      e++;
      while ((! feof ( fp_in ))  &&  (line[strlen(line)-1] != '\n'))
	 fgets ( line , maxlin , fp_in ) ; // Line length may exceed maxlin

      if (feof ( fp_in ))
	 break ;
      }  /* Endless loop until a file runs out */

   MEMTEXT ( "EXECUTE:line, inputs" ) ;
   fclose ( fp_in ) ;
   fclose ( fp_out ) ;
   FREE ( line ) ;
   FREE ( inputs ) ;
}
コード例 #14
0
ファイル: bee_colony.cpp プロジェクト: irwenqiang/pagmo
void bee_colony::evolve(population &pop) const
{
	// Let's store some useful variables.
	const problem::base &prob = pop.problem();
	const problem::base::size_type prob_i_dimension = prob.get_i_dimension(), D = prob.get_dimension(), Dc = D - prob_i_dimension, prob_c_dimension = prob.get_c_dimension();
	const decision_vector &lb = prob.get_lb(), &ub = prob.get_ub();
	const population::size_type NP = (int) pop.size();

	//We perform some checks to determine wether the problem/population are suitable for ABC
	if ( Dc == 0 ) {
		pagmo_throw(value_error,"There is no continuous part in the problem decision vector for ABC to optimise");
	}

	if ( prob.get_f_dimension() != 1 ) {
		pagmo_throw(value_error,"The problem is not single objective and ABC is not suitable to solve it");
	}

	if ( prob_c_dimension != 0 ) {
		pagmo_throw(value_error,"The problem is not box constrained and ABC is not suitable to solve it");
	}

	if (NP < 2) {
		pagmo_throw(value_error,"for ABC at least 2 individuals in the population are needed");
	}

	// Get out if there is nothing to do.
	if (m_iter == 0) {
		return;
	}

	// Some vectors used during evolution are allocated here.
	fitness_vector fnew(prob.get_f_dimension());
	decision_vector dummy(D,0);			//used for initialisation purposes
	std::vector<decision_vector > X(NP,dummy);	//set of food sources
	std::vector<fitness_vector> fit(NP);		//food sources fitness

	decision_vector temp_solution(D,0);

	std::vector<int> trial(NP,0);

	std::vector<double> probability(NP);

	population::size_type neighbour = 0;

	decision_vector::size_type param2change = 0;

	std::vector<double> selectionfitness(NP), cumsum(NP), cumsumTemp(NP);
	std::vector <population::size_type> selection(NP);


	double r = 0;

	// Copy the food sources position and their fitness
	for ( population::size_type i = 0; i<NP; i++ ) {
		X[i]	=	pop.get_individual(i).cur_x;
		fit[i]	=	pop.get_individual(i).cur_f;
	}

	// Main ABC loop
	for (int j = 0; j < m_iter; ++j) {
		//1- Send employed bees
		for (population::size_type ii = 0; ii< NP; ++ii) {
			//selects a random component (only of the continuous part) of the decision vector
			param2change = boost::uniform_int<decision_vector::size_type>(0,Dc-1)(m_urng);
			//randomly chose a solution to be used to produce a mutant solution of solution ii
			//randomly selected solution must be different from ii
			do{
				neighbour = boost::uniform_int<population::size_type>(0,NP-1)(m_urng);
			}
			while(neighbour == ii);

			//copy local solution into temp_solution (the whole decision_vector, also the integer part)
			for(population::size_type i=0; i<D; ++i) {
				temp_solution[i] = X[ii][i];
			}

			//mutate temp_solution
			temp_solution[param2change] = X[ii][param2change] + boost::uniform_real<double>(-1,1)(m_drng) * (X[ii][param2change] - X[neighbour][param2change]);

			//if generated parameter value is out of boundaries, it is shifted onto the boundaries*/
			if (temp_solution[param2change]<lb[param2change]) {
				temp_solution[param2change] = lb[param2change];
			}
			if (temp_solution[param2change]>ub[param2change]) {
				temp_solution[param2change] = ub[param2change];
			}

			//Calling void prob.objfun(fitness_vector,decision_vector) is more efficient as no memory allocation occur
			//A call to fitness_vector prob.objfun(decision_vector) allocates memory for the return value.
			prob.objfun(fnew,temp_solution);
			//If the new solution is better than the old one replace it with the mutant one and reset its trial counter
			if(prob.compare_fitness(fnew, fit[ii])) {
				X[ii][param2change] = temp_solution[param2change];
				pop.set_x(ii,X[ii]);
				prob.objfun(fit[ii], X[ii]); //update the fitness vector
				trial[ii] = 0;
			}
			else {
				trial[ii]++; //if the solution can't be improved incrase its trial counter
			}
		} //End of loop on the population members

		//2 - Send onlooker bees
		//We scale all fitness values from 0 (worst) to absolute value of the best fitness
		fitness_vector worstfit=fit[0];
		for (pagmo::population::size_type i = 1; i < NP;i++) {
			if (prob.compare_fitness(worstfit,fit[i])) worstfit=fit[i];
		}

		for (pagmo::population::size_type i = 0; i < NP; i++) {
			selectionfitness[i] = fabs(worstfit[0] - fit[i][0]) + 1.;
		}

		// We build and normalise the cumulative sum
		cumsumTemp[0] = selectionfitness[0];
		for (pagmo::population::size_type i = 1; i< NP; i++) {
			cumsumTemp[i] = cumsumTemp[i - 1] + selectionfitness[i];
		}
		for (pagmo::population::size_type i = 0; i < NP; i++) {
			cumsum[i] = cumsumTemp[i]/cumsumTemp[NP-1];
		}

		for (pagmo::population::size_type i = 0; i < NP; i++) {
			r = m_drng();
			for (pagmo::population::size_type j = 0; j < NP; j++) {
				if (cumsum[j] > r) {
					selection[i]=j;
					break;
				}
			}
		}

		for(pagmo::population::size_type t = 0; t < NP; ++t) {
			r = m_drng();
			pagmo::population::size_type ii = selection[t];
			//selects a random component (only of the continuous part) of the decision vector
			param2change = boost::uniform_int<decision_vector::size_type>(0,Dc-1)(m_urng);
			//randomly chose a solution to be used to produce a mutant solution of solution ii
			//randomly selected solution must be different from ii
			do{
				neighbour = boost::uniform_int<population::size_type>(0,NP-1)(m_urng);
			}
			while(neighbour == ii);

			//copy local solution into temp_solution (also integer part)
			for(population::size_type i=0; i<D; ++i) {
				temp_solution[i] = X[ii][i];
			}

			//mutate temp_solution
			temp_solution[param2change] = X[ii][param2change] + boost::uniform_real<double>(-1,1)(m_drng) * (X[ii][param2change] - X[neighbour][param2change]);

			/*if generated parameter value is out of boundaries, it is shifted onto the boundaries*/
			if (temp_solution[param2change]<lb[param2change]) {
				temp_solution[param2change] = lb[param2change];
			}
			if (temp_solution[param2change]>ub[param2change]) {
				temp_solution[param2change] = ub[param2change];
			}

			//Calling void prob.objfun(fitness_vector,decision_vector) is more efficient as no memory allocation occur
			//A call to fitness_vector prob.objfun(decision_vector) allocates memory for the return value.
			prob.objfun(fnew,temp_solution);
			//If the new solution is better than the old one replace it with the mutant one and reset its trial counter
			if(prob.compare_fitness(fnew, fit[ii])) {
				X[ii][param2change] = temp_solution[param2change];
				pop.set_x(ii,X[ii]);
				prob.objfun(fit[ii], X[ii]); //update the fitness vector
				trial[ii] = 0;
			}
			else {
				trial[ii]++; //if the solution can't be improved incrase its  trial counter
			}
		}

		//3 - Send scout bees
		int maxtrialindex = 0;
		for (population::size_type ii=1; ii<NP; ++ii)
		{
			if (trial[ii] > trial[maxtrialindex]) {
				maxtrialindex = ii;
			}
		}
		if(trial[maxtrialindex] >= m_limit)
		{
			//select a new random solution
			for(problem::base::size_type jj = 0; jj < Dc; ++jj) {
				X[maxtrialindex][jj] = boost::uniform_real<double>(lb[jj],ub[jj])(m_drng);
			}
			trial[maxtrialindex] = 0;
			pop.set_x(maxtrialindex,X[maxtrialindex]);
		}




	} // end of main ABC loop

}
コード例 #15
0
ファイル: CONJGRAD.CPP プロジェクト: amirna2/fingerprints
float LayerNet::find_grad (
   TrainingSet *tptr ,
   float *hid2delta ,
   float *outdelta ,
   float *grad
   )
{
   int i, j, size, tset, tclass, n, nprev, nnext ;
   float error, *dptr, diff, delta, *hid1grad, *hid2grad, *outgrad ;
   float *outprev,  *prevact, *nextcoefs, *nextdelta, *gradptr ;
   char msg[80];
/*
   Compute size of each training sample
*/

   if (outmod == OUTMOD_CLASSIFY)
      size = nin + 1 ;
   else if (outmod == OUTMOD_AUTO)
      size = nin ;
   else if (outmod == OUTMOD_GENERAL)
      size = nin + nout ;

/*
   Compute length of grad vector and gradient positions in it.
   Also point to layer previous to output and its size.
   Ditto for layer after hid1.
*/

   if (nhid1 == 0) {      // No hidden layer
      n = nout * (nin+1) ;
      outgrad = grad ;
      nprev = nin ;
      }
   else if (nhid2 == 0) { // One hidden layer
      n = nhid1 * (nin+1) + nout * (nhid1+1) ;
      hid1grad = grad ;
      outgrad = grad + nhid1 * (nin+1) ;
      outprev = hid1 ;
      nprev = nhid1 ;
      nnext = nout ;
      nextcoefs = out_coefs ;
      nextdelta = outdelta ;
      }
   else {                 // Two hidden layers
      n = nhid1 * (nin+1) + nhid2 * (nhid1+1) + nout * (nhid2+1) ;
      hid1grad = grad ;
      hid2grad = grad + nhid1 * (nin+1) ;
      outgrad = hid2grad + nhid2 * (nhid1+1) ;
      outprev = hid2 ;
      nprev = nhid2 ;
      nnext = nhid2 ;
      nextcoefs = hid2_coefs ;
      nextdelta = hid2delta ;
      }

   for (i=0 ; i<n ; i++)  // Zero gradient for summing
      grad[i] = 0.0 ;

   error = 0.0 ;  // Will cumulate total error here
   for (tset=0 ; tset<tptr->ntrain ; tset++) { // Do all samples

      sprintf ( msg , "Learning Pattern Nø %d ", tset) ;
      normal_message ( msg ) ;

      dptr = tptr->data + size * tset ;     // Point to this sample
      trial ( dptr ) ;                      // Evaluate network for it

      if (outmod == OUTMOD_AUTO) {          // If this is AUTOASSOCIATIVE
	 for (i=0 ; i<nout ; i++) {         // then the expected outputs
	    diff = *dptr++ - out[i] ;       // are just the inputs
	    error += diff * diff ;
	    outdelta[i] = diff * actderiv ( out[i] ) ;
	    }
         }

      else if (outmod == OUTMOD_CLASSIFY) {  // If this is Classification
	 tclass = (int) dptr[nin] - 1 ;     // class is stored after inputs
         for (i=0 ; i<nout ; i++) {         // Recall that train added a
            if (tclass == i)                // fraction so that the above
               diff = NEURON_ON - out[i] ;  // truncation to get tclass is
            else                            // always safe in any radix
               diff = NEURON_OFF - out[i] ;
            error += diff * diff ;
	    outdelta[i] = diff * actderiv ( out[i] ) ;
            }
         }

      else if (outmod == OUTMOD_GENERAL) {  // If this is GENERAL output
	 dptr += nin ;                      // outputs stored after inputs
         for (i=0 ; i<nout ; i++) {
            diff = *dptr++ - out[i] ;
            error += diff * diff ;
            outdelta[i] = diff * actderiv ( out[i] ) ;
            }
         }

/*
   Cumulate output gradient
*/

      if (nhid1 == 0)         // No hidden layer
         prevact = tptr->data + size * tset ;
      else
         prevact = outprev ;  // Point to previous layer
      gradptr = outgrad ;
      for (i=0 ; i<nout ; i++) {
         delta = outdelta[i] ;
	 for (j=0 ; j<nprev ; j++)
            *gradptr++ += delta * prevact[j] ;
         *gradptr++ += delta ;   // Bias activation is always 1
         }

/*
   Cumulate hid2 gradient (if it exists)
*/
   
      if (nhid2) {
         gradptr = hid2grad ;
         for (i=0 ; i<nhid2 ; i++) {
	    delta = 0.0 ;
            for (j=0 ; j<nout ; j++)
               delta += outdelta[j] * out_coefs[j*(nhid2+1)+i] ;
            delta *= actderiv ( hid2[i] ) ;
            hid2delta[i] = delta ;
	    for (j=0 ; j<nhid1 ; j++)
               *gradptr++ += delta * hid1[j] ;
            *gradptr++ += delta ;   // Bias activation is always 1
            }
         }

/*
   Cumulate hid1 gradient (if it exists)
*/
   
      if (nhid1) {
	 prevact = tptr->data + size * tset ;
	 gradptr = hid1grad ;
         for (i=0 ; i<nhid1 ; i++) {
            delta = 0.0 ;
            for (j=0 ; j<nnext ; j++)
               delta += nextdelta[j] * nextcoefs[j*(nhid1+1)+i] ;
            delta *= actderiv ( hid1[i] ) ;
            for (j=0 ; j<nin ; j++)
	       *gradptr++ += delta * prevact[j] ;
            *gradptr++ += delta ;   // Bias activation is always 1
            }
         }

      } // for all tsets
   
   return error / ((float) tptr->ntrain * (float) nout) ;
}
コード例 #16
0
ファイル: firm.cpp プロジェクト: omelyanchikd/firm_household
void firm::learn(macro *world)
{
    if (type == "foreign")
    {
        price = 5 * world->price;
        sold = 0;
        sales = 0;
    }
    else
    {
        money += profit;
        /*	if (profit/(price * sold) > margin)
        		salary *= 1.01;
        	/*if (profit > 0)
        		price *= 1.01;//*/
        margin = (0.6 * profit/(price * sold) + 0.4 * margin) * 1.01 >= 0? (0.6 * profit/(price * sold) + 0.4 * margin) * 1.01: 0.01;
        share = (0.6 * sold/world->sold + 0.4 * share);
        expected = world->sales * share;
        plan = expected/price - storage;
        if (plan > 0)
        {
            if (plan <= labor_capacity * labor_productivity)
            {
                if (trial(expected, salary, labor_capacity) >= margin)
                {
                    while (trial(expected, 1.01 * salary, labor_capacity) >= margin)
                        salary *= 1.01;
                }
                else
                {
                    while (labor_capacity - 1 >= 0 && plan <= (labor_capacity - 1) * labor_productivity)
                    {
                        labor_capacity--;
                        if (trial(expected, salary, labor_capacity) >= margin)
                            break;
                    }
                    while (trial(expected, 0.99 * salary, labor_capacity) < margin)
                        salary *= 0.99;
                }
            }
            else
            {
                while (plan > (labor_capacity + 1)* labor_productivity)
                {
                    labor_capacity++;
                    if (trial(expected, 0.99* salary, labor_capacity) < margin)
                        salary *= 0.99;
                }
            }
        }
        else
        {
            labor_capacity = 1;
        }
        /*
        if (trial(expected, salary, labor_capacity) > 2 * margin)
        {
        	while (true)
        	{
        		if (trial(expected, salary, labor_capacity+1) <= 2* margin)
        		{
        			labor_capacity++;
        			break;
        		}
        		else
        			labor_capacity++;
        	}
        }
        else
        	if (trial(expected, salary, labor_capacity) < margin)
        	{
        		while (true)
        		{
        			if (trial(expected, salary, labor_capacity - 1) >= margin && labor_capacity - 1 > 0)
        			{
        				labor_capacity--;
        				break;
        			}
        			else
        				if (labor_capacity - 1 > 0)
        					labor_capacity--;
        				else
        					break;
        		}
        	}
        	else
        	{
        		while (true)
        		{
        			if (trial(expected, salary, labor_capacity+1) < 2 * margin &&trial(expected, salary, labor_capacity+1) >= margin)
        				labor_capacity++;
        			else
        				break;
        		}
        	}//*/
    }
    time++;
    sold = 0;
    sales = 0;
}
コード例 #17
0
/* test to make sure alloc list does what it's supposed to do */
static int testAllocList( void )
{
  int keep = lalDebugLevel;

  s = malloc( sizeof( *s ) );

  XLALClobberDebugLevel(lalDebugLevel | LALMEMDBGBIT | LALMEMTRKBIT);
  XLALClobberDebugLevel(lalDebugLevel & ~LALMEMPADBIT);

  /* empty allocation list */
  trial( LALCheckMemoryLeaks(), 0, "" );
  trial( LALFree( s ), SIGSEGV, "not found" );

  /* can't find allocation in PopAlloc */
  trial( p = LALMalloc( 2 * sizeof( *p ) ), 0, "" );
  trial( q = LALMalloc( 4 * sizeof( *q ) ), 0, "" );
  trial( r = LALMalloc( 8 * sizeof( *r ) ), 0, "" );
  trial( LALFree( s ), SIGSEGV, "not found" );
  trial( LALFree( p ), 0, "" );
  trial( LALFree( r ), 0, "" );
  trial( LALCheckMemoryLeaks(), SIGSEGV, "memory leak" );
  trial( LALFree( q ), 0, "" );
  trial( LALCheckMemoryLeaks(), 0, "" );

  /* can't find allocation in ModAlloc */
  /* For some reason this next test fails on Snow Leopard... */
  /* trial( s = LALRealloc( s, 1024 ), SIGSEGV, "not found" ); */
  trial( p = LALRealloc( NULL, 2 * sizeof( *p ) ), 0, "" );
  /* trial( s = LALRealloc( s, 1024 ), SIGSEGV, "not found" ); */
  trial( LALFree( p ), 0, "" );
  trial( LALCheckMemoryLeaks(), 0, "" );

  free( s );
  XLALClobberDebugLevel(keep);
  return 0;
}
コード例 #18
0
ファイル: confuse.c プロジェクト: andermic/cs534_2_project
void Network::classify_from_file ( char *name , double thresh )
{
   int i, maxlin, did_any, best ;
   double *inputs, *iptr, maxact ;
   char msg[81], *line, *lptr ;
   FILE *fp ;

/*
   Open the file which contains the data to be classified
*/

   if ((fp = fopen ( name , "rt" )) == NULL) {
      strcpy ( msg , "Cannot open " ) ;
      strcat ( msg , name ) ;
      error_message ( msg ) ;
      return ;
      }

/*
   Allocate for the file lines as read. Conservatively guess length.
   Also allocate for network input vector.
*/

   maxlin = nin * 20 + 100 ;
   if (maxlin < 1024)
      maxlin = 1024 ;

   MEMTEXT ( "CONFUSE:line, inputs" ) ;
   line = (char *) MALLOC ( maxlin ) ;
   inputs = (double *) MALLOC ( nin * sizeof(double) ) ;

   if ((line == NULL)  ||  (inputs == NULL)) {
      memory_message ( "to classify" ) ;
      fclose ( fp ) ;
      if (line != NULL)
         FREE ( line ) ;
      if (inputs != NULL)
         FREE ( inputs ) ;
      return ;
      }

/*
   Read the file.
*/

   did_any = 0 ;  /* If file runs out on first try, ERROR! */

   for (;;) {  // Endless loop reads until file exhausted

      if ((fgets ( line , maxlin , fp ) == NULL) || (strlen ( line ) < 2)) {
         if ((! did_any)  ||  ferror ( fp )) {
            strcpy ( msg , "Problem reading file " ) ;
            strcat ( msg , name ) ;
            error_message ( msg ) ;
            }
         break ;
         }

      lptr = line ;              // Parse the data from this line
      iptr = inputs ;            // This will be the network inputs
      for (i=0 ; i<nin ; i++)
         *iptr++ = ParseDouble ( &lptr ) ;

      did_any = 1 ;              // Flag that at least one found
      trial ( inputs ) ;         // Compute network's outputs

      maxact = -1.e30 ;          // Will keep highest activity here
      best = 0 ;                 // Insurance only (good habit)
      for (i=0 ; i<nout ; i++) { // Find winning output
         if (out[i] > maxact) {
            maxact = out[i] ;
            best = i ;
            }
         }

      if (maxact >= thresh)   // If winner has enough activation
         ++confusion[best] ;  // count it in confusion
      else                    // If too little, throw it
         ++confusion[nout] ;  // in the reject category

      while ((! feof ( fp ))  &&  (line[strlen(line)-1] != '\n'))
         fgets ( line , maxlin , fp ) ; // Line length may exceed maxlin

      if (feof ( fp ))
         break ;
      }  /* Endless loop until a file runs out */

   fclose ( fp ) ;
   MEMTEXT ( "CONFUSE:line, inputs" ) ;
   FREE ( line ) ;
   FREE ( inputs ) ;
}
コード例 #19
0
/* do a bunch of allocations/deallocations that are OK */
static int testOK( void )
{
  int keep = lalDebugLevel;

  XLALClobberDebugLevel(lalDebugLevel | LALMEMDBGBIT | LALMEMPADBIT | LALMEMTRKBIT);
  trial( p = LALMalloc( 1024 * sizeof( *p ) ), 0, "" );
  for ( i = 0; i < 1024; ++i ) p[i] = i;
  trial( q = LALCalloc( 1024, sizeof( *q ) ), 0, "" );
  for ( i = 0; i < 1024; ++i ) if ( q[i] ) die( memory not blanked );
  trial( p = LALRealloc( p, 4096 * sizeof( *p ) ), 0, "" );
  for ( i = 0; i < 1024; ++i ) if ( p[i] != i ) die( memory not copied );
  trial( q = LALRealloc( q, 0 ), 0, "" );
  if ( q ) die( memory not freed );
  trial( LALCheckMemoryLeaks(), SIGSEGV, "LALCheckMemoryLeaks: memory leak\n" );
  if ( *( p - 1 ) != (size_t)0xABadCafe ) die( wrong magic );
  if ( *( p - 2 ) != 4096 * sizeof( *p ) ) die( wrong size );
  trial( LALFree( p ), 0, "" );
  trial( LALCheckMemoryLeaks(), 0, "" );

  XLALClobberDebugLevel(lalDebugLevel & ~LALMEMPADBIT);
  trial( p = LALMalloc( 1024 * sizeof( *p ) ), 0, "" );
  for ( i = 0; i < 1024; ++i ) p[i] = i;
  trial( q = LALCalloc( 1024, sizeof( *q ) ), 0, "" );
  for ( i = 0; i < 1024; ++i ) if ( q[i] ) die( memory not blanked );
  trial( p = LALRealloc( p, 4096 * sizeof( *p ) ), 0, "" );
  for ( i = 0; i < 1024; ++i ) if ( p[i] != i ) die( memory not copied );
  trial( q = LALRealloc( q, 0 ), 0, "" );
  if ( q ) die( memory not freed );
  trial( LALCheckMemoryLeaks(), SIGSEGV, "LALCheckMemoryLeaks: memory leak\n" );
  trial( LALFree( p ), 0, "" );
  trial( LALCheckMemoryLeaks(), 0, "" );

  XLALClobberDebugLevel(lalDebugLevel | LALMEMPADBIT);
  XLALClobberDebugLevel(lalDebugLevel & ~LALMEMTRKBIT);
  trial( p = LALMalloc( 1024 * sizeof( *p ) ), 0, "" );
  for ( i = 0; i < 1024; ++i ) p[i] = i;
  trial( q = LALCalloc( 1024, sizeof( *q ) ), 0, "" );
  for ( i = 0; i < 1024; ++i ) if ( q[i] ) die( memory not blanked );
  trial( p = LALRealloc( p, 4096 * sizeof( *p ) ), 0, "" );
  for ( i = 0; i < 1024; ++i ) if ( p[i] != i ) die( memory not copied );
  trial( q = LALRealloc( q, 0 ), 0, "" );
  if ( q ) die( memory not freed );
  trial( LALCheckMemoryLeaks(), SIGSEGV, "LALCheckMemoryLeaks: memory leak\n" );
  if ( *( p - 1 ) != (size_t)0xABadCafe ) die( wrong magic );
  if ( *( p - 2 ) != 4096 * sizeof( *p ) ) die( wrong size );
  trial( LALFree( p ), 0, "" );
  trial( LALCheckMemoryLeaks(), 0, "" );

  XLALClobberDebugLevel(lalDebugLevel & ~LALMEMDBGBIT);
  trial( p = LALMalloc( 1024 * sizeof( *p ) ), 0, "" );
  for ( i = 0; i < 1024; ++i ) p[i] = i;
  trial( q = LALCalloc( 1024, sizeof( *q ) ), 0, "" );
  for ( i = 0; i < 1024; ++i ) if ( q[i] ) die( memory not blanked );
  trial( p = LALRealloc( p, 4096 * sizeof( *p ) ), 0, "" );
  for ( i = 0; i < 1024; ++i ) if ( p[i] != i ) die( memory not copied );
  trial( q = LALRealloc( q, 0 ), 0, "" );
  /* if ( q ) die( memory not freed ); */
  trial( LALCheckMemoryLeaks(), 0, "" );
  trial( LALFree( p ), 0, "" );
  trial( LALCheckMemoryLeaks(), 0, "" );

  XLALClobberDebugLevel(keep);
  return 0;
}