コード例 #1
0
ファイル: calendar.cpp プロジェクト: Madnus/Cataclysm-DDA
float calendar::sunlight() const
{
    int seconds = seconds_past_midnight();
    int sunrise_seconds = sunrise().seconds_past_midnight();
    int sunset_seconds = sunset().seconds_past_midnight();

    int current_phase = int(moon());
    if ( current_phase > int(MOON_PHASE_MAX)/2 ) {
        current_phase = int(MOON_PHASE_MAX) - current_phase;
    }

    int moonlight = 1 + int(current_phase * MOONLIGHT_PER_QUATER);

    if( seconds > sunset_seconds + TWILIGHT_SECONDS || seconds < sunrise_seconds ) { // Night
        return moonlight;
    } else if( seconds >= sunrise_seconds && seconds <= sunrise_seconds + TWILIGHT_SECONDS ) {
        double percent = double(seconds - sunrise_seconds) / TWILIGHT_SECONDS;
        return double(moonlight) * (1. - percent) + double(DAYLIGHT_LEVEL) * percent;
    } else if( seconds >= sunset_seconds && seconds <= sunset_seconds + TWILIGHT_SECONDS ) {
        double percent = double(seconds - sunset_seconds) / TWILIGHT_SECONDS;
        return double(DAYLIGHT_LEVEL) * (1. - percent) + double(moonlight) * percent;
    } else {
        return DAYLIGHT_LEVEL;
    }
}
コード例 #2
0
ファイル: calendar.cpp プロジェクト: 8Z/Cataclysm
int calendar::sunlight()
{
 calendar sunrise_time = sunrise(), sunset_time = sunset();

 int mins = 0, sunrise_mins = 0, sunset_mins = 0;
 mins = minutes_past_midnight();
 sunrise_mins = sunrise_time.minutes_past_midnight();
 sunset_mins = sunset_time.minutes_past_midnight();

 int moonlight = 1 + int(moon()) * MOONLIGHT_LEVEL;

 if (mins > sunset_mins + TWILIGHT_MINUTES || mins < sunrise_mins) // Night
  return moonlight;

 else if (mins >= sunrise_mins && mins <= sunrise_mins + TWILIGHT_MINUTES) {

  double percent = double(mins - sunrise_mins) / TWILIGHT_MINUTES;
  return int( double(moonlight)      * (1. - percent) +
              double(DAYLIGHT_LEVEL) * percent         );

 } else if (mins >= sunset_mins && mins <= sunset_mins + TWILIGHT_MINUTES) {

  double percent = double(mins - sunset_mins) / TWILIGHT_MINUTES;
  return int( double(DAYLIGHT_LEVEL) * (1. - percent) +
              double(moonlight)      * percent         );

 } else
  return DAYLIGHT_LEVEL;
}
コード例 #3
0
ファイル: calendar.cpp プロジェクト: 0x90sled/Cataclysm-DDA
float calendar::sunlight() const
{
    //Recent lightning strike has lit the area
    if( g->lightning_active ) {
        return DAYLIGHT_LEVEL;
    }

    int seconds = seconds_past_midnight();
    int sunrise_seconds = sunrise().seconds_past_midnight();
    int sunset_seconds = sunset().seconds_past_midnight();

    int moonlight = 1 + int(moon()) * MOONLIGHT_LEVEL;

    if( seconds > sunset_seconds + TWILIGHT_SECONDS || seconds < sunrise_seconds ) { // Night
        return moonlight;
    } else if( seconds >= sunrise_seconds && seconds <= sunrise_seconds + TWILIGHT_SECONDS ) {
        double percent = double(seconds - sunrise_seconds) / TWILIGHT_SECONDS;
        return double(moonlight) * (1. - percent) + double(DAYLIGHT_LEVEL) * percent;
    } else if( seconds >= sunset_seconds && seconds <= sunset_seconds + TWILIGHT_SECONDS ) {
        double percent = double(seconds - sunset_seconds) / TWILIGHT_SECONDS;
        return double(DAYLIGHT_LEVEL) * (1. - percent) + double(moonlight) * percent;
    } else {
        return DAYLIGHT_LEVEL;
    }
}
コード例 #4
0
ファイル: calendar.cpp プロジェクト: Atzerkins/Cataclysm-DDA
int calendar::sunlight() const
{
    //Recent lightning strike has lit the area
    if( g->lightning_active ) {
        return DAYLIGHT_LEVEL;
    }

    int mins = minutes_past_midnight(),
        sunrise_mins = sunrise().minutes_past_midnight(),
        sunset_mins = sunset().minutes_past_midnight();

    int moonlight = 1 + int(moon()) * MOONLIGHT_LEVEL;

    if (mins > sunset_mins + TWILIGHT_MINUTES || mins < sunrise_mins) { // Night
        return moonlight;
    }

    else if (mins >= sunrise_mins && mins <= sunrise_mins + TWILIGHT_MINUTES) {

        double percent = double(mins - sunrise_mins) / TWILIGHT_MINUTES;
        return int( double(moonlight)      * (1. - percent) +
                    double(DAYLIGHT_LEVEL) * percent         );

    } else if (mins >= sunset_mins && mins <= sunset_mins + TWILIGHT_MINUTES) {

        double percent = double(mins - sunset_mins) / TWILIGHT_MINUTES;
        return int( double(DAYLIGHT_LEVEL) * (1. - percent) +
                    double(moonlight)      * percent         );

    } else {
        return DAYLIGHT_LEVEL;
    }
}
コード例 #5
0
ファイル: calendar.cpp プロジェクト: Madnus/Cataclysm-DDA
bool calendar::is_night() const
{
    int seconds         = seconds_past_midnight();
    int sunrise_seconds = sunrise().seconds_past_midnight();
    int sunset_seconds  = sunset().seconds_past_midnight();

    return (seconds > sunset_seconds + TWILIGHT_SECONDS || seconds < sunrise_seconds);
}
コード例 #6
0
ファイル: calendar.cpp プロジェクト: Atzerkins/Cataclysm-DDA
bool calendar::is_night() const
{
    int mins         = minutes_past_midnight(),
        sunrise_mins = sunrise().minutes_past_midnight(),
        sunset_mins  = sunset().minutes_past_midnight();

    return (mins > sunset_mins + TWILIGHT_MINUTES || mins < sunrise_mins);
}
コード例 #7
0
ファイル: globcor.c プロジェクト: abouthydrology/meltmodel
void getzenith()

{
    timekorr = 0.;        /*wenn Messdaten andere Zeit als MEZ not 0*/
    sunaltitudeangle = 0;

    jd2monat();           /*CONVERT JULIAN DAY TO MONTH AND DAY*/

    /* gibt die Verschiebung der realen Sonnenzeit gegenueber der
     mittleren Sonnenzeit in min an (Elliptische Bahn) das Array steht
     an jeder Seite um eins ueber, d.h., es kann auch mit monat-1
     bzw. monat+1 gerechnet werden*/

    timeequation[0]  =  11.3;
    timeequation[1]  =  -3.2;     /*Januar*/
    timeequation[2]  = -13.6;
    timeequation[3]  = -12.6;
    timeequation[4]  =  -4.2;
    timeequation[5]  =   2.8;
    timeequation[6]  =   2.5;
    timeequation[7]  =  -3.5;
    timeequation[8]  =  -6.3;
    timeequation[9]  =  -0.3;
    timeequation[10] =  10.0;
    timeequation[11] =  16.4;
    timeequation[12] =  11.3;
    timeequation[13] =  -3.2;

    /*-----------------------------------------*/
    /* Berechnen von sunazimuthangle, sunaltitudeangle, sunzenithangle fuer diese Stunde
       Angaben der Ergebnisse in rad, der Eingangsdaten aber in Grad! */

    /* SUNRISE AND SUNSET FOR THE DAY */
    sunrise(tag,monat,breite,laenge,&sunr,&suns);      /*!!!!!!!!!!*/

    /* Teilintervall am Anfang der Integration (Mitte des timestep) */
    sp = zeit - timestep/2;

    /* GET SUN ZENITH ANGLE */
    getsuncoordinates(tag,monat,breite,laenge,sp,&sunazimuthangle,&sunaltitudeangle);
    sunzenithangle = pi/2 - sunaltitudeangle;

    return;

}
コード例 #8
0
ファイル: main.cpp プロジェクト: laCour/sunrise
void reply(DBusMessage *msg, DBusConnection *conn) {
  DBusMessage *reply;
  DBusMessageIter args;

  long t_response = -1;
  double d_response = -1;

  if (dbus_message_is_method_call(msg, DBUS_NAMESPACE, "Sunrise")) { t_response = sunrise(msg); }
  if (dbus_message_is_method_call(msg, DBUS_NAMESPACE, "Sunset")) { t_response = sunset(msg); }
  if (dbus_message_is_method_call(msg, DBUS_NAMESPACE, "Brightness")) { d_response = brightness(msg); }

  reply = dbus_message_new_method_return(msg);
  dbus_message_iter_init_append(reply, &args);

  if (t_response >= 0) { sendT(conn, reply, &args, t_response); }
  if (d_response >= 0) { sendD(conn, reply, &args, d_response); }

  dbus_connection_flush(conn);
  dbus_message_unref(reply);
}
コード例 #9
0
bool
CityWeather::isDayTime( const YawpDay * day ) const
{
    if( !day || !day->sunset().isValid() || !day->sunrise().isValid() )
        return true;

    QDateTime currentTime;
    if( observationPeriode().isValid() )
        currentTime = observationPeriode();
    else
        currentTime = localTime();

    QDateTime sunrise( currentTime.date(), day->sunrise() );
    QDateTime sunset( currentTime.date(), day->sunset() );

    bool bReturn = (currentTime > sunrise && currentTime  < sunset);

    dTracing() << "City: " << m_sLocalizedCity <<"   current Time:" << currentTime
               << "   sunrise:" << sunrise << "   sunset:" << sunset
               << "   daytime:" << bReturn;

    return bReturn;
}
コード例 #10
0
ファイル: globcor.c プロジェクト: abouthydrology/meltmodel
void schatten()

{
    float  z;       /*elevation*/
    int    *indexx,*indexy;
    float  faktorstationhoriz = 0;  /*for correction factor assuming the climate station */
    /* grid to be horizontal */
    float  slopehoriz = 0;     /* slope of the climate station for horizontal calculation*/

    /*** $$$  NEU OPTION : SCHATTENGRIDS DER SUBINTERVALLE AUF FILE SCHREIBEN 1=yes ***/
    int    subintfileyes=0;        /*** $$$ **********************/
    /*zum steuern, ob alle Schattengrids aller Subintervalle auf ein File
      geschrieben werden sollen, Name: sub__.__ mit Zeit als real*/

    FILE   *shadesubint=NULL;
    char   namesubint[21];
    float  faktorstation;  /*NEU NUR KONTROLL-SCREEN-OUTPUT $$$ */

    exkorstationhoriz  = 0.0;
    directstationhoriz = 0.0;  /*must be set to 0 every timestep before subinterval loop*/

    timekorr = 0.;        /*wenn Messdaten andere Zeit als MEZ not 0*/
    InV=timestep*60;      /*Intervallaenge in Minuten*/
    se = zeit;
    /*if time step=1 h, time=8, split=4 calculation at: 7h7.5min 7h22.5min etc*/


    jd2monat();           /*CONVERT JULIAN DAY TO MONTH AND DAY*/

    /* Initialisieren des Arrays fuer die Abweichung der wahren Sonnenzeit von der Ortszeit
        in Abhaengigkeit vom Monat */
    /* gibt die Verschiebung der realen Sonnenzeit gegenueber der
     mittleren Sonnenzeit in min an (Elliptische Bahn) das Array steht
     an jeder Seite um eis ueber, d.h., es kann auch mit monat-1
     bzw. monat+1 gerechnet werden*/

    timeequation[0]  =  11.3;
    timeequation[1]  =  -3.2;     /*Januar*/
    timeequation[2]  = -13.6;
    timeequation[3]  = -12.6;
    timeequation[4]  =  -4.2;
    timeequation[5]  =   2.8;
    timeequation[6]  =   2.5;
    timeequation[7]  =  -3.5;
    timeequation[8]  =  -6.3;
    timeequation[9]  =  -0.3;
    timeequation[10] =  10.0;
    timeequation[11] =  16.4;
    timeequation[12] =  11.3;
    timeequation[13] =  -3.2;


    /* Suchen der groessten Hoehe, um den Schattensuchalgorithmus abbrechen zu koennen,
        wenn die Gerade ueber hmax steigt, und immer noch kein Schatten berechnet wurde */

    if (hmaxcalculated == 0) {   /*nur einmal berechnen - aendert sich nicht*/
        hmax=-1e10;
        for (i=1; i<=nrows; i++)
            for (j=1; j<=ncols; j++)
                if (griddgm[i][j]>hmax)   hmax=griddgm[i][j];

        hmaxcalculated = 1;
    }


    /* Ausfuehren der expositions-, gefaelle- und
       abschattungsabhaengigen Korrektur fuer die direkte Sonnenstrahlung */

    cn=1;
    gewicht=1.0/(float)split;

    /* es werden jeweils split Teilintervalle gebildet. Fuer jedes dieser
         Teilintervalle wird die Mittelzeit genommen, fuer diese Mittelzeit wird dann
         die Expositionskorrektur gerechnet. Der Mittelwert aus allen Berechnungen
         wird als repraesentativ fuer das Intervall angenommen. Es werden nur Intervalle
         beruecksichtigt, an denen die Sonne ueber dem Horizont steht.
         Bei einem Zeitintervall von 24 Stunden kann split z.B. 24 sein, es werden dann
         nach jeweils count Rechenaufrufen (also count Tagen) fuer alle 24 Stunden
         die Korrekturwerte ermittelt un dann ein repraesentetiver Tageswert errechnet. */

    /*-----------------------------------------*/
    /* Berechnen von sunazimuthangle, sunaltitudeangle, sunzenithangle fuer diese Stunde
       Angaben der Ergebnisse in rad, der Eingangsdaten aber in Grad! */

    /* SUNRISE AND SUNSET FOR THE DAY */
    sunrise(tag,monat,breite,laenge,&sunr,&suns);      /*!!!!!!!!!!*/

    /* Nullsetzen der Korrekturfaktoren erfolgt explizit, da die Zuweisung in der
       Schleife zur Korrekturfaktorermittlung incrementell erfolt (es wird dann fuer
       jedes Teilintervall eine um den Korrekturfaktor fuer dieses Zeitintervall korrigierte
       Strahlung addiert, so dass zum Intervallende genau <split> Teilintervall-Ergebnisse
       addiert sind. Der Wert in EXKORR entspricht dann dem Korrigierten Stundenwert der
       Strahlung (Korrekturfaktoren mit der astronomisch und topographisch moeglichen
       Strahlung gewichtet). Ganz am Ende wird dann durch eine separat ermittelte
       unkrrigierte Intervallsumme der STrahlung geteilt, um so den effektiven
       Korrekturfaktor zu erhalten */

    for (i=1; i<=nrows; i++)     /*CORRECTION FACTOR GRID INITIALISIEREN AUF NULL*/
        for (j=1; j<=ncols; j++) {
            EXKORR[i][j]=0.0;
            SHADE[i][j]=0.0;      /*must be zero, because summing up of SHAPE*/
            Isenk[i][j]=0.0;      /*clear sky solar radiation, momentanwert*/
            strlsumme[i][j]=0.0;  /*Isenk*cosZ summed up (refers to horizontal surface)*/
            /*clear sky solar radiation Wh/m2: mean for time step interval*/
            DIRECT[i][j]=0.0;
        }

    /*SHADE = mean shade value for timestep, d.h. sum up 0 or 1 for each subinterval,
      divide by split for each time step*/

    /* Da fuer mehrere Intervalle die Strahlung unterschiedlich gross sein kann,
       muessen die Korrekturfaktoren mit den jeweils astronomisch moegl. Strahlungen
       gewichtet werden. Es wird also das Integral der korrigierten maximal
       moeglichen Strahlungen errechnet, anschliessend durch das Integral der
       unkorrigierten maximal moeglichen Strahlung geteilt (me) und so
       der mittlere Korrekturfaktor erhalten. */

    /* Teilintervall am Anfang der Integration (Mitte des 1. der <split> Teilintervalle) */
    spa = se-InV/60.0*(1-0.5/(float)split)+timekorr;

    /* Teilintervall am Ende der Integration (Mitte des letzten der <split> Teilintervalle*/
    spe = se+0.01+timekorr;


    /* ------------------------------------------------------------------------------------ */
    /******* ZEIT-SCHLEIFE : UEBER ALLE ZEITUNTERINTERVALLE (je nach SPLIT) BERECHNUNG VON
    			     clear-sky direct radiation Isenk = height-dependent
    			     ABSCHATTUNG und CORRECTION FACTOR  ******/

    for (sp=(float)spa; sp<(float)spe; sp+=gewicht*(InV/60.0))

        /* sp ist die Stundennummer (Bruchteile erlaubt und noetig) des aktuellen Teilintervalles,
           korrigiert mit der Zeitverschiebung der mittleren gegen die wahre Sonnenzeit;
           so ist spa bei einem Zeitintervall von 2 Stunden und split=4 (jede halbe Stunde neu
           berechnen) nach obiger Berechnung fuer se=10 (die an die Routine uebergebene
           Stundennummer [fuer das Ende des Intervalls])
           10 - 120/60 * (1 - 0.5/4) + korr = 10 - 2 * (1-0.25) = 10 - 2 + 0.5 = 8.5.
           Das erste Teiintervall ist also 0.5 Stunden lang und endet um 8:30.
           Als Increment wird jeweils die mit 1/<split> gewichtete Laenge eines
           Intervalles in Stunden (hier 0.25*120/60 = 0.5 addiert */

    {

        /*** $$$ NEU KONTROLL-OUTPUT, SCHATTEN DER SUBINTERVALLE */
        if (subintfileyes == 1) {
            sprintf(namesubint,"sun%4.2f",sp);
            strcpy(dummy,outpath);
            strcat(dummy,namesubint);

            if ((shadesubint = fopen(dummy,"wb")) == NULL) {
                printf("\n ERROR in opening shade file (subintervals)");
                printf("\n       file globcor.c\n\n");
                exit(10);
            }
        } /*endif*/

        /*** $$$ ***********/

        /* wenn der Beginn des aktuellen Intervalls vor Sonnenaufgang oder
           das Ende des aktuellen Berechnungsintervalles nach
           Sonnenuntergang liegt, wird keine Strahlung beruecksichtigt
           (nur vollstaendig "besonnte" Intervalle werden beruecksichtigt) */
        /* fuer alle Grids gleich */

        /* neu Modifikation vom 21.1.1997 in shading.c hier 22.7.1997 eingebaut,
           da Fehler in bestimmten Faellen noerdlich vom Polarkreis: */
        split_temp = InV/60.0/(float)split; /* Dauer eines Teilintervalles in h */
        inta = sp-split_temp/2.0;
        inte = sp+split_temp/2.0;
        sunr = fmod(sunr+24.0,24.0); /* Sonnenaufgang zwischen 0 ... 24 Uhr fixieren */
        suns = fmod(suns+24.0,24.0); /* Sonnenuntergang ebenfalls fixieren */
        /* Wie lange ist es am Anfang eines Teilintervalls noch dunkel und am Ende schon dunkel? */

        /* dark_a */
        if (sunr<inta)
            dark_a = 0.0;
        else if (sunr<inte)
            dark_a = sunr - inta;
        else /* Stunde komplett vor Sonnenaufgang */
            dark_a = 0.0;

        /* dark_e */
        if (suns>sunr) {
            /* der Normalfall */
            if ((suns>inte)&&(sunr<inte))
                dark_e = 0.0;
            else if ((suns>inta)&&(suns<inte))
                dark_e = inte - suns;
            else
                dark_e = split_temp;
        } else {
            /* der Fall, dass die Sonne erst nach Mitternacht gesetzl. Zeit untergeht */
            if (suns>inte)
                dark_e = 0.0;
            else if (suns>inta)
                dark_e = inte - suns;
            else
                dark_e = sunr > inte ? split_temp : 0.0;
        }

        Anteil_dunkel = (dark_a + dark_e)/split_temp;
        /* Wenn die Sonne im Intervall erst unter, dann aufgeht, muss zum Anfang und Ende
           des Intervalls das Komplement zu 1 von dark_a und dark_e gebildet und addiert werden
           Anteil_hell=(1-dark_a)+(1-dark_e) = 2-(dark_a+dark_e) = 2.0 - Anteil_dunkel
           was f’r Anteil_dunkel zu Anteil_dunkel = 1-Anteil_hell = 1 - 2 + Anteil_hell =
           Anteil_dunkel-1 fuehrt */

        if (Anteil_dunkel>1.0) Anteil_dunkel--;

        /* wenn die Sonne nur ganz kurz auftaucht, nuetzt es gar nichts!
           Da kann sie auch gleich untergetaucht bleiben */
        if (Anteil_dunkel > 0.95) Anteil_dunkel=1.0;
        Anteil_hell   = 1.0 - Anteil_dunkel;

        if ((Anteil_hell>0.5)&&((dark_a+dark_e)<=1))
            /*    if ( (sp-InV/60.0*0.5/(float)split <= sunr) || (sp > suns) ) nostrl = 1 */
            nostrl = 0;    /*day*/
        else
            nostrl = 1;    /*night*/

        /*---------------------------------------------------------------------------------*/
        /*      Berechnung der clear-sky solar radiation   for all grids                   */
        /*---------------------------------------------------------------------------------*/

        if (!nostrl) {           /*Sonne aufgegangen ueber horizontaler Ebene*/
            /* wo steht die Sonne? */
            getsuncoordinates(tag,monat,breite,laenge,sp,&sunazimuthangle,&sunaltitudeangle);
            sunzenithangle = pi/2 - sunaltitudeangle;

            radiussunearth();    /*ratio of mean radius to earth to tru radius to earth*/

            /*NEU : Isenk hoehenabhaengig -> daher Berechnung fuer jedes Grid*/
            for (i=1; i<=nrows; i++)
                for (j=1; j<=ncols; j++) {
                    if (sunaltitudeangle>0.017) { /* 0.017=1 Grad */
                        /* Berechnung der bei Wolkenfreiem Himmel und klarer Atmosphaere auf einen
                           waagerechten Quadratmeter auftreffender Strahlungsenergie [Isenk] = Wh/m^2 */
                        /* cos(sunazimuthangle) wirkt hier auf den Extinktionskoeffizienten!  */

                        /*------------------------------------------------*/
                        p = exp(-0.0001184*griddgm[i][j]) * P0;           /* air pressure */
                        /*------------------------------------------------*/

                        /* Formel aus Oke S.345  transmissivity read from input.dat */
                        /*gewicht=1.0/(float)split,  InV=Intervalllaenge in Minuten=timestep*60 */
                        /*-!!!------------------------------------------------------------------------!!!-*/
                        Isenk[i][j] = gewicht*InV*1368.0*radius2sun/60.0 *
                                      pow(trans,(p/P0)/cos(sunzenithangle));
                        /*-!!!------------------------------------------------------------------------!!!-*/
                        /** beim Teilen durch cos(sunzenithangle) : braucht nicht begrenzt werden **/

                    }  /*endif*/
                    else Isenk[i][j]=0.0; /* no direct radiation at night */

                    strlsumme[i][j] += (Isenk[i][j]*cos(sunzenithangle));
                    /*direct rad uncorrected over timeinterval referred to horizontal surface*/

                }  /*endfor  next grid*/

        }  /*endif  !nostrl*/

        /*---------------------------------------------------------------------------------*/
        /*      Berechnung der Abschattung   for all grids for one point of time           */
        /*         algorithm by Joerg Schulla                                              */
        /*---------------------------------------------------------------------------------*/

        for (i=1; i<=nrows; i++)
            for (j=1; j<=ncols; j++) {
                if (nostrl == 1)     /*before sunrise over horizontal surface (night) */
                    SHAPE[i][j]=1.0;      /*must be 1, because no shade calculation before sunrise*/
                else                 /*after sunrise -> shade calculation below*/
                    SHAPE[i][j]=0.0;      /*must be 0 if algorithm below used*/
            }


        if (shadefromfile != 1) {        /*shading calculated here*/
            if (!nostrl) {        /*Sonne aufgegangen ueber horizontaler Ebene*/
                /* Vorzeichen der Geradenanstiege in x- und y-Richtung */
                if (sunazimuthangle<=pi/2.0) {
                    vx = 1;
                    vy = 1;
                } else {
                    if (sunazimuthangle<=pi) {
                        vx = 1;
                        vy =-1;
                    } else {
                        if (sunazimuthangle<=pi*1.5) {
                            vx =-1;
                            vy =-1;
                        } else {
                            vx =-1;
                            vy = 1;
                        }
                    }
                }

                /* in x Richtung kleiner 45 Grad Neigung */
                if (fabs(cos(sunazimuthangle))<= (float)0.707106781)
                    /* x-schritt ist immer 1, y-schritt wird sukzessive nachgefuehrt */
                {
                    dy=(int)fabs((ncols*cos(sunazimuthangle)/sin(sunazimuthangle)));
                    dx=ncols;

                    dz=fabs((float)cs/sin(sunazimuthangle))*tan(sunaltitudeangle);
                    indexx = (int*)calloc(ncols+1,sizeof(int));
                    indexy = (int*)calloc(ncols+1,sizeof(int));

                    if (vx>0)
                        /* von links nach rechts */
                    {
                        /* alle Punkte im Grid durchlaufen i=1..nrows,j=1..ncols */
                        for (i=1; i<=nrows; i++) {
                            for (j=1; j<=ncols; j++) {
                                fx=dx/2;
                                ii=i;
                                jj=j;
                                z=griddgm[i][j];
                                k=1;
                                indexy[k]=ii;
                                indexx[k]=jj;
                                while ((ii<nrows)&&(ii>1)&&(jj<ncols)&&(z<hmax)&&(SHAPE[i][j]<0.5)) {
                                    z+=dz;
                                    jj+=vx;
                                    fx-=dy;
                                    if (fx<=0) {
                                        fx+=dx;
                                        ii-=vy;
                                    }
                                    k++;
                                    indexy[k]=ii;
                                    indexx[k]=jj;
                                    if (griddgm[ii][jj]>z) {
                                        for (m=1; m<k; m++)
                                            SHAPE[indexy[m]][indexx[m]]=1.0;
                                    }
                                }
                            }
                        }
                    } else
                        /* von rechts nach links */
                    {
                        /* alle Punkte im Grid durchlaufen i=1..nrows,j=ncols..1 */
                        for (i=1; i<=nrows; i++) {
                            for (j=ncols; j>=1; j--) {
                                fx=dx/2;
                                ii=i;
                                jj=j;
                                z=griddgm[i][j];
                                k=1;
                                indexy[k]=ii;
                                indexx[k]=jj;
                                while ((ii<nrows)&&(ii>1)&&(jj>1)&&(z<hmax)&&(SHAPE[i][j]<0.5)) {
                                    z+=dz;
                                    jj+=vx;
                                    fx-=dy;
                                    if (fx<=0) {
                                        fx+=dx;
                                        ii-=vy;
                                    }
                                    k++;
                                    indexy[k]=ii;
                                    indexx[k]=jj;
                                    if (griddgm[ii][jj]>z) {
                                        for (m=1; m<k; m++)
                                            SHAPE[indexy[m]][indexx[m]]=1.0;
                                    }
                                }
                            }
                        }
                    }
                    free(indexx);
                    free(indexy);
                } else
                    /* y-schritt ist immer 1, x-schritt wird nachgefuehrt */
                {
                    dx=(int)fabs(nrows*sin(sunazimuthangle)/cos(sunazimuthangle));
                    dy=nrows;
                    dz=fabs((float)cs/cos(sunazimuthangle))*tan(sunaltitudeangle);
                    indexx = (int*)calloc(ncols+1,sizeof(int));
                    indexy = (int*)calloc(ncols+1,sizeof(int));

                    if (vy>0)
                        /* von unten nach oben */
                    {
                        /* alle Punkte im Grid durchlaufen i=nrows..1,j=1..ncols */
                        for (i=nrows; i>=1; i--) {
                            for (j=1; j<=ncols; j++) {
                                fy=dy/2;
                                ii=i;
                                jj=j;
                                z=griddgm[i][j];
                                k=1;
                                indexy[k]=ii;
                                indexx[k]=jj;
                                while ((ii>1)&&(jj>1)&&(jj<ncols)&&(z<hmax)&&(SHAPE[i][j]<0.5)) {
                                    z+=dz;
                                    ii-=vy;
                                    fy-=dx;
                                    if (fy<=0) {
                                        fy+=dy;
                                        jj+=vx;
                                    }
                                    k++;
                                    indexy[k]=ii;
                                    indexx[k]=jj;
                                    if (griddgm[ii][jj]>z) {
                                        for (m=1; m<k; m++)
                                            SHAPE[indexy[m]][indexx[m]]=1.0;
                                    }
                                }
                            }
                        }
                    } else
                        /* von oben nach unten */
                    {
                        /* alle Punkte im Grid durchlaufen i=1..nrows,j=1..ncols */
                        for (i=1; i<=nrows; i++) {
                            for (j=1; j<=ncols; j++) {
                                fy=dy/2;
                                ii=i;
                                jj=j;
                                z=griddgm[i][j];
                                k=1;
                                indexy[k]=ii;
                                indexx[k]=jj;
                                while ((ii<nrows)&&(jj>1)&&(jj<ncols)&&(z<hmax)&&(SHAPE[i][j]<0.5)) {
                                    z+=dz;
                                    ii-=vy;
                                    fy-=dx;
                                    if (fy<=0) {
                                        fy+=dy;
                                        jj+=vx;
                                    }
                                    k++;
                                    indexy[k]=ii;
                                    indexx[k]=jj;
                                    if (griddgm[ii][jj]>z) {
                                        for (m=1; m<k; m++)
                                            SHAPE[indexy[m]][indexx[m]]=1.0;
                                    }
                                }
                            }
                        }
                    }
                    free(indexx);
                    free(indexy);

                }
            }

        }   /*endif shadefromfile ==1 */

        else {   /*shading read from existing files*/
            strcpy(dummy,pathdirectfile);
            sprintf(nameshade,"sha%03d%02d.bin",(int)jd,(int)zeit);
            strcat(dummy,nameshade);
            if ((inshade = fopen (dummy,"rb")) == NULL)  {
                printf("\n shade file not found \n\n");
                exit(4);
            }  /*ENDIF*/

            if ( (fread(&(x[1]),sizeof(float),12,inshade)) !=12 )  {            /*FIRST 12 ROWS*/
                printf("\n ERROR in file %s \n",nameshade);
                exit(9);
            }
            if ((fread(&(SHAPE[1][1]),sizeof(float),ncols*nrows,inshade)) != ncols*nrows)  {
                printf("\n ERROR in reading shade file %s  jd=%4.1f\n",nameshade,jd);
                exit(10);
            }
            closefile(&inshade,nameshade);

        }  /*end else  shading from files*/

        /*------------------------------------------------------------------------------------*/
        /*   expositions- und neigungsbedingte Strahlunsgkorrektur    still same subinterval  */
        /*------------------------------------------------------------------------------------*/

        for (i=1; i<=nrows; i++) /* ueber alle Reihen */
            for (j=1; j<=ncols; j++) { /* Spalten des Grids */
                SHADE[i][j] += (SHAPE[i][j]);  /*fuer Mittelwertberechnung des ganzen time steps*/

                /*Aufsummieren des Schattenergebnisses fuer das split subinterval (=SHAPE ist 0 oder 1),
                  nach Ende aller split Teilintervalle teilen durch die Anzahl Teilintervalle => gibt
                  mittlere Beschattung waehrend des Zeitintervalls 0 oder 1 oder ein Wert zw. 0 und 1,
                  d.h dann innerhalb dieses time steps ist die Sonne unter oder aufgegangen. */

                if ((!nostrl)&&(SHAPE[i][j]<0.5)) {    /*AFTER SUNRISE AND NO SHADE*/
                    /*faktor=cos of angle of incidence*/
                    faktor = getcosincidence(ASP[i][j]*pi/180.0,SLOPE[i][j]*pi/180.0,
                                             sunazimuthangle,sunzenithangle);

                    if (faktor<=0)
                        faktor=0.0;

                    /*if((i==54) && (j==104))
                      printf("\n   costheta=%8.5f  Z=%10.4f  cosZ=%10.5f   exk=%5.2f ",
                         faktor,sunzenithangle,cos(sunzenithangle),
                         faktor/cos(sunzenithangle));  */

                    /*Begrenzung ? ==> faktor/cos(sunzenithangle) > 5. => faktor = 5*cosZ */
                    if(faktor/cos(sunzenithangle) > 5.) {
                        faktor=5*cos(sunzenithangle);

                        /* if((i==54) && (j==104))
                          printf("\n     groesser5 costheta 5.2%",faktor); */

                    }
                } else  faktor=0;     /*BEFORE SUNRISE OR IN SHADE*/


                /***********FUER OUTPUT SHADE EACH SUBINTERVAL *****/
                if ((i==rowclim) && (j==colclim))
                    faktorstation = faktor;
                /***********/

                /* Korrektur fuer direkte Sonnenstrahlung:
                   wenn Sonne unter Horizont      : 0 (keine Korrektur)
                   wenn Sonne Flaeche nicht trifft: 0 (keine Korrektur)
                */

                DIRECT[i][j] += (faktor*Isenk[i][j]);

                /*Begrenzung ?
                faktor/cos(sunzenithangle) > 5.   ->  faktor*cosZ*Isenk   */

            }  /*endfor  next grid*/


        /*for the grid of the climate station, a horizontal slope must be taken for calculation of
          the direct radiation, because the pyranometer was installed horizontally. Thus, the
          ratio of global radiation and direct radiation must refer to a horizontal plane.
          Therefore, for the grid of the climate station the factor is recalculated using a slope
          zero. The slope of the grid is not set to zero a priori, because the output files of
          exkorr and direct radiation should refer to the actual slope. Thus, new variables are
          needed to preserve the actual slope*/

        if ((!nostrl)&&(SHAPE[rowclim][colclim]<0.5)) {    /*AFTER SUNRISE AND NO SHADE*/
            faktorstationhoriz = getcosincidence(ASP[rowclim][colclim]*pi/180.0,
                                                 slopehoriz,sunazimuthangle,sunzenithangle);    /*slopehoriz=0*/

            if (faktorstationhoriz<=0)
                faktorstationhoriz=0.0;
        } else  faktorstationhoriz=0;     /*BEFORE SUNRISE OR IN SHADE*/

        directstationhoriz += (faktorstationhoriz*Isenk[rowclim][colclim]);

        /**** $$$  KONTROLL-OUTPUT SCHATTENFILES FUER JEDES SUBINTERVAL*****/
        if (subintfileyes == 1) {
            printf("\n\ttime=%5.2f  shape=%5.2f  zenith=%6.2811f faktor=%5.2f direct =%6.2f",
                   sp,SHAPE[rowclim][colclim],sunzenithangle*180/pi,faktorstation,
                   Isenk[rowclim][colclim]/timestep*split);

            if (shadesubint) {    /*FILE IS OPEN*/
                fwrite(&(x[1]),sizeof(float),12,shadesubint);   /*WRITE TO FILE*/
                for (i=1; i<=nrows; i++)        /*ueber alle Reihen*/
                    fwrite(&(SHAPE[i][1]),sizeof(float),ncols,shadesubint);

                fclose(shadesubint);
                shadesubint = NULL;     /*pointer freigeben*/
            }/*endif*/
        } /*endif fileyes*/

        /* $$$ *********/


    }   /* Schleife fuer die <split> Teil-(zeit-)intervalle                   ********/
    /* *******************************************  NEXT SPLIT TIME INTERVAL ************ */

    /* Strahlungssumme aller Teilintervalle wieder wegdividieren,
       also den effektiven Faktor, das eigentliche Ergebniss dieses Teilmodells,
       errechnen */

    for (i=1; i<=nrows; i++)
        for (j=1; j<=ncols; j++) {
            SHADE[i][j]  = SHADE[i][j]/split;     /*mittlere Beschattung des time steps*/
            EXKORR[i][j] = strlsumme[i][j] > 0.0 ?  DIRECT[i][j]/strlsumme[i][j] : 0.;
            /*correction factor is the ratio of corrected rad to uncorrected radiation*/
            DIRECT[i][j] = DIRECT[i][j]/timestep;     /*solar rad in W/m2 */

        }

    /*climate station grid must be assumed to be horizontal for calculation of ratio glob/direct */
    exkorstationhoriz = strlsumme[rowclim][colclim] > 0.0 ?
                        directstationhoriz/strlsumme[rowclim][colclim] : 0 ;
    directstationhoriz = (directstationhoriz/timestep);

    /* $$$ *********/
    if (subintfileyes == 1) {
        printf("\n\t  EXKORR = %6.2f strlsume= %6.2f, SHADE= %4.2f,   %d %d",
               EXKORR[rowclim][colclim],strlsumme[rowclim][colclim],
               SHADE[rowclim][colclim],rowclim,colclim);
    }
    /* $$$ *********/

    return;

}
コード例 #11
0
ファイル: 2ac_functFreq.c プロジェクト: gentnerlab/operant_c
/**********************************************************************
*                           MAIN
**********************************************************************/	
int main(int argc, char *argv[])
{
	FILE *stimfp = NULL, *datafp = NULL, *dsumfp = NULL;
	char *stimfname = NULL;
	char *stimfroot, *pcm_name, *entseq=NULL, tmpExemplar[1024];
	const char delimiters[] = " .,;:!-";
	char datafname[1024], hour[16], min[16], month[16],day[16], year[16], dsumfname[1024], stimftemp[1024],outsf[1024];
	char  buf[1024], stimexm[1024],fstim[1024], timebuff[64], tod[256], date_out[256], buffer[30],temphour[16],tempmin[16];
	int stim_class, resp_sel, resp_acc, subjectid, period, foo; 
	int played, resp_wind=0,trial_num, session_num, i,j, correction, loop, stim_number; 
	int dosunrise=0,dosunset=0,starttime,stoptime,currtime, tmpClass=0, mindx=0,cindx=0;
	long unsigned int tmpDur=0;
	
	float timeout_val=0.0, resp_rxt=0.0, tmpHit=0.0;
	int respwin_sec, respwin_usec, resp_sec, resp_usec;  /* debugging variables */
	int nstims=0, nclasses=0;
	int motmax =1, motmin=1, prbrate=0, CRf=0, XRf=0, prbRf=0, prbTO=0;
	int ret, do_prb, nprbclasses=0;


	float latitude = 32.82, longitude = 117.14;
	time_t curr_tt, rise_tt, set_tt;
	struct timeval stimoff,stimon, resp_window, resp_lag, resp_rt, stim_dur;
	struct tm *loctime;
	Failures f = {0,0,0,0};
	int left = 0, right= 0, center = 0, fed = 0;
	int reinfor_sum = 0, reinfor = 0;
	sigset_t trial_mask; 

	Seqstim seqstims[MAXCLASS], *pseqstims;

	struct resp{
	  int left;
	  int right;
	  int no;
	  int count;
	  float p_left;
	  float p_right;
	}classRses[MAXCLASS], classRtot[MAXCLASS];

	srand (time (0) );
       
	/* set up termination handler*/
	if (signal(SIGPIPE, sig_pipe) == SIG_ERR){
	  perror("error installing signal handler for SIG_PIPE");
	  exit (-1);
	}

	sigemptyset (&trial_mask);
	sigaddset (&trial_mask, SIGINT);
	sigaddset (&trial_mask, SIGTERM);
	signal(SIGTERM, termination_handler);
	signal(SIGINT, termination_handler);


	/* Parse the command line */
        command_line_parse(argc,argv,&box_id,&subjectid,&starthour,&stophour,&startmin,&stopmin,
			   &resp_wind,&timeout_val,&stimfname,
			   &prbrate,&CRf,&XRf,&prbRf,&prbTO); 
       	if(DEBUG){
	  fprintf(stderr, "command_line_parse(): box_id=%d, subjectid=%d, startH=%d, stopH=%d, startM=%d, stopM=%d, xresp=%d, resp_wind=%d, do_rand_start=%d, timeout_val=%f flash=%d stimfile:%s, prbrate=%d, CRf=%d, XRf=%d, prbRf=%d, prbTO=%d, motmax=%d, motmin=%d\n",
		  box_id, subjectid, starthour, stophour, startmin, stopmin, xresp, resp_wind, do_rand_start, timeout_val, flash, stimfname,
		  prbrate, CRf, XRf, prbRf, prbTO, motmax, motmin);
	}
	sprintf(pcm_name, "dac%i", box_id);
	if(DEBUG){fprintf(stderr,"dac: %s\n",pcm_name);}

	if(DEBUG){fprintf(stderr,"commandline done, now checking for errors\n");}
	
	/* watch for terminal errors*/
	if( (stophour!=99) && (starthour !=99) ){
	  if ((stophour <= starthour) && (stopmin<=startmin)){
	    fprintf(stderr, "\tTERMINAL ERROR: exp start-time must be greater than stop-time\n");
	    exit(-1);
	  } 
	}
	if (box_id <= 0){
	  fprintf(stderr, "\tYou must enter a box ID!\n"); 
	  fprintf(stderr, "\tERROR: try '2ac_entropy -help' for available options\n");
	  exit(-1);
	}
	if( (prbRf<0) || (prbTO<0) || (CRf<=0) || (XRf<=0) ){
	  fprintf(stderr, "\tYou must specify the reinforcemnt rate for all baseline and probe stimuli on the command line!\n"); 
	  fprintf(stderr, "\tERROR: try '2ac_entropy -help' for available options\n");
	  snd_pcm_close(handle);
	  exit(-1);
	}
	else if ((prbRf+prbTO)>100){
	  fprintf(stderr, "\tFATAL ERROR: The sum of the probe feed (prbRf) and timeout (prbTO) rates can't be greater than 100!\n"); 
	  snd_pcm_close(handle);
	  exit(-1);
	}
	if(motmax > MAXMOTSPERSEQ ){
	  fprintf(stderr, "\tyou can't have more than %d motifs in each sequence\n", MAXMOTSPERSEQ); 
	  fprintf(stderr, "\tERROR: try '2ac_entropy -help'\n");
	  snd_pcm_close(handle);
	  exit(-1);
	}


	/*set some variables as needed*/
	if (resp_wind>0)
	  respoff.tv_sec = resp_wind;
	fprintf(stderr, "response window duration set to %d secs\n", (int) respoff.tv_sec);	
	if(timeout_val>0.0)
	  timeout_duration = (int) (timeout_val*1000000);
	fprintf(stderr, "timeout duration set to %d microsecs\n", (int) timeout_duration);
	
	if(DEBUG){fprintf(stderr, "starthour: %d\tstartmin: %d\tstophour: %d\tstopmin: %d\n", starthour,startmin,stophour,stopmin);}
	
	curr_tt = time(NULL);
	loctime = localtime (&curr_tt);
	strftime (year, 16, "%Y", loctime);
	strftime(month, 16, "%m", loctime);
	strftime(day, 16,"%d", loctime);

	if(starthour==99){
	  dosunrise=1;
	  rise_tt = sunrise(atoi(year), atoi(month), atoi(day), latitude, longitude);
	  strftime(temphour, 16, "%H", localtime(&rise_tt));
	  strftime(tempmin, 16, "%M", localtime(&rise_tt));
	  starthour=atoi(temphour);
	  startmin=atoi(tempmin);
	  strftime(buffer,30,"%m-%d-%Y %H:%M:%S",localtime(&rise_tt));
	  printf("Sessions start at sunrise (Today: '%s')\n",buffer);
	}
	if(stophour==99){
	  dosunset=1;
	  set_tt = sunset(atoi(year), atoi(month), atoi(day), latitude, longitude);
	  strftime(temphour, 16, "%H", localtime(&set_tt));
	  strftime(tempmin, 16, "%M", localtime(&set_tt));
	  stophour=atoi(temphour);
	  stopmin=atoi(tempmin);
	  strftime(buffer,30,"%m-%d-%Y  %T",localtime(&set_tt));
	  printf("Sessions stop at sunset (Today: '%s')\n",buffer);
	}
	
	starttime=(starthour*60)+startmin;
	stoptime=(stophour*60)+stopmin;
	if(DEBUG){fprintf(stderr, "starthour: %d\tstartmin: %d\tstophour: %d\tstopmin: %d\n", starthour,startmin,stophour,stopmin);}

	/* Initialize box */
	if(DEBUG){
	  printf("Initializing box %d ...\n", box_id);
	  printf("trying to execute setup(%s)\n", pcm_name);
	}
	if((period= setup_pcmdev(pcm_name))<0){
	  fprintf(stderr,"FAILED to set up the pcm device %s\n", pcm_name);
	  exit (-1);}
	if (operant_open()!=0){
	  fprintf(stderr, "Problem opening IO interface\n");
	  snd_pcm_close(handle);
	  exit (-1);
	}
	operant_clear(box_id);
	if(DEBUG){printf("done\n");}

	/* give user some feedback*/
	fprintf(stderr, "Loading stimuli from file '%s' for session in box '%d' \n", stimfname, box_id); 
	fprintf(stderr, "Subject ID number: %i\n", subjectid);
	if(flash){fprintf(stderr, "!!WARNING: Flashing keylights during response window!!\n");}
	if(xresp){fprintf(stderr, "!!WARNING: Enabling correction trials for 'No' responses !!\n");}
	
	/* Read in the list of exmplars */
	if ((stimfp = fopen(stimfname, "r")) != NULL){
	  while (fgets(buf, sizeof(buf), stimfp))
	    nstims++;
	  fprintf(stderr, "Found %d stimulus exemplars in '%s'\n", nstims, stimfname);
	  rewind(stimfp);
	                
	  for (i = 0; i < nstims; i++){
	    fgets(buf, 128, stimfp);
	    tmpDur=0.0; mindx =0; cindx=0; 
	    if((ret=sscanf(buf, "%d\%s\%g", &tmpClass, tmpExemplar, &tmpHit)) != 3){
	      printf("ERROR: bad line in '.stim' file (read in '%s'\n", buf);
	      snd_pcm_close(handle);
	      exit(-1);
	    } 
	    if(DEBUG){fprintf(stderr, "\n%d %s\n", tmpClass, tmpExemplar);}
      
	    /* count total stim and probe classes*/
		/*NOTE: these counters only work if classes are numbered consecutively in the .stim file w/o any skips */
	    if (nclasses<tmpClass){  
	      nclasses=tmpClass;
	      if (DEBUG){printf("total number of stimlus classes set to: %d\n", nclasses);}
	    }
	    if((tmpClass>=3) && (nprbclasses<tmpClass-2)){ /*count the number of probe classes*/
		  nprbclasses=tmpClass-2;
		  if (DEBUG){fprintf(stderr,"number of probe classes set to %d\n", nprbclasses);}
	    }
			
		/*verify soundfile*/
	    sprintf(fstim,"%s%s", STIMPATH, tmpExemplar);  
	    if((tmpDur = verify_soundfile(fstim))<1){
		 fprintf(stderr, "Unable to verify %s!\n",fstim );  
		 snd_pcm_close(handle);
		 exit(0); 
		} 
	    if(DEBUG){printf("soundfile %s verified, duration: %lu \tclass: %d\n", tmpExemplar, tmpDur, tmpClass);}

		/*now load up the seqstims struct*/
		cindx = tmpClass-1;
		seqstims[cindx].count++;
		mindx = seqstims[cindx].count-1;
		seqstims[cindx].exemplar[mindx] = (malloc(sizeof (tmpExemplar)));   
	    memcpy(seqstims[cindx].exemplar[mindx], tmpExemplar, sizeof(tmpExemplar));
	    seqstims[cindx].hit[mindx]=tmpHit;
		if(DEBUG){fprintf(stderr,"seqstims[%d].exemplar[%d]: %s ", cindx, mindx, seqstims[cindx].exemplar[mindx]);}
		if (DEBUG){printf("occurs at sequence postion '%d' in %g%% of all sequences in class %d\n", mindx+1, seqstims[cindx].hit[mindx], cindx+1);}
	  }
	}
コード例 #12
0
ファイル: songchoice1.c プロジェクト: gentnerlab/operant_c
/**********************************************************************
 MAIN
**********************************************************************/	
int main(int argc, char *argv[]){
  if(DEBUG){fprintf(stderr, "start songchoice");}
  FILE *stimfp = NULL, *datafp = NULL, *dsumfp = NULL;
  char *stimfname = NULL;
  char *stimfroot, *tmpstr;
  const char delimiters[] = " .,;:!-";
  const char stereopcm [] = "doubledac";
  char datafname[128], hour[16], min[16], month[16],day[16], year[16], dsumfname[128], stimftemp[128], pcm_name[128];
  char  buf[256],distexm[128],targetloc[128],stimexm[128],fstim[256], fdist [256],timebuff[64],buffer[30],*bplist= NULL,
    temphour[16],tempmin[16],tod[256], date_out[256];
  int nclasses, nstims, stim_class, stim_reinf, stim_punish, stim_nbps, resp_sel, resp_acc, subjectid, period, tot_trial_num,
    played, resp_wind=0,trial_num, session_num, i,j,k, correction, playval, distval, loop,stim_number,targloc, nbps,minlength,
    *playlist=NULL, totnstims=0,dosunrise=0,dosunset=0,starttime,stoptime,currtime,doprobes,dist_number,breakval;
  float timeout_val=0.0, resp_rxt=0.0, breakpoint = 0.0, cueint = 0.0, targlength = 0.0;
  int stimoff_sec, stimoff_usec, respwin_sec, respwin_usec, resp_sec, resp_usec;  /* debugging variables */
  float latitude = 32.82, longitude = 117.14;
  time_t curr_tt, rise_tt, set_tt;
  struct timeval stimoff, resp_window, resp_lag, resp_rt;
  struct tm *loctime;
  Failures f = {0,0,0,0};
  int left = 0, right= 0, center = 0, fed = 0;
  int reinfor_sum = 0, reinfor = 0;
  float probeCO=68.0;
  SNDFILE *sf;
  SF_INFO *sfinfo;
  struct stim {
    char exemplar[128];
    float breakpt[MAXBP];
    int reinf;
    int punish;
    int freq;
    int nbps;
    unsigned long int dur; 
    int num;
  }stimulus[MAXSTIM];
  struct resp{
    int C;
    int X;
    int no;
    int CbyBP[MAXBP];
    int XbyBP[MAXBP];
    int nobyBP[MAXBP];
    int countbyBP[MAXBP];
    int left;
    int center;
    int right;
    int count;
  }Rstim[MAXSTIM], Tstim[MAXSTIM];
  
  sigset_t trial_mask;
  
  srand (time (0) );
  if(DEBUG){fprintf(stderr, "start songchoice");}
  
  /* set up termination handler*/
  if (signal(SIGPIPE, sig_pipe) == SIG_ERR){
    perror("error installing signal handler for SIG_PIPE");
    exit (-1);
  }
  
  sigemptyset (&trial_mask);
  sigaddset (&trial_mask, SIGINT);
  sigaddset (&trial_mask, SIGTERM);
  signal(SIGTERM, termination_handler);
  signal(SIGINT, termination_handler);
  
  
  /* Parse the command line */
  command_line_parse(argc, argv, &box_id, &subjectid, &starthour, &stophour, &startmin, &stopmin, &resp_wind, &timeout_val, &targlength, &cueint, &stimfname); 
  if(DEBUG){
    fprintf(stderr, "command_line_parse(): box_id=%d, subjectid=%d, startH=%d, stopH=%d, startM=%d, stopM=%d, resp_wind=%d, timeout_val=%f, targlength=%f, cueint=%f, stimfile:%s",    box_id, subjectid, starthour, stophour, startmin, stopmin, resp_wind, timeout_val, targlength, cueint, stimfname);
  }
  sprintf(pcm_name, "%s", stereopcm);
  if(DEBUG){fprintf(stderr,"dac: %s\n",pcm_name);}
  
  if(DEBUG){fprintf(stderr,"commandline done, now checking for errors\n");}
  
  /* watch for terminal errors*/
  if( (stophour!=99) && (starthour !=99) ){
    if ((stophour <= starthour) && (stopmin<=startmin)){
      fprintf(stderr, "\tTERMINAL ERROR: exp start-time must be greater than stop-time\n");
      exit(-1);
    } 
  }
  if (box_id <= 0){
    fprintf(stderr, "\tYou must enter a box ID!\n"); 
    fprintf(stderr, "\tERROR: try 'SONGCHOICE -help' for available options\n");
    exit(-1);
  }
  
  /* set some variables as needed*/
  if (resp_wind>0)
    respoff.tv_sec = resp_wind;
  fprintf(stderr, "response window duration set to %d secs\n", (int) respoff.tv_sec);	
  if(timeout_val>0.0)
    timeout_duration = (int) (timeout_val*1000000);
  fprintf(stderr, "timeout duration set to %d microsecs\n", (int) timeout_duration);
  if(targlength>0.0)
    target_duration = (int) (targlength*1000000);
  fprintf(stderr, "timeout duration set to %d microsecs\n", (int) target_duration);
  if(cueint>0.0)
    cue_stim_interval = cueint;
  fprintf(stderr, "timeout duration set to %f seconds\n", cue_stim_interval);

  if(DEBUG){fprintf(stderr, "starthour: %d\tstartmin: %d\tstophour: %d\tstopmin: %d\n", starthour,startmin,stophour,stopmin);}
  
  curr_tt = time(NULL);
  loctime = localtime (&curr_tt);
  strftime (year, 16, "%Y", loctime);
  strftime(month, 16, "%m", loctime);
  strftime(day, 16,"%d", loctime);
  
  if(starthour==99){
    dosunrise=1;
    rise_tt = sunrise(atoi(year), atoi(month), atoi(day), latitude, longitude);
    strftime(temphour, 16, "%H", localtime(&rise_tt));
    strftime(tempmin, 16, "%M", localtime(&rise_tt));
    starthour=atoi(temphour);
    startmin=atoi(tempmin);
    strftime(buffer,30,"%m-%d-%Y %H:%M:%S",localtime(&rise_tt));
    printf("Sessions start at sunrise (Today: '%s')\n",buffer);
  }
  if(stophour==99){
    dosunset=1;
    set_tt = sunset(atoi(year), atoi(month), atoi(day), latitude, longitude);
    strftime(temphour, 16, "%H", localtime(&set_tt));
    strftime(tempmin, 16, "%M", localtime(&set_tt));
    stophour=atoi(temphour);
    stopmin=atoi(tempmin);
    strftime(buffer,30,"%m-%d-%Y  %T",localtime(&set_tt));
    printf("Sessions stop at sunset (Today: '%s')\n",buffer);
  }
  
  starttime=(starthour*60)+startmin;
  stoptime=(stophour*60)+stopmin;
  if(DEBUG){fprintf(stderr, "starthour: %d\tstartmin: %d\tstophour: %d\tstopmin: %d\n", starthour,startmin,stophour,stopmin);}
  
  /* Initialize box */
  if(DEBUG){
    printf("Initializing box %d ...\n", box_id);
    printf("trying to execute setup(%s)\n", pcm_name);
  }
  if((period= setup_pcmdev(pcm_name))<0){
    fprintf(stderr,"FAILED to set up the pcm device %s\n", pcm_name);
    exit (-1);}
  if (operant_open()!=0){
    fprintf(stderr, "Problem opening IO interface\n");
    snd_pcm_close(handle);
    exit (-1);
  }
  operant_clear(box_id);
  if(DEBUG){printf("done\n");}
  
  /* give user some feedback*/
  fprintf(stderr, "Loading stimuli from file '%s' for session in box '%d' \n", stimfname, box_id); 
  fprintf(stderr, "Subject ID number: %i\n", subjectid);
  if(flash){fprintf(stderr, "!!WARNING: Flashing keylights during response window!!\n");}
  if(xresp){fprintf(stderr, "!!WARNING: Enabling correction trials for 'No' responses !!\n");}
  
  /* Read in the list of exemplars */
  nstims = 0;
  if ((stimfp = fopen(stimfname, "r")) != NULL){
    while (fgets(buf, sizeof(buf), stimfp))
      nstims++;
    fprintf(stderr, "Found %d stimulus exemplars in '%s'\n", nstims, stimfname);
    rewind(stimfp);
    for (i = 0; i < nstims; i++){
      fgets(buf, 128, stimfp);
      stimulus[i].freq = stimulus[i].reinf=0;
      sscanf(buf, "%s\%d\%d\%d", 
	     stimulus[i].exemplar, &stimulus[i].freq, &stimulus[i].reinf, &stimulus[i].punish);
      bplist = strstr(buf, "0.00");
      /* Parse break points */
      if (bplist == NULL){
	fprintf(stderr,"ERROR: cannot read breakpoints. Try 'SONGCHOICE -help'\n");}
      else{	
	tmpstr = strtok (bplist," ");
	j=0;
	nbps = 0;
	while (tmpstr != NULL)	   {
	  tmpstr = strtok (NULL, " ");
	  if (tmpstr != NULL)	   {
	    if(DEBUG){fprintf(stderr,"%s", tmpstr);}
	    sscanf(tmpstr, "%f\t",  &stimulus[i].breakpt[j]);
	    if(DEBUG){fprintf(stderr,"%1.2f",stimulus[i].breakpt[j]);}
	    j++;
	    nbps++;
	  }	  
	}
	if(DEBUG){fprintf(stderr," %i", nbps);}
	stimulus[i].nbps = nbps;        
      }
      if((stimulus[i].freq==0) || (stimulus[i].reinf==0)|| (stimulus[i].punish==0)){
	fprintf(stderr,"%i, %i, %i\n", stimulus[i].freq, stimulus[i].reinf, stimulus[i].punish);
	fprintf(stderr,"ERROR: insufficient data or bad format in '.stim' file. Try 'SONGCHOICE -help'\n");
	exit(0);} 
      totnstims += stimulus[i].freq;
      if(DEBUG){fprintf(stderr,"totnstims: %d\n", totnstims);}
      
      
      /*check the reinforcement rates */
      fprintf(stderr, "Reinforcement rate for %s is set to %d%% for correct responses\n", 
	      stimulus[i].exemplar, stimulus[i].reinf);
      fprintf(stderr, "Punishment rate for %s is set to %d%% for incorrect responses\n", 
	      stimulus[i].exemplar, stimulus[i].punish);    
    }
  }
  else{
    fprintf(stderr,"Error opening stimulus input file! Try 'SONGCHOICE -help' for proper file formatting.\n");  
    snd_pcm_close(handle);
    exit(0);     
  }
  fclose(stimfp);
  if(DEBUG){printf("Done reading in stims; %d stims found\n", nstims);}
  
  /* Check stim files and determine min song length - must allow sufficient time for targets and distractors */
  minlength = MAXFILESIZE;
  for (i = 0; i<nstims; i++){
    strcpy (stimexm, stimulus[i].exemplar);                       /* get exemplar filename */  
    sprintf(fstim,"%s%s", STIMPATH, stimexm);
    /* memory for SF_INFO structures */
    sfinfo = (SF_INFO *) malloc(sizeof(SF_INFO));
    /* open input files*/
    if(!(sf = sf_open(fstim,SFM_READ,sfinfo))){
      fprintf(stderr,"error opening input file %s\n", stimexm);
      return -1;
    }
    if (DEBUG){
      /*  print out some info about the file one */
      fprintf(stderr,"\n ---------- Stimulus parameters from playwav ------------ \n");
      fprintf (stderr, "    Samples: %d\n", (int)sfinfo->frames) ;
      fprintf (stderr, "Sample Rate: %d\n", sfinfo->samplerate) ;
      fprintf (stderr, "   Channels: %d\n", sfinfo->channels) ;
    }
    /* check that some assumptions are met */
    if (sfinfo->frames > MAXFILESIZE){
      fprintf(stderr,"%s is too large!\n", stimexm);
      sf_close(sf);
      return -1;
    }
    else if (sfinfo->frames < minlength)
      minlength = sfinfo->frames;
    if (sfinfo->samplerate != 44100){
      fprintf(stderr, "Sample rate for %s is not equal to 44.1 KHz!\n", stimexm);
      sf_close(sf);
      return -1;
    }
    if (sfinfo->channels != 1){
      fprintf(stderr, "Sound file %s is not mono!\n", stimexm);
      sf_close(sf);
      return -1;
    }
    if ((sfinfo->format & SF_FORMAT_TYPEMASK) != SF_FORMAT_WAV ){
      fprintf(stderr, "Sound file %s is not in wav format!\n", stimexm);
      sf_close(sf);
      return -1;
    }
    sf_close(sf);
    free(sfinfo);
  }
  /* check probe times */
    
  /* Don't allow correction trials when probe stimuli are presented */
  if(xresp==1 && doprobes==1){
    fprintf(stderr, "ERROR!: You cannot use correction trials and probe stimuli in the same session.\n  Exiting now\n");
    snd_pcm_close(handle);
    exit(-1);
  }
  
  /* build the stimulus playlist */
  if(DEBUG){printf("flag: making the playlist\n");}
  free(playlist);
  playlist = malloc( (totnstims+1)*sizeof(int) );
  i=j=0;
  for (i=0;i<nstims; i++){
    k=0;
    for(k=0;k<stimulus[i].freq;k++){
      playlist[j]=i;
      if(DEBUG){printf("value for playlist entry '%d' is '%d'\n", j, i);}
      j++;
    }
  }
  if(DEBUG){printf("there are %d stims in the playlist\n", totnstims);}
  
  /*  Open & setup data logging files */
  curr_tt = time (NULL);
  loctime = localtime (&curr_tt);
  strftime (timebuff, 64, "%d%b%y", loctime);
  sprintf (stimftemp, "%s", stimfname);
  stimfroot = strtok (stimftemp, delimiters);
  sprintf(datafname, "%i_%s.SC_rDAT", subjectid, stimfroot);
  sprintf(dsumfname, "%i.SCsummaryDAT", subjectid);
  datafp = fopen(datafname, "a");
  dsumfp = fopen(dsumfname, "w");
  
  if ( (datafp==NULL) || (dsumfp==NULL) ){
    fprintf(stderr, "ERROR!: problem opening data output file!: %s\n", datafname);
    snd_pcm_close(handle);
    fclose(datafp);
    fclose(dsumfp);
    exit(-1);
  }
  
  /* Write data file header info */
  fprintf (stderr,"Data output to '%s'\n", datafname);
  fprintf (datafp, "File name: %s\n", datafname);
  fprintf (datafp, "Procedure source: %s\n", exp_name);
  fprintf (datafp, "Start time: %s", asctime(loctime));
  fprintf (datafp, "Subject ID: %d\n", subjectid);
  fprintf (datafp, "Stimulus source: %s\n", stimfname);
  fprintf (datafp, "Sess#\tTrl#\tStimulus\t\t\tBreakPt\tCueSrc\tR_sel\tR_acc\tRT\tReinf\tTOD\tDate\n");
  
  /********************************************
    +++++++++++ Trial sequence ++++++++++++++
  ********************************************/
  session_num = 1;
  trial_num = 0;
  tot_trial_num = 0;
  correction = 1;
  
  /*zero out the response tallies */
  for(i = 0; i<nstims;++i){
    Rstim[i].C =  Rstim[i].no = Rstim[i].X = Rstim[i].count = 0;
    Tstim[i].C = Tstim[i].no = Tstim[i].X = Tstim[i].count = 0;
    for(j = 0; j<stimulus[i].nbps; ++j){
       Rstim[i].CbyBP[j] =  Rstim[i].nobyBP[j] = Rstim[i].XbyBP[j] = Rstim[i].countbyBP[j] = 0;
       Tstim[i].CbyBP[j] =  Tstim[i].nobyBP[j] = Tstim[i].XbyBP[j] = Tstim[i].countbyBP[j] = 0;
    }
  }
  curr_tt = time(NULL);
  loctime = localtime (&curr_tt);
  strftime (hour, 16, "%H", loctime);
  strftime(min, 16, "%M", loctime);
  if (DEBUG){printf("hour:min at loop start: %d:%d \n", atoi(hour),atoi(min));}
  currtime=(atoi(hour)*60)+atoi(min);
	
  operant_write (box_id, HOUSELT, 1);        /* make sure houselight is on */

  do{                                                                               /* start the main loop */
    while ((currtime>=starttime) && (currtime<stoptime)){                          /* start main trial loop */
      if (DEBUG){printf("minutes since midnight at loop start: %d\t starttime: %d\tstoptime: %d\n",currtime,starttime,stoptime);}
      srand(time(0));

      /* select stim exemplar at random */
      playval = (int) ((totnstims+0.0)*rand()/(RAND_MAX+0.0));
      if (DEBUG){printf(" %d\t", playval);}
      stim_number = playlist[playval];
      stim_nbps = stimulus[stim_number].nbps;
      strcpy (stimexm, stimulus[stim_number].exemplar);                       /* get exemplar filename */
      stim_reinf = stimulus[stim_number].reinf;
      stim_punish = stimulus[stim_number].punish;
      sprintf(fstim,"%s%s", STIMPATH, stimexm);                                /* add full path to file name */

      /* select a break point from target */
      breakval = (int) ((stim_nbps+0.0)*rand()/(RAND_MAX+0.0));
      breakpoint = stimulus[stim_number].breakpt[breakval];

      /* select stim distractor at random */
      distval = playval;
      while (distval == playval)
	distval = (int) ((totnstims+0.0)*rand()/(RAND_MAX+0.0));
      dist_number = playlist[distval];
      strcpy(distexm, stimulus[dist_number].exemplar);
      sprintf(fdist,"%s%s", STIMPATH, distexm);                                /* add full path to file name */
          
      /* select a target source at random */
      targloc = 1+(int) (2*rand()/(RAND_MAX+1.0));
      if (targloc == 1){
	/* target source is right */
	sprintf(targetloc, "right");}
      else if (targloc == 2) {
	/* target source is left */
	sprintf(targetloc, "left");}
      else{
	printf("ERROR: incorrect cue choice\n");
	exit(0);}
      if(DEBUG){fprintf(stderr, "target is on %s\n", targetloc);}
        
      do{                                             /* start correction trial loop */
	left = right = center = 0;                    /* zero trial peckcounts       */
	resp_sel = resp_acc = resp_rxt = 0;           /* zero trial variables        */
	++trial_num;++tot_trial_num;
	
	/* Wait for center key press */
	if (DEBUG){printf("\n\nWaiting for center  key press\n");}
	operant_write (box_id, HOUSELT, 1);        /* house light on */
	right=left=center=0;
	do{
	  nanosleep(&rsi, NULL);
	  center = operant_read(box_id, CENTERPECK);   /*get value at center response port*/
	}while (center==0);

	sigprocmask (SIG_BLOCK, &trial_mask, NULL);     /* block termination signals*/
		
	/* play the stimulus*/
	if (DEBUG){fprintf(stderr,"start sound file\n");}
	if (DEBUG){fprintf(stderr, "tying to playstereo with target: %s, distractor : %s, cue length: %f, target location:'%s', cue-stim interval: %1.2f\n",
			   stimexm, distexm, breakpoint, targetloc, cue_stim_interval ); }
	played = playstereo(fstim, fdist, breakpoint, targlength, targloc, cue_stim_interval, period);
	if (DEBUG){fprintf(stderr, "played: %d\n", played);}
	if(played != 1){
	  fprintf(stderr, "playwav failed on pcm:%s stimfile:%s. Program aborted %s\n",
		  pcm_name, stimexm, asctime(localtime (&curr_tt)) );
	  fclose(datafp);
	  fclose(dsumfp);
	  exit(-1);
	}
	if (DEBUG){fprintf(stderr,"stop sound file\n");}
	gettimeofday(&stimoff, NULL);
	if (DEBUG){
	  stimoff_sec = stimoff.tv_sec;
	  stimoff_usec = stimoff.tv_usec;
	  fprintf(stderr,"stim_off sec: %d \t usec: %d\n", stimoff_sec, stimoff_usec);}
	
	/* Wait for response */
	if (DEBUG){fprintf(stderr, "flag: waiting for right/left response\n");}
	timeradd (&stimoff, &respoff, &resp_window);
	if (DEBUG){respwin_sec = resp_window.tv_sec;}
	if (DEBUG){respwin_usec = resp_window.tv_usec;}
	if (DEBUG){fprintf(stderr,"resp window sec: %d \t usec: %d\n", respwin_sec, respwin_usec);}
	
	loop=left=right=center=0;
	do{
	  nanosleep(&rsi, NULL);
	  left = operant_read(box_id, LEFTPECK);
	  right = operant_read(box_id, RIGHTPECK );
	  center = operant_read(box_id, CENTERPECK);
	  if((left==0) && (right==0) && (center==0) && flash){
	    ++loop;
	    if(loop%80==0){
	      if(loop%160==0){
		operant_write (box_id, LFTKEYLT, 1);
		operant_write (box_id, RGTKEYLT, 1);
	      }
	      else{
		operant_write (box_id, LFTKEYLT, 0);
		operant_write (box_id, RGTKEYLT, 0);
	      }
	    }
	  }
	  gettimeofday(&resp_lag, NULL);
	  if (DEBUG==2){printf("flag: value at right=%d, left=%d, center=%d\t", right, left, center);}
	}while ( (left==0) && (right==0) && (center==0) && (timercmp(&resp_lag, &resp_window, <)) );
                   
	operant_write (box_id, LFTKEYLT, 0);    /*make sure the key lights are off after resp interval*/
	operant_write (box_id, RGTKEYLT, 0);
	operant_write (box_id, CTRKEYLT, 0);

	/* Calculate response time */
	curr_tt = time (NULL);
	loctime = localtime (&curr_tt);                     /* date and wall clock time of resp */
	timersub (&resp_lag, &stimoff, &resp_rt);           /* reaction time */
	if (DEBUG){resp_sec = resp_rt.tv_sec;}
	if (DEBUG){ resp_usec = resp_rt.tv_usec;}
	if (DEBUG){printf("resp rt sec: %d \t usec: %d\n", resp_sec, resp_usec);}
	resp_rxt = (float) resp_rt.tv_sec + ( (float) resp_rt.tv_usec/1000000);  /* format reaction time */
	if (DEBUG){printf("flag: resp_rxt = %.4f\n", resp_rxt);}
	
	strftime (hour, 16, "%H", loctime);                    /* format wall clock times */
	strftime (min, 16, "%M", loctime);
	strftime (month, 16, "%m", loctime);
	strftime (day, 16, "%d", loctime);
	
	
	/* Consequate responses */
	if (DEBUG){printf("flag: stim_class = %d\n", stim_class);}
	if (DEBUG){printf("flag: exit value left = %d, right = %d\n", left, right);}
	
	if(targloc == 1){ /* go right */
	  if  ((left==0 ) && (right==1) && (center==0)){ /* correct, went right */
	    resp_sel = 2;
	    resp_acc = 1;
	    ++Rstim[stim_number].C; ++Tstim[stim_number].C;
	    ++Rstim[stim_number].CbyBP[breakval]; ++Tstim[stim_number].CbyBP[breakval];
	    ++Rstim[stim_number].right;++Tstim[stim_number].right;
	    reinfor=feed(stim_reinf, &f);
	    if (reinfor == 1) { ++fed;}
	    if (DEBUG){ printf("flag: correct response to stimtype 2\n");}
	  }
	  else if (left == 1){ /* incorrect, went left */
	    resp_sel = 1;
	    resp_acc = 0;
	    ++Rstim[stim_number].X;++Tstim[stim_number].X;
	    ++Rstim[stim_number].XbyBP[breakval]; ++Tstim[stim_number].XbyBP[breakval];
	    ++Rstim[stim_number].left;++Tstim[stim_number].left;
	    reinfor =  timeout(stim_punish);
	    if (DEBUG){printf("flag: left response to right target, lights out\n");}
	  }
	  else if (center == 1){ /* incorrect, went center - NOTE: CURRENTLY NO PENALTY FOR CENTER RESPONSE*/
	    resp_sel = 0;
	    resp_acc = 0;
	    ++Rstim[stim_number].X;++Tstim[stim_number].X;
	    ++Rstim[stim_number].XbyBP[breakval]; ++Tstim[stim_number].XbyBP[breakval];
	    ++Rstim[stim_number].center;++Tstim[stim_number].center;
	    reinfor = 0;
	    if (DEBUG){printf("flag: center response to right target, no punishment\n");}
	  }
	  else{
	    resp_sel = -1;
	    resp_acc = 2;
	    ++Rstim[stim_number].no;++Tstim[stim_number].no;
	    ++Rstim[stim_number].nobyBP[breakval]; ++Tstim[stim_number].nobyBP[breakval];
	    reinfor = 0;
	    if (DEBUG){printf("flag: no response to right target\n");}
	    fprintf(datafp, "DEFAULT SWITCH for bit value:ERROR CODE REMOVED");
	  }
	}
	else if (targloc == 2){
	  if  ((left==1 ) && (right== 0) && (center==0)){ /* correct, went left */
	    resp_sel = 1;
	    resp_acc = 1;
	    ++Rstim[stim_number].C; ++Tstim[stim_number].C;
	    ++Rstim[stim_number].CbyBP[breakval]; ++Tstim[stim_number].CbyBP[breakval];
	    ++Rstim[stim_number].left;++Tstim[stim_number].left;
	    reinfor=feed(stim_reinf, &f);
	    if (reinfor == 1) { ++fed;}
	    if (DEBUG){ printf("flag: correct response to left target\n");}
	  }
	  else if (right == 1){ /* incorrect, went right */
	    resp_sel = 2;
	    resp_acc = 0;
	    ++Rstim[stim_number].X;++Tstim[stim_number].X;
	    ++Rstim[stim_number].XbyBP[breakval]; ++Tstim[stim_number].XbyBP[breakval];
	    ++Rstim[stim_number].right;++Tstim[stim_number].right;
	    reinfor =  timeout(stim_punish);
	    if (DEBUG){printf("flag: right response to left target, lights out\n");}
	  }
	  else if (center == 1){ /* incorrect, went center - NOTE: CURRENTLY NO PENALTY FOR CENTER RESPONSE*/
	    resp_sel = 0;
	    resp_acc = 0;
	    ++Rstim[stim_number].X;++Tstim[stim_number].X;
	    ++Rstim[stim_number].XbyBP[breakval]; ++Tstim[stim_number].XbyBP[breakval];
	    ++Rstim[stim_number].center;++Tstim[stim_number].center;
	    reinfor = 0;
	    if (DEBUG){printf("flag: center response to left target, no punishment\n");}
	    
	  }
	  else{
	    resp_sel = -1;
	    resp_acc = 2;
	    ++Rstim[stim_number].no;++Tstim[stim_number].no;
	    ++Rstim[stim_number].nobyBP[breakval]; ++Tstim[stim_number].nobyBP[breakval];
	    reinfor = 0;
	    if (DEBUG){printf("flag: no response to left target\n");}
	    fprintf(datafp, "DEFAULT SWITCH for bit value:ERROR CODE REMOVED");
	  }
	}
	else{
	  fprintf(stderr, "Unrecognized stimulus class: Fatal Error");
	  fclose(datafp);
	  fclose(dsumfp);
	  exit(-1);
	}	
	
	/* Pause for ITI */
	reinfor_sum = reinfor + reinfor_sum;
	operant_write(box_id, HOUSELT, 1);         /* make sure the houselight is on */
	nanosleep(&iti, NULL);                                   /* wait intertrial interval */
	if (DEBUG){printf("flag: ITI passed\n");}
	
	/* Write trial data to output file */
	strftime (tod, 256, "%H%M", loctime);
	strftime (date_out, 256, "%m%d", loctime);
	fprintf(datafp, "%d\t%d\t%d\t%s\t\t%s\t%d\t%d\t%d\t%.4f\t%d\t%s\t%s\n", session_num, trial_num, 
		correction, stimexm, distexm, stim_class, resp_sel, resp_acc, resp_rxt, reinfor, tod, date_out );
	fflush (datafp);
	
	if (DEBUG){printf("flag: trial data written\n");}
	/*generate some output numbers*/
	for (i = 0; i<nstims; i++){
	  Rstim[i].count = Rstim[i].X + Rstim[i].C + Rstim[i].no;
	  Tstim[i].count = Tstim[i].X + Tstim[i].C + Tstim[i].no;
	  for (j = 0; j<stimulus[j].nbps; j++){
	    Rstim[i].countbyBP[j] = Rstim[i].XbyBP[j] + Rstim[i].CbyBP[j] + Rstim[i].nobyBP[j];
	    Tstim[i].countbyBP[j] = Tstim[i].XbyBP[j] + Tstim[i].CbyBP[j] + Tstim[i].nobyBP[j];
	  }
	}
	
	/* Update summary data */
	
	if(freopen(dsumfname,"w",dsumfp)!= NULL){
	  fprintf (dsumfp, "          SUMMARY DATA FOR st%d, %s\n", subjectid, exp_name);
	  fprintf (dsumfp, "\tPERCENT CORRECT RESPONSES (by stim, including correction trials and no response trials)\n");
	  fprintf (dsumfp, "\tStim\t\tCount\tToday     \t\tCount\tTotals\n");
	  for (i = 0; i<nstims;++i){
	    fprintf (dsumfp, "\t%s\t%d\t%1.4f     \t\t%d\t%1.4f\n",
		     stimulus[i].exemplar, Rstim[i].count, (float)Rstim[i].C/(float)Rstim[i].count, Tstim[i].count, (float)Tstim[i].C/(float)Tstim[i].count );
	  }
	  fprintf(stderr, "nstims: %d ", nstims);
	  for (i = 0; i<nstims; ++i){
	    fprintf (dsumfp, "\tTrials by Probe Time for %s\n", stimulus[i].exemplar );
	    fprintf (dsumfp, "\tProbe Time\t\tCount\tToday     \tProbe Time\tCount\tTotals\n");
	    for (j = 0; j<stimulus[i].nbps; ++j){
	      fprintf (dsumfp, "\t%1.2f\t%d\t%1.4f     \t\t%d\t%1.4f\n",
		       stimulus[i].breakpt[j], Rstim[i].countbyBP[j], (float)Rstim[i].CbyBP[j]/(float)Rstim[i].countbyBP[j],
		       Tstim[i].countbyBP[j], (float)Tstim[i].CbyBP[j]/(float)Tstim[i].countbyBP[j] );
	    }
	  }
	  fprintf (dsumfp, "Last trial run @: %s\n", asctime(loctime) );
	  fprintf (dsumfp, "Trials this session: %d\n",trial_num);
	  fprintf (dsumfp, "Feeder ops today: %d\n", fed );
	  fprintf (dsumfp, "Hopper failures today: %d\n", f.hopper_failures);
	  fprintf (dsumfp, "Hopper won't go down failures today: %d\n",f.hopper_wont_go_down_failures);
	  fprintf (dsumfp, "Hopper already up failures today: %d\n",f.hopper_already_up_failures);
	  fprintf (dsumfp, "Responses during feed: %d\n", f.response_failures);
	  fprintf (dsumfp, "Rf'd responses: %d\n\n", reinfor_sum);
	  fflush (dsumfp);
	  
	}
	else
	  fprintf(stderr, "ERROR!: problem re-opening summary output file!: %s\n", dsumfname);
	
	
	if (DEBUG){printf("flag: summaries updated\n");}
	
	
	
	/* End of trial chores */
	sigprocmask (SIG_UNBLOCK, &trial_mask, NULL);                  /* unblock termination signals */
	if (resp_acc == 0){
	  correction = 0;}
	else if (resp_acc == 0){
	  correction = 0;}
	else
	  correction = 1;                                              /* set correction trial var */
	if ((xresp==1)&&(resp_acc == 2)){
	  correction = 0;}                                             /* set correction trial var for no-resp */
	fprintf(stderr, "probeCO=%f, correction=%i\n", probeCO, correction);
	
	curr_tt = time(NULL);
	loctime = localtime (&curr_tt);
	strftime (hour, 16, "%H", loctime);
	strftime(min, 16, "%M", loctime);
	currtime=(atoi(hour)*60)+atoi(min);
	if (DEBUG){printf("minutes since midnight at trial end: %d\t starttime: %d\tstoptime: %d\n",currtime,starttime,stoptime);}
	
      }while ((correction==0)&&(trial_num<=trial_max)&&(currtime>=starttime)&&(currtime<stoptime)); /* correction trial loop */
      
      stim_number = -1;                                                /* reset the stim number for correct trial*/
    }                                                                  /* trial loop */
    
    /* You'll end up here if its night time or if you skip a day
       The latter only happens if the night window elapses between the time a stimulus is chosen
       and the time its actually played--i.e. if the subject doesn't initiates a cued trial during
       the night window, which is rare
    */

    
    /* Loop while lights out */
    if (DEBUG){printf("minutes since midnight: %d\t starttime: %d\tstoptime: %d\n",currtime,starttime,stoptime);}
    while( (currtime<starttime) || (currtime>=stoptime) ){
      operant_write(box_id, HOUSELT, 0);
      operant_write(box_id, FEEDER, 0);
      operant_write(box_id, LFTKEYLT, 0);
      operant_write(box_id, CTRKEYLT, 0);
      operant_write(box_id, RGTKEYLT, 0);
      operant_write(box_id, GREENLT, 0);
      operant_write(box_id, BLUELT, 0);
      operant_write(box_id, REDLT, 0);
      sleep (sleep_interval);
      curr_tt = time(NULL);
      loctime = localtime (&curr_tt);
      strftime (hour, 16, "%H", loctime);
      strftime (min, 16, "%M", loctime);
      currtime=(atoi(hour)*60)+atoi(min);
      if (DEBUG){printf("minutes since midnight: %d\t starttime: %d\tstoptime: %d\n",currtime,starttime,stoptime);}
    }
    operant_write(box_id, HOUSELT, 1);
    
    /*reset some vars for the new day */
    ++session_num;
    trial_num = 0;
    for(i = 0; i<nstims;++i){
      Rstim[i].C = Rstim[i].X = Rstim[i].count = Rstim[i].left = Rstim[i].center = Rstim[i].right = 0;
    }
    
    f.hopper_wont_go_down_failures = f.hopper_already_up_failures = f.hopper_failures =f.response_failures = fed = reinfor_sum = 0;
    
    /*figure new sunrise/set times*/
    curr_tt = time(NULL);
    loctime = localtime (&curr_tt);
    strftime (year, 16, "%Y", loctime);
    strftime(month, 16, "%m", loctime);
    strftime(day, 16,"%d", loctime);
    
    if(dosunrise){
      rise_tt = sunrise(atoi(year), atoi(month), atoi(day), latitude, longitude);
      strftime(temphour, 16, "%H", localtime(&rise_tt));
      strftime(tempmin, 16, "%M", localtime(&rise_tt));
      starthour=atoi(temphour);
      startmin=atoi(tempmin);
      strftime(buffer,30,"%m-%d-%Y %H:%M:%S",localtime(&rise_tt));
      if(DEBUG){fprintf(stderr,"Sessions start at sunrise(Today: '%s')\n",buffer);}
    }
    if(dosunset){
      set_tt = sunset(atoi(year), atoi(month), atoi(day), latitude, longitude);
      strftime(temphour, 16, "%H", localtime(&set_tt));
      strftime(tempmin, 16, "%M", localtime(&set_tt));
      stophour=atoi(temphour);
      stopmin=atoi(tempmin);
      strftime(buffer,30,"%m-%d-%Y  %T",localtime(&set_tt));
      if(DEBUG){fprintf(stderr,"Session stop at sunset(Today: '%s')\n",buffer);}
    }
    
    if(DEBUG){fprintf(stderr, "starthour: %d\tstartmin: %d\tstophour: %d\tstopmin: %d\n", starthour,startmin,stophour,stopmin);}
    
    
    
  }while (1);/*main trial loop*/
  
  
  /*  Cleanup */
  fclose(datafp);
  fclose(dsumfp);
  free(playlist);
  return 1;
}
コード例 #13
0
ファイル: risk.c プロジェクト: gentnerlab/operant_c
/******************************
 *    main                    *
 ******************************/
int main(int ac, char *av[])
{
  if(DEBUG){printf("into main\n");}
  int initstate, leftTime, rightTime, leftProb, rightProb;
  int i, subjectid, starthour, startmin, stophour, stopmin;
  int dosunrise=0, dosunset=0,starttime,stoptime;
  int lowProb=100, midProb=100, highProb=100; /*default risk per response port (completely equal, always yields reward)*/
  int lowTime, midTime,highTime;
  time_t curr_tt, rise_tt, set_tt;
  float latitude = 32.82, longitude = 117.14;
  char  timebuff[64],month[16],day[16], year[16], buffer[30],temphour[16],tempmin[16];

  srand ( time (0) );	
  
  /* Parse the command line */
  
  for (i = 1; i < ac; i++)
    {
      if (*av[i] == '-')
	{
	  if (strncmp(av[i], "-B", 2) == 0){ 
	    sscanf(av[++i], "%i", &box_id);
	    if(DEBUG){printf("box number = %d\n", box_id);}
	  }
	  else if (strncmp(av[i], "-S", 2) == 0){
	    sscanf(av[++i], "%i", &subjectid);
	    if(DEBUG){printf("subject ID number = %d\n", subjectid);}
	  }
      else if (strncmp(av[i], "-state", 4) == 0){
        sscanf(av[++i], "%i", &initstate);
	  }
      else if (strncmp(av[i], "-P", 2) == 0){
	    sscanf(av[++i], "%i:%i:%i", &lowProb, &midProb, &highProb);
	  }
      else if(strncmp(av[i], "-T", 2) == 0){
        sscanf(av[++i], "%i:%i:%i", &lowTime, &midTime, &highTime);
      }
	  else if (strncmp(av[i], "-on", 3) == 0)
	    sscanf(av[++i], "%i:%i", &starthour, &startmin);
	  else if (strncmp(av[i], "-off", 4) == 0)
	    sscanf(av[++i], "%i:%i", &stophour, &stopmin);
	  else if (strncmp(av[i], "-h", 2) == 0){
	    fprintf(stderr, "shape usage:\n");
	    fprintf(stderr, "    shape [-h] [-B x] [-T x] [-S x] \n\n");
	    fprintf(stderr, "     -h              = show this help message\n");
	    fprintf(stderr, "     -B int          = use '-B 1' '-B 2' ... '-B 12' for box 1-12\n");
	    fprintf(stderr, "     -S int          = specifies the subject ID number\n");
	    fprintf(stderr, "     -state int      = species whether the left perch is mid or high risk (1 or 2)\n");
        fprintf(stderr, "     -P int:int:int  = specifies probability of low, mid, high risk feeding\n");
	    fprintf(stderr, "     -T int:int:int  = species time hopper is up for low, mid and high risk\n");
	    fprintf(stderr, "     -on int:int     = set hour:min for exp to start eg: '-on 7:35' (default is 7AM, use 99 for sunrise)\n");
	    fprintf(stderr, "     -off int:int    = set hour:min for exp to stop eg: '-off 19:01' (default is 7PM, use 99 for sunset)\n");
	    exit(-1);
	  }
	  else
	    {
	      fprintf(stderr, "Unknown option: %s\n", av[i]);  
	      fprintf(stderr, "Try 'shape -h' for help\n");
	    }
	}
    }
  
  /* check for errors and Initialize box */
  if (box_id < 0)
    {
      fprintf(stderr, "\tYou must enter a box ID!: %s \n", av[i]); 
      fprintf(stderr, "\tERROR: try '2choice -help' for help\n");
      exit(-1);
  } else{
    printf("Initializing box #%d...", box_id);
    if (operant_open()!=0){
      fprintf(stderr, "Problem opening IO interface\n");
      exit (-1);
    }
    operant_clear(box_id);
    printf("done\n");
  }
  

  fprintf(stderr, "Session started:\n"); 
  fprintf(stderr, "   Subject ID: %d\n", subjectid);
  fprintf(stderr, "          Box: %d\n", box_id);


  /*Open & setup data logging files */
  
  curr_tt = time(NULL);
  loctime = localtime (&curr_tt); 
  strftime (timebuff, 64, "%d%b%y", loctime);
  sprintf(datafname, "%i_%s.riskDAT", subjectid, timebuff);
  datafp = fopen(datafname, "a");

  if(starthour==99){
    dosunrise=1;
    rise_tt = sunrise(atoi(year), atoi(month), atoi(day), latitude, longitude);
    strftime(temphour, 16, "%H", localtime(&rise_tt));
    strftime(tempmin, 16, "%M", localtime(&rise_tt));
    starthour=atoi(temphour);
    startmin=atoi(tempmin);
    strftime(buffer,30,"%m-%d-%Y %H:%M:%S",localtime(&rise_tt));
    printf("Sessions start at sunrise (Today: '%s')\n",buffer);
  }
  if(stophour==99){
    dosunset=1;
    set_tt = sunset(atoi(year), atoi(month), atoi(day), latitude, longitude);
    strftime(temphour, 16, "%H", localtime(&set_tt));
    strftime(tempmin, 16, "%M", localtime(&set_tt));
    stophour=atoi(temphour);
    stopmin=atoi(tempmin);
    strftime(buffer,30,"%m-%d-%Y  %T",localtime(&set_tt));
    printf("Sessions stop at sunset (Today: '%s')\n",buffer);
  }
	
  starttime=(starthour*60)+startmin;
  stoptime=(stophour*60)+stopmin;
  if(DEBUG){fprintf(stderr, "starthour: %d\tstartmin: %d\tstophour: %d\tstopmin: %d\n", starthour,startmin,stophour,stopmin);}

        
  if (datafp==NULL) {
    fprintf(stderr, "ERROR!: problem opening data output file!: %s\n", datafname);
    fclose(datafp);
    operant_close();
    exit(-1); }

  /* Write data file header info */
  fprintf (datafp, "File name: %s\n", datafname);
  fprintf (datafp, "Start time: %s", asctime(loctime));
  fprintf (datafp, "Subject ID: %d\n\n", subjectid);

    switch(initstate){
    case 1:
      leftTime = midTime;
      rightTime = highTime;
      leftProb = midProb;
      rightProb = highProb;
      break;
    case 2:
      leftTime = highTime;
      rightTime = midTime;
      leftProb = highProb;
      rightProb = midProb;
      break;
    default:
      printf("FATAL ERROR: unknown swap state %d!!\n\n", initstate);
      exit(-1);
  }
                                                          

  /*Run the appropriate shaping sequence */
  if(DEBUG){printf("start sequence list\n");}	
  
  block_num = 1;
  foragingRisk(block_num, leftTime, leftProb, rightTime, rightProb, lowTime, lowProb, starttime, stoptime);
   

  /*Cleanup */

  curr_tt = time(NULL);
  fclose(datafp);
  return 0;
}