repo
string | commit
string | message
string | diff
string |
---|---|---|---|
heracek/x36osy-producenti-konzumenti-processes
|
fd8db2a5f441b71e7784d305573508f6769e02d1
|
Pridano osetreni vyjimek v main().
|
diff --git a/main.cpp b/main.cpp
index 967e33e..61d8c23 100644
--- a/main.cpp
+++ b/main.cpp
@@ -1,437 +1,452 @@
/**
* X36OSY - Producenti a konzumenti
*
* vypracoval: Tomas Horacek <[email protected]>
*
*/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <queue>
#include <signal.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
using namespace std;
struct Prvek;
struct Fronta;
struct Shared;
const int M_PRODUCENTU = 5;
const int N_KONZUMENTU = 3;
const int K_POLOZEK = 3;
const int LIMIT_PRVKU = 10;
const int MAX_NAME_SIZE = 30;
const int NUM_CHILDREN = M_PRODUCENTU + N_KONZUMENTU;
const int MAX_NAHODNA_DOBA = 50000;
pid_t *child_pids;
int shared_mem_segment_id;
Shared *shared;
Fronta **fronty;
char process_name[MAX_NAME_SIZE];
struct Prvek {
int cislo_producenta;
int poradove_cislo;
int pocet_precteni;
Prvek(int cislo_producenta, int poradove_cislo) :
cislo_producenta(cislo_producenta),
poradove_cislo(poradove_cislo),
pocet_precteni(0) { }
};
class Fronta {
/**
* Pametove rozlozeni fronty:
Fronta:
Instance tridy Fronta:
[_size]
[_index_of_first]
Prvky fronty: (nasleduji okamzite za instanci Fronta)
[instance 0 (tridy Prvek) fronty]
[instance 1 (tridy Prvek) fronty]
...
[instance K_POLOZEK - 1 (tridy Prvek) fronty] (fixni pocet prvku)
*/
unsigned int _size;
unsigned int _index_of_first;
Prvek *_get_array_of_prvky() {
unsigned char *tmp_ptr = (unsigned char *) this;
tmp_ptr += sizeof(Fronta);
return (Prvek *) tmp_ptr;
}
public:
void init() {
this->_size = 0;
this->_index_of_first = 0;
}
int size() {
return this->_size;
}
int full() {
return this->_size == K_POLOZEK;
}
int empty() {
return this->_size == 0;
}
void front() {
}
void push(Prvek &prvek) {
}
void pop() {
}
static int get_total_sizeof() {
return sizeof(Fronta) + sizeof(Prvek) * K_POLOZEK;
}
};
typedef Fronta *p_Fronta;
struct Shared {
/**
*
* Struktura sdilene pameti:
Shared:
[pokracovat_ve_vypoctu]
Fronta 0:
[instance 0 tridy Fronta]
[prveky fronty 0]
Fronta 1:
[instance 1 tridy Fronta]
[prveky fronty 1]
...
Fronta M_PRODUCENTU - 1:
[instance M_PRODUCENTU - 1 tridy Fronta]
[prveky fronty M_PRODUCENTU - 1]
*/
volatile sig_atomic_t pokracovat_ve_vypoctu;
static void connect_and_init_local_ptrs() {
/** Pripoji pament a inicializuje lokalni ukazatele na sdilenou pamet. */
shared = (Shared *) shmat(shared_mem_segment_id, NULL, NULL);
fronty = new p_Fronta[M_PRODUCENTU];
unsigned char *tmp_ptr = (unsigned char *) shared;
tmp_ptr += sizeof(Shared);
for (int i = 0; i < M_PRODUCENTU; i++) {
fronty[i] = (Fronta *) tmp_ptr;
tmp_ptr += Fronta::get_total_sizeof();
}
}
static int get_total_sizeof() {
int velikost_vesech_front = Fronta::get_total_sizeof() * M_PRODUCENTU;
return sizeof(Shared) + velikost_vesech_front;
}
};
pthread_cond_t condy_front[M_PRODUCENTU];
pthread_mutex_t mutexy_front[M_PRODUCENTU];
queue<Prvek*> xfronty[M_PRODUCENTU];
void pockej_nahodnou_dobu() {
double result = 0.0;
int doba = random() % MAX_NAHODNA_DOBA;
for (int j = 0; j < doba; j++)
result = result + (double)random();
}
/**
* void *my_producent(void *idp)
*
* pseudokod:
*
def my_producent():
for cislo_prvku in range(LIMIT_PRVKU):
while je_fronta_plna():
pockej_na_uvolneni_prvku()
zamkni_frontu()
pridej_prvek_do_fronty()
odemkni_frontu()
pockej_nahodnou_dobu()
ukonci_vlakno()
*/
void *xmy_producent(void *idp) {
int cislo_producenta = *((int *) idp);
Prvek *prvek;
int velikos_fronty;
for (int poradove_cislo = 0; poradove_cislo < LIMIT_PRVKU; poradove_cislo++) {
prvek = new Prvek(cislo_producenta, poradove_cislo);
pthread_mutex_lock(&mutexy_front[cislo_producenta]);
while ((velikos_fronty = xfronty[cislo_producenta].size()) > K_POLOZEK) {
printf("PRODUCENT %i je zablokovan - velikost fronty %i\n", cislo_producenta, velikos_fronty);
pthread_cond_wait(&condy_front[cislo_producenta], &mutexy_front[cislo_producenta]);
}
xfronty[cislo_producenta].push(prvek);
pthread_mutex_unlock(&mutexy_front[cislo_producenta]);
printf("PRODUCENT %i pridal prvek %i - velikos fronty %i\n",
cislo_producenta,
poradove_cislo,
velikos_fronty
);
pockej_nahodnou_dobu();
}
printf("PRODUCENT %i konec\n", cislo_producenta);
pthread_exit(NULL);
}
/**
* void *konzument(void *idp)
*
* pseudokod:
*
def konzument():
while True:
pockej_nahodnou_dobu()
ukonci_cteni = True
for producent in range(M_PRODUCENTU):
zamkni_frontu()
if not fornta_je_prazdna():
prvek = fronta[producent].front()
if prvek.poradove_cislo != poradova_cisla_poslednich_prectenych_prveku[producent]:
prvek.pocet_precteni++
if prvek.pocet_precteni == N_KONZUMENTU:
fronta[producent].pop()
delete prvek;
zavolej_uvolneni_prvku()
poradova_cisla_poslednich_prectenych_prveku[producent] = prvek.poradove_cislo
odemkni_frontu()
if ukonci_cteni:
ukonci_cteni = poradova_cisla_poslednich_prectenych_prveku[producent] == (LIMIT_PRVKU - 1)
if ukonci_cteni:
ukonci_vlakno()
*/
void *xkonzument(void *idp) {
int cislo_konzumenta = *((int *) idp) - M_PRODUCENTU;
bool ukonci_cteni;
int cislo_producenta;
int prectene_poradove_cislo;
int prectene_cislo_producenta;
int velikos_fronty;
Prvek *prvek;
int poradova_cisla_poslednich_prectenych_prveku[M_PRODUCENTU];
bool prvek_odstranen = false;
int nova_velikos_fronty;
bool nove_nacteny = false;
int pocet_precteni;
for (int cislo_producenta = 0; cislo_producenta < M_PRODUCENTU; cislo_producenta++) {
poradova_cisla_poslednich_prectenych_prveku[cislo_producenta] = -1;
}
while (1) {
pockej_nahodnou_dobu();
ukonci_cteni = true;
for (cislo_producenta = 0; cislo_producenta < M_PRODUCENTU; cislo_producenta++) {
pthread_mutex_lock(&mutexy_front[cislo_producenta]);
if ( ! xfronty[cislo_producenta].empty()) {
prvek = xfronty[cislo_producenta].front();
velikos_fronty = xfronty[cislo_producenta].size();
prectene_poradove_cislo = prvek->poradove_cislo;
prectene_cislo_producenta = prvek->cislo_producenta;
if (prectene_poradove_cislo != poradova_cisla_poslednich_prectenych_prveku[cislo_producenta]) {
nove_nacteny = true;
pocet_precteni = ++(prvek->pocet_precteni);
if (prvek->pocet_precteni == N_KONZUMENTU) {
xfronty[cislo_producenta].pop();
delete prvek;
pthread_cond_signal(&condy_front[cislo_producenta]);
prvek_odstranen = true;
nova_velikos_fronty = xfronty[cislo_producenta].size();
if (nova_velikos_fronty == (K_POLOZEK - 1)) {
pthread_cond_signal(&condy_front[cislo_producenta]);
printf("konzument %i odblokoval frontu %i - velikost fronty %i\n",
cislo_konzumenta,
cislo_producenta,
velikos_fronty);
}
}
poradova_cisla_poslednich_prectenych_prveku[cislo_producenta] = prectene_poradove_cislo;
}
}
pthread_mutex_unlock(&mutexy_front[cislo_producenta]);
if (nove_nacteny) {
printf("konzument %i cte z fronty %i prvek %i - pocet precteni %i\n",
cislo_konzumenta,
cislo_producenta,
prectene_poradove_cislo,
pocet_precteni);
nove_nacteny = false;
}
if (prvek_odstranen) {
printf("konzument %i odsranil z fronty %i prvek %i - velikost fronty %i\n",
cislo_konzumenta,
cislo_producenta,
prectene_poradove_cislo,
nova_velikos_fronty);
prvek_odstranen = false;
}
if (ukonci_cteni) {
ukonci_cteni = poradova_cisla_poslednich_prectenych_prveku[cislo_producenta] == (LIMIT_PRVKU - 1);
}
}
if (ukonci_cteni) {
printf("konzument %i konec\n", cislo_konzumenta);
pthread_exit(NULL);
return NULL;
}
}
pthread_exit(NULL);
}
void producent(int cislo_producenta) {
snprintf(process_name, MAX_NAME_SIZE, "Producent %d [PID:%d]", cislo_producenta, (int) getpid());
-
printf("%s.\n", process_name);
+ Shared::connect_and_init_local_ptrs();
+
sleep(3);
printf("%s done.\n", process_name);
}
void konzument(int cislo_konzumenta) {
snprintf(process_name, MAX_NAME_SIZE, "Konzument %d [PID:%d]", cislo_konzumenta, (int) getpid());
-
printf("%s.\n", process_name);
+
+ Shared::connect_and_init_local_ptrs();
+
sleep(3);
printf("%s done.\n", process_name);
}
void alloc_shared_mem() {
int shared_segment_size = Shared::get_total_sizeof();
printf("%s alokuje pamet velikosti %dB.\n", process_name, shared_segment_size);
shared_mem_segment_id = shmget(IPC_PRIVATE, shared_segment_size, IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR);
}
void dealloc_shared_mem() {
shmctl(shared_mem_segment_id, IPC_RMID, NULL);
}
void wait_for_all_children() {
int status;
for (int i = 0; i < NUM_CHILDREN; i++) {
wait(&status);
}
}
void root_init() {
child_pids = new pid_t[NUM_CHILDREN];
alloc_shared_mem();
}
void dealloc_shared_resources() {
dealloc_shared_mem();
printf("%s dealokoval sdilene prostredky.\n", process_name);
}
void root_finish() {
wait_for_all_children();
dealloc_shared_resources();
delete[] child_pids;
}
int main(int argc, char * const argv[]) {
- pid_t root_pid = getpid();
- pid_t child_pid;
+ bool exception = false;
- snprintf(process_name, MAX_NAME_SIZE, "Hlavni proces [PID:%d]", (int) getpid());
- printf ("%s.\n", process_name, (int) root_pid);
+ try {
+ pid_t root_pid = getpid();
+ pid_t child_pid;
- root_init();
+ snprintf(process_name, MAX_NAME_SIZE, "Hlavni proces [PID:%d]", (int) getpid());
+ printf ("%s.\n", process_name, (int) root_pid);
- Shared::connect_and_init_local_ptrs();
+ root_init();
- printf("Shared: %p (%d)\n", shared, (unsigned int) shared);
+ printf("Velikos Shared: %d, velikost Fronta: %d, velikost Prvek: %d.\n",
+ Shared::get_total_sizeof(), Fronta::get_total_sizeof(), sizeof(Prvek));
- for (int i = 0; i < M_PRODUCENTU; i++) {
-
- printf("Fronta %d: %p (%d)\n", i , fronty[i], (unsigned int) fronty[i] - (unsigned int) shared);
+ Shared::connect_and_init_local_ptrs();
+
+ printf("Shared addr: %p (%d).\n", shared, (unsigned int) shared);
+
+ for (int i = 0; i < M_PRODUCENTU; i++) {
+ printf("Fronta %d addr: %p (relativni: %d).\n", i , fronty[i], (unsigned int) fronty[i] - (unsigned int) shared);
- fronty[i]->init();
+ fronty[i]->init();
- child_pid = fork();
- if (child_pid != 0) {
- child_pids[i] = child_pid;
- } else {
- producent(i);
- exit(0);
+ child_pid = fork();
+ if (child_pid != 0) {
+ child_pids[i] = child_pid;
+ } else {
+ producent(i);
+ exit(0);
+ }
}
- }
- for (int i = 0; i < N_KONZUMENTU; i++) {
- child_pid = fork ();
- if (child_pid != 0) {
- child_pids[i + M_PRODUCENTU] = child_pid;
- } else {
- konzument(i);
- exit(0);
+ for (int i = 0; i < N_KONZUMENTU; i++) {
+ child_pid = fork ();
+ if (child_pid != 0) {
+ child_pids[i + M_PRODUCENTU] = child_pid;
+ } else {
+ konzument(i);
+ exit(0);
+ }
}
+ } catch(...) {
+ exception = true;
}
-
root_finish();
- printf("All done.\n");
- return 0;
+ if ( ! exception) {
+ printf("All OK. Done.\n");
+ return 0;
+ } else {
+ printf("Exception caught in main(). Done.\n");
+ return 1;
+ }
}
\ No newline at end of file
|
heracek/x36osy-producenti-konzumenti-processes
|
f1f714f5f0401e5235e2e7cdd3fcf5eb33ed67ae
|
Funkcni alokace a inicializace sdilenych (nefunkcnich) front.
|
diff --git a/main.cpp b/main.cpp
index c71efe2..967e33e 100644
--- a/main.cpp
+++ b/main.cpp
@@ -1,285 +1,437 @@
/**
* X36OSY - Producenti a konzumenti
*
* vypracoval: Tomas Horacek <[email protected]>
*
*/
#include <pthread.h>
#include <stdio.h>
+#include <stdlib.h>
#include <iostream>
#include <queue>
+#include <signal.h>
+#include <sys/shm.h>
+#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
using namespace std;
-#define M_PRODUCENTU 5
-#define N_KONZUMENTU 3
-#define K_POLOZEK 3
-#define LIMIT_PRVKU 10
+struct Prvek;
+struct Fronta;
+struct Shared;
-#define NUM_CHILDREN M_PRODUCENTU + N_KONZUMENTU
-#define MAX_NAHODNA_DOBA 50000
+const int M_PRODUCENTU = 5;
+const int N_KONZUMENTU = 3;
+const int K_POLOZEK = 3;
+const int LIMIT_PRVKU = 10;
+const int MAX_NAME_SIZE = 30;
+const int NUM_CHILDREN = M_PRODUCENTU + N_KONZUMENTU;
+const int MAX_NAHODNA_DOBA = 50000;
pid_t *child_pids;
-pthread_cond_t condy_front[M_PRODUCENTU];
-pthread_mutex_t mutexy_front[M_PRODUCENTU];
-struct Prvek;
-queue<Prvek*> fronty[M_PRODUCENTU];
+int shared_mem_segment_id;
+Shared *shared;
+Fronta **fronty;
+char process_name[MAX_NAME_SIZE];
struct Prvek {
int cislo_producenta;
int poradove_cislo;
int pocet_precteni;
Prvek(int cislo_producenta, int poradove_cislo) :
cislo_producenta(cislo_producenta),
poradove_cislo(poradove_cislo),
pocet_precteni(0) { }
};
+class Fronta {
+ /**
+ * Pametove rozlozeni fronty:
+
+ Fronta:
+ Instance tridy Fronta:
+ [_size]
+ [_index_of_first]
+ Prvky fronty: (nasleduji okamzite za instanci Fronta)
+ [instance 0 (tridy Prvek) fronty]
+ [instance 1 (tridy Prvek) fronty]
+
+ ...
+
+ [instance K_POLOZEK - 1 (tridy Prvek) fronty] (fixni pocet prvku)
+
+ */
+ unsigned int _size;
+ unsigned int _index_of_first;
+
+ Prvek *_get_array_of_prvky() {
+ unsigned char *tmp_ptr = (unsigned char *) this;
+ tmp_ptr += sizeof(Fronta);
+
+ return (Prvek *) tmp_ptr;
+ }
+public:
+ void init() {
+ this->_size = 0;
+ this->_index_of_first = 0;
+ }
+
+ int size() {
+ return this->_size;
+ }
+
+ int full() {
+ return this->_size == K_POLOZEK;
+ }
+
+ int empty() {
+ return this->_size == 0;
+ }
+
+ void front() {
+
+ }
+
+ void push(Prvek &prvek) {
+
+ }
+
+ void pop() {
+
+ }
+
+ static int get_total_sizeof() {
+ return sizeof(Fronta) + sizeof(Prvek) * K_POLOZEK;
+ }
+};
+
+typedef Fronta *p_Fronta;
+
+struct Shared {
+ /**
+ *
+ * Struktura sdilene pameti:
+
+ Shared:
+ [pokracovat_ve_vypoctu]
+ Fronta 0:
+ [instance 0 tridy Fronta]
+ [prveky fronty 0]
+ Fronta 1:
+ [instance 1 tridy Fronta]
+ [prveky fronty 1]
+
+ ...
+
+ Fronta M_PRODUCENTU - 1:
+ [instance M_PRODUCENTU - 1 tridy Fronta]
+ [prveky fronty M_PRODUCENTU - 1]
+
+ */
+
+ volatile sig_atomic_t pokracovat_ve_vypoctu;
+
+ static void connect_and_init_local_ptrs() {
+ /** Pripoji pament a inicializuje lokalni ukazatele na sdilenou pamet. */
+
+ shared = (Shared *) shmat(shared_mem_segment_id, NULL, NULL);
+
+ fronty = new p_Fronta[M_PRODUCENTU];
+
+ unsigned char *tmp_ptr = (unsigned char *) shared;
+ tmp_ptr += sizeof(Shared);
+
+ for (int i = 0; i < M_PRODUCENTU; i++) {
+ fronty[i] = (Fronta *) tmp_ptr;
+ tmp_ptr += Fronta::get_total_sizeof();
+ }
+ }
+
+ static int get_total_sizeof() {
+ int velikost_vesech_front = Fronta::get_total_sizeof() * M_PRODUCENTU;
+ return sizeof(Shared) + velikost_vesech_front;
+ }
+};
+
+
+pthread_cond_t condy_front[M_PRODUCENTU];
+pthread_mutex_t mutexy_front[M_PRODUCENTU];
+queue<Prvek*> xfronty[M_PRODUCENTU];
+
void pockej_nahodnou_dobu() {
double result = 0.0;
int doba = random() % MAX_NAHODNA_DOBA;
for (int j = 0; j < doba; j++)
result = result + (double)random();
}
/**
* void *my_producent(void *idp)
*
* pseudokod:
*
def my_producent():
for cislo_prvku in range(LIMIT_PRVKU):
while je_fronta_plna():
pockej_na_uvolneni_prvku()
zamkni_frontu()
pridej_prvek_do_fronty()
odemkni_frontu()
pockej_nahodnou_dobu()
ukonci_vlakno()
*/
void *xmy_producent(void *idp) {
int cislo_producenta = *((int *) idp);
Prvek *prvek;
int velikos_fronty;
for (int poradove_cislo = 0; poradove_cislo < LIMIT_PRVKU; poradove_cislo++) {
prvek = new Prvek(cislo_producenta, poradove_cislo);
pthread_mutex_lock(&mutexy_front[cislo_producenta]);
- while ((velikos_fronty = fronty[cislo_producenta].size()) > K_POLOZEK) {
+ while ((velikos_fronty = xfronty[cislo_producenta].size()) > K_POLOZEK) {
printf("PRODUCENT %i je zablokovan - velikost fronty %i\n", cislo_producenta, velikos_fronty);
pthread_cond_wait(&condy_front[cislo_producenta], &mutexy_front[cislo_producenta]);
}
- fronty[cislo_producenta].push(prvek);
+ xfronty[cislo_producenta].push(prvek);
pthread_mutex_unlock(&mutexy_front[cislo_producenta]);
printf("PRODUCENT %i pridal prvek %i - velikos fronty %i\n",
cislo_producenta,
poradove_cislo,
velikos_fronty
);
pockej_nahodnou_dobu();
}
printf("PRODUCENT %i konec\n", cislo_producenta);
pthread_exit(NULL);
}
/**
* void *konzument(void *idp)
*
* pseudokod:
*
def konzument():
while True:
pockej_nahodnou_dobu()
ukonci_cteni = True
for producent in range(M_PRODUCENTU):
zamkni_frontu()
if not fornta_je_prazdna():
prvek = fronta[producent].front()
if prvek.poradove_cislo != poradova_cisla_poslednich_prectenych_prveku[producent]:
prvek.pocet_precteni++
if prvek.pocet_precteni == N_KONZUMENTU:
fronta[producent].pop()
delete prvek;
zavolej_uvolneni_prvku()
poradova_cisla_poslednich_prectenych_prveku[producent] = prvek.poradove_cislo
odemkni_frontu()
if ukonci_cteni:
ukonci_cteni = poradova_cisla_poslednich_prectenych_prveku[producent] == (LIMIT_PRVKU - 1)
if ukonci_cteni:
ukonci_vlakno()
*/
void *xkonzument(void *idp) {
int cislo_konzumenta = *((int *) idp) - M_PRODUCENTU;
bool ukonci_cteni;
int cislo_producenta;
int prectene_poradove_cislo;
int prectene_cislo_producenta;
int velikos_fronty;
Prvek *prvek;
int poradova_cisla_poslednich_prectenych_prveku[M_PRODUCENTU];
bool prvek_odstranen = false;
int nova_velikos_fronty;
bool nove_nacteny = false;
int pocet_precteni;
for (int cislo_producenta = 0; cislo_producenta < M_PRODUCENTU; cislo_producenta++) {
poradova_cisla_poslednich_prectenych_prveku[cislo_producenta] = -1;
}
while (1) {
pockej_nahodnou_dobu();
ukonci_cteni = true;
for (cislo_producenta = 0; cislo_producenta < M_PRODUCENTU; cislo_producenta++) {
pthread_mutex_lock(&mutexy_front[cislo_producenta]);
- if ( ! fronty[cislo_producenta].empty()) {
- prvek = fronty[cislo_producenta].front();
- velikos_fronty = fronty[cislo_producenta].size();
+ if ( ! xfronty[cislo_producenta].empty()) {
+ prvek = xfronty[cislo_producenta].front();
+ velikos_fronty = xfronty[cislo_producenta].size();
prectene_poradove_cislo = prvek->poradove_cislo;
prectene_cislo_producenta = prvek->cislo_producenta;
if (prectene_poradove_cislo != poradova_cisla_poslednich_prectenych_prveku[cislo_producenta]) {
nove_nacteny = true;
pocet_precteni = ++(prvek->pocet_precteni);
if (prvek->pocet_precteni == N_KONZUMENTU) {
- fronty[cislo_producenta].pop();
+ xfronty[cislo_producenta].pop();
delete prvek;
pthread_cond_signal(&condy_front[cislo_producenta]);
prvek_odstranen = true;
- nova_velikos_fronty = fronty[cislo_producenta].size();
+ nova_velikos_fronty = xfronty[cislo_producenta].size();
if (nova_velikos_fronty == (K_POLOZEK - 1)) {
pthread_cond_signal(&condy_front[cislo_producenta]);
printf("konzument %i odblokoval frontu %i - velikost fronty %i\n",
cislo_konzumenta,
cislo_producenta,
velikos_fronty);
}
}
poradova_cisla_poslednich_prectenych_prveku[cislo_producenta] = prectene_poradove_cislo;
}
}
pthread_mutex_unlock(&mutexy_front[cislo_producenta]);
if (nove_nacteny) {
printf("konzument %i cte z fronty %i prvek %i - pocet precteni %i\n",
cislo_konzumenta,
cislo_producenta,
prectene_poradove_cislo,
pocet_precteni);
nove_nacteny = false;
}
if (prvek_odstranen) {
printf("konzument %i odsranil z fronty %i prvek %i - velikost fronty %i\n",
cislo_konzumenta,
cislo_producenta,
prectene_poradove_cislo,
nova_velikos_fronty);
prvek_odstranen = false;
}
if (ukonci_cteni) {
ukonci_cteni = poradova_cisla_poslednich_prectenych_prveku[cislo_producenta] == (LIMIT_PRVKU - 1);
}
}
if (ukonci_cteni) {
printf("konzument %i konec\n", cislo_konzumenta);
pthread_exit(NULL);
return NULL;
}
}
pthread_exit(NULL);
}
void producent(int cislo_producenta) {
- printf("Producent %d.\n", cislo_producenta);
- sleep(10);
- printf("Producent %d done.\n", cislo_producenta);
+ snprintf(process_name, MAX_NAME_SIZE, "Producent %d [PID:%d]", cislo_producenta, (int) getpid());
+
+ printf("%s.\n", process_name);
+
+ sleep(3);
+ printf("%s done.\n", process_name);
}
void konzument(int cislo_konzumenta) {
- printf("Konzument %d.\n", cislo_konzumenta);
- sleep(10);
- printf("Konzument %d done.\n", cislo_konzumenta);
+ snprintf(process_name, MAX_NAME_SIZE, "Konzument %d [PID:%d]", cislo_konzumenta, (int) getpid());
+
+ printf("%s.\n", process_name);
+ sleep(3);
+ printf("%s done.\n", process_name);
+}
+
+void alloc_shared_mem() {
+ int shared_segment_size = Shared::get_total_sizeof();
+ printf("%s alokuje pamet velikosti %dB.\n", process_name, shared_segment_size);
+ shared_mem_segment_id = shmget(IPC_PRIVATE, shared_segment_size, IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR);
+}
+
+void dealloc_shared_mem() {
+ shmctl(shared_mem_segment_id, IPC_RMID, NULL);
}
void wait_for_all_children() {
int status;
for (int i = 0; i < NUM_CHILDREN; i++) {
wait(&status);
}
}
+void root_init() {
+ child_pids = new pid_t[NUM_CHILDREN];
+ alloc_shared_mem();
+}
+
+void dealloc_shared_resources() {
+ dealloc_shared_mem();
+ printf("%s dealokoval sdilene prostredky.\n", process_name);
+}
+
+void root_finish() {
+ wait_for_all_children();
+
+ dealloc_shared_resources();
+ delete[] child_pids;
+}
+
int main(int argc, char * const argv[]) {
pid_t root_pid = getpid();
pid_t child_pid;
- char typ;
- int cislo;
- printf ("the main program process id is %d\n", (int) getpid ());
- child_pids = new pid_t[NUM_CHILDREN];
+ snprintf(process_name, MAX_NAME_SIZE, "Hlavni proces [PID:%d]", (int) getpid());
+ printf ("%s.\n", process_name, (int) root_pid);
+
+ root_init();
+
+ Shared::connect_and_init_local_ptrs();
+
+ printf("Shared: %p (%d)\n", shared, (unsigned int) shared);
for (int i = 0; i < M_PRODUCENTU; i++) {
- typ = 'P';
- cislo = i;
- child_pid = fork ();
+ printf("Fronta %d: %p (%d)\n", i , fronty[i], (unsigned int) fronty[i] - (unsigned int) shared);
+
+ fronty[i]->init();
+
+ child_pid = fork();
if (child_pid != 0) {
child_pids[i] = child_pid;
- }
- else {
+ } else {
producent(i);
exit(0);
}
}
for (int i = 0; i < N_KONZUMENTU; i++) {
- typ = 'K';
- cislo = i;
-
child_pid = fork ();
if (child_pid != 0) {
child_pids[i + M_PRODUCENTU] = child_pid;
- }
- else {
+ } else {
konzument(i);
exit(0);
}
}
- wait_for_all_children();
+ root_finish();
printf("All done.\n");
-
- delete[] child_pids;
-
return 0;
}
\ No newline at end of file
diff --git a/readme.html b/readme.html
index 758af72..0186735 100644
--- a/readme.html
+++ b/readme.html
@@ -1,96 +1,98 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Semestrálnà úloha X36OSY 2007</title>
</head>
<body>
<center><h1>Semestrálnà úloha X36OSY 2007</h1></center>
<center>Téma úlohy: Producenti a konzumenti</center>
<center>Vypracoval: Tomas Horacek <[email protected]></center>
<br />
<center>6. roÄnÃk, obor VýpoÄetnà technika, K336 FEL ÄVUT,<br />
Karlovo nám. 13, 121 35 Praha 2 </center>
<h2>Zadánà úlohy</h2>
<p>
MÄjme <i>m</i> producentů a <i>n</i> konzumentů.
Každý producent má svojà frontu o kapacitÄ <i>k</i> položek,
do které v náhodných intervalech zapisuje pokud je v nà volno, jinak se zablokuje a Äeká.
Položky ve frontách obsahujà ÄÃslo producenta a poÅadové ÄÃslo, ve kterém byly zapsány do fronty.
Konzumenti v náhodných intervalech Ätou položky z front. Každý konzument musà pÅeÄÃst vÅ¡echny
položky od všech producentů, tzn. že položky se mohou odstranit z front až
po pÅeÄtenà vÅ¡emi konzumenty.
</p>
<p><b>Vstup:</b> Producenti a konzumenti jsou reprezentováni vlákny/procesy a náhodnÄ generujÃ/Ätou položky.</p>
<p><b>Výstup:</b> Informace o tom, jak se mÄnà obsah jednotlivých front a informace v jakém stavu se producenti a konzument nacházejÃ.</p>
<h2>Analýza úlohy</h2>
<h2>ÅeÅ¡enà úlohy pomocà vláken</h2>
<p>Reseni je za pomoci mutexu, pseoudokod popisujici algoritmus je zde:</p>
<code><pre>
def my_producent():
for cislo_prvku in range(LIMIT_PRVKU):
while je_fronta_plna():
pockej_na_uvolneni_prvku()
zamkni_frontu()
pridej_prvek_do_fronty()
odemkni_frontu()
pockej_nahodnou_dobu()
ukonci_vlakno()
</pre></code>
<code><pre>
def konzument():
while True:
pockej_nahodnou_dobu()
ukonci_cteni = True
for producent in range(M_PRODUCENTU):
zamkni_frontu()
if not fornta_je_prazdna():
prvek = fronta[producent].front()
if prvek.poradove_cislo != poradova_cisla_poslednich_prectenych_prveku[producent]:
prvek.pocet_precteni++
if prvek.pocet_precteni == N_KONZUMENTU:
fronta[producent].pop()
delete prvek;
zavolej_uvolneni_prvku()
poradova_cisla_poslednich_prectenych_prveku[producent] = prvek.poradove_cislo
odemkni_frontu()
if ukonci_cteni:
ukonci_cteni = poradova_cisla_poslednich_prectenych_prveku[producent] == (LIMIT_PRVKU - 1)
if ukonci_cteni:
ukonci_vlakno()
</pre></code>
<h2>ÅeÅ¡enà úlohy pomocà procesů</h2>
<h2>ZávÄr</h2>
Uloha mi pomohla prakticky vyzkouset tvoreni vlaken a jejich synchronizaci.
<h2>Literatura</h2>
<ol>
<li>Slides ze cviceni</li>
<li>Priklady ze cviceni</li>
<li>manualove stranky</li>
+ <li><a href="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_21.html" title="The GNU C Library - Signal Handling">The GNU C Library - Signal Handling</a></li>
+ <li><a href="http://www.cplusplus.com/reference/stl/queue/queue.html" title="queue::queue - C++ Reference">queue::queue - C++ Reference</a></li>
</ol>
</body>
</html>
\ No newline at end of file
|
heracek/x36osy-producenti-konzumenti-processes
|
0afbe7f8f5f00561bdfa0ac80aca1147d9f93a0a
|
Pridano cekani na ukonceni vsech podprocesu.
|
diff --git a/main.cpp b/main.cpp
index bcbbb05..c71efe2 100644
--- a/main.cpp
+++ b/main.cpp
@@ -1,275 +1,285 @@
/**
* X36OSY - Producenti a konzumenti
*
* vypracoval: Tomas Horacek <[email protected]>
*
*/
#include <pthread.h>
#include <stdio.h>
#include <iostream>
#include <queue>
#include <sys/types.h>
#include <unistd.h>
using namespace std;
#define M_PRODUCENTU 5
#define N_KONZUMENTU 3
#define K_POLOZEK 3
#define LIMIT_PRVKU 10
-#define NUM_THREADS M_PRODUCENTU + N_KONZUMENTU
+#define NUM_CHILDREN M_PRODUCENTU + N_KONZUMENTU
#define MAX_NAHODNA_DOBA 50000
-int thread_ids[NUM_THREADS];
+pid_t *child_pids;
pthread_cond_t condy_front[M_PRODUCENTU];
pthread_mutex_t mutexy_front[M_PRODUCENTU];
struct Prvek;
queue<Prvek*> fronty[M_PRODUCENTU];
struct Prvek {
int cislo_producenta;
int poradove_cislo;
int pocet_precteni;
Prvek(int cislo_producenta, int poradove_cislo) :
cislo_producenta(cislo_producenta),
poradove_cislo(poradove_cislo),
pocet_precteni(0) { }
};
void pockej_nahodnou_dobu() {
double result = 0.0;
int doba = random() % MAX_NAHODNA_DOBA;
for (int j = 0; j < doba; j++)
result = result + (double)random();
}
/**
* void *my_producent(void *idp)
*
* pseudokod:
*
def my_producent():
for cislo_prvku in range(LIMIT_PRVKU):
while je_fronta_plna():
pockej_na_uvolneni_prvku()
zamkni_frontu()
pridej_prvek_do_fronty()
odemkni_frontu()
pockej_nahodnou_dobu()
ukonci_vlakno()
*/
-void *my_producent(void *idp) {
+void *xmy_producent(void *idp) {
int cislo_producenta = *((int *) idp);
Prvek *prvek;
int velikos_fronty;
for (int poradove_cislo = 0; poradove_cislo < LIMIT_PRVKU; poradove_cislo++) {
prvek = new Prvek(cislo_producenta, poradove_cislo);
pthread_mutex_lock(&mutexy_front[cislo_producenta]);
while ((velikos_fronty = fronty[cislo_producenta].size()) > K_POLOZEK) {
printf("PRODUCENT %i je zablokovan - velikost fronty %i\n", cislo_producenta, velikos_fronty);
pthread_cond_wait(&condy_front[cislo_producenta], &mutexy_front[cislo_producenta]);
}
fronty[cislo_producenta].push(prvek);
pthread_mutex_unlock(&mutexy_front[cislo_producenta]);
printf("PRODUCENT %i pridal prvek %i - velikos fronty %i\n",
cislo_producenta,
poradove_cislo,
velikos_fronty
);
pockej_nahodnou_dobu();
}
printf("PRODUCENT %i konec\n", cislo_producenta);
pthread_exit(NULL);
}
/**
* void *konzument(void *idp)
*
* pseudokod:
*
def konzument():
while True:
pockej_nahodnou_dobu()
ukonci_cteni = True
for producent in range(M_PRODUCENTU):
zamkni_frontu()
if not fornta_je_prazdna():
prvek = fronta[producent].front()
if prvek.poradove_cislo != poradova_cisla_poslednich_prectenych_prveku[producent]:
prvek.pocet_precteni++
if prvek.pocet_precteni == N_KONZUMENTU:
fronta[producent].pop()
delete prvek;
zavolej_uvolneni_prvku()
poradova_cisla_poslednich_prectenych_prveku[producent] = prvek.poradove_cislo
odemkni_frontu()
if ukonci_cteni:
ukonci_cteni = poradova_cisla_poslednich_prectenych_prveku[producent] == (LIMIT_PRVKU - 1)
if ukonci_cteni:
ukonci_vlakno()
*/
-void *konzument(void *idp) {
+void *xkonzument(void *idp) {
int cislo_konzumenta = *((int *) idp) - M_PRODUCENTU;
bool ukonci_cteni;
int cislo_producenta;
int prectene_poradove_cislo;
int prectene_cislo_producenta;
int velikos_fronty;
Prvek *prvek;
int poradova_cisla_poslednich_prectenych_prveku[M_PRODUCENTU];
bool prvek_odstranen = false;
int nova_velikos_fronty;
bool nove_nacteny = false;
int pocet_precteni;
for (int cislo_producenta = 0; cislo_producenta < M_PRODUCENTU; cislo_producenta++) {
poradova_cisla_poslednich_prectenych_prveku[cislo_producenta] = -1;
}
while (1) {
pockej_nahodnou_dobu();
ukonci_cteni = true;
for (cislo_producenta = 0; cislo_producenta < M_PRODUCENTU; cislo_producenta++) {
pthread_mutex_lock(&mutexy_front[cislo_producenta]);
if ( ! fronty[cislo_producenta].empty()) {
prvek = fronty[cislo_producenta].front();
velikos_fronty = fronty[cislo_producenta].size();
prectene_poradove_cislo = prvek->poradove_cislo;
prectene_cislo_producenta = prvek->cislo_producenta;
if (prectene_poradove_cislo != poradova_cisla_poslednich_prectenych_prveku[cislo_producenta]) {
nove_nacteny = true;
pocet_precteni = ++(prvek->pocet_precteni);
if (prvek->pocet_precteni == N_KONZUMENTU) {
fronty[cislo_producenta].pop();
delete prvek;
pthread_cond_signal(&condy_front[cislo_producenta]);
prvek_odstranen = true;
nova_velikos_fronty = fronty[cislo_producenta].size();
if (nova_velikos_fronty == (K_POLOZEK - 1)) {
pthread_cond_signal(&condy_front[cislo_producenta]);
printf("konzument %i odblokoval frontu %i - velikost fronty %i\n",
cislo_konzumenta,
cislo_producenta,
velikos_fronty);
}
}
poradova_cisla_poslednich_prectenych_prveku[cislo_producenta] = prectene_poradove_cislo;
}
}
pthread_mutex_unlock(&mutexy_front[cislo_producenta]);
if (nove_nacteny) {
printf("konzument %i cte z fronty %i prvek %i - pocet precteni %i\n",
cislo_konzumenta,
cislo_producenta,
prectene_poradove_cislo,
pocet_precteni);
nove_nacteny = false;
}
if (prvek_odstranen) {
printf("konzument %i odsranil z fronty %i prvek %i - velikost fronty %i\n",
cislo_konzumenta,
cislo_producenta,
prectene_poradove_cislo,
nova_velikos_fronty);
prvek_odstranen = false;
}
if (ukonci_cteni) {
ukonci_cteni = poradova_cisla_poslednich_prectenych_prveku[cislo_producenta] == (LIMIT_PRVKU - 1);
}
}
if (ukonci_cteni) {
printf("konzument %i konec\n", cislo_konzumenta);
pthread_exit(NULL);
return NULL;
}
}
pthread_exit(NULL);
}
+void producent(int cislo_producenta) {
+ printf("Producent %d.\n", cislo_producenta);
+ sleep(10);
+ printf("Producent %d done.\n", cislo_producenta);
+}
+
+void konzument(int cislo_konzumenta) {
+ printf("Konzument %d.\n", cislo_konzumenta);
+ sleep(10);
+ printf("Konzument %d done.\n", cislo_konzumenta);
+}
+
+void wait_for_all_children() {
+ int status;
+
+ for (int i = 0; i < NUM_CHILDREN; i++) {
+ wait(&status);
+ }
+}
+
int main(int argc, char * const argv[]) {
pid_t root_pid = getpid();
pid_t child_pid;
char typ;
int cislo;
-
printf ("the main program process id is %d\n", (int) getpid ());
+ child_pids = new pid_t[NUM_CHILDREN];
+
for (int i = 0; i < M_PRODUCENTU; i++) {
typ = 'P';
cislo = i;
child_pid = fork ();
if (child_pid != 0) {
- if (root_pid == 0) {
- root_pid = getpid();
- }
- printf ("this is the parent process, with id %d\n", (int) getpid ());
- printf ("the child's process id is %d\n", (int) child_pid);
- sleep(1);
+ child_pids[i] = child_pid;
}
else {
- printf ("this is the child process, with id %d, ROOT: %d, typ: %c, cislo: %i\n", (int) getpid (), (int) root_pid, typ, cislo);
- sleep(20);
- break;
+ producent(i);
+ exit(0);
}
}
- if (root_pid == getpid()) {
- for (int i = 0; i < N_KONZUMENTU; i++) {
- typ = 'K';
- cislo = i;
+ for (int i = 0; i < N_KONZUMENTU; i++) {
+ typ = 'K';
+ cislo = i;
- child_pid = fork ();
- if (child_pid != 0) {
- if (root_pid == 0) {
- root_pid = getpid();
- }
- printf ("this is the parent process, with id %d\n", (int) getpid ());
- printf ("the child's process id is %d\n", (int) child_pid);
- sleep(1);
- }
- else {
- printf ("this is the child process, with id %d, ROOT: %d, typ: %c, cislo: %i\n", (int) getpid (), (int) root_pid, typ, cislo);
- sleep(20);
- break;
- }
+ child_pid = fork ();
+ if (child_pid != 0) {
+ child_pids[i + M_PRODUCENTU] = child_pid;
}
- if (root_pid == getpid()) {
- sleep(20);
+ else {
+ konzument(i);
+ exit(0);
}
}
+ wait_for_all_children();
+
+ printf("All done.\n");
+
+ delete[] child_pids;
+
return 0;
}
\ No newline at end of file
|
heracek/x36osy-producenti-konzumenti-processes
|
92b9669bb907fdacaa535fed6117918319483a28
|
Prvni verze s procesy - vytvoreni nefunkcnich producentu a konzumentu.
|
diff --git a/.gitignore b/.gitignore
index 496ee2c..ddc98a8 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1 +1,2 @@
-.DS_Store
\ No newline at end of file
+.DS_Store
+main
\ No newline at end of file
diff --git a/Makefile b/Makefile
index f189cc1..512e1cd 100644
--- a/Makefile
+++ b/Makefile
@@ -1,16 +1,19 @@
# all after symbol '#' is comment
# === which communication library to use ===
CC = g++
CFLAGS =
LIBS = -lpthread
# -lrt
default: main
main:main.cpp
$(CC) $(CFLAGS) -o main main.cpp $(LIBS)
+run:main
+ ./main
+
clear:
\rm main
diff --git a/main.cpp b/main.cpp
index 8232d0e..bcbbb05 100644
--- a/main.cpp
+++ b/main.cpp
@@ -1,262 +1,275 @@
/**
* X36OSY - Producenti a konzumenti
*
* vypracoval: Tomas Horacek <[email protected]>
*
*/
#include <pthread.h>
#include <stdio.h>
#include <iostream>
#include <queue>
+#include <sys/types.h>
+#include <unistd.h>
using namespace std;
#define M_PRODUCENTU 5
#define N_KONZUMENTU 3
#define K_POLOZEK 3
#define LIMIT_PRVKU 10
#define NUM_THREADS M_PRODUCENTU + N_KONZUMENTU
#define MAX_NAHODNA_DOBA 50000
int thread_ids[NUM_THREADS];
pthread_cond_t condy_front[M_PRODUCENTU];
pthread_mutex_t mutexy_front[M_PRODUCENTU];
struct Prvek;
queue<Prvek*> fronty[M_PRODUCENTU];
struct Prvek {
int cislo_producenta;
int poradove_cislo;
int pocet_precteni;
Prvek(int cislo_producenta, int poradove_cislo) :
cislo_producenta(cislo_producenta),
poradove_cislo(poradove_cislo),
pocet_precteni(0) { }
};
void pockej_nahodnou_dobu() {
double result = 0.0;
int doba = random() % MAX_NAHODNA_DOBA;
for (int j = 0; j < doba; j++)
result = result + (double)random();
}
/**
* void *my_producent(void *idp)
*
* pseudokod:
*
def my_producent():
for cislo_prvku in range(LIMIT_PRVKU):
while je_fronta_plna():
pockej_na_uvolneni_prvku()
zamkni_frontu()
pridej_prvek_do_fronty()
odemkni_frontu()
pockej_nahodnou_dobu()
ukonci_vlakno()
*/
void *my_producent(void *idp) {
int cislo_producenta = *((int *) idp);
Prvek *prvek;
int velikos_fronty;
for (int poradove_cislo = 0; poradove_cislo < LIMIT_PRVKU; poradove_cislo++) {
prvek = new Prvek(cislo_producenta, poradove_cislo);
pthread_mutex_lock(&mutexy_front[cislo_producenta]);
while ((velikos_fronty = fronty[cislo_producenta].size()) > K_POLOZEK) {
printf("PRODUCENT %i je zablokovan - velikost fronty %i\n", cislo_producenta, velikos_fronty);
pthread_cond_wait(&condy_front[cislo_producenta], &mutexy_front[cislo_producenta]);
}
fronty[cislo_producenta].push(prvek);
pthread_mutex_unlock(&mutexy_front[cislo_producenta]);
printf("PRODUCENT %i pridal prvek %i - velikos fronty %i\n",
cislo_producenta,
poradove_cislo,
velikos_fronty
);
pockej_nahodnou_dobu();
}
printf("PRODUCENT %i konec\n", cislo_producenta);
pthread_exit(NULL);
}
/**
* void *konzument(void *idp)
*
* pseudokod:
*
def konzument():
while True:
pockej_nahodnou_dobu()
ukonci_cteni = True
for producent in range(M_PRODUCENTU):
zamkni_frontu()
if not fornta_je_prazdna():
prvek = fronta[producent].front()
if prvek.poradove_cislo != poradova_cisla_poslednich_prectenych_prveku[producent]:
prvek.pocet_precteni++
if prvek.pocet_precteni == N_KONZUMENTU:
fronta[producent].pop()
delete prvek;
zavolej_uvolneni_prvku()
poradova_cisla_poslednich_prectenych_prveku[producent] = prvek.poradove_cislo
odemkni_frontu()
if ukonci_cteni:
ukonci_cteni = poradova_cisla_poslednich_prectenych_prveku[producent] == (LIMIT_PRVKU - 1)
if ukonci_cteni:
ukonci_vlakno()
*/
void *konzument(void *idp) {
int cislo_konzumenta = *((int *) idp) - M_PRODUCENTU;
bool ukonci_cteni;
int cislo_producenta;
int prectene_poradove_cislo;
int prectene_cislo_producenta;
int velikos_fronty;
Prvek *prvek;
int poradova_cisla_poslednich_prectenych_prveku[M_PRODUCENTU];
bool prvek_odstranen = false;
int nova_velikos_fronty;
bool nove_nacteny = false;
int pocet_precteni;
for (int cislo_producenta = 0; cislo_producenta < M_PRODUCENTU; cislo_producenta++) {
poradova_cisla_poslednich_prectenych_prveku[cislo_producenta] = -1;
}
while (1) {
pockej_nahodnou_dobu();
ukonci_cteni = true;
for (cislo_producenta = 0; cislo_producenta < M_PRODUCENTU; cislo_producenta++) {
pthread_mutex_lock(&mutexy_front[cislo_producenta]);
if ( ! fronty[cislo_producenta].empty()) {
prvek = fronty[cislo_producenta].front();
velikos_fronty = fronty[cislo_producenta].size();
prectene_poradove_cislo = prvek->poradove_cislo;
prectene_cislo_producenta = prvek->cislo_producenta;
if (prectene_poradove_cislo != poradova_cisla_poslednich_prectenych_prveku[cislo_producenta]) {
nove_nacteny = true;
pocet_precteni = ++(prvek->pocet_precteni);
if (prvek->pocet_precteni == N_KONZUMENTU) {
fronty[cislo_producenta].pop();
delete prvek;
pthread_cond_signal(&condy_front[cislo_producenta]);
prvek_odstranen = true;
nova_velikos_fronty = fronty[cislo_producenta].size();
if (nova_velikos_fronty == (K_POLOZEK - 1)) {
pthread_cond_signal(&condy_front[cislo_producenta]);
printf("konzument %i odblokoval frontu %i - velikost fronty %i\n",
cislo_konzumenta,
cislo_producenta,
velikos_fronty);
}
}
poradova_cisla_poslednich_prectenych_prveku[cislo_producenta] = prectene_poradove_cislo;
}
}
pthread_mutex_unlock(&mutexy_front[cislo_producenta]);
if (nove_nacteny) {
printf("konzument %i cte z fronty %i prvek %i - pocet precteni %i\n",
cislo_konzumenta,
cislo_producenta,
prectene_poradove_cislo,
pocet_precteni);
nove_nacteny = false;
}
if (prvek_odstranen) {
printf("konzument %i odsranil z fronty %i prvek %i - velikost fronty %i\n",
cislo_konzumenta,
cislo_producenta,
prectene_poradove_cislo,
nova_velikos_fronty);
prvek_odstranen = false;
}
if (ukonci_cteni) {
ukonci_cteni = poradova_cisla_poslednich_prectenych_prveku[cislo_producenta] == (LIMIT_PRVKU - 1);
}
}
if (ukonci_cteni) {
printf("konzument %i konec\n", cislo_konzumenta);
pthread_exit(NULL);
return NULL;
}
}
pthread_exit(NULL);
}
-int main (int argc, char * const argv[]) {
- int i;
- pthread_t threads[NUM_THREADS];
- pthread_attr_t attr;
+int main(int argc, char * const argv[]) {
+ pid_t root_pid = getpid();
+ pid_t child_pid;
+ char typ;
+ int cislo;
- for (int cislo_producenta = 0; cislo_producenta < M_PRODUCENTU; cislo_producenta++) {
- pthread_mutex_init(&mutexy_front[cislo_producenta], NULL);
- pthread_cond_init (&condy_front[cislo_producenta], NULL);
- }
-
- for (int thread_id = 0; thread_id < NUM_THREADS; thread_id++) {
- thread_ids[thread_id] = thread_id;
- }
-
- /*
- For portability, explicitly create threads in a joinable state
- */
- pthread_attr_init(&attr);
- pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
+ printf ("the main program process id is %d\n", (int) getpid ());
- int thred_i;
- for (thred_i = 0; thred_i < M_PRODUCENTU; thred_i++) {
- pthread_create(&threads[thred_i], &attr, my_producent, (void *)&thread_ids[thred_i]);
- }
-
- for (thred_i = M_PRODUCENTU; thred_i < NUM_THREADS; thred_i++) {
- pthread_create(&threads[thred_i], &attr, konzument, (void *)&thread_ids[thred_i]);
+ for (int i = 0; i < M_PRODUCENTU; i++) {
+ typ = 'P';
+ cislo = i;
+
+ child_pid = fork ();
+ if (child_pid != 0) {
+ if (root_pid == 0) {
+ root_pid = getpid();
+ }
+ printf ("this is the parent process, with id %d\n", (int) getpid ());
+ printf ("the child's process id is %d\n", (int) child_pid);
+ sleep(1);
+ }
+ else {
+ printf ("this is the child process, with id %d, ROOT: %d, typ: %c, cislo: %i\n", (int) getpid (), (int) root_pid, typ, cislo);
+ sleep(20);
+ break;
+ }
}
- /* Wait for all threads to complete */
- for (i = 0; i < NUM_THREADS; i++) {
- pthread_join(threads[i], NULL);
- }
- printf ("Main(): Waited on %d threads. Done.\n", NUM_THREADS);
+ if (root_pid == getpid()) {
+ for (int i = 0; i < N_KONZUMENTU; i++) {
+ typ = 'K';
+ cislo = i;
- /* Clean up and exit */
- pthread_attr_destroy(&attr);
- for (int cislo_producenta = 0; cislo_producenta < M_PRODUCENTU; cislo_producenta++) {
- pthread_mutex_destroy(&mutexy_front[cislo_producenta]);
- pthread_cond_destroy(&condy_front[cislo_producenta]);
+ child_pid = fork ();
+ if (child_pid != 0) {
+ if (root_pid == 0) {
+ root_pid = getpid();
+ }
+ printf ("this is the parent process, with id %d\n", (int) getpid ());
+ printf ("the child's process id is %d\n", (int) child_pid);
+ sleep(1);
+ }
+ else {
+ printf ("this is the child process, with id %d, ROOT: %d, typ: %c, cislo: %i\n", (int) getpid (), (int) root_pid, typ, cislo);
+ sleep(20);
+ break;
+ }
+ }
+ if (root_pid == getpid()) {
+ sleep(20);
+ }
}
- pthread_exit (NULL);
+
return 0;
-}
+}
\ No newline at end of file
|
heracek/x36osy-producenti-konzumenti-processes
|
0108242def6e08883f8369730f8f47a64635213c
|
Pridana vychozi verze pouzivajici vlakna.
|
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..496ee2c
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+.DS_Store
\ No newline at end of file
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..f189cc1
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,16 @@
+# all after symbol '#' is comment
+
+# === which communication library to use ===
+CC = g++
+CFLAGS =
+LIBS = -lpthread
+# -lrt
+
+default: main
+
+main:main.cpp
+ $(CC) $(CFLAGS) -o main main.cpp $(LIBS)
+
+clear:
+ \rm main
+
diff --git a/main.cpp b/main.cpp
new file mode 100644
index 0000000..8232d0e
--- /dev/null
+++ b/main.cpp
@@ -0,0 +1,262 @@
+/**
+ * X36OSY - Producenti a konzumenti
+ *
+ * vypracoval: Tomas Horacek <[email protected]>
+ *
+ */
+
+#include <pthread.h>
+#include <stdio.h>
+#include <iostream>
+#include <queue>
+using namespace std;
+
+#define M_PRODUCENTU 5
+#define N_KONZUMENTU 3
+#define K_POLOZEK 3
+#define LIMIT_PRVKU 10
+
+#define NUM_THREADS M_PRODUCENTU + N_KONZUMENTU
+#define MAX_NAHODNA_DOBA 50000
+
+int thread_ids[NUM_THREADS];
+pthread_cond_t condy_front[M_PRODUCENTU];
+pthread_mutex_t mutexy_front[M_PRODUCENTU];
+struct Prvek;
+queue<Prvek*> fronty[M_PRODUCENTU];
+
+struct Prvek {
+ int cislo_producenta;
+ int poradove_cislo;
+ int pocet_precteni;
+
+ Prvek(int cislo_producenta, int poradove_cislo) :
+ cislo_producenta(cislo_producenta),
+ poradove_cislo(poradove_cislo),
+ pocet_precteni(0) { }
+};
+
+void pockej_nahodnou_dobu() {
+ double result = 0.0;
+ int doba = random() % MAX_NAHODNA_DOBA;
+
+ for (int j = 0; j < doba; j++)
+ result = result + (double)random();
+}
+
+/**
+ * void *my_producent(void *idp)
+ *
+ * pseudokod:
+ *
+def my_producent():
+ for cislo_prvku in range(LIMIT_PRVKU):
+ while je_fronta_plna():
+ pockej_na_uvolneni_prvku()
+
+ zamkni_frontu()
+ pridej_prvek_do_fronty()
+ odemkni_frontu()
+
+ pockej_nahodnou_dobu()
+
+ ukonci_vlakno()
+ */
+void *my_producent(void *idp) {
+ int cislo_producenta = *((int *) idp);
+ Prvek *prvek;
+ int velikos_fronty;
+ for (int poradove_cislo = 0; poradove_cislo < LIMIT_PRVKU; poradove_cislo++) {
+ prvek = new Prvek(cislo_producenta, poradove_cislo);
+
+ pthread_mutex_lock(&mutexy_front[cislo_producenta]);
+
+ while ((velikos_fronty = fronty[cislo_producenta].size()) > K_POLOZEK) {
+ printf("PRODUCENT %i je zablokovan - velikost fronty %i\n", cislo_producenta, velikos_fronty);
+ pthread_cond_wait(&condy_front[cislo_producenta], &mutexy_front[cislo_producenta]);
+ }
+
+ fronty[cislo_producenta].push(prvek);
+
+ pthread_mutex_unlock(&mutexy_front[cislo_producenta]);
+
+ printf("PRODUCENT %i pridal prvek %i - velikos fronty %i\n",
+ cislo_producenta,
+ poradove_cislo,
+ velikos_fronty
+ );
+
+ pockej_nahodnou_dobu();
+ }
+
+ printf("PRODUCENT %i konec\n", cislo_producenta);
+ pthread_exit(NULL);
+}
+
+/**
+ * void *konzument(void *idp)
+ *
+ * pseudokod:
+ *
+def konzument():
+ while True:
+ pockej_nahodnou_dobu()
+
+ ukonci_cteni = True
+ for producent in range(M_PRODUCENTU):
+ zamkni_frontu()
+ if not fornta_je_prazdna():
+ prvek = fronta[producent].front()
+
+ if prvek.poradove_cislo != poradova_cisla_poslednich_prectenych_prveku[producent]:
+ prvek.pocet_precteni++
+
+ if prvek.pocet_precteni == N_KONZUMENTU:
+ fronta[producent].pop()
+ delete prvek;
+ zavolej_uvolneni_prvku()
+
+ poradova_cisla_poslednich_prectenych_prveku[producent] = prvek.poradove_cislo
+ odemkni_frontu()
+
+ if ukonci_cteni:
+ ukonci_cteni = poradova_cisla_poslednich_prectenych_prveku[producent] == (LIMIT_PRVKU - 1)
+
+ if ukonci_cteni:
+ ukonci_vlakno()
+ */
+void *konzument(void *idp) {
+ int cislo_konzumenta = *((int *) idp) - M_PRODUCENTU;
+ bool ukonci_cteni;
+ int cislo_producenta;
+ int prectene_poradove_cislo;
+ int prectene_cislo_producenta;
+ int velikos_fronty;
+ Prvek *prvek;
+ int poradova_cisla_poslednich_prectenych_prveku[M_PRODUCENTU];
+ bool prvek_odstranen = false;
+ int nova_velikos_fronty;
+ bool nove_nacteny = false;
+ int pocet_precteni;
+
+ for (int cislo_producenta = 0; cislo_producenta < M_PRODUCENTU; cislo_producenta++) {
+ poradova_cisla_poslednich_prectenych_prveku[cislo_producenta] = -1;
+ }
+
+ while (1) {
+ pockej_nahodnou_dobu();
+
+ ukonci_cteni = true;
+ for (cislo_producenta = 0; cislo_producenta < M_PRODUCENTU; cislo_producenta++) {
+ pthread_mutex_lock(&mutexy_front[cislo_producenta]);
+
+ if ( ! fronty[cislo_producenta].empty()) {
+ prvek = fronty[cislo_producenta].front();
+ velikos_fronty = fronty[cislo_producenta].size();
+
+ prectene_poradove_cislo = prvek->poradove_cislo;
+ prectene_cislo_producenta = prvek->cislo_producenta;
+
+ if (prectene_poradove_cislo != poradova_cisla_poslednich_prectenych_prveku[cislo_producenta]) {
+ nove_nacteny = true;
+ pocet_precteni = ++(prvek->pocet_precteni);
+
+ if (prvek->pocet_precteni == N_KONZUMENTU) {
+ fronty[cislo_producenta].pop();
+ delete prvek;
+
+ pthread_cond_signal(&condy_front[cislo_producenta]);
+
+ prvek_odstranen = true;
+ nova_velikos_fronty = fronty[cislo_producenta].size();
+ if (nova_velikos_fronty == (K_POLOZEK - 1)) {
+ pthread_cond_signal(&condy_front[cislo_producenta]);
+ printf("konzument %i odblokoval frontu %i - velikost fronty %i\n",
+ cislo_konzumenta,
+ cislo_producenta,
+ velikos_fronty);
+ }
+ }
+
+ poradova_cisla_poslednich_prectenych_prveku[cislo_producenta] = prectene_poradove_cislo;
+ }
+ }
+
+ pthread_mutex_unlock(&mutexy_front[cislo_producenta]);
+
+ if (nove_nacteny) {
+ printf("konzument %i cte z fronty %i prvek %i - pocet precteni %i\n",
+ cislo_konzumenta,
+ cislo_producenta,
+ prectene_poradove_cislo,
+ pocet_precteni);
+ nove_nacteny = false;
+ }
+
+ if (prvek_odstranen) {
+ printf("konzument %i odsranil z fronty %i prvek %i - velikost fronty %i\n",
+ cislo_konzumenta,
+ cislo_producenta,
+ prectene_poradove_cislo,
+ nova_velikos_fronty);
+ prvek_odstranen = false;
+ }
+
+ if (ukonci_cteni) {
+ ukonci_cteni = poradova_cisla_poslednich_prectenych_prveku[cislo_producenta] == (LIMIT_PRVKU - 1);
+ }
+ }
+
+ if (ukonci_cteni) {
+ printf("konzument %i konec\n", cislo_konzumenta);
+ pthread_exit(NULL);
+ return NULL;
+ }
+ }
+ pthread_exit(NULL);
+}
+
+int main (int argc, char * const argv[]) {
+ int i;
+ pthread_t threads[NUM_THREADS];
+ pthread_attr_t attr;
+
+ for (int cislo_producenta = 0; cislo_producenta < M_PRODUCENTU; cislo_producenta++) {
+ pthread_mutex_init(&mutexy_front[cislo_producenta], NULL);
+ pthread_cond_init (&condy_front[cislo_producenta], NULL);
+ }
+
+ for (int thread_id = 0; thread_id < NUM_THREADS; thread_id++) {
+ thread_ids[thread_id] = thread_id;
+ }
+
+ /*
+ For portability, explicitly create threads in a joinable state
+ */
+ pthread_attr_init(&attr);
+ pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
+
+ int thred_i;
+ for (thred_i = 0; thred_i < M_PRODUCENTU; thred_i++) {
+ pthread_create(&threads[thred_i], &attr, my_producent, (void *)&thread_ids[thred_i]);
+ }
+
+ for (thred_i = M_PRODUCENTU; thred_i < NUM_THREADS; thred_i++) {
+ pthread_create(&threads[thred_i], &attr, konzument, (void *)&thread_ids[thred_i]);
+ }
+
+ /* Wait for all threads to complete */
+ for (i = 0; i < NUM_THREADS; i++) {
+ pthread_join(threads[i], NULL);
+ }
+ printf ("Main(): Waited on %d threads. Done.\n", NUM_THREADS);
+
+ /* Clean up and exit */
+ pthread_attr_destroy(&attr);
+ for (int cislo_producenta = 0; cislo_producenta < M_PRODUCENTU; cislo_producenta++) {
+ pthread_mutex_destroy(&mutexy_front[cislo_producenta]);
+ pthread_cond_destroy(&condy_front[cislo_producenta]);
+ }
+ pthread_exit (NULL);
+ return 0;
+}
diff --git a/readme.html b/readme.html
new file mode 100644
index 0000000..758af72
--- /dev/null
+++ b/readme.html
@@ -0,0 +1,96 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+ <title>Semestrálnà úloha X36OSY 2007</title>
+</head>
+<body>
+ <center><h1>Semestrálnà úloha X36OSY 2007</h1></center>
+ <center>Téma úlohy: Producenti a konzumenti</center>
+ <center>Vypracoval: Tomas Horacek <[email protected]></center>
+ <br />
+ <center>6. roÄnÃk, obor VýpoÄetnà technika, K336 FEL ÄVUT,<br />
+ Karlovo nám. 13, 121 35 Praha 2 </center>
+
+ <h2>Zadánà úlohy</h2>
+ <p>
+ MÄjme <i>m</i> producentů a <i>n</i> konzumentů.
+ Každý producent má svojà frontu o kapacitÄ <i>k</i> položek,
+ do které v náhodných intervalech zapisuje pokud je v nà volno, jinak se zablokuje a Äeká.
+ Položky ve frontách obsahujà ÄÃslo producenta a poÅadové ÄÃslo, ve kterém byly zapsány do fronty.
+ Konzumenti v náhodných intervalech Ätou položky z front. Každý konzument musà pÅeÄÃst vÅ¡echny
+ položky od všech producentů, tzn. že položky se mohou odstranit z front až
+ po pÅeÄtenà vÅ¡emi konzumenty.
+ </p>
+
+
+ <p><b>Vstup:</b> Producenti a konzumenti jsou reprezentováni vlákny/procesy a náhodnÄ generujÃ/Ätou položky.</p>
+ <p><b>Výstup:</b> Informace o tom, jak se mÄnà obsah jednotlivých front a informace v jakém stavu se producenti a konzument nacházejÃ.</p>
+
+ <h2>Analýza úlohy</h2>
+
+
+
+ <h2>ÅeÅ¡enà úlohy pomocà vláken</h2>
+
+ <p>Reseni je za pomoci mutexu, pseoudokod popisujici algoritmus je zde:</p>
+
+ <code><pre>
+ def my_producent():
+ for cislo_prvku in range(LIMIT_PRVKU):
+ while je_fronta_plna():
+ pockej_na_uvolneni_prvku()
+
+ zamkni_frontu()
+ pridej_prvek_do_fronty()
+ odemkni_frontu()
+
+ pockej_nahodnou_dobu()
+
+ ukonci_vlakno()
+ </pre></code>
+ <code><pre>
+ def konzument():
+ while True:
+ pockej_nahodnou_dobu()
+
+ ukonci_cteni = True
+ for producent in range(M_PRODUCENTU):
+ zamkni_frontu()
+ if not fornta_je_prazdna():
+ prvek = fronta[producent].front()
+
+ if prvek.poradove_cislo != poradova_cisla_poslednich_prectenych_prveku[producent]:
+ prvek.pocet_precteni++
+
+ if prvek.pocet_precteni == N_KONZUMENTU:
+ fronta[producent].pop()
+ delete prvek;
+ zavolej_uvolneni_prvku()
+
+ poradova_cisla_poslednich_prectenych_prveku[producent] = prvek.poradove_cislo
+ odemkni_frontu()
+
+ if ukonci_cteni:
+ ukonci_cteni = poradova_cisla_poslednich_prectenych_prveku[producent] == (LIMIT_PRVKU - 1)
+
+ if ukonci_cteni:
+ ukonci_vlakno()
+ </pre></code>
+
+ <h2>ÅeÅ¡enà úlohy pomocà procesů</h2>
+
+ <h2>ZávÄr</h2>
+
+ Uloha mi pomohla prakticky vyzkouset tvoreni vlaken a jejich synchronizaci.
+
+ <h2>Literatura</h2>
+
+ <ol>
+ <li>Slides ze cviceni</li>
+ <li>Priklady ze cviceni</li>
+ <li>manualove stranky</li>
+ </ol>
+
+</body>
+</html>
\ No newline at end of file
|
jeromer/modmemcachedinclude
|
764cdfb47ef1d6f563487a451f193ca397198156
|
- Added .hgignore
|
diff --git a/.hgignore b/.hgignore
new file mode 100644
index 0000000..888cef8
--- /dev/null
+++ b/.hgignore
@@ -0,0 +1,19 @@
+syntax: glob
+
+autom4te.cache/*
+src/.deps/*
+src/.libs/*
+config.*
+config/*
+Makefile
+Makefile.in
+aclocal.m4
+configure
+libtool
+src/ssi_include_memcached.la
+src/ssi_include_memcached_config.h
+src/ssi_include_memcached_la-ssi_include_memcached.lo
+src/ssi_include_memcached_la-ssi_include_memcached.o
+src/stamp-h1
+session.vim
+*.orig
\ No newline at end of file
|
jeromer/modmemcachedinclude
|
4f6408d0aa14198c1690fd25ea849dd6e7ac8e30
|
- Updated copyright
|
diff --git a/LICENSE b/LICENSE
index 189ed97..4498e4e 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,14 +1,17 @@
+Copyright [2008] [Jérôme Renard, [email protected]]
+Copyright [2009] [Jérôme Renard, [email protected]]
+
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
-limitations under the License.
+limitations under the License.
\ No newline at end of file
|
jeromer/modmemcachedinclude
|
eb8cb4e40157063ac83b9083a8f80302bff2abe9
|
- Updated installation documentation
|
diff --git a/INSTALL b/INSTALL
index 73a2458..715c6f6 100644
--- a/INSTALL
+++ b/INSTALL
@@ -1,101 +1,126 @@
What is this extension made for ?
=================================
This module may be used with any file that is pushed
in Memcached and meant to be fetched from an SSI tag.
How to compile this extension ?
===============================
Run
::
./autogen.sh
./configure
make
sudo make install
Depending on your system and your apr_memcache installation path
you may need to specify the following arguments for the configure script:
--with-apxs=/path/to/apache/bin/apxs
--with-apr-memcache=/path/to/apr_memcache/
For example here is my configuration
::
./configure --with-apxs=/usr/local/apache-2.2.9/bin/apxs \
- --with-apr-memcache=/opt/local
+ --with-apr-memcache=/usr/local/apache-2.2.9
Where apr_memcache.h is located in :
::
- /opt/local/include/apr_memcache-0/apr_memcache.h
+ /usr/local/apache-2.2.9/include/apr_memcache.h
Once everything is compiled, restart Apache
+Loading the module
+==================
+
+Edit your httpd.conf and add the following line :
+
+::
+
+ LoadModule ssi_include_memcached_module modules/ssi_include_memcached.so
+
How to test this extension ?
============================
In order to test the extension you have to first compile
the module and install it, once you are done you have to
launch test/push.php to store some contents in Memcached.
You can configure your Memcached host by editing push.php
After that you may create the following configuration
for Apache :
::
- LoadModule memcached_include_module modules/mod_memcached_include.so
- <Directory /path/to/mod_memcached_include/tests/>
- AddType text/html .shtml
- AddOutputFilter INCLUDES .shtml
- Options +Includes
- MemcachedHost localhost:11211
- MemcachedSoftMaxConn 10
- MemcachedHardMaxConn 15
- MemcachedTTL 10
- </Directory>
-
-You may also try this one
-
-::
-
- LoadModule memcached_include_module modules/mod_memcached_include.so
<Directory /path/to/mod_memcached_include/tests/>
AddType text/html .shtml
+ DefaultType text/html
Options Indexes FollowSymLinks +Includes
FilterDeclare SSI
FilterProvider SSI INCLUDES resp=Content-Type $text/html
FilterChain SSI
- MemcachedHost localhost:11211
+ MemcachedHost 127.0.0.1:11211
MemcachedSoftMaxConn 10
MemcachedHardMaxConn 15
MemcachedTTL 10
</Directory>
+Or in a VirtualHost
+
+::
+ <VirtualHost *:80>
+ ServerName example.com
+ DocumentRoot /path/to/documentroot/
+
+ #
+ # mod_memcached_include configuration
+ #
+ <Directory /path/to/documentroot/>
+ AddType .shtml text/html
+ DefaultType text/html
+ Options Indexes FollowSymLinks +Includes
+ FilterDeclare SSI
+ FilterProvider SSI INCLUDES resp=Content-Type $text/html
+ FilterChain SSI
+
+ MemcachedHost localhost:11211
+ MemcachedSoftMaxConn 100
+ MemcachedHardMaxConn 150
+ MemcachedTTL 100
+ </Directory>
+ </VirtualHost>
+
Once the file is stored in Memcached, you can ``test/pull-*.shtml`` files.
+If you have PHP installed, you can also run ``test/backgendgen.php`` but this
+require the pecl_memcache extension, available via the follwiing command :
+
+::
+
+ pecl install memcache
Compiling on Debian
===================
In order to compile this module for Debian, you will need the following packages :
- apache2-mpm-prefork
- libapr1-dev
- libaprutil1-dev
- apach2-prefork-dev
::
sudo apt-get install apache2-mpm-prefork libapr1-dev libaprutil1-dev apache2-prefork-dev libtool
..
Local Variables:
mode: rst
fill-column: 79
End:
vim: et syn=rst tw=79
\ No newline at end of file
|
jeromer/modmemcachedinclude
|
9ca3ddc3ed74e9fa706d15b532eadb7577a3f0ad
|
- Fixed wrong path to apr_memcache.h
|
diff --git a/m4/apr_memcache.m4 b/m4/apr_memcache.m4
index 512c073..921394a 100644
--- a/m4/apr_memcache.m4
+++ b/m4/apr_memcache.m4
@@ -1,59 +1,58 @@
dnl -------------------------------------------------------- -*- autoconf -*-
dnl Copyright 2005 The Apache Software Foundation
dnl
dnl Licensed under the Apache License, Version 2.0 (the "License");
dnl you may not use this file except in compliance with the License.
dnl You may obtain a copy of the License at
dnl
dnl http://www.apache.org/licenses/LICENSE-2.0
dnl
dnl Unless required by applicable law or agreed to in writing, software
dnl distributed under the License is distributed on an "AS IS" BASIS,
dnl WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
dnl See the License for the specific language governing permissions and
dnl limitations under the License.
dnl Check for apr_memcache
dnl CHECK_APR_MEMCACHE(ACTION-IF-FOUND [, ACTION-IF-NOT-FOUND])
AC_DEFUN([CHECK_APR_MEMCACHE],
[dnl
APR_MEMCACHE_URL="http://www.outoforder.cc/projects/libs/apr_memcache/"
AC_ARG_WITH(
apr_memcache,
[AC_HELP_STRING([--with-apr-memcache=PATH],[Path to apr_memcache library])],
mc_path="$withval",
:)
if test -z $mc_path; then
test_paths="/usr/local/apr_memcache /usr/local /usr /opt/local"
else
test_paths="${mc_path}"
fi
for x in $test_paths ; do
AC_MSG_CHECKING([for apr_memcache library in ${x}])
- if test -f ${x}/include/apr_memcache-0/apr_memcache.h; then
+ if test -f ${x}/include/apr_memcache.h; then
AC_MSG_RESULT([yes])
APR_MEMCACHE_LIBS="-R${x}/lib -L${x}/lib -lapr_memcache"
APR_MEMCACHE_CFLAGS="-I${x}/include/apr_memcache-0"
break
else
AC_MSG_RESULT([no])
fi
done
AC_SUBST(APR_MEMCACHE_LIBS)
AC_SUBST(APR_MEMCACHE_CFLAGS)
if test -z "${APR_MEMCACHE_LIBS}"; then
AC_MSG_NOTICE([*** apr_memcache library not found.])
ifelse([$2], , AC_MSG_ERROR([The apr_memcache library is required.
See $APR_MEMCACHE_URL]), [$2])
else
AC_MSG_NOTICE([found apr_memcache.])
ifelse([$1], , , [$1])
fi
])
-
|
jeromer/modmemcachedinclude
|
e48d95c428b5552f6e402b2152328c0805436a8d
|
- Updated README
|
diff --git a/README b/README
index 16b8d39..fb9fa90 100644
--- a/README
+++ b/README
@@ -1,18 +1,22 @@
History of this project.
-Date : 2009/05/06, 2.00 pm
+Date : 2009/05/06, 4.00 pm
+--------------------------
+The contents of branches/ssi_include_memcached is now merged in trunk
+Date : 2009/05/06, 2.00 pm
+-------------------------
At the very beginning this module was made for a customer.
But he decided not to use this module for some reason.
So I decided to open this project to anyone interested by SSIs and Memcached.
At the beginning the module was sort of a big patch integrated directly
into mod_include, this is why it was required to disable mod_include in order
to use it.
After a few months I decided to rewrite everything because it looked too inelegant to me.
This is why I decided to create the "ssi_include_memcached" branche which is the future
of this project, I changed its name as I found "ssi_include_memcached" to be more relevant and self explanatory.
-This branche will be integrated back in trunk in a near future.
\ No newline at end of file
+This branch will be integrated back in trunk in a near future.
\ No newline at end of file
|
jeromer/modmemcachedinclude
|
2dfcdc1bcab409172a5136bca6efc9e5dab2a59b
|
- Merged branches/ssi_include_memcached rev.42 in trunk
|
diff --git a/README b/README
index e69de29..16b8d39 100644
--- a/README
+++ b/README
@@ -0,0 +1,18 @@
+History of this project.
+
+Date : 2009/05/06, 2.00 pm
+
+At the very beginning this module was made for a customer.
+But he decided not to use this module for some reason.
+
+So I decided to open this project to anyone interested by SSIs and Memcached.
+
+At the beginning the module was sort of a big patch integrated directly
+into mod_include, this is why it was required to disable mod_include in order
+to use it.
+
+After a few months I decided to rewrite everything because it looked too inelegant to me.
+This is why I decided to create the "ssi_include_memcached" branche which is the future
+of this project, I changed its name as I found "ssi_include_memcached" to be more relevant and self explanatory.
+
+This branche will be integrated back in trunk in a near future.
\ No newline at end of file
diff --git a/build.sh b/build.sh
index 805a5b3..3cb2fbe 100755
--- a/build.sh
+++ b/build.sh
@@ -1,15 +1,13 @@
#! /bin/bash
APR_MEMCACHE=/usr/local/apache-2.2.9
APXS_PATH=/usr/local/apache-2.2.9/bin/apxs
APACHECTL_PATH=/usr/local/apache-2.2.9/bin/apachectl
-# enable debug informations
-# export CFLAGS="-D DEBUG_MEMCACHED_INCLUDE"
+make clean
./autogen.sh && \
-make clean && \
./configure --with-apr-memcache=$APR_MEMCACHE --with-apxs=$APXS_PATH && \
make && \
make install && \
sudo $APACHECTL_PATH restart
\ No newline at end of file
diff --git a/configure.ac b/configure.ac
index 46ecaf5..93c36e3 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1,43 +1,43 @@
-AC_INIT(mod_memcached_include, 1.0)
+AC_INIT(ssi_include_memcached, 1.0)
MAKE_CONFIG_NICE(config.nice)
AC_PREREQ(2.53)
-AC_CONFIG_SRCDIR([src/mod_memcached_include.c])
+AC_CONFIG_SRCDIR([src/ssi_include_memcached.c])
AC_CONFIG_AUX_DIR(config)
AC_PROG_LIBTOOL
AM_MAINTAINER_MODE
AC_CANONICAL_TARGET
AM_INIT_AUTOMAKE(AC_PACKAGE_NAME, AC_PACKAGE_VERSION)
-AM_CONFIG_HEADER([src/mod_memcached_include_config.h:config.in])
+AM_CONFIG_HEADER([src/ssi_include_memcached_config.h:config.in])
AC_PROG_CC
AC_PROG_CXX
AC_PROG_LD
AC_PROG_INSTALL
CHECK_APR_MEMCACHE()
AP_VERSION=2.2.9
CHECK_APACHE(,$AP_VERSION,
:,:,
AC_MSG_ERROR([*** Apache version $AP_VERSION not found!])
)
prefix=${AP_PREFIX}
LIBTOOL="`${APR_CONFIG} --apr-libtool`"
AC_SUBST(LIBTOOL)
MODULE_CFLAGS="${APXS_CFLAGS} ${AP_INCLUDES} ${APR_INCLUDES} ${APU_INCLUDES} ${APR_MEMCACHE_CFLAGS}"
AC_SUBST(MODULE_CFLAGS)
MODULE_LDFLAGS=" `${APR_CONFIG} --link-libtool` `${APU_CONFIG} --link-libtool`"
AC_SUBST(MODULE_LDFLAGS)
BIN_LDFLAGS=" `${APR_CONFIG} --link-libtool` `${APU_CONFIG} --link-libtool` `${APU_CONFIG} --ldflags --libs` `${APR_CONFIG} --ldflags --libs`"
AC_SUBST(BIN_LDFLAGS)
dnl this should be a list to all of the makefiles you expect to be generated
AC_CONFIG_FILES([Makefile src/Makefile])
-AC_OUTPUT
+AC_OUTPUT
\ No newline at end of file
diff --git a/src/Makefile.am b/src/Makefile.am
index bc0183d..c075677 100644
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -1,10 +1,10 @@
-mod_memcached_include_la_SOURCES = mod_memcached_include.c mod_memcached_include.h
-mod_memcached_include_la_CFLAGS = -Wall ${MODULE_CFLAGS}
-mod_memcached_include_la_LDFLAGS = -rpath ${AP_LIBEXECDIR} -module -avoid-version ${MODULE_LDFLAGS}
+ssi_include_memcached_la_SOURCES = ssi_include_memcached.c
+ssi_include_memcached_la_CFLAGS = -Wall ${MODULE_CFLAGS}
+ssi_include_memcached_la_LDFLAGS = -rpath ${AP_LIBEXECDIR} -module -avoid-version ${MODULE_LDFLAGS}
-mod_LTLIBRARIES = mod_memcached_include.la
+mod_LTLIBRARIES = ssi_include_memcached.la
moddir=${AP_LIBEXECDIR}
install: install-am
- rm -f $(DESTDIR)${AP_LIBEXECDIR}/mod_memcached_include.a
- rm -f $(DESTDIR)${AP_LIBEXECDIR}/mod_memcached_include.la
+ rm -f $(DESTDIR)${AP_LIBEXECDIR}/ssi_include_memcached.a
+ rm -f $(DESTDIR)${AP_LIBEXECDIR}/ssi_include_memcached.la
\ No newline at end of file
diff --git a/src/mod_memcached_include.c b/src/mod_memcached_include.c
deleted file mode 100644
index 8c6fe81..0000000
--- a/src/mod_memcached_include.c
+++ /dev/null
@@ -1,4066 +0,0 @@
-/* Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "apr.h"
-#include "apr_strings.h"
-#include "apr_thread_proc.h"
-#include "apr_hash.h"
-#include "apr_user.h"
-#include "apr_lib.h"
-#include "apr_optional.h"
-
-#define APR_WANT_STRFUNC
-#define APR_WANT_MEMFUNC
-#include "apr_want.h"
-
-#include "ap_config.h"
-#include "util_filter.h"
-#include "httpd.h"
-#include "http_config.h"
-#include "http_core.h"
-#include "http_request.h"
-#include "http_core.h"
-#include "http_protocol.h"
-#include "http_log.h"
-#include "http_main.h"
-#include "util_script.h"
-#include "http_core.h"
-#include "mod_memcached_include.h"
-
-#include "apr_memcache.h"
-
-/* helper for Latin1 <-> entity encoding */
-#if APR_CHARSET_EBCDIC
-#include "util_ebcdic.h"
-#define RAW_ASCII_CHAR(ch) apr_xlate_conv_byte(ap_hdrs_from_ascii, \
- (unsigned char)ch)
-#else /* APR_CHARSET_EBCDIC */
-#define RAW_ASCII_CHAR(ch) (ch)
-#endif /* !APR_CHARSET_EBCDIC */
-
-
-/*
- * +-------------------------------------------------------+
- * | |
- * | Types and Structures
- * | |
- * +-------------------------------------------------------+
- */
-
-/* sll used for string expansion */
-typedef struct result_item {
- struct result_item *next;
- apr_size_t len;
- const char *string;
-} result_item_t;
-
-/* conditional expression parser stuff */
-typedef enum {
- TOKEN_STRING,
- TOKEN_RE,
- TOKEN_AND,
- TOKEN_OR,
- TOKEN_NOT,
- TOKEN_EQ,
- TOKEN_NE,
- TOKEN_RBRACE,
- TOKEN_LBRACE,
- TOKEN_GROUP,
- TOKEN_GE,
- TOKEN_LE,
- TOKEN_GT,
- TOKEN_LT,
- TOKEN_ACCESS
-} token_type_t;
-
-typedef struct {
- token_type_t type;
- const char *value;
-#ifdef DEBUG_INCLUDE
- const char *s;
-#endif
-} token_t;
-
-typedef struct parse_node {
- struct parse_node *parent;
- struct parse_node *left;
- struct parse_node *right;
- token_t token;
- int value;
- int done;
-#ifdef DEBUG_INCLUDE
- int dump_done;
-#endif
-} parse_node_t;
-
-typedef enum {
- XBITHACK_OFF,
- XBITHACK_ON,
- XBITHACK_FULL
-} xbithack_t;
-
-typedef struct {
- const char *default_error_msg;
- const char *default_time_fmt;
- const char *undefined_echo;
- xbithack_t xbithack;
- const int accessenable;
-
- apr_memcache_t *memcached;
- apr_array_header_t *servers;
-
- apr_uint32_t conn_min;
- apr_uint32_t conn_smax;
- apr_uint32_t conn_max;
- apr_uint32_t conn_ttl;
- apr_uint16_t max_servers;
- apr_off_t min_size;
- apr_off_t max_size;
-} include_dir_config;
-
-typedef struct {
- const char *host;
- apr_port_t port;
- apr_memcache_server_t *server;
-} memcached_include_server_t;
-
-#define DEFAULT_MAX_SERVERS 1
-#define DEFAULT_MIN_CONN 1
-#define DEFAULT_SMAX 10
-#define DEFAULT_MAX 15
-#define DEFAULT_TTL 10
-#define DEFAULT_MIN_SIZE 1
-#define DEFAULT_MAX_SIZE 1048576
-
-typedef struct {
- const char *default_start_tag;
- const char *default_end_tag;
-} include_server_config;
-
-/* main parser states */
-typedef enum {
- PARSE_PRE_HEAD,
- PARSE_HEAD,
- PARSE_DIRECTIVE,
- PARSE_DIRECTIVE_POSTNAME,
- PARSE_DIRECTIVE_TAIL,
- PARSE_DIRECTIVE_POSTTAIL,
- PARSE_PRE_ARG,
- PARSE_ARG,
- PARSE_ARG_NAME,
- PARSE_ARG_POSTNAME,
- PARSE_ARG_EQ,
- PARSE_ARG_PREVAL,
- PARSE_ARG_VAL,
- PARSE_ARG_VAL_ESC,
- PARSE_ARG_POSTVAL,
- PARSE_TAIL,
- PARSE_TAIL_SEQ,
- PARSE_EXECUTE
-} parse_state_t;
-
-typedef struct arg_item {
- struct arg_item *next;
- char *name;
- apr_size_t name_len;
- char *value;
- apr_size_t value_len;
-} arg_item_t;
-
-typedef struct {
- const char *source;
- const char *rexp;
- apr_size_t nsub;
- ap_regmatch_t match[AP_MAX_REG_MATCH];
-} backref_t;
-
-typedef struct {
- unsigned int T[256];
- unsigned int x;
- apr_size_t pattern_len;
-} bndm_t;
-
-struct ssi_internal_ctx {
- parse_state_t state;
- int seen_eos;
- int error;
- char quote; /* quote character value (or \0) */
- apr_size_t parse_pos; /* parse position of partial matches */
- apr_size_t bytes_read;
-
- apr_bucket_brigade *tmp_bb;
-
- request_rec *r;
- const char *start_seq;
- bndm_t *start_seq_pat;
- const char *end_seq;
- apr_size_t end_seq_len;
- char *directive; /* name of the current directive */
- apr_size_t directive_len; /* length of the current directive name */
-
- arg_item_t *current_arg; /* currently parsed argument */
- arg_item_t *argv; /* all arguments */
-
- backref_t *re; /* NULL if there wasn't a regex yet */
-
- const char *undefined_echo;
- apr_size_t undefined_echo_len;
-
- int accessenable; /* is using the access tests allowed? */
-
-#ifdef DEBUG_INCLUDE
- struct {
- ap_filter_t *f;
- apr_bucket_brigade *bb;
- } debug;
-#endif
-};
-
-
-/*
- * +-------------------------------------------------------+
- * | |
- * | Debugging Utilities
- * | |
- * +-------------------------------------------------------+
- */
-
-#ifdef DEBUG_INCLUDE
-
-#define TYPE_TOKEN(token, ttype) do { \
- (token)->type = ttype; \
- (token)->s = #ttype; \
-} while(0)
-
-#define CREATE_NODE(ctx, name) do { \
- (name) = apr_palloc((ctx)->dpool, sizeof(*(name))); \
- (name)->parent = (name)->left = (name)->right = NULL; \
- (name)->done = 0; \
- (name)->dump_done = 0; \
-} while(0)
-
-static void debug_printf(include_ctx_t *ctx, const char *fmt, ...)
-{
- va_list ap;
- char *debug__str;
-
- va_start(ap, fmt);
- debug__str = apr_pvsprintf(ctx->pool, fmt, ap);
- va_end(ap);
-
- APR_BRIGADE_INSERT_TAIL(ctx->intern->debug.bb, apr_bucket_pool_create(
- debug__str, strlen(debug__str), ctx->pool,
- ctx->intern->debug.f->c->bucket_alloc));
-}
-
-#define DUMP__CHILD(ctx, is, node, child) if (1) { \
- parse_node_t *d__c = node->child; \
- if (d__c) { \
- if (!d__c->dump_done) { \
- if (d__c->parent != node) { \
- debug_printf(ctx, "!!! Parse tree is not consistent !!!\n"); \
- if (!d__c->parent) { \
- debug_printf(ctx, "Parent of " #child " child node is " \
- "NULL.\n"); \
- } \
- else { \
- debug_printf(ctx, "Parent of " #child " child node " \
- "points to another node (of type %s)!\n", \
- d__c->parent->token.s); \
- } \
- return; \
- } \
- node = d__c; \
- continue; \
- } \
- } \
- else { \
- debug_printf(ctx, "%s(missing)\n", is); \
- } \
-}
-
-static void debug_dump_tree(include_ctx_t *ctx, parse_node_t *root)
-{
- parse_node_t *current;
- char *is;
-
- if (!root) {
- debug_printf(ctx, " -- Parse Tree empty --\n\n");
- return;
- }
-
- debug_printf(ctx, " ----- Parse Tree -----\n");
- current = root;
- is = " ";
-
- while (current) {
- switch (current->token.type) {
- case TOKEN_STRING:
- case TOKEN_RE:
- debug_printf(ctx, "%s%s (%s)\n", is, current->token.s,
- current->token.value);
- current->dump_done = 1;
- current = current->parent;
- continue;
-
- case TOKEN_NOT:
- case TOKEN_GROUP:
- case TOKEN_RBRACE:
- case TOKEN_LBRACE:
- if (!current->dump_done) {
- debug_printf(ctx, "%s%s\n", is, current->token.s);
- is = apr_pstrcat(ctx->dpool, is, " ", NULL);
- current->dump_done = 1;
- }
-
- DUMP__CHILD(ctx, is, current, right)
-
- if (!current->right || current->right->dump_done) {
- is = apr_pstrmemdup(ctx->dpool, is, strlen(is) - 4);
- if (current->right) current->right->dump_done = 0;
- current = current->parent;
- }
- continue;
-
- default:
- if (!current->dump_done) {
- debug_printf(ctx, "%s%s\n", is, current->token.s);
- is = apr_pstrcat(ctx->dpool, is, " ", NULL);
- current->dump_done = 1;
- }
-
- DUMP__CHILD(ctx, is, current, left)
- DUMP__CHILD(ctx, is, current, right)
-
- if ((!current->left || current->left->dump_done) &&
- (!current->right || current->right->dump_done)) {
-
- is = apr_pstrmemdup(ctx->dpool, is, strlen(is) - 4);
- if (current->left) current->left->dump_done = 0;
- if (current->right) current->right->dump_done = 0;
- current = current->parent;
- }
- continue;
- }
- }
-
- /* it is possible to call this function within the parser loop, to see
- * how the tree is built. That way, we must cleanup after us to dump
- * always the whole tree
- */
- root->dump_done = 0;
- if (root->left) root->left->dump_done = 0;
- if (root->right) root->right->dump_done = 0;
-
- debug_printf(ctx, " --- End Parse Tree ---\n\n");
-
- return;
-}
-
-#define DEBUG_INIT(ctx, filter, brigade) do { \
- (ctx)->intern->debug.f = filter; \
- (ctx)->intern->debug.bb = brigade; \
-} while(0)
-
-#define DEBUG_PRINTF(arg) debug_printf arg
-
-#define DEBUG_DUMP_TOKEN(ctx, token) do { \
- token_t *d__t = (token); \
- \
- if (d__t->type == TOKEN_STRING || d__t->type == TOKEN_RE) { \
- DEBUG_PRINTF(((ctx), " Found: %s (%s)\n", d__t->s, d__t->value)); \
- } \
- else { \
- DEBUG_PRINTF((ctx, " Found: %s\n", d__t->s)); \
- } \
-} while(0)
-
-#define DEBUG_DUMP_EVAL(ctx, node) do { \
- char c = '"'; \
- switch ((node)->token.type) { \
- case TOKEN_STRING: \
- debug_printf((ctx), " Evaluate: %s (%s) -> %c\n", (node)->token.s,\
- (node)->token.value, ((node)->value) ? '1':'0'); \
- break; \
- case TOKEN_AND: \
- case TOKEN_OR: \
- debug_printf((ctx), " Evaluate: %s (Left: %s; Right: %s) -> %c\n",\
- (node)->token.s, \
- (((node)->left->done) ? ((node)->left->value ?"1":"0") \
- : "short circuited"), \
- (((node)->right->done) ? ((node)->right->value?"1":"0") \
- : "short circuited"), \
- (node)->value ? '1' : '0'); \
- break; \
- case TOKEN_EQ: \
- case TOKEN_NE: \
- case TOKEN_GT: \
- case TOKEN_GE: \
- case TOKEN_LT: \
- case TOKEN_LE: \
- if ((node)->right->token.type == TOKEN_RE) c = '/'; \
- debug_printf((ctx), " Compare: %s (\"%s\" with %c%s%c) -> %c\n", \
- (node)->token.s, \
- (node)->left->token.value, \
- c, (node)->right->token.value, c, \
- (node)->value ? '1' : '0'); \
- break; \
- default: \
- debug_printf((ctx), " Evaluate: %s -> %c\n", (node)->token.s, \
- (node)->value ? '1' : '0'); \
- break; \
- } \
-} while(0)
-
-#define DEBUG_DUMP_UNMATCHED(ctx, unmatched) do { \
- if (unmatched) { \
- DEBUG_PRINTF(((ctx), " Unmatched %c\n", (char)(unmatched))); \
- } \
-} while(0)
-
-#define DEBUG_DUMP_COND(ctx, text) \
- DEBUG_PRINTF(((ctx), "**** %s cond status=\"%c\"\n", (text), \
- ((ctx)->flags & SSI_FLAG_COND_TRUE) ? '1' : '0'))
-
-#define DEBUG_DUMP_TREE(ctx, root) debug_dump_tree(ctx, root)
-
-#else /* DEBUG_INCLUDE */
-
-#define TYPE_TOKEN(token, ttype) (token)->type = ttype
-
-#define CREATE_NODE(ctx, name) do { \
- (name) = apr_palloc((ctx)->dpool, sizeof(*(name))); \
- (name)->parent = (name)->left = (name)->right = NULL; \
- (name)->done = 0; \
-} while(0)
-
-#define DEBUG_INIT(ctx, f, bb)
-#define DEBUG_PRINTF(arg)
-#define DEBUG_DUMP_TOKEN(ctx, token)
-#define DEBUG_DUMP_EVAL(ctx, node)
-#define DEBUG_DUMP_UNMATCHED(ctx, unmatched)
-#define DEBUG_DUMP_COND(ctx, text)
-#define DEBUG_DUMP_TREE(ctx, root)
-
-#endif /* !DEBUG_INCLUDE */
-
-
-/*
- * +-------------------------------------------------------+
- * | |
- * | Static Module Data
- * | |
- * +-------------------------------------------------------+
- */
-
-/* global module structure */
-module AP_MODULE_DECLARE_DATA memcached_include_module;
-
-/* function handlers for include directives */
-static apr_hash_t *include_handlers;
-
-/* forward declaration of handler registry */
-static APR_OPTIONAL_FN_TYPE(ap_register_memcached_include_handler) *ssi_pfn_register;
-
-/* Sentinel value to store in subprocess_env for items that
- * shouldn't be evaluated until/unless they're actually used
- */
-static const char lazy_eval_sentinel;
-#define LAZY_VALUE (&lazy_eval_sentinel)
-
-/* default values */
-#define DEFAULT_START_SEQUENCE "<!--#"
-#define DEFAULT_END_SEQUENCE "-->"
-#define DEFAULT_ERROR_MSG "[an error occurred while processing this directive]"
-#define DEFAULT_TIME_FORMAT "%A, %d-%b-%Y %H:%M:%S %Z"
-#define DEFAULT_UNDEFINED_ECHO "(none)"
-
-#ifdef XBITHACK
-#define DEFAULT_XBITHACK XBITHACK_FULL
-#else
-#define DEFAULT_XBITHACK XBITHACK_OFF
-#endif
-
-
-/*
- * +-------------------------------------------------------+
- * | |
- * | Environment/Expansion Functions
- * | |
- * +-------------------------------------------------------+
- */
-
-/*
- * decodes a string containing html entities or numeric character references.
- * 's' is overwritten with the decoded string.
- * If 's' is syntatically incorrect, then the followed fixups will be made:
- * unknown entities will be left undecoded;
- * references to unused numeric characters will be deleted.
- * In particular, � will not be decoded, but will be deleted.
- */
-
-/* maximum length of any ISO-LATIN-1 HTML entity name. */
-#define MAXENTLEN (6)
-
-/* The following is a shrinking transformation, therefore safe. */
-
-static void decodehtml(char *s)
-{
- int val, i, j;
- char *p;
- const char *ents;
- static const char * const entlist[MAXENTLEN + 1] =
- {
- NULL, /* 0 */
- NULL, /* 1 */
- "lt\074gt\076", /* 2 */
- "amp\046ETH\320eth\360", /* 3 */
- "quot\042Auml\304Euml\313Iuml\317Ouml\326Uuml\334auml\344euml"
- "\353iuml\357ouml\366uuml\374yuml\377", /* 4 */
-
- "Acirc\302Aring\305AElig\306Ecirc\312Icirc\316Ocirc\324Ucirc"
- "\333THORN\336szlig\337acirc\342aring\345aelig\346ecirc\352"
- "icirc\356ocirc\364ucirc\373thorn\376", /* 5 */
-
- "Agrave\300Aacute\301Atilde\303Ccedil\307Egrave\310Eacute\311"
- "Igrave\314Iacute\315Ntilde\321Ograve\322Oacute\323Otilde"
- "\325Oslash\330Ugrave\331Uacute\332Yacute\335agrave\340"
- "aacute\341atilde\343ccedil\347egrave\350eacute\351igrave"
- "\354iacute\355ntilde\361ograve\362oacute\363otilde\365"
- "oslash\370ugrave\371uacute\372yacute\375" /* 6 */
- };
-
- /* Do a fast scan through the string until we find anything
- * that needs more complicated handling
- */
- for (; *s != '&'; s++) {
- if (*s == '\0') {
- return;
- }
- }
-
- for (p = s; *s != '\0'; s++, p++) {
- if (*s != '&') {
- *p = *s;
- continue;
- }
- /* find end of entity */
- for (i = 1; s[i] != ';' && s[i] != '\0'; i++) {
- continue;
- }
-
- if (s[i] == '\0') { /* treat as normal data */
- *p = *s;
- continue;
- }
-
- /* is it numeric ? */
- if (s[1] == '#') {
- for (j = 2, val = 0; j < i && apr_isdigit(s[j]); j++) {
- val = val * 10 + s[j] - '0';
- }
- s += i;
- if (j < i || val <= 8 || (val >= 11 && val <= 31) ||
- (val >= 127 && val <= 160) || val >= 256) {
- p--; /* no data to output */
- }
- else {
- *p = RAW_ASCII_CHAR(val);
- }
- }
- else {
- j = i - 1;
- if (j > MAXENTLEN || entlist[j] == NULL) {
- /* wrong length */
- *p = '&';
- continue; /* skip it */
- }
- for (ents = entlist[j]; *ents != '\0'; ents += i) {
- if (strncmp(s + 1, ents, j) == 0) {
- break;
- }
- }
-
- if (*ents == '\0') {
- *p = '&'; /* unknown */
- }
- else {
- *p = RAW_ASCII_CHAR(((const unsigned char *) ents)[j]);
- s += i;
- }
- }
- }
-
- *p = '\0';
-}
-
-static void add_include_vars(request_rec *r, const char *timefmt)
-{
- apr_table_t *e = r->subprocess_env;
- char *t;
-
- apr_table_setn(e, "DATE_LOCAL", LAZY_VALUE);
- apr_table_setn(e, "DATE_GMT", LAZY_VALUE);
- apr_table_setn(e, "LAST_MODIFIED", LAZY_VALUE);
- apr_table_setn(e, "DOCUMENT_URI", r->uri);
- if (r->path_info && *r->path_info) {
- apr_table_setn(e, "DOCUMENT_PATH_INFO", r->path_info);
- }
- apr_table_setn(e, "USER_NAME", LAZY_VALUE);
- if (r->filename && (t = strrchr(r->filename, '/'))) {
- apr_table_setn(e, "DOCUMENT_NAME", ++t);
- }
- else {
- apr_table_setn(e, "DOCUMENT_NAME", r->uri);
- }
- if (r->args) {
- char *arg_copy = apr_pstrdup(r->pool, r->args);
-
- ap_unescape_url(arg_copy);
- apr_table_setn(e, "QUERY_STRING_UNESCAPED",
- ap_escape_shell_cmd(r->pool, arg_copy));
- }
-}
-
-static const char *add_include_vars_lazy(request_rec *r, const char *var)
-{
- char *val;
- if (!strcasecmp(var, "DATE_LOCAL")) {
- include_dir_config *conf =
- (include_dir_config *)ap_get_module_config(r->per_dir_config,
- &memcached_include_module);
- val = ap_ht_time(r->pool, r->request_time, conf->default_time_fmt, 0);
- }
- else if (!strcasecmp(var, "DATE_GMT")) {
- include_dir_config *conf =
- (include_dir_config *)ap_get_module_config(r->per_dir_config,
- &memcached_include_module);
- val = ap_ht_time(r->pool, r->request_time, conf->default_time_fmt, 1);
- }
- else if (!strcasecmp(var, "LAST_MODIFIED")) {
- include_dir_config *conf =
- (include_dir_config *)ap_get_module_config(r->per_dir_config,
- &memcached_include_module);
- val = ap_ht_time(r->pool, r->finfo.mtime, conf->default_time_fmt, 0);
- }
- else if (!strcasecmp(var, "USER_NAME")) {
- if (apr_uid_name_get(&val, r->finfo.user, r->pool) != APR_SUCCESS) {
- val = "<unknown>";
- }
- }
- else {
- val = NULL;
- }
-
- if (val) {
- apr_table_setn(r->subprocess_env, var, val);
- }
- return val;
-}
-
-static const char *get_include_var(const char *var, include_ctx_t *ctx)
-{
- const char *val;
- request_rec *r = ctx->intern->r;
-
- if (apr_isdigit(*var) && !var[1]) {
- apr_size_t idx = *var - '0';
- backref_t *re = ctx->intern->re;
-
- /* Handle $0 .. $9 from the last regex evaluated.
- * The choice of returning NULL strings on not-found,
- * v.s. empty strings on an empty match is deliberate.
- */
- if (!re) {
- ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
- "regex capture $%" APR_SIZE_T_FMT " refers to no regex in %s",
- idx, r->filename);
- return NULL;
- }
- else {
- if (re->nsub < idx || idx >= AP_MAX_REG_MATCH) {
- ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
- "regex capture $%" APR_SIZE_T_FMT
- " is out of range (last regex was: '%s') in %s",
- idx, re->rexp, r->filename);
- return NULL;
- }
-
- if (re->match[idx].rm_so < 0 || re->match[idx].rm_eo < 0) {
- return NULL;
- }
-
- val = apr_pstrmemdup(ctx->dpool, re->source + re->match[idx].rm_so,
- re->match[idx].rm_eo - re->match[idx].rm_so);
- }
- }
- else {
- val = apr_table_get(r->subprocess_env, var);
-
- if (val == LAZY_VALUE) {
- val = add_include_vars_lazy(r, var);
- }
- }
-
- return val;
-}
-
-/*
- * Do variable substitution on strings
- *
- * (Note: If out==NULL, this function allocs a buffer for the resulting
- * string from ctx->pool. The return value is always the parsed string)
- */
-static char *ap_ssi_parse_string(include_ctx_t *ctx, const char *in, char *out,
- apr_size_t length, int leave_name)
-{
- request_rec *r = ctx->intern->r;
- result_item_t *result = NULL, *current = NULL;
- apr_size_t outlen = 0, inlen, span;
- char *ret = NULL, *eout = NULL;
- const char *p;
-
- if (out) {
- /* sanity check, out && !length is not supported */
- ap_assert(out && length);
-
- ret = out;
- eout = out + length - 1;
- }
-
- span = strcspn(in, "\\$");
- inlen = strlen(in);
-
- /* fast exit */
- if (inlen == span) {
- if (out) {
- apr_cpystrn(out, in, length);
- }
- else {
- ret = apr_pstrmemdup(ctx->pool, in, (length && length <= inlen)
- ? length - 1 : inlen);
- }
-
- return ret;
- }
-
- /* well, actually something to do */
- p = in + span;
-
- if (out) {
- if (span) {
- memcpy(out, in, (out+span <= eout) ? span : (eout-out));
- out += span;
- }
- }
- else {
- current = result = apr_palloc(ctx->dpool, sizeof(*result));
- current->next = NULL;
- current->string = in;
- current->len = span;
- outlen = span;
- }
-
- /* loop for specials */
- do {
- if ((out && out >= eout) || (length && outlen >= length)) {
- break;
- }
-
- /* prepare next entry */
- if (!out && current->len) {
- current->next = apr_palloc(ctx->dpool, sizeof(*current->next));
- current = current->next;
- current->next = NULL;
- current->len = 0;
- }
-
- /*
- * escaped character
- */
- if (*p == '\\') {
- if (out) {
- *out++ = (p[1] == '$') ? *++p : *p;
- ++p;
- }
- else {
- current->len = 1;
- current->string = (p[1] == '$') ? ++p : p;
- ++p;
- ++outlen;
- }
- }
-
- /*
- * variable expansion
- */
- else { /* *p == '$' */
- const char *newp = NULL, *ep, *key = NULL;
-
- if (*++p == '{') {
- ep = ap_strchr_c(++p, '}');
- if (!ep) {
- ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Missing '}' on "
- "variable \"%s\" in %s", p, r->filename);
- break;
- }
-
- if (p < ep) {
- key = apr_pstrmemdup(ctx->dpool, p, ep - p);
- newp = ep + 1;
- }
- p -= 2;
- }
- else {
- ep = p;
- while (*ep == '_' || apr_isalnum(*ep)) {
- ++ep;
- }
-
- if (p < ep) {
- key = apr_pstrmemdup(ctx->dpool, p, ep - p);
- newp = ep;
- }
- --p;
- }
-
- /* empty name results in a copy of '$' in the output string */
- if (!key) {
- if (out) {
- *out++ = *p++;
- }
- else {
- current->len = 1;
- current->string = p++;
- ++outlen;
- }
- }
- else {
- const char *val = get_include_var(key, ctx);
- apr_size_t len = 0;
-
- if (val) {
- len = strlen(val);
- }
- else if (leave_name) {
- val = p;
- len = ep - p;
- }
-
- if (val && len) {
- if (out) {
- memcpy(out, val, (out+len <= eout) ? len : (eout-out));
- out += len;
- }
- else {
- current->len = len;
- current->string = val;
- outlen += len;
- }
- }
-
- p = newp;
- }
- }
-
- if ((out && out >= eout) || (length && outlen >= length)) {
- break;
- }
-
- /* check the remainder */
- if (*p && (span = strcspn(p, "\\$")) > 0) {
- if (!out && current->len) {
- current->next = apr_palloc(ctx->dpool, sizeof(*current->next));
- current = current->next;
- current->next = NULL;
- }
-
- if (out) {
- memcpy(out, p, (out+span <= eout) ? span : (eout-out));
- out += span;
- }
- else {
- current->len = span;
- current->string = p;
- outlen += span;
- }
-
- p += span;
- }
- } while (p < in+inlen);
-
- /* assemble result */
- if (out) {
- if (out > eout) {
- *eout = '\0';
- }
- else {
- *out = '\0';
- }
- }
- else {
- const char *ep;
-
- if (length && outlen > length) {
- outlen = length - 1;
- }
-
- ret = out = apr_palloc(ctx->pool, outlen + 1);
- ep = ret + outlen;
-
- do {
- if (result->len) {
- memcpy(out, result->string, (out+result->len <= ep)
- ? result->len : (ep-out));
- out += result->len;
- }
- result = result->next;
- } while (result && out < ep);
-
- ret[outlen] = '\0';
- }
-
- return ret;
-}
-
-
-/*
- * +-------------------------------------------------------+
- * | |
- * | Conditional Expression Parser
- * | |
- * +-------------------------------------------------------+
- */
-
-static APR_INLINE int re_check(include_ctx_t *ctx, const char *string,
- const char *rexp)
-{
- ap_regex_t *compiled;
- backref_t *re = ctx->intern->re;
- int rc;
-
- compiled = ap_pregcomp(ctx->dpool, rexp, AP_REG_EXTENDED);
- if (!compiled) {
- ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, ctx->intern->r, "unable to "
- "compile pattern \"%s\"", rexp);
- return -1;
- }
-
- if (!re) {
- re = ctx->intern->re = apr_palloc(ctx->pool, sizeof(*re));
- }
-
- re->source = apr_pstrdup(ctx->pool, string);
- re->rexp = apr_pstrdup(ctx->pool, rexp);
- re->nsub = compiled->re_nsub;
- rc = !ap_regexec(compiled, string, AP_MAX_REG_MATCH, re->match, 0);
-
- ap_pregfree(ctx->dpool, compiled);
- return rc;
-}
-
-static int get_ptoken(include_ctx_t *ctx, const char **parse, token_t *token, token_t *previous)
-{
- const char *p;
- apr_size_t shift;
- int unmatched;
-
- token->value = NULL;
-
- if (!*parse) {
- return 0;
- }
-
- /* Skip leading white space */
- while (apr_isspace(**parse)) {
- ++*parse;
- }
-
- if (!**parse) {
- *parse = NULL;
- return 0;
- }
-
- TYPE_TOKEN(token, TOKEN_STRING); /* the default type */
- p = *parse;
- unmatched = 0;
-
- switch (*(*parse)++) {
- case '(':
- TYPE_TOKEN(token, TOKEN_LBRACE);
- return 0;
- case ')':
- TYPE_TOKEN(token, TOKEN_RBRACE);
- return 0;
- case '=':
- if (**parse == '=') ++*parse;
- TYPE_TOKEN(token, TOKEN_EQ);
- return 0;
- case '!':
- if (**parse == '=') {
- TYPE_TOKEN(token, TOKEN_NE);
- ++*parse;
- return 0;
- }
- TYPE_TOKEN(token, TOKEN_NOT);
- return 0;
- case '\'':
- unmatched = '\'';
- break;
- case '/':
- /* if last token was ACCESS, this token is STRING */
- if (previous != NULL && TOKEN_ACCESS == previous->type) {
- break;
- }
- TYPE_TOKEN(token, TOKEN_RE);
- unmatched = '/';
- break;
- case '|':
- if (**parse == '|') {
- TYPE_TOKEN(token, TOKEN_OR);
- ++*parse;
- return 0;
- }
- break;
- case '&':
- if (**parse == '&') {
- TYPE_TOKEN(token, TOKEN_AND);
- ++*parse;
- return 0;
- }
- break;
- case '>':
- if (**parse == '=') {
- TYPE_TOKEN(token, TOKEN_GE);
- ++*parse;
- return 0;
- }
- TYPE_TOKEN(token, TOKEN_GT);
- return 0;
- case '<':
- if (**parse == '=') {
- TYPE_TOKEN(token, TOKEN_LE);
- ++*parse;
- return 0;
- }
- TYPE_TOKEN(token, TOKEN_LT);
- return 0;
- case '-':
- if (**parse == 'A' && (ctx->intern->accessenable)) {
- TYPE_TOKEN(token, TOKEN_ACCESS);
- ++*parse;
- return 0;
- }
- break;
- }
-
- /* It's a string or regex token
- * Now search for the next token, which finishes this string
- */
- shift = 0;
- p = *parse = token->value = unmatched ? *parse : p;
-
- for (; **parse; p = ++*parse) {
- if (**parse == '\\') {
- if (!*(++*parse)) {
- p = *parse;
- break;
- }
-
- ++shift;
- }
- else {
- if (unmatched) {
- if (**parse == unmatched) {
- unmatched = 0;
- ++*parse;
- break;
- }
- } else if (apr_isspace(**parse)) {
- break;
- }
- else {
- int found = 0;
-
- switch (**parse) {
- case '(':
- case ')':
- case '=':
- case '!':
- case '<':
- case '>':
- ++found;
- break;
-
- case '|':
- case '&':
- if ((*parse)[1] == **parse) {
- ++found;
- }
- break;
- }
-
- if (found) {
- break;
- }
- }
- }
- }
-
- if (unmatched) {
- token->value = apr_pstrdup(ctx->dpool, "");
- }
- else {
- apr_size_t len = p - token->value - shift;
- char *c = apr_palloc(ctx->dpool, len + 1);
-
- p = token->value;
- token->value = c;
-
- while (shift--) {
- const char *e = ap_strchr_c(p, '\\');
-
- memcpy(c, p, e-p);
- c += e-p;
- *c++ = *++e;
- len -= e-p;
- p = e+1;
- }
-
- if (len) {
- memcpy(c, p, len);
- }
- c[len] = '\0';
- }
-
- return unmatched;
-}
-
-static int parse_expr(include_ctx_t *ctx, const char *expr, int *was_error)
-{
- parse_node_t *new, *root = NULL, *current = NULL;
- request_rec *r = ctx->intern->r;
- request_rec *rr = NULL;
- const char *error = "Invalid expression \"%s\" in file %s";
- const char *parse = expr;
- int was_unmatched = 0;
- unsigned regex = 0;
-
- *was_error = 0;
-
- if (!parse) {
- return 0;
- }
-
- /* Create Parse Tree */
- while (1) {
- /* uncomment this to see how the tree a built:
- *
- * DEBUG_DUMP_TREE(ctx, root);
- */
- CREATE_NODE(ctx, new);
-
- was_unmatched = get_ptoken(ctx, &parse, &new->token,
- (current != NULL ? ¤t->token : NULL));
- if (!parse) {
- break;
- }
-
- DEBUG_DUMP_UNMATCHED(ctx, was_unmatched);
- DEBUG_DUMP_TOKEN(ctx, &new->token);
-
- if (!current) {
- switch (new->token.type) {
- case TOKEN_STRING:
- case TOKEN_NOT:
- case TOKEN_ACCESS:
- case TOKEN_LBRACE:
- root = current = new;
- continue;
-
- default:
- ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, error, expr,
- r->filename);
- *was_error = 1;
- return 0;
- }
- }
-
- switch (new->token.type) {
- case TOKEN_STRING:
- switch (current->token.type) {
- case TOKEN_STRING:
- current->token.value =
- apr_pstrcat(ctx->dpool, current->token.value,
- *current->token.value ? " " : "",
- new->token.value, NULL);
- continue;
-
- case TOKEN_RE:
- case TOKEN_RBRACE:
- case TOKEN_GROUP:
- break;
-
- default:
- new->parent = current;
- current = current->right = new;
- continue;
- }
- break;
-
- case TOKEN_RE:
- switch (current->token.type) {
- case TOKEN_EQ:
- case TOKEN_NE:
- new->parent = current;
- current = current->right = new;
- ++regex;
- continue;
-
- default:
- break;
- }
- break;
-
- case TOKEN_AND:
- case TOKEN_OR:
- switch (current->token.type) {
- case TOKEN_STRING:
- case TOKEN_RE:
- case TOKEN_GROUP:
- current = current->parent;
-
- while (current) {
- switch (current->token.type) {
- case TOKEN_AND:
- case TOKEN_OR:
- case TOKEN_LBRACE:
- break;
-
- default:
- current = current->parent;
- continue;
- }
- break;
- }
-
- if (!current) {
- new->left = root;
- root->parent = new;
- current = root = new;
- continue;
- }
-
- new->left = current->right;
- new->left->parent = new;
- new->parent = current;
- current = current->right = new;
- continue;
-
- default:
- break;
- }
- break;
-
- case TOKEN_EQ:
- case TOKEN_NE:
- case TOKEN_GE:
- case TOKEN_GT:
- case TOKEN_LE:
- case TOKEN_LT:
- if (current->token.type == TOKEN_STRING) {
- current = current->parent;
-
- if (!current) {
- new->left = root;
- root->parent = new;
- current = root = new;
- continue;
- }
-
- switch (current->token.type) {
- case TOKEN_LBRACE:
- case TOKEN_AND:
- case TOKEN_OR:
- new->left = current->right;
- new->left->parent = new;
- new->parent = current;
- current = current->right = new;
- continue;
-
- default:
- break;
- }
- }
- break;
-
- case TOKEN_RBRACE:
- while (current && current->token.type != TOKEN_LBRACE) {
- current = current->parent;
- }
-
- if (current) {
- TYPE_TOKEN(¤t->token, TOKEN_GROUP);
- continue;
- }
-
- error = "Unmatched ')' in \"%s\" in file %s";
- break;
-
- case TOKEN_NOT:
- case TOKEN_ACCESS:
- case TOKEN_LBRACE:
- switch (current->token.type) {
- case TOKEN_STRING:
- case TOKEN_RE:
- case TOKEN_RBRACE:
- case TOKEN_GROUP:
- break;
-
- default:
- current->right = new;
- new->parent = current;
- current = new;
- continue;
- }
- break;
-
- default:
- break;
- }
-
- ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, error, expr, r->filename);
- *was_error = 1;
- return 0;
- }
-
- DEBUG_DUMP_TREE(ctx, root);
-
- /* Evaluate Parse Tree */
- current = root;
- error = NULL;
- while (current) {
- switch (current->token.type) {
- case TOKEN_STRING:
- current->token.value =
- ap_ssi_parse_string(ctx, current->token.value, NULL, 0,
- SSI_EXPAND_DROP_NAME);
- current->value = !!*current->token.value;
- break;
-
- case TOKEN_AND:
- case TOKEN_OR:
- if (!current->left || !current->right) {
- ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
- "Invalid expression \"%s\" in file %s",
- expr, r->filename);
- *was_error = 1;
- return 0;
- }
-
- if (!current->left->done) {
- switch (current->left->token.type) {
- case TOKEN_STRING:
- current->left->token.value =
- ap_ssi_parse_string(ctx, current->left->token.value,
- NULL, 0, SSI_EXPAND_DROP_NAME);
- current->left->value = !!*current->left->token.value;
- DEBUG_DUMP_EVAL(ctx, current->left);
- current->left->done = 1;
- break;
-
- default:
- current = current->left;
- continue;
- }
- }
-
- /* short circuit evaluation */
- if (!current->right->done && !regex &&
- ((current->token.type == TOKEN_AND && !current->left->value) ||
- (current->token.type == TOKEN_OR && current->left->value))) {
- current->value = current->left->value;
- }
- else {
- if (!current->right->done) {
- switch (current->right->token.type) {
- case TOKEN_STRING:
- current->right->token.value =
- ap_ssi_parse_string(ctx,current->right->token.value,
- NULL, 0, SSI_EXPAND_DROP_NAME);
- current->right->value = !!*current->right->token.value;
- DEBUG_DUMP_EVAL(ctx, current->right);
- current->right->done = 1;
- break;
-
- default:
- current = current->right;
- continue;
- }
- }
-
- if (current->token.type == TOKEN_AND) {
- current->value = current->left->value &&
- current->right->value;
- }
- else {
- current->value = current->left->value ||
- current->right->value;
- }
- }
- break;
-
- case TOKEN_EQ:
- case TOKEN_NE:
- if (!current->left || !current->right ||
- current->left->token.type != TOKEN_STRING ||
- (current->right->token.type != TOKEN_STRING &&
- current->right->token.type != TOKEN_RE)) {
- ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
- "Invalid expression \"%s\" in file %s",
- expr, r->filename);
- *was_error = 1;
- return 0;
- }
- current->left->token.value =
- ap_ssi_parse_string(ctx, current->left->token.value, NULL, 0,
- SSI_EXPAND_DROP_NAME);
- current->right->token.value =
- ap_ssi_parse_string(ctx, current->right->token.value, NULL, 0,
- SSI_EXPAND_DROP_NAME);
-
- if (current->right->token.type == TOKEN_RE) {
- current->value = re_check(ctx, current->left->token.value,
- current->right->token.value);
- --regex;
- }
- else {
- current->value = !strcmp(current->left->token.value,
- current->right->token.value);
- }
-
- if (current->token.type == TOKEN_NE) {
- current->value = !current->value;
- }
- break;
-
- case TOKEN_GE:
- case TOKEN_GT:
- case TOKEN_LE:
- case TOKEN_LT:
- if (!current->left || !current->right ||
- current->left->token.type != TOKEN_STRING ||
- current->right->token.type != TOKEN_STRING) {
- ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
- "Invalid expression \"%s\" in file %s",
- expr, r->filename);
- *was_error = 1;
- return 0;
- }
-
- current->left->token.value =
- ap_ssi_parse_string(ctx, current->left->token.value, NULL, 0,
- SSI_EXPAND_DROP_NAME);
- current->right->token.value =
- ap_ssi_parse_string(ctx, current->right->token.value, NULL, 0,
- SSI_EXPAND_DROP_NAME);
-
- current->value = strcmp(current->left->token.value,
- current->right->token.value);
-
- switch (current->token.type) {
- case TOKEN_GE: current->value = current->value >= 0; break;
- case TOKEN_GT: current->value = current->value > 0; break;
- case TOKEN_LE: current->value = current->value <= 0; break;
- case TOKEN_LT: current->value = current->value < 0; break;
- default: current->value = 0; break; /* should not happen */
- }
- break;
-
- case TOKEN_NOT:
- case TOKEN_GROUP:
- if (current->right) {
- if (!current->right->done) {
- current = current->right;
- continue;
- }
- current->value = current->right->value;
- }
- else {
- current->value = 1;
- }
-
- if (current->token.type == TOKEN_NOT) {
- current->value = !current->value;
- }
- break;
-
- case TOKEN_ACCESS:
- if (current->left || !current->right ||
- (current->right->token.type != TOKEN_STRING &&
- current->right->token.type != TOKEN_RE)) {
- ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
- "Invalid expression \"%s\" in file %s: Token '-A' must be followed by a URI string.",
- expr, r->filename);
- *was_error = 1;
- return 0;
- }
- current->right->token.value =
- ap_ssi_parse_string(ctx, current->right->token.value, NULL, 0,
- SSI_EXPAND_DROP_NAME);
- rr = ap_sub_req_lookup_uri(current->right->token.value, r, NULL);
- /* 400 and higher are considered access denied */
- if (rr->status < HTTP_BAD_REQUEST) {
- current->value = 1;
- }
- else {
- current->value = 0;
- ap_log_rerror(APLOG_MARK, APLOG_DEBUG, rr->status, r,
- "mod_include: The tested "
- "subrequest -A \"%s\" returned an error code.",
- current->right->token.value);
- }
- ap_destroy_sub_req(rr);
- break;
-
- case TOKEN_RE:
- if (!error) {
- error = "No operator before regex in expr \"%s\" in file %s";
- }
- case TOKEN_LBRACE:
- if (!error) {
- error = "Unmatched '(' in \"%s\" in file %s";
- }
- default:
- if (!error) {
- error = "internal parser error in \"%s\" in file %s";
- }
-
- ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, error, expr,r->filename);
- *was_error = 1;
- return 0;
- }
-
- DEBUG_DUMP_EVAL(ctx, current);
- current->done = 1;
- current = current->parent;
- }
-
- return (root ? root->value : 0);
-}
-
-
-/*
- * +-------------------------------------------------------+
- * | |
- * | Action Handlers
- * | |
- * +-------------------------------------------------------+
- */
-
-/*
- * Extract the next tag name and value.
- * If there are no more tags, set the tag name to NULL.
- * The tag value is html decoded if dodecode is non-zero.
- * The tag value may be NULL if there is no tag value..
- */
-static void ap_ssi_get_tag_and_value(include_ctx_t *ctx, char **tag,
- char **tag_val, int dodecode)
-{
- if (!ctx->intern->argv) {
- *tag = NULL;
- *tag_val = NULL;
-
- return;
- }
-
- *tag_val = ctx->intern->argv->value;
- *tag = ctx->intern->argv->name;
-
- ctx->intern->argv = ctx->intern->argv->next;
-
- if (dodecode && *tag_val) {
- decodehtml(*tag_val);
- }
-
- return;
-}
-
-static int find_file(request_rec *r, const char *directive, const char *tag,
- char *tag_val, apr_finfo_t *finfo)
-{
- char *to_send = tag_val;
- request_rec *rr = NULL;
- int ret=0;
- char *error_fmt = NULL;
- apr_status_t rv = APR_SUCCESS;
-
- if (!strcmp(tag, "file")) {
- char *newpath;
-
- /* be safe; only files in this directory or below allowed */
- rv = apr_filepath_merge(&newpath, NULL, tag_val,
- APR_FILEPATH_SECUREROOTTEST |
- APR_FILEPATH_NOTABSOLUTE, r->pool);
-
- if (rv != APR_SUCCESS) {
- error_fmt = "unable to access file \"%s\" "
- "in parsed file %s";
- }
- else {
- /* note: it is okay to pass NULL for the "next filter" since
- we never attempt to "run" this sub request. */
- rr = ap_sub_req_lookup_file(newpath, r, NULL);
-
- if (rr->status == HTTP_OK && rr->finfo.filetype != 0) {
- to_send = rr->filename;
- if ((rv = apr_stat(finfo, to_send,
- APR_FINFO_GPROT | APR_FINFO_MIN, rr->pool)) != APR_SUCCESS
- && rv != APR_INCOMPLETE) {
- error_fmt = "unable to get information about \"%s\" "
- "in parsed file %s";
- }
- }
- else {
- error_fmt = "unable to lookup information about \"%s\" "
- "in parsed file %s";
- }
- }
-
- if (error_fmt) {
- ret = -1;
- ap_log_rerror(APLOG_MARK, APLOG_ERR,
- rv, r, error_fmt, to_send, r->filename);
- }
-
- if (rr) ap_destroy_sub_req(rr);
-
- return ret;
- }
- else if (!strcmp(tag, "virtual")) {
- /* note: it is okay to pass NULL for the "next filter" since
- we never attempt to "run" this sub request. */
- rr = ap_sub_req_lookup_uri(tag_val, r, NULL);
-
- if (rr->status == HTTP_OK && rr->finfo.filetype != 0) {
- memcpy((char *) finfo, (const char *) &rr->finfo,
- sizeof(rr->finfo));
- ap_destroy_sub_req(rr);
- return 0;
- }
- else {
- ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unable to get "
- "information about \"%s\" in parsed file %s",
- tag_val, r->filename);
- ap_destroy_sub_req(rr);
- return -1;
- }
- }
- else {
- ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unknown parameter \"%s\" "
- "to tag %s in %s", tag, directive, r->filename);
- return -1;
- }
-}
-
-/*
- * <!--#include virtual|file="..." [virtual|file="..."] ... -->
- */
-static apr_status_t handle_include(include_ctx_t *ctx, ap_filter_t *f,
- apr_bucket_brigade *bb)
-{
- request_rec *r = f->r;
-
- if (!ctx->argc) {
- ap_log_rerror(APLOG_MARK,
- (ctx->flags & SSI_FLAG_PRINTING)
- ? APLOG_ERR : APLOG_WARNING,
- 0, r, "missing argument for include element in %s",
- r->filename);
- }
-
- if (!(ctx->flags & SSI_FLAG_PRINTING)) {
- return APR_SUCCESS;
- }
-
- if (!ctx->argc) {
- SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
- return APR_SUCCESS;
- }
-
- while (1) {
- char *tag = NULL;
- char *tag_val = NULL;
- request_rec *rr = NULL;
- char *error_fmt = NULL;
- char *parsed_string;
-
- ap_ssi_get_tag_and_value(ctx, &tag, &tag_val, SSI_VALUE_DECODED);
- if (!tag || !tag_val) {
- break;
- }
-
- if (strcmp(tag, "virtual") && strcmp(tag, "file") && strcmp(tag, "memcached")) {
- ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unknown parameter "
- "\"%s\" to tag include in %s", tag, r->filename);
- SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
- break;
- }
-
- parsed_string = ap_ssi_parse_string(ctx, tag_val, NULL, 0,
- SSI_EXPAND_DROP_NAME);
-
- /* Fetching files from Memcached */
- if (tag[0] == 'm') {
-
- include_dir_config *conf;
- memcached_include_server_t *svr;
- apr_status_t rv;
- int i;
-
- apr_uint16_t flags;
- char *strkey = NULL;
- char *value;
- apr_size_t value_len;
-
- strkey = ap_escape_uri(r->pool, parsed_string);
-
- conf = (include_dir_config *)ap_get_module_config(r->per_dir_config, &memcached_include_module);
-
- rv = apr_memcache_create(r->pool, conf->max_servers, 0, &(conf->memcached));
-
- if(rv != APR_SUCCESS) {
- ap_log_rerror(APLOG_MARK, APLOG_DEBUG, rv, r, "Unable to create memcached structure");
- }
-
- svr = (memcached_include_server_t *)conf->servers->elts;
-
- for(i = 0; i < conf->servers->nelts; i++) {
-
- rv = apr_memcache_server_create(r->pool, svr[i].host, svr[i].port,
- conf->conn_min, conf->conn_smax,
- conf->conn_max, conf->conn_ttl,
- &(svr[i].server));
-
- if(rv != APR_SUCCESS) {
- ap_log_rerror(APLOG_MARK, APLOG_DEBUG, rv, r, "Unable to create memcache server for %s:%d is Memcached running ?", svr[i].host, svr[i].port);
- continue;
- }
-
- rv = apr_memcache_add_server(conf->memcached, svr[i].server);
-
- if(rv != APR_SUCCESS) {
- ap_log_rerror(APLOG_MARK, APLOG_DEBUG, rv, r, "Unable to add memcache server for %s:%d", svr[i].host, svr[i].port);
- }
-
-#ifdef DEBUG_MEMCACHED_INCLUDE
- ap_log_rerror(APLOG_MARK, APLOG_DEBUG, rv, r, "Memcached server successfully created %s:%d %d %d %d", svr[i].host, svr[i].port, conf->conn_smax, conf->conn_max, conf->conn_ttl);
-#endif
- }
-
-#ifdef DEBUG_MEMCACHED_INCLUDE
- ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Fetching the file with key : %s", strkey);
-#endif
-
- rv = apr_memcache_getp(conf->memcached, r->pool, strkey, &value, &value_len, &flags);
-
- if( rv == APR_SUCCESS ) {
-#ifdef DEBUG_MEMCACHED_INCLUDE
- ap_log_rerror(APLOG_MARK, APLOG_DEBUG, rv, r, "File found with key %s, value : %s", strkey, value);
-#endif
- APR_BRIGADE_INSERT_TAIL(bb,
- apr_bucket_pool_create(apr_pmemdup(ctx->pool, value, value_len),
- value_len,
- ctx->pool,
- f->c->bucket_alloc));
- return APR_SUCCESS;
- }
- else {
- error_fmt = "Unable to fetch file with key '%s' in parsed file %s";
- }
- }
- else if (tag[0] == 'f') {
- char *newpath;
- apr_status_t rv;
-
- /* be safe only files in this directory or below allowed */
- rv = apr_filepath_merge(&newpath, NULL, parsed_string,
- APR_FILEPATH_SECUREROOTTEST |
- APR_FILEPATH_NOTABSOLUTE, ctx->dpool);
-
- if (rv != APR_SUCCESS) {
- error_fmt = "unable to include file \"%s\" in parsed file %s";
- }
- else {
- rr = ap_sub_req_lookup_file(newpath, r, f->next);
- }
- }
- else {
- rr = ap_sub_req_lookup_uri(parsed_string, r, f->next);
- }
-
- if (!error_fmt && rr->status != HTTP_OK) {
- error_fmt = "unable to include \"%s\" in parsed file %s";
- }
-
- if (!error_fmt && (ctx->flags & SSI_FLAG_NO_EXEC) &&
- rr->content_type && strncmp(rr->content_type, "text/", 5)) {
-
- error_fmt = "unable to include potential exec \"%s\" in parsed "
- "file %s";
- }
-
- /* See the Kludge in includes_filter for why.
- * Basically, it puts a bread crumb in here, then looks
- * for the crumb later to see if its been here.
- */
- if (rr) {
- ap_set_module_config(rr->request_config, &memcached_include_module, r);
- }
-
- if (!error_fmt && ap_run_sub_req(rr)) {
- error_fmt = "unable to include \"%s\" in parsed file %s";
- }
-
- if (error_fmt) {
- ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, error_fmt, tag_val,
- r->filename);
- SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
- }
-
- /* Do *not* destroy the subrequest here; it may have allocated
- * variables in this r->subprocess_env in the subrequest's
- * r->pool, so that pool must survive as long as this request.
- * Yes, this is a memory leak. */
- if (error_fmt) {
- break;
- }
- }
-
- return APR_SUCCESS;
-}
-
-/*
- * <!--#echo [encoding="..."] var="..." [encoding="..."] var="..." ... -->
- */
-static apr_status_t handle_echo(include_ctx_t *ctx, ap_filter_t *f,
- apr_bucket_brigade *bb)
-{
- enum {E_NONE, E_URL, E_ENTITY} encode;
- request_rec *r = f->r;
-
- if (!ctx->argc) {
- ap_log_rerror(APLOG_MARK,
- (ctx->flags & SSI_FLAG_PRINTING)
- ? APLOG_ERR : APLOG_WARNING,
- 0, r, "missing argument for echo element in %s",
- r->filename);
- }
-
- if (!(ctx->flags & SSI_FLAG_PRINTING)) {
- return APR_SUCCESS;
- }
-
- if (!ctx->argc) {
- SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
- return APR_SUCCESS;
- }
-
- encode = E_ENTITY;
-
- while (1) {
- char *tag = NULL;
- char *tag_val = NULL;
-
- ap_ssi_get_tag_and_value(ctx, &tag, &tag_val, SSI_VALUE_DECODED);
- if (!tag || !tag_val) {
- break;
- }
-
- if (!strcmp(tag, "var")) {
- const char *val;
- const char *echo_text = NULL;
- apr_size_t e_len;
-
- val = get_include_var(ap_ssi_parse_string(ctx, tag_val, NULL,
- 0, SSI_EXPAND_DROP_NAME),
- ctx);
-
- if (val) {
- switch(encode) {
- case E_NONE:
- echo_text = val;
- break;
- case E_URL:
- echo_text = ap_escape_uri(ctx->dpool, val);
- break;
- case E_ENTITY:
- echo_text = ap_escape_html(ctx->dpool, val);
- break;
- }
-
- e_len = strlen(echo_text);
- }
- else {
- echo_text = ctx->intern->undefined_echo;
- e_len = ctx->intern->undefined_echo_len;
- }
-
- APR_BRIGADE_INSERT_TAIL(bb, apr_bucket_pool_create(
- apr_pmemdup(ctx->pool, echo_text, e_len),
- e_len, ctx->pool, f->c->bucket_alloc));
- }
- else if (!strcmp(tag, "encoding")) {
- if (!strcasecmp(tag_val, "none")) {
- encode = E_NONE;
- }
- else if (!strcasecmp(tag_val, "url")) {
- encode = E_URL;
- }
- else if (!strcasecmp(tag_val, "entity")) {
- encode = E_ENTITY;
- }
- else {
- ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unknown value "
- "\"%s\" to parameter \"encoding\" of tag echo in "
- "%s", tag_val, r->filename);
- SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
- break;
- }
- }
- else {
- ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unknown parameter "
- "\"%s\" in tag echo of %s", tag, r->filename);
- SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
- break;
- }
- }
-
- return APR_SUCCESS;
-}
-
-/*
- * <!--#config [timefmt="..."] [sizefmt="..."] [errmsg="..."]
- * [echomsg="..."] -->
- */
-static apr_status_t handle_config(include_ctx_t *ctx, ap_filter_t *f,
- apr_bucket_brigade *bb)
-{
- request_rec *r = f->r;
- apr_table_t *env = r->subprocess_env;
-
- if (!ctx->argc) {
- ap_log_rerror(APLOG_MARK,
- (ctx->flags & SSI_FLAG_PRINTING)
- ? APLOG_ERR : APLOG_WARNING,
- 0, r, "missing argument for config element in %s",
- r->filename);
- }
-
- if (!(ctx->flags & SSI_FLAG_PRINTING)) {
- return APR_SUCCESS;
- }
-
- if (!ctx->argc) {
- SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
- return APR_SUCCESS;
- }
-
- while (1) {
- char *tag = NULL;
- char *tag_val = NULL;
-
- ap_ssi_get_tag_and_value(ctx, &tag, &tag_val, SSI_VALUE_RAW);
- if (!tag || !tag_val) {
- break;
- }
-
- if (!strcmp(tag, "errmsg")) {
- ctx->error_str = ap_ssi_parse_string(ctx, tag_val, NULL, 0,
- SSI_EXPAND_DROP_NAME);
- }
- else if (!strcmp(tag, "echomsg")) {
- ctx->intern->undefined_echo =
- ap_ssi_parse_string(ctx, tag_val, NULL, 0,SSI_EXPAND_DROP_NAME);
- ctx->intern->undefined_echo_len=strlen(ctx->intern->undefined_echo);
- }
- else if (!strcmp(tag, "timefmt")) {
- apr_time_t date = r->request_time;
-
- ctx->time_str = ap_ssi_parse_string(ctx, tag_val, NULL, 0,
- SSI_EXPAND_DROP_NAME);
-
- apr_table_setn(env, "DATE_LOCAL", ap_ht_time(r->pool, date,
- ctx->time_str, 0));
- apr_table_setn(env, "DATE_GMT", ap_ht_time(r->pool, date,
- ctx->time_str, 1));
- apr_table_setn(env, "LAST_MODIFIED",
- ap_ht_time(r->pool, r->finfo.mtime,
- ctx->time_str, 0));
- }
- else if (!strcmp(tag, "sizefmt")) {
- char *parsed_string;
-
- parsed_string = ap_ssi_parse_string(ctx, tag_val, NULL, 0,
- SSI_EXPAND_DROP_NAME);
- if (!strcmp(parsed_string, "bytes")) {
- ctx->flags |= SSI_FLAG_SIZE_IN_BYTES;
- }
- else if (!strcmp(parsed_string, "abbrev")) {
- ctx->flags &= SSI_FLAG_SIZE_ABBREV;
- }
- else {
- ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unknown value "
- "\"%s\" to parameter \"sizefmt\" of tag config "
- "in %s", parsed_string, r->filename);
- SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
- break;
- }
- }
- else {
- ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unknown parameter "
- "\"%s\" to tag config in %s", tag, r->filename);
- SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
- break;
- }
- }
-
- return APR_SUCCESS;
-}
-
-/*
- * <!--#fsize virtual|file="..." [virtual|file="..."] ... -->
- */
-static apr_status_t handle_fsize(include_ctx_t *ctx, ap_filter_t *f,
- apr_bucket_brigade *bb)
-{
- request_rec *r = f->r;
-
- if (!ctx->argc) {
- ap_log_rerror(APLOG_MARK,
- (ctx->flags & SSI_FLAG_PRINTING)
- ? APLOG_ERR : APLOG_WARNING,
- 0, r, "missing argument for fsize element in %s",
- r->filename);
- }
-
- if (!(ctx->flags & SSI_FLAG_PRINTING)) {
- return APR_SUCCESS;
- }
-
- if (!ctx->argc) {
- SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
- return APR_SUCCESS;
- }
-
- while (1) {
- char *tag = NULL;
- char *tag_val = NULL;
- apr_finfo_t finfo;
- char *parsed_string;
-
- ap_ssi_get_tag_and_value(ctx, &tag, &tag_val, SSI_VALUE_DECODED);
- if (!tag || !tag_val) {
- break;
- }
-
- parsed_string = ap_ssi_parse_string(ctx, tag_val, NULL, 0,
- SSI_EXPAND_DROP_NAME);
-
- if (!find_file(r, "fsize", tag, parsed_string, &finfo)) {
- char *buf;
- apr_size_t len;
-
- if (!(ctx->flags & SSI_FLAG_SIZE_IN_BYTES)) {
- buf = apr_strfsize(finfo.size, apr_palloc(ctx->pool, 5));
- len = 4; /* omit the \0 terminator */
- }
- else {
- apr_size_t l, x, pos;
- char *tmp;
-
- tmp = apr_psprintf(ctx->dpool, "%" APR_OFF_T_FMT, finfo.size);
- len = l = strlen(tmp);
-
- for (x = 0; x < l; ++x) {
- if (x && !((l - x) % 3)) {
- ++len;
- }
- }
-
- if (len == l) {
- buf = apr_pstrmemdup(ctx->pool, tmp, len);
- }
- else {
- buf = apr_palloc(ctx->pool, len);
-
- for (pos = x = 0; x < l; ++x) {
- if (x && !((l - x) % 3)) {
- buf[pos++] = ',';
- }
- buf[pos++] = tmp[x];
- }
- }
- }
-
- APR_BRIGADE_INSERT_TAIL(bb, apr_bucket_pool_create(buf, len,
- ctx->pool, f->c->bucket_alloc));
- }
- else {
- SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
- break;
- }
- }
-
- return APR_SUCCESS;
-}
-
-/*
- * <!--#flastmod virtual|file="..." [virtual|file="..."] ... -->
- */
-static apr_status_t handle_flastmod(include_ctx_t *ctx, ap_filter_t *f,
- apr_bucket_brigade *bb)
-{
- request_rec *r = f->r;
-
- if (!ctx->argc) {
- ap_log_rerror(APLOG_MARK,
- (ctx->flags & SSI_FLAG_PRINTING)
- ? APLOG_ERR : APLOG_WARNING,
- 0, r, "missing argument for flastmod element in %s",
- r->filename);
- }
-
- if (!(ctx->flags & SSI_FLAG_PRINTING)) {
- return APR_SUCCESS;
- }
-
- if (!ctx->argc) {
- SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
- return APR_SUCCESS;
- }
-
- while (1) {
- char *tag = NULL;
- char *tag_val = NULL;
- apr_finfo_t finfo;
- char *parsed_string;
-
- ap_ssi_get_tag_and_value(ctx, &tag, &tag_val, SSI_VALUE_DECODED);
- if (!tag || !tag_val) {
- break;
- }
-
- parsed_string = ap_ssi_parse_string(ctx, tag_val, NULL, 0,
- SSI_EXPAND_DROP_NAME);
-
- if (!find_file(r, "flastmod", tag, parsed_string, &finfo)) {
- char *t_val;
- apr_size_t t_len;
-
- t_val = ap_ht_time(ctx->pool, finfo.mtime, ctx->time_str, 0);
- t_len = strlen(t_val);
-
- APR_BRIGADE_INSERT_TAIL(bb, apr_bucket_pool_create(t_val, t_len,
- ctx->pool, f->c->bucket_alloc));
- }
- else {
- SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
- break;
- }
- }
-
- return APR_SUCCESS;
-}
-
-/*
- * <!--#if expr="..." -->
- */
-static apr_status_t handle_if(include_ctx_t *ctx, ap_filter_t *f,
- apr_bucket_brigade *bb)
-{
- char *tag = NULL;
- char *expr = NULL;
- request_rec *r = f->r;
- int expr_ret, was_error;
-
- if (ctx->argc != 1) {
- ap_log_rerror(APLOG_MARK,
- (ctx->flags & SSI_FLAG_PRINTING)
- ? APLOG_ERR : APLOG_WARNING,
- 0, r, (ctx->argc)
- ? "too many arguments for if element in %s"
- : "missing expr argument for if element in %s",
- r->filename);
- }
-
- if (!(ctx->flags & SSI_FLAG_PRINTING)) {
- ++(ctx->if_nesting_level);
- return APR_SUCCESS;
- }
-
- if (ctx->argc != 1) {
- SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
- return APR_SUCCESS;
- }
-
- ap_ssi_get_tag_and_value(ctx, &tag, &expr, SSI_VALUE_RAW);
-
- if (strcmp(tag, "expr")) {
- ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unknown parameter \"%s\" "
- "to tag if in %s", tag, r->filename);
- SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
- return APR_SUCCESS;
- }
-
- if (!expr) {
- ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "missing expr value for if "
- "element in %s", r->filename);
- SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
- return APR_SUCCESS;
- }
-
- DEBUG_PRINTF((ctx, "**** if expr=\"%s\"\n", expr));
-
- expr_ret = parse_expr(ctx, expr, &was_error);
-
- if (was_error) {
- SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
- return APR_SUCCESS;
- }
-
- if (expr_ret) {
- ctx->flags |= (SSI_FLAG_PRINTING | SSI_FLAG_COND_TRUE);
- }
- else {
- ctx->flags &= SSI_FLAG_CLEAR_PRINT_COND;
- }
-
- DEBUG_DUMP_COND(ctx, " if");
-
- ctx->if_nesting_level = 0;
-
- return APR_SUCCESS;
-}
-
-/*
- * <!--#elif expr="..." -->
- */
-static apr_status_t handle_elif(include_ctx_t *ctx, ap_filter_t *f,
- apr_bucket_brigade *bb)
-{
- char *tag = NULL;
- char *expr = NULL;
- request_rec *r = f->r;
- int expr_ret, was_error;
-
- if (ctx->argc != 1) {
- ap_log_rerror(APLOG_MARK,
- (!(ctx->if_nesting_level)) ? APLOG_ERR : APLOG_WARNING,
- 0, r, (ctx->argc)
- ? "too many arguments for if element in %s"
- : "missing expr argument for if element in %s",
- r->filename);
- }
-
- if (ctx->if_nesting_level) {
- return APR_SUCCESS;
- }
-
- if (ctx->argc != 1) {
- SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
- return APR_SUCCESS;
- }
-
- ap_ssi_get_tag_and_value(ctx, &tag, &expr, SSI_VALUE_RAW);
-
- if (strcmp(tag, "expr")) {
- ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unknown parameter \"%s\" "
- "to tag if in %s", tag, r->filename);
- SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
- return APR_SUCCESS;
- }
-
- if (!expr) {
- ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "missing expr in elif "
- "statement: %s", r->filename);
- SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
- return APR_SUCCESS;
- }
-
- DEBUG_PRINTF((ctx, "**** elif expr=\"%s\"\n", expr));
- DEBUG_DUMP_COND(ctx, " elif");
-
- if (ctx->flags & SSI_FLAG_COND_TRUE) {
- ctx->flags &= SSI_FLAG_CLEAR_PRINTING;
- return APR_SUCCESS;
- }
-
- expr_ret = parse_expr(ctx, expr, &was_error);
-
- if (was_error) {
- SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
- return APR_SUCCESS;
- }
-
- if (expr_ret) {
- ctx->flags |= (SSI_FLAG_PRINTING | SSI_FLAG_COND_TRUE);
- }
- else {
- ctx->flags &= SSI_FLAG_CLEAR_PRINT_COND;
- }
-
- DEBUG_DUMP_COND(ctx, " elif");
-
- return APR_SUCCESS;
-}
-
-/*
- * <!--#else -->
- */
-static apr_status_t handle_else(include_ctx_t *ctx, ap_filter_t *f,
- apr_bucket_brigade *bb)
-{
- request_rec *r = f->r;
-
- if (ctx->argc) {
- ap_log_rerror(APLOG_MARK,
- (!(ctx->if_nesting_level)) ? APLOG_ERR : APLOG_WARNING,
- 0, r, "else directive does not take tags in %s",
- r->filename);
- }
-
- if (ctx->if_nesting_level) {
- return APR_SUCCESS;
- }
-
- if (ctx->argc) {
- if (ctx->flags & SSI_FLAG_PRINTING) {
- SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
- }
-
- return APR_SUCCESS;
- }
-
- DEBUG_DUMP_COND(ctx, " else");
-
- if (ctx->flags & SSI_FLAG_COND_TRUE) {
- ctx->flags &= SSI_FLAG_CLEAR_PRINTING;
- }
- else {
- ctx->flags |= (SSI_FLAG_PRINTING | SSI_FLAG_COND_TRUE);
- }
-
- return APR_SUCCESS;
-}
-
-/*
- * <!--#endif -->
- */
-static apr_status_t handle_endif(include_ctx_t *ctx, ap_filter_t *f,
- apr_bucket_brigade *bb)
-{
- request_rec *r = f->r;
-
- if (ctx->argc) {
- ap_log_rerror(APLOG_MARK,
- (!(ctx->if_nesting_level)) ? APLOG_ERR : APLOG_WARNING,
- 0, r, "endif directive does not take tags in %s",
- r->filename);
- }
-
- if (ctx->if_nesting_level) {
- --(ctx->if_nesting_level);
- return APR_SUCCESS;
- }
-
- if (ctx->argc) {
- SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
- return APR_SUCCESS;
- }
-
- DEBUG_DUMP_COND(ctx, "endif");
-
- ctx->flags |= (SSI_FLAG_PRINTING | SSI_FLAG_COND_TRUE);
-
- return APR_SUCCESS;
-}
-
-/*
- * <!--#set var="..." value="..." ... -->
- */
-static apr_status_t handle_set(include_ctx_t *ctx, ap_filter_t *f,
- apr_bucket_brigade *bb)
-{
- char *var = NULL;
- request_rec *r = f->r;
- request_rec *sub = r->main;
- apr_pool_t *p = r->pool;
-
- if (ctx->argc < 2) {
- ap_log_rerror(APLOG_MARK,
- (ctx->flags & SSI_FLAG_PRINTING)
- ? APLOG_ERR : APLOG_WARNING,
- 0, r, "missing argument for set element in %s",
- r->filename);
- }
-
- if (!(ctx->flags & SSI_FLAG_PRINTING)) {
- return APR_SUCCESS;
- }
-
- if (ctx->argc < 2) {
- SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
- return APR_SUCCESS;
- }
-
- /* we need to use the 'main' request pool to set notes as that is
- * a notes lifetime
- */
- while (sub) {
- p = sub->pool;
- sub = sub->main;
- }
-
- while (1) {
- char *tag = NULL;
- char *tag_val = NULL;
-
- ap_ssi_get_tag_and_value(ctx, &tag, &tag_val, SSI_VALUE_DECODED);
-
- if (!tag || !tag_val) {
- break;
- }
-
- if (!strcmp(tag, "var")) {
- var = ap_ssi_parse_string(ctx, tag_val, NULL, 0,
- SSI_EXPAND_DROP_NAME);
- }
- else if (!strcmp(tag, "value")) {
- char *parsed_string;
-
- if (!var) {
- ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "variable must "
- "precede value in set directive in %s",
- r->filename);
- SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
- break;
- }
-
- parsed_string = ap_ssi_parse_string(ctx, tag_val, NULL, 0,
- SSI_EXPAND_DROP_NAME);
- apr_table_setn(r->subprocess_env, apr_pstrdup(p, var),
- apr_pstrdup(p, parsed_string));
- }
- else {
- ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Invalid tag for set "
- "directive in %s", r->filename);
- SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
- break;
- }
- }
-
- return APR_SUCCESS;
-}
-
-/*
- * <!--#printenv -->
- */
-static apr_status_t handle_printenv(include_ctx_t *ctx, ap_filter_t *f,
- apr_bucket_brigade *bb)
-{
- request_rec *r = f->r;
- const apr_array_header_t *arr;
- const apr_table_entry_t *elts;
- int i;
-
- if (ctx->argc) {
- ap_log_rerror(APLOG_MARK,
- (ctx->flags & SSI_FLAG_PRINTING)
- ? APLOG_ERR : APLOG_WARNING,
- 0, r, "printenv directive does not take tags in %s",
- r->filename);
- }
-
- if (!(ctx->flags & SSI_FLAG_PRINTING)) {
- return APR_SUCCESS;
- }
-
- if (ctx->argc) {
- SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
- return APR_SUCCESS;
- }
-
- arr = apr_table_elts(r->subprocess_env);
- elts = (apr_table_entry_t *)arr->elts;
-
- for (i = 0; i < arr->nelts; ++i) {
- const char *key_text, *val_text;
- char *key_val, *next;
- apr_size_t k_len, v_len, kv_length;
-
- /* get key */
- key_text = ap_escape_html(ctx->dpool, elts[i].key);
- k_len = strlen(key_text);
-
- /* get value */
- val_text = elts[i].val;
- if (val_text == LAZY_VALUE) {
- val_text = add_include_vars_lazy(r, elts[i].key);
- }
- val_text = ap_escape_html(ctx->dpool, elts[i].val);
- v_len = strlen(val_text);
-
- /* assemble result */
- kv_length = k_len + v_len + sizeof("=\n");
- key_val = apr_palloc(ctx->pool, kv_length);
- next = key_val;
-
- memcpy(next, key_text, k_len);
- next += k_len;
- *next++ = '=';
- memcpy(next, val_text, v_len);
- next += v_len;
- *next++ = '\n';
- *next = 0;
-
- APR_BRIGADE_INSERT_TAIL(bb, apr_bucket_pool_create(key_val, kv_length-1,
- ctx->pool, f->c->bucket_alloc));
- }
-
- ctx->flush_now = 1;
- return APR_SUCCESS;
-}
-
-
-/*
- * +-------------------------------------------------------+
- * | |
- * | Main Includes-Filter Engine
- * | |
- * +-------------------------------------------------------+
- */
-
-/* This is an implementation of the BNDM search algorithm.
- *
- * Fast and Flexible String Matching by Combining Bit-parallelism and
- * Suffix Automata (2001)
- * Gonzalo Navarro, Mathieu Raffinot
- *
- * http://www-igm.univ-mlv.fr/~raffinot/ftp/jea2001.ps.gz
- *
- * Initial code submitted by Sascha Schumann.
- */
-
-/* Precompile the bndm_t data structure. */
-static bndm_t *bndm_compile(apr_pool_t *pool, const char *n, apr_size_t nl)
-{
- unsigned int x;
- const char *ne = n + nl;
- bndm_t *t = apr_palloc(pool, sizeof(*t));
-
- memset(t->T, 0, sizeof(unsigned int) * 256);
- t->pattern_len = nl;
-
- for (x = 1; n < ne; x <<= 1) {
- t->T[(unsigned char) *n++] |= x;
- }
-
- t->x = x - 1;
-
- return t;
-}
-
-/* Implements the BNDM search algorithm (as described above).
- *
- * h - the string to look in
- * hl - length of the string to look for
- * t - precompiled bndm structure against the pattern
- *
- * Returns the count of character that is the first match or hl if no
- * match is found.
- */
-static apr_size_t bndm(bndm_t *t, const char *h, apr_size_t hl)
-{
- const char *skip;
- const char *he, *p, *pi;
- unsigned int *T, x, d;
- apr_size_t nl;
-
- he = h + hl;
-
- T = t->T;
- x = t->x;
- nl = t->pattern_len;
-
- pi = h - 1; /* pi: p initial */
- p = pi + nl; /* compare window right to left. point to the first char */
-
- while (p < he) {
- skip = p;
- d = x;
- do {
- d &= T[(unsigned char) *p--];
- if (!d) {
- break;
- }
- if ((d & 1)) {
- if (p != pi) {
- skip = p;
- }
- else {
- return p - h + 1;
- }
- }
- d >>= 1;
- } while (d);
-
- pi = skip;
- p = pi + nl;
- }
-
- return hl;
-}
-
-/*
- * returns the index position of the first byte of start_seq (or the len of
- * the buffer as non-match)
- */
-static apr_size_t find_start_sequence(include_ctx_t *ctx, const char *data,
- apr_size_t len)
-{
- struct ssi_internal_ctx *intern = ctx->intern;
- apr_size_t slen = intern->start_seq_pat->pattern_len;
- apr_size_t index;
- const char *p, *ep;
-
- if (len < slen) {
- p = data; /* try partial match at the end of the buffer (below) */
- }
- else {
- /* try fast bndm search over the buffer
- * (hopefully the whole start sequence can be found in this buffer)
- */
- index = bndm(intern->start_seq_pat, data, len);
-
- /* wow, found it. ready. */
- if (index < len) {
- intern->state = PARSE_DIRECTIVE;
- return index;
- }
- else {
- /* ok, the pattern can't be found as whole in the buffer,
- * check the end for a partial match
- */
- p = data + len - slen + 1;
- }
- }
-
- ep = data + len;
- do {
- while (p < ep && *p != *intern->start_seq) {
- ++p;
- }
-
- index = p - data;
-
- /* found a possible start_seq start */
- if (p < ep) {
- apr_size_t pos = 1;
-
- ++p;
- while (p < ep && *p == intern->start_seq[pos]) {
- ++p;
- ++pos;
- }
-
- /* partial match found. Store the info for the next round */
- if (p == ep) {
- intern->state = PARSE_HEAD;
- intern->parse_pos = pos;
- return index;
- }
- }
-
- /* we must try all combinations; consider (e.g.) SSIStartTag "--->"
- * and a string data of "--.-" and the end of the buffer
- */
- p = data + index + 1;
- } while (p < ep);
-
- /* no match */
- return len;
-}
-
-/*
- * returns the first byte *after* the partial (or final) match.
- *
- * If we had to trick with the start_seq start, 'release' returns the
- * number of chars of the start_seq which appeared not to be part of a
- * full tag and may have to be passed down the filter chain.
- */
-static apr_size_t find_partial_start_sequence(include_ctx_t *ctx,
- const char *data,
- apr_size_t len,
- apr_size_t *release)
-{
- struct ssi_internal_ctx *intern = ctx->intern;
- apr_size_t pos, spos = 0;
- apr_size_t slen = intern->start_seq_pat->pattern_len;
- const char *p, *ep;
-
- pos = intern->parse_pos;
- ep = data + len;
- *release = 0;
-
- do {
- p = data;
-
- while (p < ep && pos < slen && *p == intern->start_seq[pos]) {
- ++p;
- ++pos;
- }
-
- /* full match */
- if (pos == slen) {
- intern->state = PARSE_DIRECTIVE;
- return (p - data);
- }
-
- /* the whole buffer is a partial match */
- if (p == ep) {
- intern->parse_pos = pos;
- return (p - data);
- }
-
- /* No match so far, but again:
- * We must try all combinations, since the start_seq is a random
- * user supplied string
- *
- * So: look if the first char of start_seq appears somewhere within
- * the current partial match. If it does, try to start a match that
- * begins with this offset. (This can happen, if a strange
- * start_seq like "---->" spans buffers)
- */
- if (spos < intern->parse_pos) {
- do {
- ++spos;
- ++*release;
- p = intern->start_seq + spos;
- pos = intern->parse_pos - spos;
-
- while (pos && *p != *intern->start_seq) {
- ++p;
- ++spos;
- ++*release;
- --pos;
- }
-
- /* if a matching beginning char was found, try to match the
- * remainder of the old buffer.
- */
- if (pos > 1) {
- apr_size_t t = 1;
-
- ++p;
- while (t < pos && *p == intern->start_seq[t]) {
- ++p;
- ++t;
- }
-
- if (t == pos) {
- /* yeah, another partial match found in the *old*
- * buffer, now test the *current* buffer for
- * continuing match
- */
- break;
- }
- }
- } while (pos > 1);
-
- if (pos) {
- continue;
- }
- }
-
- break;
- } while (1); /* work hard to find a match ;-) */
-
- /* no match at all, release all (wrongly) matched chars so far */
- *release = intern->parse_pos;
- intern->state = PARSE_PRE_HEAD;
- return 0;
-}
-
-/*
- * returns the position after the directive
- */
-static apr_size_t find_directive(include_ctx_t *ctx, const char *data,
- apr_size_t len, char ***store,
- apr_size_t **store_len)
-{
- struct ssi_internal_ctx *intern = ctx->intern;
- const char *p = data;
- const char *ep = data + len;
- apr_size_t pos;
-
- switch (intern->state) {
- case PARSE_DIRECTIVE:
- while (p < ep && !apr_isspace(*p)) {
- /* we have to consider the case of missing space between directive
- * and end_seq (be somewhat lenient), e.g. <!--#printenv-->
- */
- if (*p == *intern->end_seq) {
- intern->state = PARSE_DIRECTIVE_TAIL;
- intern->parse_pos = 1;
- ++p;
- return (p - data);
- }
- ++p;
- }
-
- if (p < ep) { /* found delimiter whitespace */
- intern->state = PARSE_DIRECTIVE_POSTNAME;
- *store = &intern->directive;
- *store_len = &intern->directive_len;
- }
-
- break;
-
- case PARSE_DIRECTIVE_TAIL:
- pos = intern->parse_pos;
-
- while (p < ep && pos < intern->end_seq_len &&
- *p == intern->end_seq[pos]) {
- ++p;
- ++pos;
- }
-
- /* full match, we're done */
- if (pos == intern->end_seq_len) {
- intern->state = PARSE_DIRECTIVE_POSTTAIL;
- *store = &intern->directive;
- *store_len = &intern->directive_len;
- break;
- }
-
- /* partial match, the buffer is too small to match fully */
- if (p == ep) {
- intern->parse_pos = pos;
- break;
- }
-
- /* no match. continue normal parsing */
- intern->state = PARSE_DIRECTIVE;
- return 0;
-
- case PARSE_DIRECTIVE_POSTTAIL:
- intern->state = PARSE_EXECUTE;
- intern->directive_len -= intern->end_seq_len;
- /* continue immediately with the next state */
-
- case PARSE_DIRECTIVE_POSTNAME:
- if (PARSE_DIRECTIVE_POSTNAME == intern->state) {
- intern->state = PARSE_PRE_ARG;
- }
- ctx->argc = 0;
- intern->argv = NULL;
-
- if (!intern->directive_len) {
- intern->error = 1;
- ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, intern->r, "missing "
- "directive name in parsed document %s",
- intern->r->filename);
- }
- else {
- char *sp = intern->directive;
- char *sep = intern->directive + intern->directive_len;
-
- /* normalize directive name */
- for (; sp < sep; ++sp) {
- *sp = apr_tolower(*sp);
- }
- }
-
- return 0;
-
- default:
- /* get a rid of a gcc warning about unhandled enumerations */
- break;
- }
-
- return (p - data);
-}
-
-/*
- * find out whether the next token is (a possible) end_seq or an argument
- */
-static apr_size_t find_arg_or_tail(include_ctx_t *ctx, const char *data,
- apr_size_t len)
-{
- struct ssi_internal_ctx *intern = ctx->intern;
- const char *p = data;
- const char *ep = data + len;
-
- /* skip leading WS */
- while (p < ep && apr_isspace(*p)) {
- ++p;
- }
-
- /* buffer doesn't consist of whitespaces only */
- if (p < ep) {
- intern->state = (*p == *intern->end_seq) ? PARSE_TAIL : PARSE_ARG;
- }
-
- return (p - data);
-}
-
-/*
- * test the stream for end_seq. If it doesn't match at all, it must be an
- * argument
- */
-static apr_size_t find_tail(include_ctx_t *ctx, const char *data,
- apr_size_t len)
-{
- struct ssi_internal_ctx *intern = ctx->intern;
- const char *p = data;
- const char *ep = data + len;
- apr_size_t pos = intern->parse_pos;
-
- if (PARSE_TAIL == intern->state) {
- intern->state = PARSE_TAIL_SEQ;
- pos = intern->parse_pos = 0;
- }
-
- while (p < ep && pos < intern->end_seq_len && *p == intern->end_seq[pos]) {
- ++p;
- ++pos;
- }
-
- /* bingo, full match */
- if (pos == intern->end_seq_len) {
- intern->state = PARSE_EXECUTE;
- return (p - data);
- }
-
- /* partial match, the buffer is too small to match fully */
- if (p == ep) {
- intern->parse_pos = pos;
- return (p - data);
- }
-
- /* no match. It must be an argument string then
- * The caller should cleanup and rewind to the reparse point
- */
- intern->state = PARSE_ARG;
- return 0;
-}
-
-/*
- * extract name=value from the buffer
- * A pcre-pattern could look (similar to):
- * name\s*(?:=\s*(["'`]?)value\1(?>\s*))?
- */
-static apr_size_t find_argument(include_ctx_t *ctx, const char *data,
- apr_size_t len, char ***store,
- apr_size_t **store_len)
-{
- struct ssi_internal_ctx *intern = ctx->intern;
- const char *p = data;
- const char *ep = data + len;
-
- switch (intern->state) {
- case PARSE_ARG:
- /*
- * create argument structure and append it to the current list
- */
- intern->current_arg = apr_palloc(ctx->dpool,
- sizeof(*intern->current_arg));
- intern->current_arg->next = NULL;
-
- ++(ctx->argc);
- if (!intern->argv) {
- intern->argv = intern->current_arg;
- }
- else {
- arg_item_t *newarg = intern->argv;
-
- while (newarg->next) {
- newarg = newarg->next;
- }
- newarg->next = intern->current_arg;
- }
-
- /* check whether it's a valid one. If it begins with a quote, we
- * can safely assume, someone forgot the name of the argument
- */
- switch (*p) {
- case '"': case '\'': case '`':
- *store = NULL;
-
- intern->state = PARSE_ARG_VAL;
- intern->quote = *p++;
- intern->current_arg->name = NULL;
- intern->current_arg->name_len = 0;
- intern->error = 1;
-
- ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, intern->r, "missing "
- "argument name for value to tag %s in %s",
- apr_pstrmemdup(intern->r->pool, intern->directive,
- intern->directive_len),
- intern->r->filename);
-
- return (p - data);
-
- default:
- intern->state = PARSE_ARG_NAME;
- }
- /* continue immediately with next state */
-
- case PARSE_ARG_NAME:
- while (p < ep && !apr_isspace(*p) && *p != '=') {
- ++p;
- }
-
- if (p < ep) {
- intern->state = PARSE_ARG_POSTNAME;
- *store = &intern->current_arg->name;
- *store_len = &intern->current_arg->name_len;
- return (p - data);
- }
- break;
-
- case PARSE_ARG_POSTNAME:
- intern->current_arg->name = apr_pstrmemdup(ctx->dpool,
- intern->current_arg->name,
- intern->current_arg->name_len);
- if (!intern->current_arg->name_len) {
- intern->error = 1;
- ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, intern->r, "missing "
- "argument name for value to tag %s in %s",
- apr_pstrmemdup(intern->r->pool, intern->directive,
- intern->directive_len),
- intern->r->filename);
- }
- else {
- char *sp = intern->current_arg->name;
-
- /* normalize the name */
- while (*sp) {
- *sp = apr_tolower(*sp);
- ++sp;
- }
- }
-
- intern->state = PARSE_ARG_EQ;
- /* continue with next state immediately */
-
- case PARSE_ARG_EQ:
- *store = NULL;
-
- while (p < ep && apr_isspace(*p)) {
- ++p;
- }
-
- if (p < ep) {
- if (*p == '=') {
- intern->state = PARSE_ARG_PREVAL;
- ++p;
- }
- else { /* no value */
- intern->current_arg->value = NULL;
- intern->state = PARSE_PRE_ARG;
- }
-
- return (p - data);
- }
- break;
-
- case PARSE_ARG_PREVAL:
- *store = NULL;
-
- while (p < ep && apr_isspace(*p)) {
- ++p;
- }
-
- /* buffer doesn't consist of whitespaces only */
- if (p < ep) {
- intern->state = PARSE_ARG_VAL;
- switch (*p) {
- case '"': case '\'': case '`':
- intern->quote = *p++;
- break;
- default:
- intern->quote = '\0';
- break;
- }
-
- return (p - data);
- }
- break;
-
- case PARSE_ARG_VAL_ESC:
- if (*p == intern->quote) {
- ++p;
- }
- intern->state = PARSE_ARG_VAL;
- /* continue with next state immediately */
-
- case PARSE_ARG_VAL:
- for (; p < ep; ++p) {
- if (intern->quote && *p == '\\') {
- ++p;
- if (p == ep) {
- intern->state = PARSE_ARG_VAL_ESC;
- break;
- }
-
- if (*p != intern->quote) {
- --p;
- }
- }
- else if (intern->quote && *p == intern->quote) {
- ++p;
- *store = &intern->current_arg->value;
- *store_len = &intern->current_arg->value_len;
- intern->state = PARSE_ARG_POSTVAL;
- break;
- }
- else if (!intern->quote && apr_isspace(*p)) {
- ++p;
- *store = &intern->current_arg->value;
- *store_len = &intern->current_arg->value_len;
- intern->state = PARSE_ARG_POSTVAL;
- break;
- }
- }
-
- return (p - data);
-
- case PARSE_ARG_POSTVAL:
- /*
- * The value is still the raw input string. Finally clean it up.
- */
- --(intern->current_arg->value_len);
-
- /* strip quote escaping \ from the string */
- if (intern->quote) {
- apr_size_t shift = 0;
- char *sp;
-
- sp = intern->current_arg->value;
- ep = intern->current_arg->value + intern->current_arg->value_len;
- while (sp < ep && *sp != '\\') {
- ++sp;
- }
- for (; sp < ep; ++sp) {
- if (*sp == '\\' && sp[1] == intern->quote) {
- ++sp;
- ++shift;
- }
- if (shift) {
- *(sp-shift) = *sp;
- }
- }
-
- intern->current_arg->value_len -= shift;
- }
-
- intern->current_arg->value[intern->current_arg->value_len] = '\0';
- intern->state = PARSE_PRE_ARG;
-
- return 0;
-
- default:
- /* get a rid of a gcc warning about unhandled enumerations */
- break;
- }
-
- return len; /* partial match of something */
-}
-
-/*
- * This is the main loop over the current bucket brigade.
- */
-static apr_status_t send_parsed_content(ap_filter_t *f, apr_bucket_brigade *bb)
-{
- include_ctx_t *ctx = f->ctx;
- struct ssi_internal_ctx *intern = ctx->intern;
- request_rec *r = f->r;
- apr_bucket *b = APR_BRIGADE_FIRST(bb);
- apr_bucket_brigade *pass_bb;
- apr_status_t rv = APR_SUCCESS;
- char *magic; /* magic pointer for sentinel use */
-
- /* fast exit */
- if (APR_BRIGADE_EMPTY(bb)) {
- return APR_SUCCESS;
- }
-
- /* we may crash, since already cleaned up; hand over the responsibility
- * to the next filter;-)
- */
- if (intern->seen_eos) {
- return ap_pass_brigade(f->next, bb);
- }
-
- /* All stuff passed along has to be put into that brigade */
- pass_bb = apr_brigade_create(ctx->pool, f->c->bucket_alloc);
-
- /* initialization for this loop */
- intern->bytes_read = 0;
- intern->error = 0;
- intern->r = r;
- ctx->flush_now = 0;
-
- /* loop over the current bucket brigade */
- while (b != APR_BRIGADE_SENTINEL(bb)) {
- const char *data = NULL;
- apr_size_t len, index, release;
- apr_bucket *newb = NULL;
- char **store = &magic;
- apr_size_t *store_len = NULL;
-
- /* handle meta buckets before reading any data */
- if (APR_BUCKET_IS_METADATA(b)) {
- newb = APR_BUCKET_NEXT(b);
-
- APR_BUCKET_REMOVE(b);
-
- if (APR_BUCKET_IS_EOS(b)) {
- intern->seen_eos = 1;
-
- /* Hit end of stream, time for cleanup ... But wait!
- * Perhaps we're not ready yet. We may have to loop one or
- * two times again to finish our work. In that case, we
- * just re-insert the EOS bucket to allow for an extra loop.
- *
- * PARSE_EXECUTE means, we've hit a directive just before the
- * EOS, which is now waiting for execution.
- *
- * PARSE_DIRECTIVE_POSTTAIL means, we've hit a directive with
- * no argument and no space between directive and end_seq
- * just before the EOS. (consider <!--#printenv--> as last
- * or only string within the stream). This state, however,
- * just cleans up and turns itself to PARSE_EXECUTE, which
- * will be passed through within the next (and actually
- * last) round.
- */
- if (PARSE_EXECUTE == intern->state ||
- PARSE_DIRECTIVE_POSTTAIL == intern->state) {
- APR_BUCKET_INSERT_BEFORE(newb, b);
- }
- else {
- break; /* END OF STREAM */
- }
- }
- else {
- APR_BRIGADE_INSERT_TAIL(pass_bb, b);
-
- if (APR_BUCKET_IS_FLUSH(b)) {
- ctx->flush_now = 1;
- }
-
- b = newb;
- continue;
- }
- }
-
- /* enough is enough ... */
- if (ctx->flush_now ||
- intern->bytes_read > AP_MIN_BYTES_TO_WRITE) {
-
- if (!APR_BRIGADE_EMPTY(pass_bb)) {
- rv = ap_pass_brigade(f->next, pass_bb);
- if (rv != APR_SUCCESS) {
- apr_brigade_destroy(pass_bb);
- return rv;
- }
- }
-
- ctx->flush_now = 0;
- intern->bytes_read = 0;
- }
-
- /* read the current bucket data */
- len = 0;
- if (!intern->seen_eos) {
- if (intern->bytes_read > 0) {
- rv = apr_bucket_read(b, &data, &len, APR_NONBLOCK_READ);
- if (APR_STATUS_IS_EAGAIN(rv)) {
- ctx->flush_now = 1;
- continue;
- }
- }
-
- if (!len || rv != APR_SUCCESS) {
- rv = apr_bucket_read(b, &data, &len, APR_BLOCK_READ);
- }
-
- if (rv != APR_SUCCESS) {
- apr_brigade_destroy(pass_bb);
- return rv;
- }
-
- intern->bytes_read += len;
- }
-
- /* zero length bucket, fetch next one */
- if (!len && !intern->seen_eos) {
- b = APR_BUCKET_NEXT(b);
- continue;
- }
-
- /*
- * it's actually a data containing bucket, start/continue parsing
- */
-
- switch (intern->state) {
- /* no current tag; search for start sequence */
- case PARSE_PRE_HEAD:
- index = find_start_sequence(ctx, data, len);
-
- if (index < len) {
- apr_bucket_split(b, index);
- }
-
- newb = APR_BUCKET_NEXT(b);
- if (ctx->flags & SSI_FLAG_PRINTING) {
- APR_BUCKET_REMOVE(b);
- APR_BRIGADE_INSERT_TAIL(pass_bb, b);
- }
- else {
- apr_bucket_delete(b);
- }
-
- if (index < len) {
- /* now delete the start_seq stuff from the remaining bucket */
- if (PARSE_DIRECTIVE == intern->state) { /* full match */
- apr_bucket_split(newb, intern->start_seq_pat->pattern_len);
- ctx->flush_now = 1; /* pass pre-tag stuff */
- }
-
- b = APR_BUCKET_NEXT(newb);
- apr_bucket_delete(newb);
- }
- else {
- b = newb;
- }
-
- break;
-
- /* we're currently looking for the end of the start sequence */
- case PARSE_HEAD:
- index = find_partial_start_sequence(ctx, data, len, &release);
-
- /* check if we mismatched earlier and have to release some chars */
- if (release && (ctx->flags & SSI_FLAG_PRINTING)) {
- char *to_release = apr_pmemdup(ctx->pool, intern->start_seq, release);
-
- newb = apr_bucket_pool_create(to_release, release, ctx->pool,
- f->c->bucket_alloc);
- APR_BRIGADE_INSERT_TAIL(pass_bb, newb);
- }
-
- if (index) { /* any match */
- /* now delete the start_seq stuff from the remaining bucket */
- if (PARSE_DIRECTIVE == intern->state) { /* final match */
- apr_bucket_split(b, index);
- ctx->flush_now = 1; /* pass pre-tag stuff */
- }
- newb = APR_BUCKET_NEXT(b);
- apr_bucket_delete(b);
- b = newb;
- }
-
- break;
-
- /* we're currently grabbing the directive name */
- case PARSE_DIRECTIVE:
- case PARSE_DIRECTIVE_POSTNAME:
- case PARSE_DIRECTIVE_TAIL:
- case PARSE_DIRECTIVE_POSTTAIL:
- index = find_directive(ctx, data, len, &store, &store_len);
-
- if (index) {
- apr_bucket_split(b, index);
- newb = APR_BUCKET_NEXT(b);
- }
-
- if (store) {
- if (index) {
- APR_BUCKET_REMOVE(b);
- apr_bucket_setaside(b, r->pool);
- APR_BRIGADE_INSERT_TAIL(intern->tmp_bb, b);
- b = newb;
- }
-
- /* time for cleanup? */
- if (store != &magic) {
- apr_brigade_pflatten(intern->tmp_bb, store, store_len,
- ctx->dpool);
- apr_brigade_cleanup(intern->tmp_bb);
- }
- }
- else if (index) {
- apr_bucket_delete(b);
- b = newb;
- }
-
- break;
-
- /* skip WS and find out what comes next (arg or end_seq) */
- case PARSE_PRE_ARG:
- index = find_arg_or_tail(ctx, data, len);
-
- if (index) { /* skipped whitespaces */
- if (index < len) {
- apr_bucket_split(b, index);
- }
- newb = APR_BUCKET_NEXT(b);
- apr_bucket_delete(b);
- b = newb;
- }
-
- break;
-
- /* currently parsing name[=val] */
- case PARSE_ARG:
- case PARSE_ARG_NAME:
- case PARSE_ARG_POSTNAME:
- case PARSE_ARG_EQ:
- case PARSE_ARG_PREVAL:
- case PARSE_ARG_VAL:
- case PARSE_ARG_VAL_ESC:
- case PARSE_ARG_POSTVAL:
- index = find_argument(ctx, data, len, &store, &store_len);
-
- if (index) {
- apr_bucket_split(b, index);
- newb = APR_BUCKET_NEXT(b);
- }
-
- if (store) {
- if (index) {
- APR_BUCKET_REMOVE(b);
- apr_bucket_setaside(b, r->pool);
- APR_BRIGADE_INSERT_TAIL(intern->tmp_bb, b);
- b = newb;
- }
-
- /* time for cleanup? */
- if (store != &magic) {
- apr_brigade_pflatten(intern->tmp_bb, store, store_len,
- ctx->dpool);
- apr_brigade_cleanup(intern->tmp_bb);
- }
- }
- else if (index) {
- apr_bucket_delete(b);
- b = newb;
- }
-
- break;
-
- /* try to match end_seq at current pos. */
- case PARSE_TAIL:
- case PARSE_TAIL_SEQ:
- index = find_tail(ctx, data, len);
-
- switch (intern->state) {
- case PARSE_EXECUTE: /* full match */
- apr_bucket_split(b, index);
- newb = APR_BUCKET_NEXT(b);
- apr_bucket_delete(b);
- b = newb;
- break;
-
- case PARSE_ARG: /* no match */
- /* PARSE_ARG must reparse at the beginning */
- APR_BRIGADE_PREPEND(bb, intern->tmp_bb);
- b = APR_BRIGADE_FIRST(bb);
- break;
-
- default: /* partial match */
- newb = APR_BUCKET_NEXT(b);
- APR_BUCKET_REMOVE(b);
- apr_bucket_setaside(b, r->pool);
- APR_BRIGADE_INSERT_TAIL(intern->tmp_bb, b);
- b = newb;
- break;
- }
-
- break;
-
- /* now execute the parsed directive, cleanup the space and
- * start again with PARSE_PRE_HEAD
- */
- case PARSE_EXECUTE:
- /* if there was an error, it was already logged; just stop here */
- if (intern->error) {
- if (ctx->flags & SSI_FLAG_PRINTING) {
- SSI_CREATE_ERROR_BUCKET(ctx, f, pass_bb);
- intern->error = 0;
- }
- }
- else {
- include_handler_fn_t *handle_func;
-
- handle_func =
- (include_handler_fn_t *)apr_hash_get(include_handlers, intern->directive,
- intern->directive_len);
-
- if (handle_func) {
- DEBUG_INIT(ctx, f, pass_bb);
- rv = handle_func(ctx, f, pass_bb);
- if (rv != APR_SUCCESS) {
- apr_brigade_destroy(pass_bb);
- return rv;
- }
- }
- else {
- ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
- "unknown directive \"%s\" in parsed doc %s",
- apr_pstrmemdup(r->pool, intern->directive,
- intern->directive_len),
- r->filename);
- if (ctx->flags & SSI_FLAG_PRINTING) {
- SSI_CREATE_ERROR_BUCKET(ctx, f, pass_bb);
- }
- }
- }
-
- /* cleanup */
- apr_pool_clear(ctx->dpool);
- apr_brigade_cleanup(intern->tmp_bb);
-
- /* Oooof. Done here, start next round */
- intern->state = PARSE_PRE_HEAD;
- break;
-
- } /* switch(ctx->state) */
-
- } /* while(brigade) */
-
- /* End of stream. Final cleanup */
- if (intern->seen_eos) {
- if (PARSE_HEAD == intern->state) {
- if (ctx->flags & SSI_FLAG_PRINTING) {
- char *to_release = apr_pmemdup(ctx->pool, intern->start_seq,
- intern->parse_pos);
-
- APR_BRIGADE_INSERT_TAIL(pass_bb,
- apr_bucket_pool_create(to_release,
- intern->parse_pos, ctx->pool,
- f->c->bucket_alloc));
- }
- }
- else if (PARSE_PRE_HEAD != intern->state) {
- ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
- "SSI directive was not properly finished at the end "
- "of parsed document %s", r->filename);
- if (ctx->flags & SSI_FLAG_PRINTING) {
- SSI_CREATE_ERROR_BUCKET(ctx, f, pass_bb);
- }
- }
-
- if (!(ctx->flags & SSI_FLAG_PRINTING)) {
- ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
- "missing closing endif directive in parsed document"
- " %s", r->filename);
- }
-
- /* cleanup our temporary memory */
- apr_brigade_destroy(intern->tmp_bb);
- apr_pool_destroy(ctx->dpool);
-
- /* don't forget to finally insert the EOS bucket */
- APR_BRIGADE_INSERT_TAIL(pass_bb, b);
- }
-
- /* if something's left over, pass it along */
- if (!APR_BRIGADE_EMPTY(pass_bb)) {
- rv = ap_pass_brigade(f->next, pass_bb);
- }
- else {
- rv = APR_SUCCESS;
- apr_brigade_destroy(pass_bb);
- }
- return rv;
-}
-
-
-/*
- * +-------------------------------------------------------+
- * | |
- * | Runtime Hooks
- * | |
- * +-------------------------------------------------------+
- */
-
-static int includes_setup(ap_filter_t *f)
-{
- include_dir_config *conf = ap_get_module_config(f->r->per_dir_config,
- &memcached_include_module);
-
- /* When our xbithack value isn't set to full or our platform isn't
- * providing group-level protection bits or our group-level bits do not
- * have group-execite on, we will set the no_local_copy value to 1 so
- * that we will not send 304s.
- */
- if ((conf->xbithack != XBITHACK_FULL)
- || !(f->r->finfo.valid & APR_FINFO_GPROT)
- || !(f->r->finfo.protection & APR_GEXECUTE)) {
- f->r->no_local_copy = 1;
- }
-
- /* Don't allow ETag headers to be generated - see RFC2616 - 13.3.4.
- * We don't know if we are going to be including a file or executing
- * a program - in either case a strong ETag header will likely be invalid.
- */
- apr_table_setn(f->r->notes, "no-etag", "");
-
- return OK;
-}
-
-static apr_status_t includes_filter(ap_filter_t *f, apr_bucket_brigade *b)
-{
- request_rec *r = f->r;
- include_ctx_t *ctx = f->ctx;
- request_rec *parent;
- include_dir_config *conf = ap_get_module_config(r->per_dir_config,
- &memcached_include_module);
-
- include_server_config *sconf= ap_get_module_config(r->server->module_config,
- &memcached_include_module);
-
- if (!(ap_allow_options(r) & OPT_INCLUDES)) {
- ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
- "mod_include: Options +Includes (or IncludesNoExec) "
- "wasn't set, INCLUDES filter removed");
- ap_remove_output_filter(f);
- return ap_pass_brigade(f->next, b);
- }
-
- if (!f->ctx) {
- struct ssi_internal_ctx *intern;
-
- /* create context for this filter */
- f->ctx = ctx = apr_palloc(r->pool, sizeof(*ctx));
- ctx->intern = intern = apr_palloc(r->pool, sizeof(*ctx->intern));
- ctx->pool = r->pool;
- apr_pool_create(&ctx->dpool, ctx->pool);
-
- /* runtime data */
- intern->tmp_bb = apr_brigade_create(ctx->pool, f->c->bucket_alloc);
- intern->seen_eos = 0;
- intern->state = PARSE_PRE_HEAD;
- ctx->flags = (SSI_FLAG_PRINTING | SSI_FLAG_COND_TRUE);
- if (ap_allow_options(r) & OPT_INCNOEXEC) {
- ctx->flags |= SSI_FLAG_NO_EXEC;
- }
- intern->accessenable = conf->accessenable;
-
- ctx->if_nesting_level = 0;
- intern->re = NULL;
-
- ctx->error_str = conf->default_error_msg;
- ctx->time_str = conf->default_time_fmt;
- intern->start_seq = sconf->default_start_tag;
- intern->start_seq_pat = bndm_compile(ctx->pool, intern->start_seq,
- strlen(intern->start_seq));
- intern->end_seq = sconf->default_end_tag;
- intern->end_seq_len = strlen(intern->end_seq);
- intern->undefined_echo = conf->undefined_echo;
- intern->undefined_echo_len = strlen(conf->undefined_echo);
- }
-
- if ((parent = ap_get_module_config(r->request_config, &memcached_include_module))) {
- /* Kludge --- for nested includes, we want to keep the subprocess
- * environment of the base document (for compatibility); that means
- * torquing our own last_modified date as well so that the
- * LAST_MODIFIED variable gets reset to the proper value if the
- * nested document resets <!--#config timefmt -->.
- */
- r->subprocess_env = r->main->subprocess_env;
- apr_pool_join(r->main->pool, r->pool);
- r->finfo.mtime = r->main->finfo.mtime;
- }
- else {
- /* we're not a nested include, so we create an initial
- * environment */
- ap_add_common_vars(r);
- ap_add_cgi_vars(r);
- add_include_vars(r, conf->default_time_fmt);
- }
- /* Always unset the content-length. There is no way to know if
- * the content will be modified at some point by send_parsed_content.
- * It is very possible for us to not find any content in the first
- * 9k of the file, but still have to modify the content of the file.
- * If we are going to pass the file through send_parsed_content, then
- * the content-length should just be unset.
- */
- apr_table_unset(f->r->headers_out, "Content-Length");
-
- /* Always unset the Last-Modified field - see RFC2616 - 13.3.4.
- * We don't know if we are going to be including a file or executing
- * a program which may change the Last-Modified header or make the
- * content completely dynamic. Therefore, we can't support these
- * headers.
- * Exception: XBitHack full means we *should* set the Last-Modified field.
- */
-
- /* Assure the platform supports Group protections */
- if ((conf->xbithack == XBITHACK_FULL)
- && (r->finfo.valid & APR_FINFO_GPROT)
- && (r->finfo.protection & APR_GEXECUTE)) {
- ap_update_mtime(r, r->finfo.mtime);
- ap_set_last_modified(r);
- }
- else {
- apr_table_unset(f->r->headers_out, "Last-Modified");
- }
-
- /* add QUERY stuff to env cause it ain't yet */
- if (r->args) {
- char *arg_copy = apr_pstrdup(r->pool, r->args);
-
- apr_table_setn(r->subprocess_env, "QUERY_STRING", r->args);
- ap_unescape_url(arg_copy);
- apr_table_setn(r->subprocess_env, "QUERY_STRING_UNESCAPED",
- ap_escape_shell_cmd(r->pool, arg_copy));
- }
-
- return send_parsed_content(f, b);
-}
-
-static int include_fixup(request_rec *r)
-{
- include_dir_config *conf;
-
- conf = ap_get_module_config(r->per_dir_config, &memcached_include_module);
-
- if (r->handler && (strcmp(r->handler, "server-parsed") == 0))
- {
- if (!r->content_type || !*r->content_type) {
- ap_set_content_type(r, "text/html");
- }
- r->handler = "default-handler";
- }
- else
-#if defined(OS2) || defined(WIN32) || defined(NETWARE)
- /* These OS's don't support xbithack. This is being worked on. */
- {
- return DECLINED;
- }
-#else
- {
- if (conf->xbithack == XBITHACK_OFF) {
- return DECLINED;
- }
-
- if (!(r->finfo.protection & APR_UEXECUTE)) {
- return DECLINED;
- }
-
- if (!r->content_type || strcmp(r->content_type, "text/html")) {
- return DECLINED;
- }
- }
-#endif
-
- /* We always return declined, because the default handler actually
- * serves the file. All we have to do is add the filter.
- */
- ap_add_output_filter("INCLUDES", NULL, r, r->connection);
- return DECLINED;
-}
-
-
-/*
- * +-------------------------------------------------------+
- * | |
- * | Configuration Handling
- * | |
- * +-------------------------------------------------------+
- */
-
-static void *create_includes_dir_config(apr_pool_t *p, char *dummy)
-{
- include_dir_config *result = apr_palloc(p, sizeof(include_dir_config));
-
- result->default_error_msg = DEFAULT_ERROR_MSG;
- result->default_time_fmt = DEFAULT_TIME_FORMAT;
- result->undefined_echo = DEFAULT_UNDEFINED_ECHO;
- result->xbithack = DEFAULT_XBITHACK;
-
- result->servers = apr_array_make(p, 1, sizeof(memcached_include_server_t));
-
- result->max_servers = DEFAULT_MAX_SERVERS;
- result->min_size = DEFAULT_MIN_SIZE;
- result->max_size = DEFAULT_MAX_SIZE;
- result->conn_min = DEFAULT_MIN_CONN;
- result->conn_smax = DEFAULT_SMAX;
- result->conn_max = DEFAULT_MAX;
- result->conn_ttl = DEFAULT_TTL;
-
- return result;
-}
-
-static void *create_includes_server_config(apr_pool_t *p, server_rec *server)
-{
- include_server_config *result;
-
- result = apr_palloc(p, sizeof(include_server_config));
- result->default_end_tag = DEFAULT_END_SEQUENCE;
- result->default_start_tag = DEFAULT_START_SEQUENCE;
-
- return result;
-}
-
-static const char *set_memcached_host(cmd_parms *cmd, void *mconfig, const char *arg)
-{
- char *host, *port;
- memcached_include_server_t *memcached_server = NULL;
- include_dir_config *conf = mconfig;
-
- /*
- * I should consider using apr_parse_addr_port instead
- * [http://apr.apache.org/docs/apr/1.3/group__apr__network__io.html#g90c31b2f012c6b1e2d842a96c4431de3]
- */
- host = apr_pstrdup(cmd->pool, arg);
-
- port = strchr(host, ':');
- if(port) {
- *(port++) = '\0';
- }
-
- if(!*host || host == NULL || !*port || port == NULL) {
- return "MemcachedCacheServer should be in the correct format : host:port";
- }
-
- memcached_server = apr_array_push(conf->servers);
- memcached_server->host = host;
- memcached_server->port = apr_atoi64(port);
-
- return NULL;
-}
-
-static const char *set_memcached_timeout(cmd_parms *cmd, void *mconfig, const char *arg)
-{
- include_dir_config *conf = mconfig;
-
- conf->conn_ttl = atoi(arg);
-
- return NULL;
-}
-
-static const char *set_memcached_soft_max_conn(cmd_parms *cmd, void *mconfig, const char *arg)
-{
- include_dir_config *conf = mconfig;
-
- conf->conn_smax = atoi(arg);
-
- return NULL;
-}
-
-static const char *set_memcached_hard_max_conn(cmd_parms *cmd, void *mconfig, const char *arg)
-{
- include_dir_config *conf = mconfig;
-
- conf->conn_max = atoi(arg);
-
- return NULL;
-}
-
-static const char *set_xbithack(cmd_parms *cmd, void *mconfig, const char *arg)
-{
- include_dir_config *conf = mconfig;
-
- if (!strcasecmp(arg, "off")) {
- conf->xbithack = XBITHACK_OFF;
- }
- else if (!strcasecmp(arg, "on")) {
- conf->xbithack = XBITHACK_ON;
- }
- else if (!strcasecmp(arg, "full")) {
- conf->xbithack = XBITHACK_FULL;
- }
- else {
- return "XBitHack must be set to Off, On, or Full";
- }
-
- return NULL;
-}
-
-static const char *set_default_start_tag(cmd_parms *cmd, void *mconfig,
- const char *tag)
-{
- include_server_config *conf;
- const char *p = tag;
-
- /* be consistent. (See below in set_default_end_tag) */
- while (*p) {
- if (apr_isspace(*p)) {
- return "SSIStartTag may not contain any whitespaces";
- }
- ++p;
- }
-
- conf= ap_get_module_config(cmd->server->module_config , &memcached_include_module);
- conf->default_start_tag = tag;
-
- return NULL;
-}
-
-static const char *set_default_end_tag(cmd_parms *cmd, void *mconfig,
- const char *tag)
-{
- include_server_config *conf;
- const char *p = tag;
-
- /* sanity check. The parser may fail otherwise */
- while (*p) {
- if (apr_isspace(*p)) {
- return "SSIEndTag may not contain any whitespaces";
- }
- ++p;
- }
-
- conf= ap_get_module_config(cmd->server->module_config , &memcached_include_module);
- conf->default_end_tag = tag;
-
- return NULL;
-}
-
-static const char *set_undefined_echo(cmd_parms *cmd, void *mconfig,
- const char *msg)
-{
- include_dir_config *conf = mconfig;
- conf->undefined_echo = msg;
-
- return NULL;
-}
-
-static const char *set_default_error_msg(cmd_parms *cmd, void *mconfig,
- const char *msg)
-{
- include_dir_config *conf = mconfig;
- conf->default_error_msg = msg;
-
- return NULL;
-}
-
-static const char *set_default_time_fmt(cmd_parms *cmd, void *mconfig,
- const char *fmt)
-{
- include_dir_config *conf = mconfig;
- conf->default_time_fmt = fmt;
-
- return NULL;
-}
-
-
-/*
- * +-------------------------------------------------------+
- * | |
- * | Module Initialization and Configuration
- * | |
- * +-------------------------------------------------------+
- */
-
-static int include_post_config(apr_pool_t *p, apr_pool_t *plog,
- apr_pool_t *ptemp, server_rec *s)
-{
- include_handlers = apr_hash_make(p);
-
- ssi_pfn_register = APR_RETRIEVE_OPTIONAL_FN(ap_register_memcached_include_handler);
-
- if(ssi_pfn_register) {
- ssi_pfn_register("if", handle_if);
- ssi_pfn_register("set", handle_set);
- ssi_pfn_register("else", handle_else);
- ssi_pfn_register("elif", handle_elif);
- ssi_pfn_register("echo", handle_echo);
- ssi_pfn_register("endif", handle_endif);
- ssi_pfn_register("fsize", handle_fsize);
- ssi_pfn_register("config", handle_config);
- ssi_pfn_register("include", handle_include);
- ssi_pfn_register("flastmod", handle_flastmod);
- ssi_pfn_register("printenv", handle_printenv);
- }
-
- return OK;
-}
-
-static const command_rec includes_cmds[] =
-{
- AP_INIT_TAKE1("MemcachedHost", set_memcached_host, NULL, OR_OPTIONS,
- "Memcached hostname or IP address with portnumber, like this, 127.0.0.1:11211"),
-
- AP_INIT_TAKE1("MemcachedTTL", set_memcached_timeout, NULL, OR_OPTIONS,
- "Memcached timeout (in seconds)"),
-
- AP_INIT_TAKE1("MemcachedSoftMaxConn", set_memcached_soft_max_conn, NULL, OR_OPTIONS,
- "Memcached low max connexions"),
-
- AP_INIT_TAKE1("MemcachedHardMaxConn", set_memcached_hard_max_conn, NULL, OR_OPTIONS,
- "Memcached high maximum connexions"),
-
- AP_INIT_TAKE1("XBitHack", set_xbithack, NULL, OR_OPTIONS,
- "Off, On, or Full"),
- AP_INIT_TAKE1("SSIErrorMsg", set_default_error_msg, NULL, OR_ALL,
- "a string"),
- AP_INIT_TAKE1("SSITimeFormat", set_default_time_fmt, NULL, OR_ALL,
- "a strftime(3) formatted string"),
- AP_INIT_TAKE1("SSIStartTag", set_default_start_tag, NULL, RSRC_CONF,
- "SSI Start String Tag"),
- AP_INIT_TAKE1("SSIEndTag", set_default_end_tag, NULL, RSRC_CONF,
- "SSI End String Tag"),
- AP_INIT_TAKE1("SSIUndefinedEcho", set_undefined_echo, NULL, OR_ALL,
- "String to be displayed if an echoed variable is undefined"),
- AP_INIT_FLAG("SSIAccessEnable", ap_set_flag_slot,
- (void *)APR_OFFSETOF(include_dir_config, accessenable),
- OR_LIMIT, "Whether testing access is enabled. Limited to 'on' or 'off'"),
- {NULL}
-};
-
-static void ap_register_memcached_include_handler(char *tag, include_handler_fn_t *func)
-{
- apr_hash_set(include_handlers, tag, strlen(tag), (const void *)func);
-}
-
-static void register_hooks(apr_pool_t *p)
-{
- APR_REGISTER_OPTIONAL_FN(ap_ssi_get_tag_and_value);
- APR_REGISTER_OPTIONAL_FN(ap_ssi_parse_string);
- APR_REGISTER_OPTIONAL_FN(ap_register_memcached_include_handler);
- ap_hook_post_config(include_post_config, NULL, NULL, APR_HOOK_REALLY_FIRST);
- ap_hook_fixups(include_fixup, NULL, NULL, APR_HOOK_LAST);
- ap_register_output_filter("INCLUDES", includes_filter, includes_setup,
- AP_FTYPE_RESOURCE);
-}
-
-module AP_MODULE_DECLARE_DATA memcached_include_module =
-{
- STANDARD20_MODULE_STUFF,
- create_includes_dir_config, /* dir config creater */
- NULL, /* dir merger --- default is to override */
- create_includes_server_config,/* server config */
- NULL, /* merge server config */
- includes_cmds, /* command apr_table_t */
- register_hooks /* register hooks */
-};
\ No newline at end of file
diff --git a/src/mod_memcached_include.h b/src/mod_memcached_include.h
deleted file mode 100644
index 1d54097..0000000
--- a/src/mod_memcached_include.h
+++ /dev/null
@@ -1,116 +0,0 @@
-/* Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/**
- * @file mod_include.h
- * @brief Server Side Include Filter Extension Module for Apache
- *
- * @defgroup MOD_INCLUDE mod_include
- * @ingroup APACHE_MODS
- * @{
- */
-
-#ifndef _MOD_INCLUDE_H
-#define _MOD_INCLUDE_H 1
-
-#include "apr_pools.h"
-#include "apr_optional.h"
-
-/*
- * Constants used for ap_ssi_get_tag_and_value's decode parameter
- */
-#define SSI_VALUE_DECODED 1
-#define SSI_VALUE_RAW 0
-
-/*
- * Constants used for ap_ssi_parse_string's leave_name parameter
- */
-#define SSI_EXPAND_LEAVE_NAME 1
-#define SSI_EXPAND_DROP_NAME 0
-
-/*
- * This macro creates a bucket which contains an error message and appends it
- * to the current pass brigade
- */
-#define SSI_CREATE_ERROR_BUCKET(ctx, f, bb) APR_BRIGADE_INSERT_TAIL((bb), \
- apr_bucket_pool_create(apr_pstrdup((ctx)->pool, (ctx)->error_str), \
- strlen((ctx)->error_str), (ctx)->pool, \
- (f)->c->bucket_alloc))
-
-/*
- * These constants are used to set or clear flag bits.
- */
-#define SSI_FLAG_PRINTING (1<<0) /* Printing conditional lines. */
-#define SSI_FLAG_COND_TRUE (1<<1) /* Conditional eval'd to true. */
-#define SSI_FLAG_SIZE_IN_BYTES (1<<2) /* Sizes displayed in bytes. */
-#define SSI_FLAG_NO_EXEC (1<<3) /* No Exec in current context. */
-
-#define SSI_FLAG_SIZE_ABBREV (~(SSI_FLAG_SIZE_IN_BYTES))
-#define SSI_FLAG_CLEAR_PRINT_COND (~((SSI_FLAG_PRINTING) | \
- (SSI_FLAG_COND_TRUE)))
-#define SSI_FLAG_CLEAR_PRINTING (~(SSI_FLAG_PRINTING))
-
-/*
- * The public SSI context structure
- */
-typedef struct {
- /* permanent pool, use this for creating bucket data */
- apr_pool_t *pool;
-
- /* temp pool; will be cleared after the execution of every directive */
- apr_pool_t *dpool;
-
- /* See the SSI_FLAG_XXXXX definitions. */
- int flags;
-
- /* nesting of *invisible* ifs */
- int if_nesting_level;
-
- /* if true, the current buffer will be passed down the filter chain before
- * continuing with next input bucket and the variable will be reset to
- * false.
- */
- int flush_now;
-
- /* argument counter (of the current directive) */
- unsigned argc;
-
- /* currently configured error string */
- const char *error_str;
-
- /* currently configured time format */
- const char *time_str;
-
- /* pointer to internal (non-public) data, don't touch */
- struct ssi_internal_ctx *intern;
-} include_ctx_t;
-
-typedef apr_status_t (include_handler_fn_t)(include_ctx_t *, ap_filter_t *,
- apr_bucket_brigade *);
-
-APR_DECLARE_OPTIONAL_FN(void, ap_ssi_get_tag_and_value,
- (include_ctx_t *ctx, char **tag, char **tag_val,
- int dodecode));
-
-APR_DECLARE_OPTIONAL_FN(char*, ap_ssi_parse_string,
- (include_ctx_t *ctx, const char *in, char *out,
- apr_size_t length, int leave_name));
-
-APR_DECLARE_OPTIONAL_FN(void, ap_register_memcached_include_handler,
- (char *tag, include_handler_fn_t *func));
-
-#endif /* MOD_INCLUDE */
-/** @} */
diff --git a/src/ssi_include_memcached.c b/src/ssi_include_memcached.c
new file mode 100644
index 0000000..b9c2ebb
--- /dev/null
+++ b/src/ssi_include_memcached.c
@@ -0,0 +1,378 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "apr.h"
+#include "apr_strings.h"
+#include "apr_hash.h"
+#include "apr_user.h"
+#include "apr_lib.h"
+#include "apr_optional.h"
+
+#include "ap_config.h"
+#include "httpd.h"
+#include "http_config.h"
+#include "http_core.h"
+#include "http_request.h"
+#include "http_protocol.h"
+#include "http_log.h"
+#include "http_main.h"
+#include "util_script.h"
+#include "mod_include.h"
+
+#include "apr_memcache.h"
+
+typedef struct {
+ apr_memcache_t *memcached;
+ apr_array_header_t *servers;
+
+ apr_uint32_t conn_min;
+ apr_uint32_t conn_smax;
+ apr_uint32_t conn_max;
+ apr_uint32_t conn_ttl;
+ apr_uint16_t max_servers;
+ apr_off_t min_size;
+ apr_off_t max_size;
+} ssi_include_dir_config;
+
+typedef struct {
+ const char *host;
+ apr_port_t port;
+ apr_memcache_server_t *server;
+} memcached_server_t;
+
+#define DEFAULT_MAX_SERVERS 1
+#define DEFAULT_MIN_CONN 1
+#define DEFAULT_SMAX 10
+#define DEFAULT_MAX 15
+#define DEFAULT_TTL 10
+#define DEFAULT_MIN_SIZE 1
+#define DEFAULT_MAX_SIZE 1048576
+
+module AP_MODULE_DECLARE_DATA ssi_include_memcached_module;
+
+static APR_OPTIONAL_FN_TYPE(ap_register_include_handler) *ssi_include_memcached_pfn_rih;
+static APR_OPTIONAL_FN_TYPE(ap_ssi_get_tag_and_value) *ssi_include_memcached_pfn_gtv;
+static APR_OPTIONAL_FN_TYPE(ap_ssi_parse_string) *ssi_include_memcached_pfn_ps;
+
+/*
+ * <!--#include virtual|file|memcached="..." [virtual|file="..."] ... -->
+ */
+static apr_status_t handle_include_memcached(include_ctx_t *ctx, ap_filter_t *f,
+ apr_bucket_brigade *bb)
+{
+ request_rec *r = f->r;
+
+ if (!ctx->argc) {
+ ap_log_rerror(APLOG_MARK,
+ (ctx->flags & SSI_FLAG_PRINTING)
+ ? APLOG_ERR : APLOG_WARNING,
+ 0, r, "missing argument for include element in %s",
+ r->filename);
+ }
+
+ if (!(ctx->flags & SSI_FLAG_PRINTING)) {
+ return APR_SUCCESS;
+ }
+
+ if (!ctx->argc) {
+ SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
+ return APR_SUCCESS;
+ }
+
+ while (1) {
+ char *tag = NULL;
+ char *tag_val = NULL;
+ request_rec *rr = NULL;
+ char *error_fmt = NULL;
+ char *parsed_string;
+
+ ssi_include_memcached_pfn_gtv(ctx, &tag, &tag_val, SSI_VALUE_DECODED);
+ if (!tag || !tag_val) {
+ break;
+ }
+
+ if (strcmp(tag, "virtual") && strcmp(tag, "file") && strcmp(tag, "memcached")) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unknown parameter "
+ "\"%s\" to tag include in %s", tag, r->filename);
+ SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
+ break;
+ }
+
+ parsed_string = ssi_include_memcached_pfn_ps(ctx, tag_val, NULL, 0, SSI_EXPAND_DROP_NAME);
+
+ /* Fetching files from Memcached */
+ if (tag[0] == 'm') {
+
+ ssi_include_dir_config *conf;
+ memcached_server_t *svr;
+ apr_status_t rv;
+ int i;
+
+ apr_uint16_t flags;
+ char *strkey = NULL;
+ char *value;
+ apr_size_t value_len;
+
+ strkey = ap_escape_uri(r->pool, parsed_string);
+
+ conf = (ssi_include_dir_config *)ap_get_module_config(r->per_dir_config, &ssi_include_memcached_module);
+
+ rv = apr_memcache_create(r->pool, conf->max_servers, 0, &(conf->memcached));
+
+ if(rv != APR_SUCCESS) {
+ ap_log_rerror(APLOG_MARK, APLOG_DEBUG, rv, r, "Unable to create memcached structure");
+ }
+
+ svr = (memcached_server_t *)conf->servers->elts;
+
+ for(i = 0; i < conf->servers->nelts; i++) {
+
+ rv = apr_memcache_server_create(r->pool, svr[i].host, svr[i].port,
+ conf->conn_min, conf->conn_smax,
+ conf->conn_max, conf->conn_ttl,
+ &(svr[i].server));
+
+ if(rv != APR_SUCCESS) {
+ ap_log_rerror(APLOG_MARK, APLOG_DEBUG, rv, r, "Unable to create memcache server for %s:%d is Memcached running ?", svr[i].host, svr[i].port);
+ continue;
+ }
+
+ rv = apr_memcache_add_server(conf->memcached, svr[i].server);
+
+ if(rv != APR_SUCCESS) {
+ ap_log_rerror(APLOG_MARK, APLOG_DEBUG, rv, r, "Unable to add memcache server for %s:%d", svr[i].host, svr[i].port);
+ }
+
+ ap_log_rerror(APLOG_MARK, APLOG_DEBUG, rv, r, "Memcached server successfully created %s:%d %d %d %d", svr[i].host, svr[i].port, conf->conn_smax, conf->conn_max, conf->conn_ttl);
+ }
+
+ ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Fetching the file with key : %s", strkey);
+
+ rv = apr_memcache_getp(conf->memcached, r->pool, strkey, &value, &value_len, &flags);
+
+ if( rv == APR_SUCCESS ) {
+ ap_log_rerror(APLOG_MARK, APLOG_DEBUG, rv, r, "File found with key %s, value : %s", strkey, value);
+ APR_BRIGADE_INSERT_TAIL(bb,
+ apr_bucket_pool_create(apr_pmemdup(ctx->pool, value, value_len),
+ value_len,
+ ctx->pool,
+ f->c->bucket_alloc));
+ return APR_SUCCESS;
+ }
+ else {
+ error_fmt = "Unable to fetch file with key '%s' in parsed file %s";
+ }
+ }
+ else if (tag[0] == 'f') {
+ char *newpath;
+ apr_status_t rv;
+
+ /* be safe only files in this directory or below allowed */
+ rv = apr_filepath_merge(&newpath, NULL, parsed_string,
+ APR_FILEPATH_SECUREROOTTEST |
+ APR_FILEPATH_NOTABSOLUTE, ctx->dpool);
+
+ if (rv != APR_SUCCESS) {
+ error_fmt = "unable to include file \"%s\" in parsed file %s";
+ }
+ else {
+ rr = ap_sub_req_lookup_file(newpath, r, f->next);
+ }
+ }
+ else {
+ rr = ap_sub_req_lookup_uri(parsed_string, r, f->next);
+ }
+
+ if (!error_fmt && rr->status != HTTP_OK) {
+ error_fmt = "unable to include \"%s\" in parsed file %s";
+ }
+
+ if (!error_fmt && (ctx->flags & SSI_FLAG_NO_EXEC) &&
+ rr->content_type && strncmp(rr->content_type, "text/", 5)) {
+
+ error_fmt = "unable to include potential exec \"%s\" in parsed "
+ "file %s";
+ }
+
+ /* See the Kludge in includes_filter for why.
+ * Basically, it puts a bread crumb in here, then looks
+ * for the crumb later to see if its been here.
+ */
+ if (rr) {
+ ap_set_module_config(rr->request_config, &ssi_include_memcached_module, r);
+ }
+
+ if (!error_fmt && ap_run_sub_req(rr)) {
+ error_fmt = "unable to include \"%s\" in parsed file %s";
+ }
+
+ if (error_fmt) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, error_fmt, tag_val,
+ r->filename);
+ SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
+ }
+
+ /* Do *not* destroy the subrequest here; it may have allocated
+ * variables in this r->subprocess_env in the subrequest's
+ * r->pool, so that pool must survive as long as this request.
+ * Yes, this is a memory leak. */
+ if (error_fmt) {
+ break;
+ }
+ }
+
+ return APR_SUCCESS;
+}
+
+static void *create_ssi_include_memcached_dir_config(apr_pool_t *p, char *dummy)
+{
+ ssi_include_dir_config *result = apr_palloc(p, sizeof(ssi_include_dir_config));
+
+ result->servers = apr_array_make(p, 1, sizeof(memcached_server_t));
+
+ result->max_servers = DEFAULT_MAX_SERVERS;
+ result->min_size = DEFAULT_MIN_SIZE;
+ result->max_size = DEFAULT_MAX_SIZE;
+ result->conn_min = DEFAULT_MIN_CONN;
+ result->conn_smax = DEFAULT_SMAX;
+ result->conn_max = DEFAULT_MAX;
+ result->conn_ttl = DEFAULT_TTL;
+
+ return result;
+}
+
+static const char *set_memcached_host(cmd_parms *cmd, void *mconfig, const char *arg)
+{
+ char *host, *port;
+ memcached_server_t *memcached_server = NULL;
+ ssi_include_dir_config *conf = mconfig;
+
+ /*
+ * I should consider using apr_parse_addr_port instead
+ * [http://apr.apache.org/docs/apr/1.3/group__apr__network__io.html#g90c31b2f012c6b1e2d842a96c4431de3]
+ */
+ host = apr_pstrdup(cmd->pool, arg);
+
+ port = strchr(host, ':');
+ if(port) {
+ *(port++) = '\0';
+ }
+
+ if(!*host || host == NULL || !*port || port == NULL) {
+ return "MemcachedCacheServer should be in the correct format : host:port";
+ }
+
+ memcached_server = apr_array_push(conf->servers);
+ memcached_server->host = host;
+ memcached_server->port = apr_atoi64(port);
+
+ return NULL;
+}
+
+static const char *set_memcached_timeout(cmd_parms *cmd, void *mconfig, const char *arg)
+{
+ ssi_include_dir_config *conf = mconfig;
+
+ conf->conn_ttl = atoi(arg);
+
+ return NULL;
+}
+
+static const char *set_memcached_soft_max_conn(cmd_parms *cmd, void *mconfig, const char *arg)
+{
+ ssi_include_dir_config *conf = mconfig;
+
+ conf->conn_smax = atoi(arg);
+
+ return NULL;
+}
+
+static const char *set_memcached_hard_max_conn(cmd_parms *cmd, void *mconfig, const char *arg)
+{
+ ssi_include_dir_config *conf = mconfig;
+
+ conf->conn_max = atoi(arg);
+
+ return NULL;
+}
+
+static int ssi_include_memcached_post_config(apr_pool_t *p, apr_pool_t *plog,
+ apr_pool_t *ptemp, server_rec *s)
+{
+ ssi_include_memcached_pfn_gtv = APR_RETRIEVE_OPTIONAL_FN(ap_ssi_get_tag_and_value);
+ ssi_include_memcached_pfn_ps = APR_RETRIEVE_OPTIONAL_FN(ap_ssi_parse_string);
+ ssi_include_memcached_pfn_rih = APR_RETRIEVE_OPTIONAL_FN(ap_register_include_handler);
+
+ if (ssi_include_memcached_pfn_gtv &&
+ ssi_include_memcached_pfn_ps &&
+ ssi_include_memcached_pfn_rih) {
+ ssi_include_memcached_pfn_rih("include", handle_include_memcached);
+ } else {
+ ap_log_error(APLOG_MARK, APLOG_ERR, 0, NULL, "unable to register a new include function");
+ }
+
+ return OK;
+}
+
+static void register_hooks(apr_pool_t *p)
+{
+ static const char * const prereq[] = { "mod_include.c", NULL };
+
+ /*APR_REGISTER_OPTIONAL_FN(ap_ssi_parse_string);*/
+ /*APR_REGISTER_OPTIONAL_FN(ap_ssi_include_memcached_register_handler);*/
+
+ ap_hook_post_config(ssi_include_memcached_post_config, prereq, NULL, APR_HOOK_FIRST);
+}
+
+static const command_rec includes_cmds[] =
+{
+ AP_INIT_TAKE1("MemcachedHost",
+ set_memcached_host,
+ NULL,
+ OR_OPTIONS,
+ "Memcached hostname or IP address with portnumber, like this, 127.0.0.1:11211"),
+
+ AP_INIT_TAKE1("MemcachedTTL",
+ set_memcached_timeout,
+ NULL,
+ OR_OPTIONS,
+ "Memcached timeout (in seconds)"),
+
+ AP_INIT_TAKE1("MemcachedSoftMaxConn",
+ set_memcached_soft_max_conn,
+ NULL,
+ OR_OPTIONS,
+ "Memcached low max connexions"),
+
+ AP_INIT_TAKE1("MemcachedHardMaxConn",
+ set_memcached_hard_max_conn,
+ NULL,
+ OR_OPTIONS,
+ "Memcached high maximum connexions"),
+
+ {NULL}
+};
+
+module AP_MODULE_DECLARE_DATA ssi_include_memcached_module =
+{
+ STANDARD20_MODULE_STUFF,
+ create_ssi_include_memcached_dir_config, /* dir config creator */
+ NULL, /* merge dir config */
+ NULL, /* create_ssi_include_memcached_server_config, server config */
+ NULL, /* merge server config */
+ includes_cmds, /* command apr_table_t */
+ register_hooks /* register hooks */
+};
\ No newline at end of file
|
jeromer/modmemcachedinclude
|
88d88a872f7887fc9885ce7c306a9e91744acd55
|
- Fixed crash when used in VHost mode
|
diff --git a/src/mod_memcached_include.c b/src/mod_memcached_include.c
index f5c5889..8c6fe81 100644
--- a/src/mod_memcached_include.c
+++ b/src/mod_memcached_include.c
@@ -1,662 +1,662 @@
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "apr.h"
#include "apr_strings.h"
#include "apr_thread_proc.h"
#include "apr_hash.h"
#include "apr_user.h"
#include "apr_lib.h"
#include "apr_optional.h"
#define APR_WANT_STRFUNC
#define APR_WANT_MEMFUNC
#include "apr_want.h"
#include "ap_config.h"
#include "util_filter.h"
#include "httpd.h"
#include "http_config.h"
#include "http_core.h"
#include "http_request.h"
#include "http_core.h"
#include "http_protocol.h"
#include "http_log.h"
#include "http_main.h"
#include "util_script.h"
#include "http_core.h"
#include "mod_memcached_include.h"
#include "apr_memcache.h"
/* helper for Latin1 <-> entity encoding */
#if APR_CHARSET_EBCDIC
#include "util_ebcdic.h"
#define RAW_ASCII_CHAR(ch) apr_xlate_conv_byte(ap_hdrs_from_ascii, \
(unsigned char)ch)
#else /* APR_CHARSET_EBCDIC */
#define RAW_ASCII_CHAR(ch) (ch)
#endif /* !APR_CHARSET_EBCDIC */
/*
* +-------------------------------------------------------+
* | |
* | Types and Structures
* | |
* +-------------------------------------------------------+
*/
/* sll used for string expansion */
typedef struct result_item {
struct result_item *next;
apr_size_t len;
const char *string;
} result_item_t;
/* conditional expression parser stuff */
typedef enum {
TOKEN_STRING,
TOKEN_RE,
TOKEN_AND,
TOKEN_OR,
TOKEN_NOT,
TOKEN_EQ,
TOKEN_NE,
TOKEN_RBRACE,
TOKEN_LBRACE,
TOKEN_GROUP,
TOKEN_GE,
TOKEN_LE,
TOKEN_GT,
TOKEN_LT,
TOKEN_ACCESS
} token_type_t;
typedef struct {
token_type_t type;
const char *value;
#ifdef DEBUG_INCLUDE
const char *s;
#endif
} token_t;
typedef struct parse_node {
struct parse_node *parent;
struct parse_node *left;
struct parse_node *right;
token_t token;
int value;
int done;
#ifdef DEBUG_INCLUDE
int dump_done;
#endif
} parse_node_t;
typedef enum {
XBITHACK_OFF,
XBITHACK_ON,
XBITHACK_FULL
} xbithack_t;
typedef struct {
const char *default_error_msg;
const char *default_time_fmt;
const char *undefined_echo;
xbithack_t xbithack;
const int accessenable;
+
+ apr_memcache_t *memcached;
+ apr_array_header_t *servers;
+
+ apr_uint32_t conn_min;
+ apr_uint32_t conn_smax;
+ apr_uint32_t conn_max;
+ apr_uint32_t conn_ttl;
+ apr_uint16_t max_servers;
+ apr_off_t min_size;
+ apr_off_t max_size;
} include_dir_config;
typedef struct {
const char *host;
apr_port_t port;
apr_memcache_server_t *server;
} memcached_include_server_t;
#define DEFAULT_MAX_SERVERS 1
#define DEFAULT_MIN_CONN 1
#define DEFAULT_SMAX 10
#define DEFAULT_MAX 15
#define DEFAULT_TTL 10
#define DEFAULT_MIN_SIZE 1
#define DEFAULT_MAX_SIZE 1048576
typedef struct {
const char *default_start_tag;
const char *default_end_tag;
-
- apr_memcache_t *memcached;
- apr_array_header_t *servers;
-
- apr_uint32_t conn_min;
- apr_uint32_t conn_smax;
- apr_uint32_t conn_max;
- apr_uint32_t conn_ttl;
- apr_uint16_t max_servers;
- apr_off_t min_size;
- apr_off_t max_size;
} include_server_config;
/* main parser states */
typedef enum {
PARSE_PRE_HEAD,
PARSE_HEAD,
PARSE_DIRECTIVE,
PARSE_DIRECTIVE_POSTNAME,
PARSE_DIRECTIVE_TAIL,
PARSE_DIRECTIVE_POSTTAIL,
PARSE_PRE_ARG,
PARSE_ARG,
PARSE_ARG_NAME,
PARSE_ARG_POSTNAME,
PARSE_ARG_EQ,
PARSE_ARG_PREVAL,
PARSE_ARG_VAL,
PARSE_ARG_VAL_ESC,
PARSE_ARG_POSTVAL,
PARSE_TAIL,
PARSE_TAIL_SEQ,
PARSE_EXECUTE
} parse_state_t;
typedef struct arg_item {
struct arg_item *next;
char *name;
apr_size_t name_len;
char *value;
apr_size_t value_len;
} arg_item_t;
typedef struct {
const char *source;
const char *rexp;
apr_size_t nsub;
ap_regmatch_t match[AP_MAX_REG_MATCH];
} backref_t;
typedef struct {
unsigned int T[256];
unsigned int x;
apr_size_t pattern_len;
} bndm_t;
struct ssi_internal_ctx {
parse_state_t state;
int seen_eos;
int error;
char quote; /* quote character value (or \0) */
apr_size_t parse_pos; /* parse position of partial matches */
apr_size_t bytes_read;
apr_bucket_brigade *tmp_bb;
request_rec *r;
const char *start_seq;
bndm_t *start_seq_pat;
const char *end_seq;
apr_size_t end_seq_len;
char *directive; /* name of the current directive */
apr_size_t directive_len; /* length of the current directive name */
arg_item_t *current_arg; /* currently parsed argument */
arg_item_t *argv; /* all arguments */
backref_t *re; /* NULL if there wasn't a regex yet */
const char *undefined_echo;
apr_size_t undefined_echo_len;
int accessenable; /* is using the access tests allowed? */
#ifdef DEBUG_INCLUDE
struct {
ap_filter_t *f;
apr_bucket_brigade *bb;
} debug;
#endif
};
/*
* +-------------------------------------------------------+
* | |
* | Debugging Utilities
* | |
* +-------------------------------------------------------+
*/
#ifdef DEBUG_INCLUDE
#define TYPE_TOKEN(token, ttype) do { \
(token)->type = ttype; \
(token)->s = #ttype; \
} while(0)
#define CREATE_NODE(ctx, name) do { \
(name) = apr_palloc((ctx)->dpool, sizeof(*(name))); \
(name)->parent = (name)->left = (name)->right = NULL; \
(name)->done = 0; \
(name)->dump_done = 0; \
} while(0)
static void debug_printf(include_ctx_t *ctx, const char *fmt, ...)
{
va_list ap;
char *debug__str;
va_start(ap, fmt);
debug__str = apr_pvsprintf(ctx->pool, fmt, ap);
va_end(ap);
APR_BRIGADE_INSERT_TAIL(ctx->intern->debug.bb, apr_bucket_pool_create(
debug__str, strlen(debug__str), ctx->pool,
ctx->intern->debug.f->c->bucket_alloc));
}
#define DUMP__CHILD(ctx, is, node, child) if (1) { \
parse_node_t *d__c = node->child; \
if (d__c) { \
if (!d__c->dump_done) { \
if (d__c->parent != node) { \
debug_printf(ctx, "!!! Parse tree is not consistent !!!\n"); \
if (!d__c->parent) { \
debug_printf(ctx, "Parent of " #child " child node is " \
"NULL.\n"); \
} \
else { \
debug_printf(ctx, "Parent of " #child " child node " \
"points to another node (of type %s)!\n", \
d__c->parent->token.s); \
} \
return; \
} \
node = d__c; \
continue; \
} \
} \
else { \
debug_printf(ctx, "%s(missing)\n", is); \
} \
}
static void debug_dump_tree(include_ctx_t *ctx, parse_node_t *root)
{
parse_node_t *current;
char *is;
if (!root) {
debug_printf(ctx, " -- Parse Tree empty --\n\n");
return;
}
debug_printf(ctx, " ----- Parse Tree -----\n");
current = root;
is = " ";
while (current) {
switch (current->token.type) {
case TOKEN_STRING:
case TOKEN_RE:
debug_printf(ctx, "%s%s (%s)\n", is, current->token.s,
current->token.value);
current->dump_done = 1;
current = current->parent;
continue;
case TOKEN_NOT:
case TOKEN_GROUP:
case TOKEN_RBRACE:
case TOKEN_LBRACE:
if (!current->dump_done) {
debug_printf(ctx, "%s%s\n", is, current->token.s);
is = apr_pstrcat(ctx->dpool, is, " ", NULL);
current->dump_done = 1;
}
DUMP__CHILD(ctx, is, current, right)
if (!current->right || current->right->dump_done) {
is = apr_pstrmemdup(ctx->dpool, is, strlen(is) - 4);
if (current->right) current->right->dump_done = 0;
current = current->parent;
}
continue;
default:
if (!current->dump_done) {
debug_printf(ctx, "%s%s\n", is, current->token.s);
is = apr_pstrcat(ctx->dpool, is, " ", NULL);
current->dump_done = 1;
}
DUMP__CHILD(ctx, is, current, left)
DUMP__CHILD(ctx, is, current, right)
if ((!current->left || current->left->dump_done) &&
(!current->right || current->right->dump_done)) {
is = apr_pstrmemdup(ctx->dpool, is, strlen(is) - 4);
if (current->left) current->left->dump_done = 0;
if (current->right) current->right->dump_done = 0;
current = current->parent;
}
continue;
}
}
/* it is possible to call this function within the parser loop, to see
* how the tree is built. That way, we must cleanup after us to dump
* always the whole tree
*/
root->dump_done = 0;
if (root->left) root->left->dump_done = 0;
if (root->right) root->right->dump_done = 0;
debug_printf(ctx, " --- End Parse Tree ---\n\n");
return;
}
#define DEBUG_INIT(ctx, filter, brigade) do { \
(ctx)->intern->debug.f = filter; \
(ctx)->intern->debug.bb = brigade; \
} while(0)
#define DEBUG_PRINTF(arg) debug_printf arg
#define DEBUG_DUMP_TOKEN(ctx, token) do { \
token_t *d__t = (token); \
\
if (d__t->type == TOKEN_STRING || d__t->type == TOKEN_RE) { \
DEBUG_PRINTF(((ctx), " Found: %s (%s)\n", d__t->s, d__t->value)); \
} \
else { \
DEBUG_PRINTF((ctx, " Found: %s\n", d__t->s)); \
} \
} while(0)
#define DEBUG_DUMP_EVAL(ctx, node) do { \
char c = '"'; \
switch ((node)->token.type) { \
case TOKEN_STRING: \
debug_printf((ctx), " Evaluate: %s (%s) -> %c\n", (node)->token.s,\
(node)->token.value, ((node)->value) ? '1':'0'); \
break; \
case TOKEN_AND: \
case TOKEN_OR: \
debug_printf((ctx), " Evaluate: %s (Left: %s; Right: %s) -> %c\n",\
(node)->token.s, \
(((node)->left->done) ? ((node)->left->value ?"1":"0") \
: "short circuited"), \
(((node)->right->done) ? ((node)->right->value?"1":"0") \
: "short circuited"), \
(node)->value ? '1' : '0'); \
break; \
case TOKEN_EQ: \
case TOKEN_NE: \
case TOKEN_GT: \
case TOKEN_GE: \
case TOKEN_LT: \
case TOKEN_LE: \
if ((node)->right->token.type == TOKEN_RE) c = '/'; \
debug_printf((ctx), " Compare: %s (\"%s\" with %c%s%c) -> %c\n", \
(node)->token.s, \
(node)->left->token.value, \
c, (node)->right->token.value, c, \
(node)->value ? '1' : '0'); \
break; \
default: \
debug_printf((ctx), " Evaluate: %s -> %c\n", (node)->token.s, \
(node)->value ? '1' : '0'); \
break; \
} \
} while(0)
#define DEBUG_DUMP_UNMATCHED(ctx, unmatched) do { \
if (unmatched) { \
DEBUG_PRINTF(((ctx), " Unmatched %c\n", (char)(unmatched))); \
} \
} while(0)
#define DEBUG_DUMP_COND(ctx, text) \
DEBUG_PRINTF(((ctx), "**** %s cond status=\"%c\"\n", (text), \
((ctx)->flags & SSI_FLAG_COND_TRUE) ? '1' : '0'))
#define DEBUG_DUMP_TREE(ctx, root) debug_dump_tree(ctx, root)
#else /* DEBUG_INCLUDE */
#define TYPE_TOKEN(token, ttype) (token)->type = ttype
#define CREATE_NODE(ctx, name) do { \
(name) = apr_palloc((ctx)->dpool, sizeof(*(name))); \
(name)->parent = (name)->left = (name)->right = NULL; \
(name)->done = 0; \
} while(0)
#define DEBUG_INIT(ctx, f, bb)
#define DEBUG_PRINTF(arg)
#define DEBUG_DUMP_TOKEN(ctx, token)
#define DEBUG_DUMP_EVAL(ctx, node)
#define DEBUG_DUMP_UNMATCHED(ctx, unmatched)
#define DEBUG_DUMP_COND(ctx, text)
#define DEBUG_DUMP_TREE(ctx, root)
#endif /* !DEBUG_INCLUDE */
/*
* +-------------------------------------------------------+
* | |
* | Static Module Data
* | |
* +-------------------------------------------------------+
*/
/* global module structure */
module AP_MODULE_DECLARE_DATA memcached_include_module;
/* function handlers for include directives */
static apr_hash_t *include_handlers;
/* forward declaration of handler registry */
static APR_OPTIONAL_FN_TYPE(ap_register_memcached_include_handler) *ssi_pfn_register;
/* Sentinel value to store in subprocess_env for items that
* shouldn't be evaluated until/unless they're actually used
*/
static const char lazy_eval_sentinel;
#define LAZY_VALUE (&lazy_eval_sentinel)
/* default values */
#define DEFAULT_START_SEQUENCE "<!--#"
#define DEFAULT_END_SEQUENCE "-->"
#define DEFAULT_ERROR_MSG "[an error occurred while processing this directive]"
#define DEFAULT_TIME_FORMAT "%A, %d-%b-%Y %H:%M:%S %Z"
#define DEFAULT_UNDEFINED_ECHO "(none)"
#ifdef XBITHACK
#define DEFAULT_XBITHACK XBITHACK_FULL
#else
#define DEFAULT_XBITHACK XBITHACK_OFF
#endif
/*
* +-------------------------------------------------------+
* | |
* | Environment/Expansion Functions
* | |
* +-------------------------------------------------------+
*/
/*
* decodes a string containing html entities or numeric character references.
* 's' is overwritten with the decoded string.
* If 's' is syntatically incorrect, then the followed fixups will be made:
* unknown entities will be left undecoded;
* references to unused numeric characters will be deleted.
* In particular, � will not be decoded, but will be deleted.
*/
/* maximum length of any ISO-LATIN-1 HTML entity name. */
#define MAXENTLEN (6)
/* The following is a shrinking transformation, therefore safe. */
static void decodehtml(char *s)
{
int val, i, j;
char *p;
const char *ents;
static const char * const entlist[MAXENTLEN + 1] =
{
NULL, /* 0 */
NULL, /* 1 */
"lt\074gt\076", /* 2 */
"amp\046ETH\320eth\360", /* 3 */
"quot\042Auml\304Euml\313Iuml\317Ouml\326Uuml\334auml\344euml"
"\353iuml\357ouml\366uuml\374yuml\377", /* 4 */
"Acirc\302Aring\305AElig\306Ecirc\312Icirc\316Ocirc\324Ucirc"
"\333THORN\336szlig\337acirc\342aring\345aelig\346ecirc\352"
"icirc\356ocirc\364ucirc\373thorn\376", /* 5 */
"Agrave\300Aacute\301Atilde\303Ccedil\307Egrave\310Eacute\311"
"Igrave\314Iacute\315Ntilde\321Ograve\322Oacute\323Otilde"
"\325Oslash\330Ugrave\331Uacute\332Yacute\335agrave\340"
"aacute\341atilde\343ccedil\347egrave\350eacute\351igrave"
"\354iacute\355ntilde\361ograve\362oacute\363otilde\365"
"oslash\370ugrave\371uacute\372yacute\375" /* 6 */
};
/* Do a fast scan through the string until we find anything
* that needs more complicated handling
*/
for (; *s != '&'; s++) {
if (*s == '\0') {
return;
}
}
for (p = s; *s != '\0'; s++, p++) {
if (*s != '&') {
*p = *s;
continue;
}
/* find end of entity */
for (i = 1; s[i] != ';' && s[i] != '\0'; i++) {
continue;
}
if (s[i] == '\0') { /* treat as normal data */
*p = *s;
continue;
}
/* is it numeric ? */
if (s[1] == '#') {
for (j = 2, val = 0; j < i && apr_isdigit(s[j]); j++) {
val = val * 10 + s[j] - '0';
}
s += i;
if (j < i || val <= 8 || (val >= 11 && val <= 31) ||
(val >= 127 && val <= 160) || val >= 256) {
p--; /* no data to output */
}
else {
*p = RAW_ASCII_CHAR(val);
}
}
else {
j = i - 1;
if (j > MAXENTLEN || entlist[j] == NULL) {
/* wrong length */
*p = '&';
continue; /* skip it */
}
for (ents = entlist[j]; *ents != '\0'; ents += i) {
if (strncmp(s + 1, ents, j) == 0) {
break;
}
}
if (*ents == '\0') {
*p = '&'; /* unknown */
}
else {
*p = RAW_ASCII_CHAR(((const unsigned char *) ents)[j]);
s += i;
}
}
}
*p = '\0';
}
static void add_include_vars(request_rec *r, const char *timefmt)
{
apr_table_t *e = r->subprocess_env;
char *t;
apr_table_setn(e, "DATE_LOCAL", LAZY_VALUE);
apr_table_setn(e, "DATE_GMT", LAZY_VALUE);
apr_table_setn(e, "LAST_MODIFIED", LAZY_VALUE);
apr_table_setn(e, "DOCUMENT_URI", r->uri);
if (r->path_info && *r->path_info) {
apr_table_setn(e, "DOCUMENT_PATH_INFO", r->path_info);
}
apr_table_setn(e, "USER_NAME", LAZY_VALUE);
if (r->filename && (t = strrchr(r->filename, '/'))) {
apr_table_setn(e, "DOCUMENT_NAME", ++t);
}
else {
apr_table_setn(e, "DOCUMENT_NAME", r->uri);
}
if (r->args) {
char *arg_copy = apr_pstrdup(r->pool, r->args);
ap_unescape_url(arg_copy);
apr_table_setn(e, "QUERY_STRING_UNESCAPED",
ap_escape_shell_cmd(r->pool, arg_copy));
}
}
static const char *add_include_vars_lazy(request_rec *r, const char *var)
{
char *val;
if (!strcasecmp(var, "DATE_LOCAL")) {
include_dir_config *conf =
(include_dir_config *)ap_get_module_config(r->per_dir_config,
&memcached_include_module);
val = ap_ht_time(r->pool, r->request_time, conf->default_time_fmt, 0);
}
else if (!strcasecmp(var, "DATE_GMT")) {
include_dir_config *conf =
(include_dir_config *)ap_get_module_config(r->per_dir_config,
&memcached_include_module);
val = ap_ht_time(r->pool, r->request_time, conf->default_time_fmt, 1);
}
else if (!strcasecmp(var, "LAST_MODIFIED")) {
include_dir_config *conf =
(include_dir_config *)ap_get_module_config(r->per_dir_config,
&memcached_include_module);
val = ap_ht_time(r->pool, r->finfo.mtime, conf->default_time_fmt, 0);
}
else if (!strcasecmp(var, "USER_NAME")) {
if (apr_uid_name_get(&val, r->finfo.user, r->pool) != APR_SUCCESS) {
val = "<unknown>";
}
@@ -1216,1034 +1216,1069 @@ static int parse_expr(include_ctx_t *ctx, const char *expr, int *was_error)
default:
new->parent = current;
current = current->right = new;
continue;
}
break;
case TOKEN_RE:
switch (current->token.type) {
case TOKEN_EQ:
case TOKEN_NE:
new->parent = current;
current = current->right = new;
++regex;
continue;
default:
break;
}
break;
case TOKEN_AND:
case TOKEN_OR:
switch (current->token.type) {
case TOKEN_STRING:
case TOKEN_RE:
case TOKEN_GROUP:
current = current->parent;
while (current) {
switch (current->token.type) {
case TOKEN_AND:
case TOKEN_OR:
case TOKEN_LBRACE:
break;
default:
current = current->parent;
continue;
}
break;
}
if (!current) {
new->left = root;
root->parent = new;
current = root = new;
continue;
}
new->left = current->right;
new->left->parent = new;
new->parent = current;
current = current->right = new;
continue;
default:
break;
}
break;
case TOKEN_EQ:
case TOKEN_NE:
case TOKEN_GE:
case TOKEN_GT:
case TOKEN_LE:
case TOKEN_LT:
if (current->token.type == TOKEN_STRING) {
current = current->parent;
if (!current) {
new->left = root;
root->parent = new;
current = root = new;
continue;
}
switch (current->token.type) {
case TOKEN_LBRACE:
case TOKEN_AND:
case TOKEN_OR:
new->left = current->right;
new->left->parent = new;
new->parent = current;
current = current->right = new;
continue;
default:
break;
}
}
break;
case TOKEN_RBRACE:
while (current && current->token.type != TOKEN_LBRACE) {
current = current->parent;
}
if (current) {
TYPE_TOKEN(¤t->token, TOKEN_GROUP);
continue;
}
error = "Unmatched ')' in \"%s\" in file %s";
break;
case TOKEN_NOT:
case TOKEN_ACCESS:
case TOKEN_LBRACE:
switch (current->token.type) {
case TOKEN_STRING:
case TOKEN_RE:
case TOKEN_RBRACE:
case TOKEN_GROUP:
break;
default:
current->right = new;
new->parent = current;
current = new;
continue;
}
break;
default:
break;
}
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, error, expr, r->filename);
*was_error = 1;
return 0;
}
DEBUG_DUMP_TREE(ctx, root);
/* Evaluate Parse Tree */
current = root;
error = NULL;
while (current) {
switch (current->token.type) {
case TOKEN_STRING:
current->token.value =
ap_ssi_parse_string(ctx, current->token.value, NULL, 0,
SSI_EXPAND_DROP_NAME);
current->value = !!*current->token.value;
break;
case TOKEN_AND:
case TOKEN_OR:
if (!current->left || !current->right) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
"Invalid expression \"%s\" in file %s",
expr, r->filename);
*was_error = 1;
return 0;
}
if (!current->left->done) {
switch (current->left->token.type) {
case TOKEN_STRING:
current->left->token.value =
ap_ssi_parse_string(ctx, current->left->token.value,
NULL, 0, SSI_EXPAND_DROP_NAME);
current->left->value = !!*current->left->token.value;
DEBUG_DUMP_EVAL(ctx, current->left);
current->left->done = 1;
break;
default:
current = current->left;
continue;
}
}
/* short circuit evaluation */
if (!current->right->done && !regex &&
((current->token.type == TOKEN_AND && !current->left->value) ||
(current->token.type == TOKEN_OR && current->left->value))) {
current->value = current->left->value;
}
else {
if (!current->right->done) {
switch (current->right->token.type) {
case TOKEN_STRING:
current->right->token.value =
ap_ssi_parse_string(ctx,current->right->token.value,
NULL, 0, SSI_EXPAND_DROP_NAME);
current->right->value = !!*current->right->token.value;
DEBUG_DUMP_EVAL(ctx, current->right);
current->right->done = 1;
break;
default:
current = current->right;
continue;
}
}
if (current->token.type == TOKEN_AND) {
current->value = current->left->value &&
current->right->value;
}
else {
current->value = current->left->value ||
current->right->value;
}
}
break;
case TOKEN_EQ:
case TOKEN_NE:
if (!current->left || !current->right ||
current->left->token.type != TOKEN_STRING ||
(current->right->token.type != TOKEN_STRING &&
current->right->token.type != TOKEN_RE)) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
"Invalid expression \"%s\" in file %s",
expr, r->filename);
*was_error = 1;
return 0;
}
current->left->token.value =
ap_ssi_parse_string(ctx, current->left->token.value, NULL, 0,
SSI_EXPAND_DROP_NAME);
current->right->token.value =
ap_ssi_parse_string(ctx, current->right->token.value, NULL, 0,
SSI_EXPAND_DROP_NAME);
if (current->right->token.type == TOKEN_RE) {
current->value = re_check(ctx, current->left->token.value,
current->right->token.value);
--regex;
}
else {
current->value = !strcmp(current->left->token.value,
current->right->token.value);
}
if (current->token.type == TOKEN_NE) {
current->value = !current->value;
}
break;
case TOKEN_GE:
case TOKEN_GT:
case TOKEN_LE:
case TOKEN_LT:
if (!current->left || !current->right ||
current->left->token.type != TOKEN_STRING ||
current->right->token.type != TOKEN_STRING) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
"Invalid expression \"%s\" in file %s",
expr, r->filename);
*was_error = 1;
return 0;
}
current->left->token.value =
ap_ssi_parse_string(ctx, current->left->token.value, NULL, 0,
SSI_EXPAND_DROP_NAME);
current->right->token.value =
ap_ssi_parse_string(ctx, current->right->token.value, NULL, 0,
SSI_EXPAND_DROP_NAME);
current->value = strcmp(current->left->token.value,
current->right->token.value);
switch (current->token.type) {
case TOKEN_GE: current->value = current->value >= 0; break;
case TOKEN_GT: current->value = current->value > 0; break;
case TOKEN_LE: current->value = current->value <= 0; break;
case TOKEN_LT: current->value = current->value < 0; break;
default: current->value = 0; break; /* should not happen */
}
break;
case TOKEN_NOT:
case TOKEN_GROUP:
if (current->right) {
if (!current->right->done) {
current = current->right;
continue;
}
current->value = current->right->value;
}
else {
current->value = 1;
}
if (current->token.type == TOKEN_NOT) {
current->value = !current->value;
}
break;
case TOKEN_ACCESS:
if (current->left || !current->right ||
(current->right->token.type != TOKEN_STRING &&
current->right->token.type != TOKEN_RE)) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
"Invalid expression \"%s\" in file %s: Token '-A' must be followed by a URI string.",
expr, r->filename);
*was_error = 1;
return 0;
}
current->right->token.value =
ap_ssi_parse_string(ctx, current->right->token.value, NULL, 0,
SSI_EXPAND_DROP_NAME);
rr = ap_sub_req_lookup_uri(current->right->token.value, r, NULL);
/* 400 and higher are considered access denied */
if (rr->status < HTTP_BAD_REQUEST) {
current->value = 1;
}
else {
current->value = 0;
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, rr->status, r,
"mod_include: The tested "
"subrequest -A \"%s\" returned an error code.",
current->right->token.value);
}
ap_destroy_sub_req(rr);
break;
case TOKEN_RE:
if (!error) {
error = "No operator before regex in expr \"%s\" in file %s";
}
case TOKEN_LBRACE:
if (!error) {
error = "Unmatched '(' in \"%s\" in file %s";
}
default:
if (!error) {
error = "internal parser error in \"%s\" in file %s";
}
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, error, expr,r->filename);
*was_error = 1;
return 0;
}
DEBUG_DUMP_EVAL(ctx, current);
current->done = 1;
current = current->parent;
}
return (root ? root->value : 0);
}
/*
* +-------------------------------------------------------+
* | |
* | Action Handlers
* | |
* +-------------------------------------------------------+
*/
/*
* Extract the next tag name and value.
* If there are no more tags, set the tag name to NULL.
* The tag value is html decoded if dodecode is non-zero.
* The tag value may be NULL if there is no tag value..
*/
static void ap_ssi_get_tag_and_value(include_ctx_t *ctx, char **tag,
char **tag_val, int dodecode)
{
if (!ctx->intern->argv) {
*tag = NULL;
*tag_val = NULL;
return;
}
*tag_val = ctx->intern->argv->value;
*tag = ctx->intern->argv->name;
ctx->intern->argv = ctx->intern->argv->next;
if (dodecode && *tag_val) {
decodehtml(*tag_val);
}
return;
}
static int find_file(request_rec *r, const char *directive, const char *tag,
char *tag_val, apr_finfo_t *finfo)
{
char *to_send = tag_val;
request_rec *rr = NULL;
int ret=0;
char *error_fmt = NULL;
apr_status_t rv = APR_SUCCESS;
if (!strcmp(tag, "file")) {
char *newpath;
/* be safe; only files in this directory or below allowed */
rv = apr_filepath_merge(&newpath, NULL, tag_val,
APR_FILEPATH_SECUREROOTTEST |
APR_FILEPATH_NOTABSOLUTE, r->pool);
if (rv != APR_SUCCESS) {
error_fmt = "unable to access file \"%s\" "
"in parsed file %s";
}
else {
/* note: it is okay to pass NULL for the "next filter" since
we never attempt to "run" this sub request. */
rr = ap_sub_req_lookup_file(newpath, r, NULL);
if (rr->status == HTTP_OK && rr->finfo.filetype != 0) {
to_send = rr->filename;
if ((rv = apr_stat(finfo, to_send,
APR_FINFO_GPROT | APR_FINFO_MIN, rr->pool)) != APR_SUCCESS
&& rv != APR_INCOMPLETE) {
error_fmt = "unable to get information about \"%s\" "
"in parsed file %s";
}
}
else {
error_fmt = "unable to lookup information about \"%s\" "
"in parsed file %s";
}
}
if (error_fmt) {
ret = -1;
ap_log_rerror(APLOG_MARK, APLOG_ERR,
rv, r, error_fmt, to_send, r->filename);
}
if (rr) ap_destroy_sub_req(rr);
return ret;
}
else if (!strcmp(tag, "virtual")) {
/* note: it is okay to pass NULL for the "next filter" since
we never attempt to "run" this sub request. */
rr = ap_sub_req_lookup_uri(tag_val, r, NULL);
if (rr->status == HTTP_OK && rr->finfo.filetype != 0) {
memcpy((char *) finfo, (const char *) &rr->finfo,
sizeof(rr->finfo));
ap_destroy_sub_req(rr);
return 0;
}
else {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unable to get "
"information about \"%s\" in parsed file %s",
tag_val, r->filename);
ap_destroy_sub_req(rr);
return -1;
}
}
else {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unknown parameter \"%s\" "
"to tag %s in %s", tag, directive, r->filename);
return -1;
}
}
/*
* <!--#include virtual|file="..." [virtual|file="..."] ... -->
*/
static apr_status_t handle_include(include_ctx_t *ctx, ap_filter_t *f,
apr_bucket_brigade *bb)
{
request_rec *r = f->r;
if (!ctx->argc) {
ap_log_rerror(APLOG_MARK,
(ctx->flags & SSI_FLAG_PRINTING)
? APLOG_ERR : APLOG_WARNING,
0, r, "missing argument for include element in %s",
r->filename);
}
if (!(ctx->flags & SSI_FLAG_PRINTING)) {
return APR_SUCCESS;
}
if (!ctx->argc) {
SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
return APR_SUCCESS;
}
while (1) {
char *tag = NULL;
char *tag_val = NULL;
request_rec *rr = NULL;
char *error_fmt = NULL;
char *parsed_string;
ap_ssi_get_tag_and_value(ctx, &tag, &tag_val, SSI_VALUE_DECODED);
if (!tag || !tag_val) {
break;
}
if (strcmp(tag, "virtual") && strcmp(tag, "file") && strcmp(tag, "memcached")) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unknown parameter "
"\"%s\" to tag include in %s", tag, r->filename);
SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
break;
}
parsed_string = ap_ssi_parse_string(ctx, tag_val, NULL, 0,
SSI_EXPAND_DROP_NAME);
/* Fetching files from Memcached */
if (tag[0] == 'm') {
- include_server_config *conf;
+
+ include_dir_config *conf;
+ memcached_include_server_t *svr;
+ apr_status_t rv;
+ int i;
+
apr_uint16_t flags;
char *strkey = NULL;
char *value;
apr_size_t value_len;
- apr_status_t rv;
strkey = ap_escape_uri(r->pool, parsed_string);
- conf = (include_server_config *)ap_get_module_config(r->server->module_config, &memcached_include_module);
+ conf = (include_dir_config *)ap_get_module_config(r->per_dir_config, &memcached_include_module);
+
+ rv = apr_memcache_create(r->pool, conf->max_servers, 0, &(conf->memcached));
+
+ if(rv != APR_SUCCESS) {
+ ap_log_rerror(APLOG_MARK, APLOG_DEBUG, rv, r, "Unable to create memcached structure");
+ }
+
+ svr = (memcached_include_server_t *)conf->servers->elts;
+
+ for(i = 0; i < conf->servers->nelts; i++) {
+
+ rv = apr_memcache_server_create(r->pool, svr[i].host, svr[i].port,
+ conf->conn_min, conf->conn_smax,
+ conf->conn_max, conf->conn_ttl,
+ &(svr[i].server));
+
+ if(rv != APR_SUCCESS) {
+ ap_log_rerror(APLOG_MARK, APLOG_DEBUG, rv, r, "Unable to create memcache server for %s:%d is Memcached running ?", svr[i].host, svr[i].port);
+ continue;
+ }
+
+ rv = apr_memcache_add_server(conf->memcached, svr[i].server);
+
+ if(rv != APR_SUCCESS) {
+ ap_log_rerror(APLOG_MARK, APLOG_DEBUG, rv, r, "Unable to add memcache server for %s:%d", svr[i].host, svr[i].port);
+ }
+
+#ifdef DEBUG_MEMCACHED_INCLUDE
+ ap_log_rerror(APLOG_MARK, APLOG_DEBUG, rv, r, "Memcached server successfully created %s:%d %d %d %d", svr[i].host, svr[i].port, conf->conn_smax, conf->conn_max, conf->conn_ttl);
+#endif
+ }
#ifdef DEBUG_MEMCACHED_INCLUDE
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Fetching the file with key : %s", strkey);
#endif
rv = apr_memcache_getp(conf->memcached, r->pool, strkey, &value, &value_len, &flags);
if( rv == APR_SUCCESS ) {
#ifdef DEBUG_MEMCACHED_INCLUDE
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, rv, r, "File found with key %s, value : %s", strkey, value);
#endif
APR_BRIGADE_INSERT_TAIL(bb,
apr_bucket_pool_create(apr_pmemdup(ctx->pool, value, value_len),
value_len,
ctx->pool,
f->c->bucket_alloc));
return APR_SUCCESS;
}
else {
error_fmt = "Unable to fetch file with key '%s' in parsed file %s";
}
}
else if (tag[0] == 'f') {
char *newpath;
apr_status_t rv;
/* be safe only files in this directory or below allowed */
rv = apr_filepath_merge(&newpath, NULL, parsed_string,
APR_FILEPATH_SECUREROOTTEST |
APR_FILEPATH_NOTABSOLUTE, ctx->dpool);
if (rv != APR_SUCCESS) {
error_fmt = "unable to include file \"%s\" in parsed file %s";
}
else {
rr = ap_sub_req_lookup_file(newpath, r, f->next);
}
}
else {
rr = ap_sub_req_lookup_uri(parsed_string, r, f->next);
}
if (!error_fmt && rr->status != HTTP_OK) {
error_fmt = "unable to include \"%s\" in parsed file %s";
}
if (!error_fmt && (ctx->flags & SSI_FLAG_NO_EXEC) &&
rr->content_type && strncmp(rr->content_type, "text/", 5)) {
error_fmt = "unable to include potential exec \"%s\" in parsed "
"file %s";
}
/* See the Kludge in includes_filter for why.
* Basically, it puts a bread crumb in here, then looks
* for the crumb later to see if its been here.
*/
if (rr) {
ap_set_module_config(rr->request_config, &memcached_include_module, r);
}
if (!error_fmt && ap_run_sub_req(rr)) {
error_fmt = "unable to include \"%s\" in parsed file %s";
}
if (error_fmt) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, error_fmt, tag_val,
r->filename);
SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
}
/* Do *not* destroy the subrequest here; it may have allocated
* variables in this r->subprocess_env in the subrequest's
* r->pool, so that pool must survive as long as this request.
* Yes, this is a memory leak. */
if (error_fmt) {
break;
}
}
return APR_SUCCESS;
}
/*
* <!--#echo [encoding="..."] var="..." [encoding="..."] var="..." ... -->
*/
static apr_status_t handle_echo(include_ctx_t *ctx, ap_filter_t *f,
apr_bucket_brigade *bb)
{
enum {E_NONE, E_URL, E_ENTITY} encode;
request_rec *r = f->r;
if (!ctx->argc) {
ap_log_rerror(APLOG_MARK,
(ctx->flags & SSI_FLAG_PRINTING)
? APLOG_ERR : APLOG_WARNING,
0, r, "missing argument for echo element in %s",
r->filename);
}
if (!(ctx->flags & SSI_FLAG_PRINTING)) {
return APR_SUCCESS;
}
if (!ctx->argc) {
SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
return APR_SUCCESS;
}
encode = E_ENTITY;
while (1) {
char *tag = NULL;
char *tag_val = NULL;
ap_ssi_get_tag_and_value(ctx, &tag, &tag_val, SSI_VALUE_DECODED);
if (!tag || !tag_val) {
break;
}
if (!strcmp(tag, "var")) {
const char *val;
const char *echo_text = NULL;
apr_size_t e_len;
val = get_include_var(ap_ssi_parse_string(ctx, tag_val, NULL,
0, SSI_EXPAND_DROP_NAME),
ctx);
if (val) {
switch(encode) {
case E_NONE:
echo_text = val;
break;
case E_URL:
echo_text = ap_escape_uri(ctx->dpool, val);
break;
case E_ENTITY:
echo_text = ap_escape_html(ctx->dpool, val);
break;
}
e_len = strlen(echo_text);
}
else {
echo_text = ctx->intern->undefined_echo;
e_len = ctx->intern->undefined_echo_len;
}
APR_BRIGADE_INSERT_TAIL(bb, apr_bucket_pool_create(
apr_pmemdup(ctx->pool, echo_text, e_len),
e_len, ctx->pool, f->c->bucket_alloc));
}
else if (!strcmp(tag, "encoding")) {
if (!strcasecmp(tag_val, "none")) {
encode = E_NONE;
}
else if (!strcasecmp(tag_val, "url")) {
encode = E_URL;
}
else if (!strcasecmp(tag_val, "entity")) {
encode = E_ENTITY;
}
else {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unknown value "
"\"%s\" to parameter \"encoding\" of tag echo in "
"%s", tag_val, r->filename);
SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
break;
}
}
else {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unknown parameter "
"\"%s\" in tag echo of %s", tag, r->filename);
SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
break;
}
}
return APR_SUCCESS;
}
/*
* <!--#config [timefmt="..."] [sizefmt="..."] [errmsg="..."]
* [echomsg="..."] -->
*/
static apr_status_t handle_config(include_ctx_t *ctx, ap_filter_t *f,
apr_bucket_brigade *bb)
{
request_rec *r = f->r;
apr_table_t *env = r->subprocess_env;
if (!ctx->argc) {
ap_log_rerror(APLOG_MARK,
(ctx->flags & SSI_FLAG_PRINTING)
? APLOG_ERR : APLOG_WARNING,
0, r, "missing argument for config element in %s",
r->filename);
}
if (!(ctx->flags & SSI_FLAG_PRINTING)) {
return APR_SUCCESS;
}
if (!ctx->argc) {
SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
return APR_SUCCESS;
}
while (1) {
char *tag = NULL;
char *tag_val = NULL;
ap_ssi_get_tag_and_value(ctx, &tag, &tag_val, SSI_VALUE_RAW);
if (!tag || !tag_val) {
break;
}
if (!strcmp(tag, "errmsg")) {
ctx->error_str = ap_ssi_parse_string(ctx, tag_val, NULL, 0,
SSI_EXPAND_DROP_NAME);
}
else if (!strcmp(tag, "echomsg")) {
ctx->intern->undefined_echo =
ap_ssi_parse_string(ctx, tag_val, NULL, 0,SSI_EXPAND_DROP_NAME);
ctx->intern->undefined_echo_len=strlen(ctx->intern->undefined_echo);
}
else if (!strcmp(tag, "timefmt")) {
apr_time_t date = r->request_time;
ctx->time_str = ap_ssi_parse_string(ctx, tag_val, NULL, 0,
SSI_EXPAND_DROP_NAME);
apr_table_setn(env, "DATE_LOCAL", ap_ht_time(r->pool, date,
ctx->time_str, 0));
apr_table_setn(env, "DATE_GMT", ap_ht_time(r->pool, date,
ctx->time_str, 1));
apr_table_setn(env, "LAST_MODIFIED",
ap_ht_time(r->pool, r->finfo.mtime,
ctx->time_str, 0));
}
else if (!strcmp(tag, "sizefmt")) {
char *parsed_string;
parsed_string = ap_ssi_parse_string(ctx, tag_val, NULL, 0,
SSI_EXPAND_DROP_NAME);
if (!strcmp(parsed_string, "bytes")) {
ctx->flags |= SSI_FLAG_SIZE_IN_BYTES;
}
else if (!strcmp(parsed_string, "abbrev")) {
ctx->flags &= SSI_FLAG_SIZE_ABBREV;
}
else {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unknown value "
"\"%s\" to parameter \"sizefmt\" of tag config "
"in %s", parsed_string, r->filename);
SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
break;
}
}
else {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unknown parameter "
"\"%s\" to tag config in %s", tag, r->filename);
SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
break;
}
}
return APR_SUCCESS;
}
/*
* <!--#fsize virtual|file="..." [virtual|file="..."] ... -->
*/
static apr_status_t handle_fsize(include_ctx_t *ctx, ap_filter_t *f,
apr_bucket_brigade *bb)
{
request_rec *r = f->r;
if (!ctx->argc) {
ap_log_rerror(APLOG_MARK,
(ctx->flags & SSI_FLAG_PRINTING)
? APLOG_ERR : APLOG_WARNING,
0, r, "missing argument for fsize element in %s",
r->filename);
}
if (!(ctx->flags & SSI_FLAG_PRINTING)) {
return APR_SUCCESS;
}
if (!ctx->argc) {
SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
return APR_SUCCESS;
}
while (1) {
char *tag = NULL;
char *tag_val = NULL;
apr_finfo_t finfo;
char *parsed_string;
ap_ssi_get_tag_and_value(ctx, &tag, &tag_val, SSI_VALUE_DECODED);
if (!tag || !tag_val) {
break;
}
parsed_string = ap_ssi_parse_string(ctx, tag_val, NULL, 0,
SSI_EXPAND_DROP_NAME);
if (!find_file(r, "fsize", tag, parsed_string, &finfo)) {
char *buf;
apr_size_t len;
if (!(ctx->flags & SSI_FLAG_SIZE_IN_BYTES)) {
buf = apr_strfsize(finfo.size, apr_palloc(ctx->pool, 5));
len = 4; /* omit the \0 terminator */
}
else {
apr_size_t l, x, pos;
char *tmp;
tmp = apr_psprintf(ctx->dpool, "%" APR_OFF_T_FMT, finfo.size);
len = l = strlen(tmp);
for (x = 0; x < l; ++x) {
if (x && !((l - x) % 3)) {
++len;
}
}
if (len == l) {
buf = apr_pstrmemdup(ctx->pool, tmp, len);
}
else {
buf = apr_palloc(ctx->pool, len);
for (pos = x = 0; x < l; ++x) {
if (x && !((l - x) % 3)) {
buf[pos++] = ',';
}
buf[pos++] = tmp[x];
}
}
}
APR_BRIGADE_INSERT_TAIL(bb, apr_bucket_pool_create(buf, len,
ctx->pool, f->c->bucket_alloc));
}
else {
SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
break;
}
}
return APR_SUCCESS;
}
/*
* <!--#flastmod virtual|file="..." [virtual|file="..."] ... -->
*/
static apr_status_t handle_flastmod(include_ctx_t *ctx, ap_filter_t *f,
apr_bucket_brigade *bb)
{
request_rec *r = f->r;
if (!ctx->argc) {
ap_log_rerror(APLOG_MARK,
(ctx->flags & SSI_FLAG_PRINTING)
? APLOG_ERR : APLOG_WARNING,
0, r, "missing argument for flastmod element in %s",
r->filename);
}
if (!(ctx->flags & SSI_FLAG_PRINTING)) {
return APR_SUCCESS;
}
if (!ctx->argc) {
SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
return APR_SUCCESS;
}
while (1) {
char *tag = NULL;
char *tag_val = NULL;
apr_finfo_t finfo;
char *parsed_string;
ap_ssi_get_tag_and_value(ctx, &tag, &tag_val, SSI_VALUE_DECODED);
if (!tag || !tag_val) {
break;
}
parsed_string = ap_ssi_parse_string(ctx, tag_val, NULL, 0,
SSI_EXPAND_DROP_NAME);
if (!find_file(r, "flastmod", tag, parsed_string, &finfo)) {
char *t_val;
apr_size_t t_len;
t_val = ap_ht_time(ctx->pool, finfo.mtime, ctx->time_str, 0);
t_len = strlen(t_val);
APR_BRIGADE_INSERT_TAIL(bb, apr_bucket_pool_create(t_val, t_len,
ctx->pool, f->c->bucket_alloc));
}
else {
SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
break;
}
}
return APR_SUCCESS;
}
/*
* <!--#if expr="..." -->
*/
static apr_status_t handle_if(include_ctx_t *ctx, ap_filter_t *f,
apr_bucket_brigade *bb)
{
char *tag = NULL;
char *expr = NULL;
request_rec *r = f->r;
int expr_ret, was_error;
if (ctx->argc != 1) {
ap_log_rerror(APLOG_MARK,
(ctx->flags & SSI_FLAG_PRINTING)
? APLOG_ERR : APLOG_WARNING,
0, r, (ctx->argc)
? "too many arguments for if element in %s"
: "missing expr argument for if element in %s",
r->filename);
}
if (!(ctx->flags & SSI_FLAG_PRINTING)) {
++(ctx->if_nesting_level);
return APR_SUCCESS;
}
if (ctx->argc != 1) {
SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
return APR_SUCCESS;
}
ap_ssi_get_tag_and_value(ctx, &tag, &expr, SSI_VALUE_RAW);
if (strcmp(tag, "expr")) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unknown parameter \"%s\" "
"to tag if in %s", tag, r->filename);
SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
return APR_SUCCESS;
}
if (!expr) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "missing expr value for if "
"element in %s", r->filename);
SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
return APR_SUCCESS;
}
DEBUG_PRINTF((ctx, "**** if expr=\"%s\"\n", expr));
expr_ret = parse_expr(ctx, expr, &was_error);
if (was_error) {
SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
return APR_SUCCESS;
}
if (expr_ret) {
ctx->flags |= (SSI_FLAG_PRINTING | SSI_FLAG_COND_TRUE);
}
else {
ctx->flags &= SSI_FLAG_CLEAR_PRINT_COND;
}
DEBUG_DUMP_COND(ctx, " if");
ctx->if_nesting_level = 0;
return APR_SUCCESS;
}
/*
* <!--#elif expr="..." -->
*/
static apr_status_t handle_elif(include_ctx_t *ctx, ap_filter_t *f,
apr_bucket_brigade *bb)
{
char *tag = NULL;
char *expr = NULL;
request_rec *r = f->r;
int expr_ret, was_error;
if (ctx->argc != 1) {
ap_log_rerror(APLOG_MARK,
(!(ctx->if_nesting_level)) ? APLOG_ERR : APLOG_WARNING,
0, r, (ctx->argc)
? "too many arguments for if element in %s"
: "missing expr argument for if element in %s",
r->filename);
}
if (ctx->if_nesting_level) {
return APR_SUCCESS;
}
if (ctx->argc != 1) {
SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
@@ -3241,831 +3276,791 @@ static apr_status_t send_parsed_content(ap_filter_t *f, apr_bucket_brigade *bb)
b = newb;
continue;
}
}
/* enough is enough ... */
if (ctx->flush_now ||
intern->bytes_read > AP_MIN_BYTES_TO_WRITE) {
if (!APR_BRIGADE_EMPTY(pass_bb)) {
rv = ap_pass_brigade(f->next, pass_bb);
if (rv != APR_SUCCESS) {
apr_brigade_destroy(pass_bb);
return rv;
}
}
ctx->flush_now = 0;
intern->bytes_read = 0;
}
/* read the current bucket data */
len = 0;
if (!intern->seen_eos) {
if (intern->bytes_read > 0) {
rv = apr_bucket_read(b, &data, &len, APR_NONBLOCK_READ);
if (APR_STATUS_IS_EAGAIN(rv)) {
ctx->flush_now = 1;
continue;
}
}
if (!len || rv != APR_SUCCESS) {
rv = apr_bucket_read(b, &data, &len, APR_BLOCK_READ);
}
if (rv != APR_SUCCESS) {
apr_brigade_destroy(pass_bb);
return rv;
}
intern->bytes_read += len;
}
/* zero length bucket, fetch next one */
if (!len && !intern->seen_eos) {
b = APR_BUCKET_NEXT(b);
continue;
}
/*
* it's actually a data containing bucket, start/continue parsing
*/
switch (intern->state) {
/* no current tag; search for start sequence */
case PARSE_PRE_HEAD:
index = find_start_sequence(ctx, data, len);
if (index < len) {
apr_bucket_split(b, index);
}
newb = APR_BUCKET_NEXT(b);
if (ctx->flags & SSI_FLAG_PRINTING) {
APR_BUCKET_REMOVE(b);
APR_BRIGADE_INSERT_TAIL(pass_bb, b);
}
else {
apr_bucket_delete(b);
}
if (index < len) {
/* now delete the start_seq stuff from the remaining bucket */
if (PARSE_DIRECTIVE == intern->state) { /* full match */
apr_bucket_split(newb, intern->start_seq_pat->pattern_len);
ctx->flush_now = 1; /* pass pre-tag stuff */
}
b = APR_BUCKET_NEXT(newb);
apr_bucket_delete(newb);
}
else {
b = newb;
}
break;
/* we're currently looking for the end of the start sequence */
case PARSE_HEAD:
index = find_partial_start_sequence(ctx, data, len, &release);
/* check if we mismatched earlier and have to release some chars */
if (release && (ctx->flags & SSI_FLAG_PRINTING)) {
char *to_release = apr_pmemdup(ctx->pool, intern->start_seq, release);
newb = apr_bucket_pool_create(to_release, release, ctx->pool,
f->c->bucket_alloc);
APR_BRIGADE_INSERT_TAIL(pass_bb, newb);
}
if (index) { /* any match */
/* now delete the start_seq stuff from the remaining bucket */
if (PARSE_DIRECTIVE == intern->state) { /* final match */
apr_bucket_split(b, index);
ctx->flush_now = 1; /* pass pre-tag stuff */
}
newb = APR_BUCKET_NEXT(b);
apr_bucket_delete(b);
b = newb;
}
break;
/* we're currently grabbing the directive name */
case PARSE_DIRECTIVE:
case PARSE_DIRECTIVE_POSTNAME:
case PARSE_DIRECTIVE_TAIL:
case PARSE_DIRECTIVE_POSTTAIL:
index = find_directive(ctx, data, len, &store, &store_len);
if (index) {
apr_bucket_split(b, index);
newb = APR_BUCKET_NEXT(b);
}
if (store) {
if (index) {
APR_BUCKET_REMOVE(b);
apr_bucket_setaside(b, r->pool);
APR_BRIGADE_INSERT_TAIL(intern->tmp_bb, b);
b = newb;
}
/* time for cleanup? */
if (store != &magic) {
apr_brigade_pflatten(intern->tmp_bb, store, store_len,
ctx->dpool);
apr_brigade_cleanup(intern->tmp_bb);
}
}
else if (index) {
apr_bucket_delete(b);
b = newb;
}
break;
/* skip WS and find out what comes next (arg or end_seq) */
case PARSE_PRE_ARG:
index = find_arg_or_tail(ctx, data, len);
if (index) { /* skipped whitespaces */
if (index < len) {
apr_bucket_split(b, index);
}
newb = APR_BUCKET_NEXT(b);
apr_bucket_delete(b);
b = newb;
}
break;
/* currently parsing name[=val] */
case PARSE_ARG:
case PARSE_ARG_NAME:
case PARSE_ARG_POSTNAME:
case PARSE_ARG_EQ:
case PARSE_ARG_PREVAL:
case PARSE_ARG_VAL:
case PARSE_ARG_VAL_ESC:
case PARSE_ARG_POSTVAL:
index = find_argument(ctx, data, len, &store, &store_len);
if (index) {
apr_bucket_split(b, index);
newb = APR_BUCKET_NEXT(b);
}
if (store) {
if (index) {
APR_BUCKET_REMOVE(b);
apr_bucket_setaside(b, r->pool);
APR_BRIGADE_INSERT_TAIL(intern->tmp_bb, b);
b = newb;
}
/* time for cleanup? */
if (store != &magic) {
apr_brigade_pflatten(intern->tmp_bb, store, store_len,
ctx->dpool);
apr_brigade_cleanup(intern->tmp_bb);
}
}
else if (index) {
apr_bucket_delete(b);
b = newb;
}
break;
/* try to match end_seq at current pos. */
case PARSE_TAIL:
case PARSE_TAIL_SEQ:
index = find_tail(ctx, data, len);
switch (intern->state) {
case PARSE_EXECUTE: /* full match */
apr_bucket_split(b, index);
newb = APR_BUCKET_NEXT(b);
apr_bucket_delete(b);
b = newb;
break;
case PARSE_ARG: /* no match */
/* PARSE_ARG must reparse at the beginning */
APR_BRIGADE_PREPEND(bb, intern->tmp_bb);
b = APR_BRIGADE_FIRST(bb);
break;
default: /* partial match */
newb = APR_BUCKET_NEXT(b);
APR_BUCKET_REMOVE(b);
apr_bucket_setaside(b, r->pool);
APR_BRIGADE_INSERT_TAIL(intern->tmp_bb, b);
b = newb;
break;
}
break;
/* now execute the parsed directive, cleanup the space and
* start again with PARSE_PRE_HEAD
*/
case PARSE_EXECUTE:
/* if there was an error, it was already logged; just stop here */
if (intern->error) {
if (ctx->flags & SSI_FLAG_PRINTING) {
SSI_CREATE_ERROR_BUCKET(ctx, f, pass_bb);
intern->error = 0;
}
}
else {
include_handler_fn_t *handle_func;
handle_func =
(include_handler_fn_t *)apr_hash_get(include_handlers, intern->directive,
intern->directive_len);
if (handle_func) {
DEBUG_INIT(ctx, f, pass_bb);
rv = handle_func(ctx, f, pass_bb);
if (rv != APR_SUCCESS) {
apr_brigade_destroy(pass_bb);
return rv;
}
}
else {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
"unknown directive \"%s\" in parsed doc %s",
apr_pstrmemdup(r->pool, intern->directive,
intern->directive_len),
r->filename);
if (ctx->flags & SSI_FLAG_PRINTING) {
SSI_CREATE_ERROR_BUCKET(ctx, f, pass_bb);
}
}
}
/* cleanup */
apr_pool_clear(ctx->dpool);
apr_brigade_cleanup(intern->tmp_bb);
/* Oooof. Done here, start next round */
intern->state = PARSE_PRE_HEAD;
break;
} /* switch(ctx->state) */
} /* while(brigade) */
/* End of stream. Final cleanup */
if (intern->seen_eos) {
if (PARSE_HEAD == intern->state) {
if (ctx->flags & SSI_FLAG_PRINTING) {
char *to_release = apr_pmemdup(ctx->pool, intern->start_seq,
intern->parse_pos);
APR_BRIGADE_INSERT_TAIL(pass_bb,
apr_bucket_pool_create(to_release,
intern->parse_pos, ctx->pool,
f->c->bucket_alloc));
}
}
else if (PARSE_PRE_HEAD != intern->state) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
"SSI directive was not properly finished at the end "
"of parsed document %s", r->filename);
if (ctx->flags & SSI_FLAG_PRINTING) {
SSI_CREATE_ERROR_BUCKET(ctx, f, pass_bb);
}
}
if (!(ctx->flags & SSI_FLAG_PRINTING)) {
ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
"missing closing endif directive in parsed document"
" %s", r->filename);
}
/* cleanup our temporary memory */
apr_brigade_destroy(intern->tmp_bb);
apr_pool_destroy(ctx->dpool);
/* don't forget to finally insert the EOS bucket */
APR_BRIGADE_INSERT_TAIL(pass_bb, b);
}
/* if something's left over, pass it along */
if (!APR_BRIGADE_EMPTY(pass_bb)) {
rv = ap_pass_brigade(f->next, pass_bb);
}
else {
rv = APR_SUCCESS;
apr_brigade_destroy(pass_bb);
}
return rv;
}
/*
* +-------------------------------------------------------+
* | |
* | Runtime Hooks
* | |
* +-------------------------------------------------------+
*/
static int includes_setup(ap_filter_t *f)
{
include_dir_config *conf = ap_get_module_config(f->r->per_dir_config,
&memcached_include_module);
/* When our xbithack value isn't set to full or our platform isn't
* providing group-level protection bits or our group-level bits do not
* have group-execite on, we will set the no_local_copy value to 1 so
* that we will not send 304s.
*/
if ((conf->xbithack != XBITHACK_FULL)
|| !(f->r->finfo.valid & APR_FINFO_GPROT)
|| !(f->r->finfo.protection & APR_GEXECUTE)) {
f->r->no_local_copy = 1;
}
/* Don't allow ETag headers to be generated - see RFC2616 - 13.3.4.
* We don't know if we are going to be including a file or executing
* a program - in either case a strong ETag header will likely be invalid.
*/
apr_table_setn(f->r->notes, "no-etag", "");
return OK;
}
static apr_status_t includes_filter(ap_filter_t *f, apr_bucket_brigade *b)
{
request_rec *r = f->r;
include_ctx_t *ctx = f->ctx;
request_rec *parent;
include_dir_config *conf = ap_get_module_config(r->per_dir_config,
&memcached_include_module);
include_server_config *sconf= ap_get_module_config(r->server->module_config,
&memcached_include_module);
if (!(ap_allow_options(r) & OPT_INCLUDES)) {
ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
"mod_include: Options +Includes (or IncludesNoExec) "
"wasn't set, INCLUDES filter removed");
ap_remove_output_filter(f);
return ap_pass_brigade(f->next, b);
}
if (!f->ctx) {
struct ssi_internal_ctx *intern;
/* create context for this filter */
f->ctx = ctx = apr_palloc(r->pool, sizeof(*ctx));
ctx->intern = intern = apr_palloc(r->pool, sizeof(*ctx->intern));
ctx->pool = r->pool;
apr_pool_create(&ctx->dpool, ctx->pool);
/* runtime data */
intern->tmp_bb = apr_brigade_create(ctx->pool, f->c->bucket_alloc);
intern->seen_eos = 0;
intern->state = PARSE_PRE_HEAD;
ctx->flags = (SSI_FLAG_PRINTING | SSI_FLAG_COND_TRUE);
if (ap_allow_options(r) & OPT_INCNOEXEC) {
ctx->flags |= SSI_FLAG_NO_EXEC;
}
intern->accessenable = conf->accessenable;
ctx->if_nesting_level = 0;
intern->re = NULL;
ctx->error_str = conf->default_error_msg;
ctx->time_str = conf->default_time_fmt;
intern->start_seq = sconf->default_start_tag;
intern->start_seq_pat = bndm_compile(ctx->pool, intern->start_seq,
strlen(intern->start_seq));
intern->end_seq = sconf->default_end_tag;
intern->end_seq_len = strlen(intern->end_seq);
intern->undefined_echo = conf->undefined_echo;
intern->undefined_echo_len = strlen(conf->undefined_echo);
}
if ((parent = ap_get_module_config(r->request_config, &memcached_include_module))) {
/* Kludge --- for nested includes, we want to keep the subprocess
* environment of the base document (for compatibility); that means
* torquing our own last_modified date as well so that the
* LAST_MODIFIED variable gets reset to the proper value if the
* nested document resets <!--#config timefmt -->.
*/
r->subprocess_env = r->main->subprocess_env;
apr_pool_join(r->main->pool, r->pool);
r->finfo.mtime = r->main->finfo.mtime;
}
else {
/* we're not a nested include, so we create an initial
* environment */
ap_add_common_vars(r);
ap_add_cgi_vars(r);
add_include_vars(r, conf->default_time_fmt);
}
/* Always unset the content-length. There is no way to know if
* the content will be modified at some point by send_parsed_content.
* It is very possible for us to not find any content in the first
* 9k of the file, but still have to modify the content of the file.
* If we are going to pass the file through send_parsed_content, then
* the content-length should just be unset.
*/
apr_table_unset(f->r->headers_out, "Content-Length");
/* Always unset the Last-Modified field - see RFC2616 - 13.3.4.
* We don't know if we are going to be including a file or executing
* a program which may change the Last-Modified header or make the
* content completely dynamic. Therefore, we can't support these
* headers.
* Exception: XBitHack full means we *should* set the Last-Modified field.
*/
/* Assure the platform supports Group protections */
if ((conf->xbithack == XBITHACK_FULL)
&& (r->finfo.valid & APR_FINFO_GPROT)
&& (r->finfo.protection & APR_GEXECUTE)) {
ap_update_mtime(r, r->finfo.mtime);
ap_set_last_modified(r);
}
else {
apr_table_unset(f->r->headers_out, "Last-Modified");
}
/* add QUERY stuff to env cause it ain't yet */
if (r->args) {
char *arg_copy = apr_pstrdup(r->pool, r->args);
apr_table_setn(r->subprocess_env, "QUERY_STRING", r->args);
ap_unescape_url(arg_copy);
apr_table_setn(r->subprocess_env, "QUERY_STRING_UNESCAPED",
ap_escape_shell_cmd(r->pool, arg_copy));
}
return send_parsed_content(f, b);
}
static int include_fixup(request_rec *r)
{
include_dir_config *conf;
conf = ap_get_module_config(r->per_dir_config, &memcached_include_module);
if (r->handler && (strcmp(r->handler, "server-parsed") == 0))
{
if (!r->content_type || !*r->content_type) {
ap_set_content_type(r, "text/html");
}
r->handler = "default-handler";
}
else
#if defined(OS2) || defined(WIN32) || defined(NETWARE)
/* These OS's don't support xbithack. This is being worked on. */
{
return DECLINED;
}
#else
{
if (conf->xbithack == XBITHACK_OFF) {
return DECLINED;
}
if (!(r->finfo.protection & APR_UEXECUTE)) {
return DECLINED;
}
if (!r->content_type || strcmp(r->content_type, "text/html")) {
return DECLINED;
}
}
#endif
/* We always return declined, because the default handler actually
* serves the file. All we have to do is add the filter.
*/
- ap_add_output_filter("INCLUDES", NULL, r, r->connection);
+ ap_add_output_filter("INCLUDES", NULL, r, r->connection);
return DECLINED;
}
/*
* +-------------------------------------------------------+
* | |
* | Configuration Handling
* | |
* +-------------------------------------------------------+
*/
static void *create_includes_dir_config(apr_pool_t *p, char *dummy)
{
include_dir_config *result = apr_palloc(p, sizeof(include_dir_config));
result->default_error_msg = DEFAULT_ERROR_MSG;
result->default_time_fmt = DEFAULT_TIME_FORMAT;
result->undefined_echo = DEFAULT_UNDEFINED_ECHO;
result->xbithack = DEFAULT_XBITHACK;
- return result;
-}
-
-static void *create_includes_server_config(apr_pool_t *p, server_rec *server)
-{
- include_server_config *result;
-
- result = apr_palloc(p, sizeof(include_server_config));
- result->default_end_tag = DEFAULT_END_SEQUENCE;
- result->default_start_tag = DEFAULT_START_SEQUENCE;
-
result->servers = apr_array_make(p, 1, sizeof(memcached_include_server_t));
result->max_servers = DEFAULT_MAX_SERVERS;
result->min_size = DEFAULT_MIN_SIZE;
result->max_size = DEFAULT_MAX_SIZE;
result->conn_min = DEFAULT_MIN_CONN;
result->conn_smax = DEFAULT_SMAX;
result->conn_max = DEFAULT_MAX;
result->conn_ttl = DEFAULT_TTL;
return result;
}
+static void *create_includes_server_config(apr_pool_t *p, server_rec *server)
+{
+ include_server_config *result;
+
+ result = apr_palloc(p, sizeof(include_server_config));
+ result->default_end_tag = DEFAULT_END_SEQUENCE;
+ result->default_start_tag = DEFAULT_START_SEQUENCE;
+
+ return result;
+}
+
static const char *set_memcached_host(cmd_parms *cmd, void *mconfig, const char *arg)
{
char *host, *port;
memcached_include_server_t *memcached_server = NULL;
- include_server_config *conf = ap_get_module_config(cmd->server->module_config, &memcached_include_module);
+ include_dir_config *conf = mconfig;
/*
* I should consider using apr_parse_addr_port instead
* [http://apr.apache.org/docs/apr/1.3/group__apr__network__io.html#g90c31b2f012c6b1e2d842a96c4431de3]
*/
host = apr_pstrdup(cmd->pool, arg);
port = strchr(host, ':');
if(port) {
*(port++) = '\0';
}
if(!*host || host == NULL || !*port || port == NULL) {
return "MemcachedCacheServer should be in the correct format : host:port";
}
memcached_server = apr_array_push(conf->servers);
memcached_server->host = host;
memcached_server->port = apr_atoi64(port);
- /* ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, cmd->server, "Arg : %s Host : %s, Port : %d", arg, memcached_server->host, memcached_server->port); */
-
return NULL;
}
static const char *set_memcached_timeout(cmd_parms *cmd, void *mconfig, const char *arg)
{
- include_server_config *conf = ap_get_module_config(cmd->server->module_config, &memcached_include_module);
+ include_dir_config *conf = mconfig;
conf->conn_ttl = atoi(arg);
return NULL;
}
static const char *set_memcached_soft_max_conn(cmd_parms *cmd, void *mconfig, const char *arg)
{
- include_server_config *conf = ap_get_module_config(cmd->server->module_config, &memcached_include_module);
+ include_dir_config *conf = mconfig;
conf->conn_smax = atoi(arg);
return NULL;
}
static const char *set_memcached_hard_max_conn(cmd_parms *cmd, void *mconfig, const char *arg)
{
- include_server_config *conf = ap_get_module_config(cmd->server->module_config, &memcached_include_module);
+ include_dir_config *conf = mconfig;
conf->conn_max = atoi(arg);
return NULL;
}
static const char *set_xbithack(cmd_parms *cmd, void *mconfig, const char *arg)
{
include_dir_config *conf = mconfig;
if (!strcasecmp(arg, "off")) {
conf->xbithack = XBITHACK_OFF;
}
else if (!strcasecmp(arg, "on")) {
conf->xbithack = XBITHACK_ON;
}
else if (!strcasecmp(arg, "full")) {
conf->xbithack = XBITHACK_FULL;
}
else {
return "XBitHack must be set to Off, On, or Full";
}
return NULL;
}
static const char *set_default_start_tag(cmd_parms *cmd, void *mconfig,
const char *tag)
{
include_server_config *conf;
const char *p = tag;
/* be consistent. (See below in set_default_end_tag) */
while (*p) {
if (apr_isspace(*p)) {
return "SSIStartTag may not contain any whitespaces";
}
++p;
}
conf= ap_get_module_config(cmd->server->module_config , &memcached_include_module);
conf->default_start_tag = tag;
return NULL;
}
static const char *set_default_end_tag(cmd_parms *cmd, void *mconfig,
const char *tag)
{
include_server_config *conf;
const char *p = tag;
/* sanity check. The parser may fail otherwise */
while (*p) {
if (apr_isspace(*p)) {
return "SSIEndTag may not contain any whitespaces";
}
++p;
}
conf= ap_get_module_config(cmd->server->module_config , &memcached_include_module);
conf->default_end_tag = tag;
return NULL;
}
static const char *set_undefined_echo(cmd_parms *cmd, void *mconfig,
const char *msg)
{
include_dir_config *conf = mconfig;
conf->undefined_echo = msg;
return NULL;
}
static const char *set_default_error_msg(cmd_parms *cmd, void *mconfig,
const char *msg)
{
include_dir_config *conf = mconfig;
conf->default_error_msg = msg;
return NULL;
}
static const char *set_default_time_fmt(cmd_parms *cmd, void *mconfig,
const char *fmt)
{
include_dir_config *conf = mconfig;
conf->default_time_fmt = fmt;
return NULL;
}
/*
* +-------------------------------------------------------+
* | |
* | Module Initialization and Configuration
* | |
* +-------------------------------------------------------+
*/
static int include_post_config(apr_pool_t *p, apr_pool_t *plog,
apr_pool_t *ptemp, server_rec *s)
{
include_handlers = apr_hash_make(p);
ssi_pfn_register = APR_RETRIEVE_OPTIONAL_FN(ap_register_memcached_include_handler);
if(ssi_pfn_register) {
ssi_pfn_register("if", handle_if);
ssi_pfn_register("set", handle_set);
ssi_pfn_register("else", handle_else);
ssi_pfn_register("elif", handle_elif);
ssi_pfn_register("echo", handle_echo);
ssi_pfn_register("endif", handle_endif);
ssi_pfn_register("fsize", handle_fsize);
ssi_pfn_register("config", handle_config);
ssi_pfn_register("include", handle_include);
ssi_pfn_register("flastmod", handle_flastmod);
ssi_pfn_register("printenv", handle_printenv);
}
- include_server_config *conf;
- memcached_include_server_t *svr;
- apr_status_t rv;
- int i;
-
- conf = (include_server_config *)ap_get_module_config(s->module_config, &memcached_include_module);
-
- rv = apr_memcache_create(p, conf->max_servers, 0, &(conf->memcached));
-
- if(rv != APR_SUCCESS) {
- ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, s, "Unable to create memcached structure");
- }
-
- svr = (memcached_include_server_t *)conf->servers->elts;
-
- for(i = 0; i < conf->servers->nelts; i++) {
-
- rv = apr_memcache_server_create(p, svr[i].host, svr[i].port,
- conf->conn_min, conf->conn_smax,
- conf->conn_max, conf->conn_ttl,
- &(svr[i].server));
- if(rv != APR_SUCCESS) {
- ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, s, "Unable to create memcache server for %s:%d is Memcached running ?", svr[i].host, svr[i].port);
- continue;
- }
-
- rv = apr_memcache_add_server(conf->memcached, svr[i].server);
-
- if(rv != APR_SUCCESS) {
- ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, s, "Unable to add memcache server for %s:%d", svr[i].host, svr[i].port);
- }
-
-#ifdef DEBUG_MEMCACHED_INCLUDE
- ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, s, "Memcached server successfully created %s:%d %d %d %d", svr[i].host, svr[i].port, conf->conn_smax, conf->conn_max, conf->conn_ttl);
-#endif
- }
-
return OK;
}
static const command_rec includes_cmds[] =
{
AP_INIT_TAKE1("MemcachedHost", set_memcached_host, NULL, OR_OPTIONS,
"Memcached hostname or IP address with portnumber, like this, 127.0.0.1:11211"),
AP_INIT_TAKE1("MemcachedTTL", set_memcached_timeout, NULL, OR_OPTIONS,
"Memcached timeout (in seconds)"),
AP_INIT_TAKE1("MemcachedSoftMaxConn", set_memcached_soft_max_conn, NULL, OR_OPTIONS,
"Memcached low max connexions"),
AP_INIT_TAKE1("MemcachedHardMaxConn", set_memcached_hard_max_conn, NULL, OR_OPTIONS,
"Memcached high maximum connexions"),
AP_INIT_TAKE1("XBitHack", set_xbithack, NULL, OR_OPTIONS,
"Off, On, or Full"),
AP_INIT_TAKE1("SSIErrorMsg", set_default_error_msg, NULL, OR_ALL,
"a string"),
AP_INIT_TAKE1("SSITimeFormat", set_default_time_fmt, NULL, OR_ALL,
"a strftime(3) formatted string"),
AP_INIT_TAKE1("SSIStartTag", set_default_start_tag, NULL, RSRC_CONF,
"SSI Start String Tag"),
AP_INIT_TAKE1("SSIEndTag", set_default_end_tag, NULL, RSRC_CONF,
"SSI End String Tag"),
AP_INIT_TAKE1("SSIUndefinedEcho", set_undefined_echo, NULL, OR_ALL,
"String to be displayed if an echoed variable is undefined"),
AP_INIT_FLAG("SSIAccessEnable", ap_set_flag_slot,
(void *)APR_OFFSETOF(include_dir_config, accessenable),
OR_LIMIT, "Whether testing access is enabled. Limited to 'on' or 'off'"),
{NULL}
};
static void ap_register_memcached_include_handler(char *tag, include_handler_fn_t *func)
{
apr_hash_set(include_handlers, tag, strlen(tag), (const void *)func);
}
static void register_hooks(apr_pool_t *p)
{
APR_REGISTER_OPTIONAL_FN(ap_ssi_get_tag_and_value);
APR_REGISTER_OPTIONAL_FN(ap_ssi_parse_string);
APR_REGISTER_OPTIONAL_FN(ap_register_memcached_include_handler);
ap_hook_post_config(include_post_config, NULL, NULL, APR_HOOK_REALLY_FIRST);
ap_hook_fixups(include_fixup, NULL, NULL, APR_HOOK_LAST);
ap_register_output_filter("INCLUDES", includes_filter, includes_setup,
AP_FTYPE_RESOURCE);
- /* ap_hook_handler(memcached_include_handler, NULL, NULL, APR_HOOK_MIDDLE); */
}
module AP_MODULE_DECLARE_DATA memcached_include_module =
{
STANDARD20_MODULE_STUFF,
create_includes_dir_config, /* dir config creater */
NULL, /* dir merger --- default is to override */
create_includes_server_config,/* server config */
NULL, /* merge server config */
includes_cmds, /* command apr_table_t */
register_hooks /* register hooks */
-};
+};
\ No newline at end of file
|
jeromer/modmemcachedinclude
|
484a090ca6401789bad69dfffca85d892afde304
|
- Added more practical test files
|
diff --git a/tests/backendgen.php b/tests/backendgen.php
new file mode 100755
index 0000000..686fa87
--- /dev/null
+++ b/tests/backendgen.php
@@ -0,0 +1,33 @@
+<?php
+define( 'MEMCACHED_HOST', '127.0.0.1' );
+define( 'MEMCACHED_PORT', '11211' );
+define( 'MEMCACHED_TIMEOUT', '10' );
+
+if( !extension_loaded( 'memcache' ) )
+{
+ die( 'Extension not loaded' );
+}
+if( $cr = memcache_connect( MEMCACHED_HOST, MEMCACHED_PORT, MEMCACHED_TIMEOUT ) )
+{
+ $fileContents = 'SSI block added at ' . date( 'Y/m/d H:i:s', time( ) );
+ $flag = false;
+
+ $finalKey = md5( time( ) + rand( 0, 100 ) ) . '.html';
+ $fileFinalContents = file_get_contents( './lipsum.txt');
+
+ //the file does not exists
+ if( !memcache_replace( $cr, $finalKey, $fileFinalContents, $flag, 0 ) )
+ {
+ if( !memcache_add( $cr, $finalKey, $fileFinalContents, $flag, 0 ) )
+ {
+ print( 'Unable to add file' );
+ }
+ }
+
+ echo '<!--#include memcached="' . $finalKey . '" -->';
+}
+else
+{
+ print( 'unable to connect to memcached' );
+}
+?>
\ No newline at end of file
diff --git a/tests/lipsum.txt b/tests/lipsum.txt
new file mode 100644
index 0000000..8b9c686
--- /dev/null
+++ b/tests/lipsum.txt
@@ -0,0 +1,22 @@
+Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy
+nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
+
+Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit
+lobortis nisl ut aliquip ex ea commodo consequat.
+
+Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat,
+vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim
+qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.
+
+Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod
+mazim placerat facer possim assum.
+
+Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem.
+
+Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius.
+
+Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum.
+
+Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum
+formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis
+videntur parum clari, fiant sollemnes in futurum.
\ No newline at end of file
|
jeromer/modmemcachedinclude
|
9eadf1a0f002938899b12563e5a1d2fee034886a
|
- Added a quick builder
|
diff --git a/build.sh b/build.sh
new file mode 100755
index 0000000..805a5b3
--- /dev/null
+++ b/build.sh
@@ -0,0 +1,15 @@
+#! /bin/bash
+
+APR_MEMCACHE=/usr/local/apache-2.2.9
+APXS_PATH=/usr/local/apache-2.2.9/bin/apxs
+APACHECTL_PATH=/usr/local/apache-2.2.9/bin/apachectl
+
+# enable debug informations
+# export CFLAGS="-D DEBUG_MEMCACHED_INCLUDE"
+
+./autogen.sh && \
+make clean && \
+./configure --with-apr-memcache=$APR_MEMCACHE --with-apxs=$APXS_PATH && \
+make && \
+make install && \
+sudo $APACHECTL_PATH restart
\ No newline at end of file
|
jeromer/modmemcachedinclude
|
444a4abcfda4dce38c0ecfcddddf639442125227
|
- Added libtool for apt-get
|
diff --git a/INSTALL b/INSTALL
index 8835b11..73a2458 100644
--- a/INSTALL
+++ b/INSTALL
@@ -1,101 +1,101 @@
What is this extension made for ?
=================================
This module may be used with any file that is pushed
in Memcached and meant to be fetched from an SSI tag.
How to compile this extension ?
===============================
Run
::
./autogen.sh
./configure
make
sudo make install
Depending on your system and your apr_memcache installation path
you may need to specify the following arguments for the configure script:
--with-apxs=/path/to/apache/bin/apxs
--with-apr-memcache=/path/to/apr_memcache/
For example here is my configuration
::
./configure --with-apxs=/usr/local/apache-2.2.9/bin/apxs \
--with-apr-memcache=/opt/local
Where apr_memcache.h is located in :
::
/opt/local/include/apr_memcache-0/apr_memcache.h
Once everything is compiled, restart Apache
How to test this extension ?
============================
In order to test the extension you have to first compile
the module and install it, once you are done you have to
launch test/push.php to store some contents in Memcached.
You can configure your Memcached host by editing push.php
After that you may create the following configuration
for Apache :
::
LoadModule memcached_include_module modules/mod_memcached_include.so
<Directory /path/to/mod_memcached_include/tests/>
AddType text/html .shtml
AddOutputFilter INCLUDES .shtml
Options +Includes
MemcachedHost localhost:11211
MemcachedSoftMaxConn 10
MemcachedHardMaxConn 15
MemcachedTTL 10
</Directory>
You may also try this one
::
LoadModule memcached_include_module modules/mod_memcached_include.so
<Directory /path/to/mod_memcached_include/tests/>
AddType text/html .shtml
Options Indexes FollowSymLinks +Includes
FilterDeclare SSI
FilterProvider SSI INCLUDES resp=Content-Type $text/html
FilterChain SSI
MemcachedHost localhost:11211
MemcachedSoftMaxConn 10
MemcachedHardMaxConn 15
MemcachedTTL 10
</Directory>
Once the file is stored in Memcached, you can ``test/pull-*.shtml`` files.
Compiling on Debian
===================
In order to compile this module for Debian, you will need the following packages :
- apache2-mpm-prefork
- libapr1-dev
- libaprutil1-dev
- apach2-prefork-dev
::
- sudo apt-get install apache2-mpm-prefork libapr1-dev libaprutil1-dev apache2-prefork-dev
+ sudo apt-get install apache2-mpm-prefork libapr1-dev libaprutil1-dev apache2-prefork-dev libtool
..
Local Variables:
mode: rst
fill-column: 79
End:
- vim: et syn=rst tw=79
+ vim: et syn=rst tw=79
\ No newline at end of file
|
jeromer/modmemcachedinclude
|
08494cbea1de595eda166381e513d2da43236ecd
|
- Reduced image size
|
diff --git a/misc/modmemcachedinclude.png b/misc/modmemcachedinclude.png
index 930aa09..e581e0d 100644
Binary files a/misc/modmemcachedinclude.png and b/misc/modmemcachedinclude.png differ
|
jeromer/modmemcachedinclude
|
c343bd2d7778d88ed759fc5cacbb737184e12ddf
|
- Fixed bug #5
|
diff --git a/tests/push.php b/tests/push.php
index 99bf266..1cf8f1c 100755
--- a/tests/push.php
+++ b/tests/push.php
@@ -1,37 +1,37 @@
<?php
-define( MEMCACHED_HOST, '127.0.0.1' );
-define( MEMCACHED_PORT, '11211' );
-define( MEMCACHED_TIMEOUT, '10' );
+define( 'MEMCACHED_HOST', '127.0.0.1' );
+define( 'MEMCACHED_PORT', '11211' );
+define( 'MEMCACHED_TIMEOUT', '10' );
if( !extension_loaded( 'memcache' ) )
{
die( 'Extension not loaded' );
}
if( $cr = memcache_connect( MEMCACHED_HOST, MEMCACHED_PORT, MEMCACHED_TIMEOUT ) )
{
$key = 'mod_memcached_include_tests';
$fileContents = 'SSI block added at ' . date( 'Y/m/d H:i:s', time( ) );
$flag = false;
for( $i = 1; $i < 3; $i++)
{
$finalKey = $key . '_' . $i;
$fileFinalContents = $fileContents . '::' . $i;
print( 'Adding file : ' . $finalKey . ' with contents '. $fileFinalContents . chr( 10 ) );
//the file does not exists
if( !memcache_replace( $cr, $finalKey, $fileFinalContents, $flag, 0 ) )
{
if( !memcache_add( $cr, $finalKey, $fileFinalContents, $flag, 0 ) )
{
print( 'Unable to add file' );
}
}
}
}
else
{
print( 'unable to connect to memcached' );
}
-?>
+?>
\ No newline at end of file
|
jeromer/modmemcachedinclude
|
1be35e2aec2e5273d31f07c8541c14fe0713470e
|
- added modmemcachedinclude schema
|
diff --git a/misc/modmemcachedinclude.png b/misc/modmemcachedinclude.png
new file mode 100644
index 0000000..930aa09
Binary files /dev/null and b/misc/modmemcachedinclude.png differ
|
jeromer/modmemcachedinclude
|
bd34eb2549e5eacdd94ff474e39bfa7425f96a64
|
- updated FAQ file - created a patch for configure.ac
|
diff --git a/FAQ b/FAQ
index 8a282a6..f89b1e8 100644
--- a/FAQ
+++ b/FAQ
@@ -1,15 +1,45 @@
When compiling apr_memcache, I get the following error message : "unable to infer tagged configuration"
------------------------------------------------------------------------------------------------------
Open configure.ac and change the following line
-LIBTOOL="`${APR_CONFIG} --apr-libtool`"
+::
+
+ LIBTOOL="`${APR_CONFIG} --apr-libtool`"
By the following one :
-LIBTOOL="`${APR_CONFIG} --apr-libtool` --tag=CC"
+::
+
+ LIBTOOL="`${APR_CONFIG} --apr-libtool` --tag=CC"
-And then run 'autoconf'.
+And then run `autoconf`.
Run make clean and restart the configuration process
-Note: this advice applies for mod_memcached_include as well
+.. Note::
+If you do not feel comfortable in editing configure.ac
+or do not think it is safe you may also apply the configure.diff
+patch available in patches/configure.diff.
+In order to test if the patch is applicable you can run the following
+command
+
+::
+
+ patch --dry-run --verbose -p0 < patches/configure.diff
+
+If everything looks OK, then you can appy the patch
+
+::
+
+
+ patch --verbose -p0 < patches/configure.diff
+
+.. Note::
+This advice applies for mod_memcached_include as well
+
+..
+ Local Variables:
+ mode: rst
+ fill-column: 79
+ End:
+ vim: et syn=rst tw=79
diff --git a/patches/configure.diff b/patches/configure.diff
new file mode 100644
index 0000000..562e068
--- /dev/null
+++ b/patches/configure.diff
@@ -0,0 +1,13 @@
+Index: configure.ac
+===================================================================
+--- configure.ac (revision 20)
++++ configure.ac (working copy)
+@@ -26,7 +26,7 @@
+
+ prefix=${AP_PREFIX}
+
+-LIBTOOL="`${APR_CONFIG} --apr-libtool`"
++LIBTOOL="`${APR_CONFIG} --apr-libtool` --tag=CC"
+ AC_SUBST(LIBTOOL)
+
+ MODULE_CFLAGS="${APXS_CFLAGS} ${AP_INCLUDES} ${APR_INCLUDES} ${APU_INCLUDES} ${APR_MEMCACHE_CFLAGS}"
|
jeromer/modmemcachedinclude
|
88b666e9802b500eccc70c7239e00ac9124b8cec
|
- added Apache2 License terms
|
diff --git a/LICENSE b/LICENSE
index e69de29..189ed97 100644
--- a/LICENSE
+++ b/LICENSE
@@ -0,0 +1,14 @@
+Licensed to the Apache Software Foundation (ASF) under one or more
+contributor license agreements. See the NOTICE file distributed with
+this work for additional information regarding copyright ownership.
+The ASF licenses this file to You under the Apache License, Version 2.0
+(the "License"); you may not use this file except in compliance with
+the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
|
jeromer/modmemcachedinclude
|
5a44951f21368225f78b1ac0f8ce775d7045f37b
|
- fixed linking issues in configure.ac - updated documentation - update svn:ignore tag in order to ignore another cache file
|
diff --git a/INSTALL b/INSTALL
index 04e4c8f..8835b11 100644
--- a/INSTALL
+++ b/INSTALL
@@ -1,72 +1,101 @@
What is this extension made for ?
=================================
This module may be used with any file that is pushed
in Memcached and meant to be fetched from an SSI tag.
How to compile this extension ?
===============================
-You will have to install and compiler apr_memcache first.
-This module uses version 0.7.0 do not use older versions.
-apr_memcache may be downloaded here :
-
-- http://www.outoforder.cc/projects/libs/apr_memcache/
-- http://www.outoforder.cc/downloads/apr_memcache/apr_memcache-0.7.0.tar.bz2
-
-Once apr_memcache is downloaded, extract it and compile it.
-
-Note the path where it has been installed, you will need it.
-
Run
::
./autogen.sh
./configure
make
sudo make install
Depending on your system and your apr_memcache installation path
you may need to specify the following arguments for the configure script:
--with-apxs=/path/to/apache/bin/apxs
--with-apr-memcache=/path/to/apr_memcache/
For example here is my configuration
::
./configure --with-apxs=/usr/local/apache-2.2.9/bin/apxs \
- --with-apr-memcache=/opt/local/
+ --with-apr-memcache=/opt/local
+
+Where apr_memcache.h is located in :
+
+::
+
+ /opt/local/include/apr_memcache-0/apr_memcache.h
Once everything is compiled, restart Apache
How to test this extension ?
============================
In order to test the extension you have to first compile
the module and install it, once you are done you have to
launch test/push.php to store some contents in Memcached.
You can configure your Memcached host by editing push.php
After that you may create the following configuration
for Apache :
::
LoadModule memcached_include_module modules/mod_memcached_include.so
<Directory /path/to/mod_memcached_include/tests/>
AddType text/html .shtml
AddOutputFilter INCLUDES .shtml
Options +Includes
MemcachedHost localhost:11211
+ MemcachedSoftMaxConn 10
+ MemcachedHardMaxConn 15
+ MemcachedTTL 10
</Directory>
-Once the file is stored in Memcached, you can ``test/pull-*.shtml``
-files.
+You may also try this one
+
+::
+
+ LoadModule memcached_include_module modules/mod_memcached_include.so
+ <Directory /path/to/mod_memcached_include/tests/>
+ AddType text/html .shtml
+ Options Indexes FollowSymLinks +Includes
+ FilterDeclare SSI
+ FilterProvider SSI INCLUDES resp=Content-Type $text/html
+ FilterChain SSI
+ MemcachedHost localhost:11211
+ MemcachedSoftMaxConn 10
+ MemcachedHardMaxConn 15
+ MemcachedTTL 10
+ </Directory>
+
+Once the file is stored in Memcached, you can ``test/pull-*.shtml`` files.
+
+
+Compiling on Debian
+===================
+
+In order to compile this module for Debian, you will need the following packages :
+
+- apache2-mpm-prefork
+- libapr1-dev
+- libaprutil1-dev
+- apach2-prefork-dev
+
+::
+ sudo apt-get install apache2-mpm-prefork libapr1-dev libaprutil1-dev apache2-prefork-dev
+
..
Local Variables:
mode: rst
fill-column: 79
End:
vim: et syn=rst tw=79
diff --git a/configure.ac b/configure.ac
index 322df39..46ecaf5 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1,51 +1,43 @@
AC_INIT(mod_memcached_include, 1.0)
MAKE_CONFIG_NICE(config.nice)
AC_PREREQ(2.53)
AC_CONFIG_SRCDIR([src/mod_memcached_include.c])
AC_CONFIG_AUX_DIR(config)
AC_PROG_LIBTOOL
AM_MAINTAINER_MODE
AC_CANONICAL_TARGET
AM_INIT_AUTOMAKE(AC_PACKAGE_NAME, AC_PACKAGE_VERSION)
AM_CONFIG_HEADER([src/mod_memcached_include_config.h:config.in])
AC_PROG_CC
AC_PROG_CXX
AC_PROG_LD
AC_PROG_INSTALL
CHECK_APR_MEMCACHE()
AP_VERSION=2.2.9
CHECK_APACHE(,$AP_VERSION,
:,:,
AC_MSG_ERROR([*** Apache version $AP_VERSION not found!])
)
prefix=${AP_PREFIX}
LIBTOOL="`${APR_CONFIG} --apr-libtool`"
AC_SUBST(LIBTOOL)
-MODULE_CFLAGS="${APXS_CFLAGS} ${AP_INCLUDES} ${APR_INCLUDES} ${APU_INCLUDES}"
+MODULE_CFLAGS="${APXS_CFLAGS} ${AP_INCLUDES} ${APR_INCLUDES} ${APU_INCLUDES} ${APR_MEMCACHE_CFLAGS}"
AC_SUBST(MODULE_CFLAGS)
MODULE_LDFLAGS=" `${APR_CONFIG} --link-libtool` `${APU_CONFIG} --link-libtool`"
AC_SUBST(MODULE_LDFLAGS)
BIN_LDFLAGS=" `${APR_CONFIG} --link-libtool` `${APU_CONFIG} --link-libtool` `${APU_CONFIG} --ldflags --libs` `${APR_CONFIG} --ldflags --libs`"
AC_SUBST(BIN_LDFLAGS)
dnl this should be a list to all of the makefiles you expect to be generated
AC_CONFIG_FILES([Makefile src/Makefile])
AC_OUTPUT
-
-dnl whatever you want here, or nothing
-echo "---"
-echo "Configuration summary for mod_memcached_include"
-echo ""
-echo " * Apache Modules Directory: $AP_LIBEXECDIR"
-echo ""
-echo "---"
|
jeromer/modmemcachedinclude
|
c2a2368dd64e76cb47105d50585925c71b4c7a1f
|
-added basic TODO
|
diff --git a/TODO b/TODO
index e69de29..030dbc1 100644
--- a/TODO
+++ b/TODO
@@ -0,0 +1 @@
+- Writing compilation guide for Red Hat and non .deb based distributions
|
jeromer/modmemcachedinclude
|
b176d24955d395d2f284a513c44df50b7b557de3
|
-added ltmain.sh script
|
diff --git a/config/ltmain.sh b/config/ltmain.sh
new file mode 100644
index 0000000..4598ec6
--- /dev/null
+++ b/config/ltmain.sh
@@ -0,0 +1,6930 @@
+# ltmain.sh - Provide generalized library-building support services.
+# NOTE: Changing this file will not affect anything until you rerun configure.
+#
+# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006,
+# 2007 Free Software Foundation, Inc.
+# Originally by Gordon Matzigkeit <[email protected]>, 1996
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that program.
+
+basename="s,^.*/,,g"
+
+# Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh
+# is ksh but when the shell is invoked as "sh" and the current value of
+# the _XPG environment variable is not equal to 1 (one), the special
+# positional parameter $0, within a function call, is the name of the
+# function.
+progpath="$0"
+
+# The name of this program:
+progname=`echo "$progpath" | $SED $basename`
+modename="$progname"
+
+# Global variables:
+EXIT_SUCCESS=0
+EXIT_FAILURE=1
+
+PROGRAM=ltmain.sh
+PACKAGE=libtool
+VERSION=1.5.24
+TIMESTAMP=" (1.1220.2.455 2007/06/24 02:13:29)"
+
+# Be Bourne compatible (taken from Autoconf:_AS_BOURNE_COMPATIBLE).
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
+ emulate sh
+ NULLCMD=:
+ # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
+ # is contrary to our usage. Disable this feature.
+ alias -g '${1+"$@"}'='"$@"'
+ setopt NO_GLOB_SUBST
+else
+ case `(set -o) 2>/dev/null` in *posix*) set -o posix;; esac
+fi
+BIN_SH=xpg4; export BIN_SH # for Tru64
+DUALCASE=1; export DUALCASE # for MKS sh
+
+# Check that we have a working $echo.
+if test "X$1" = X--no-reexec; then
+ # Discard the --no-reexec flag, and continue.
+ shift
+elif test "X$1" = X--fallback-echo; then
+ # Avoid inline document here, it may be left over
+ :
+elif test "X`($echo '\t') 2>/dev/null`" = 'X\t'; then
+ # Yippee, $echo works!
+ :
+else
+ # Restart under the correct shell, and then maybe $echo will work.
+ exec $SHELL "$progpath" --no-reexec ${1+"$@"}
+fi
+
+if test "X$1" = X--fallback-echo; then
+ # used as fallback echo
+ shift
+ cat <<EOF
+$*
+EOF
+ exit $EXIT_SUCCESS
+fi
+
+default_mode=
+help="Try \`$progname --help' for more information."
+magic="%%%MAGIC variable%%%"
+mkdir="mkdir"
+mv="mv -f"
+rm="rm -f"
+
+# Sed substitution that helps us do robust quoting. It backslashifies
+# metacharacters that are still active within double-quoted strings.
+Xsed="${SED}"' -e 1s/^X//'
+sed_quote_subst='s/\([\\`\\"$\\\\]\)/\\\1/g'
+# test EBCDIC or ASCII
+case `echo X|tr X '\101'` in
+ A) # ASCII based system
+ # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr
+ SP2NL='tr \040 \012'
+ NL2SP='tr \015\012 \040\040'
+ ;;
+ *) # EBCDIC based system
+ SP2NL='tr \100 \n'
+ NL2SP='tr \r\n \100\100'
+ ;;
+esac
+
+# NLS nuisances.
+# Only set LANG and LC_ALL to C if already set.
+# These must not be set unconditionally because not all systems understand
+# e.g. LANG=C (notably SCO).
+# We save the old values to restore during execute mode.
+for lt_var in LANG LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES
+do
+ eval "if test \"\${$lt_var+set}\" = set; then
+ save_$lt_var=\$$lt_var
+ $lt_var=C
+ export $lt_var
+ fi"
+done
+
+# Make sure IFS has a sensible default
+lt_nl='
+'
+IFS=" $lt_nl"
+
+if test "$build_libtool_libs" != yes && test "$build_old_libs" != yes; then
+ $echo "$modename: not configured to build any kind of library" 1>&2
+ $echo "Fatal configuration error. See the $PACKAGE docs for more information." 1>&2
+ exit $EXIT_FAILURE
+fi
+
+# Global variables.
+mode=$default_mode
+nonopt=
+prev=
+prevopt=
+run=
+show="$echo"
+show_help=
+execute_dlfiles=
+duplicate_deps=no
+preserve_args=
+lo2o="s/\\.lo\$/.${objext}/"
+o2lo="s/\\.${objext}\$/.lo/"
+extracted_archives=
+extracted_serial=0
+
+#####################################
+# Shell function definitions:
+# This seems to be the best place for them
+
+# func_mktempdir [string]
+# Make a temporary directory that won't clash with other running
+# libtool processes, and avoids race conditions if possible. If
+# given, STRING is the basename for that directory.
+func_mktempdir ()
+{
+ my_template="${TMPDIR-/tmp}/${1-$progname}"
+
+ if test "$run" = ":"; then
+ # Return a directory name, but don't create it in dry-run mode
+ my_tmpdir="${my_template}-$$"
+ else
+
+ # If mktemp works, use that first and foremost
+ my_tmpdir=`mktemp -d "${my_template}-XXXXXXXX" 2>/dev/null`
+
+ if test ! -d "$my_tmpdir"; then
+ # Failing that, at least try and use $RANDOM to avoid a race
+ my_tmpdir="${my_template}-${RANDOM-0}$$"
+
+ save_mktempdir_umask=`umask`
+ umask 0077
+ $mkdir "$my_tmpdir"
+ umask $save_mktempdir_umask
+ fi
+
+ # If we're not in dry-run mode, bomb out on failure
+ test -d "$my_tmpdir" || {
+ $echo "cannot create temporary directory \`$my_tmpdir'" 1>&2
+ exit $EXIT_FAILURE
+ }
+ fi
+
+ $echo "X$my_tmpdir" | $Xsed
+}
+
+
+# func_win32_libid arg
+# return the library type of file 'arg'
+#
+# Need a lot of goo to handle *both* DLLs and import libs
+# Has to be a shell function in order to 'eat' the argument
+# that is supplied when $file_magic_command is called.
+func_win32_libid ()
+{
+ win32_libid_type="unknown"
+ win32_fileres=`file -L $1 2>/dev/null`
+ case $win32_fileres in
+ *ar\ archive\ import\ library*) # definitely import
+ win32_libid_type="x86 archive import"
+ ;;
+ *ar\ archive*) # could be an import, or static
+ if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null | \
+ $EGREP -e 'file format pe-i386(.*architecture: i386)?' >/dev/null ; then
+ win32_nmres=`eval $NM -f posix -A $1 | \
+ $SED -n -e '1,100{
+ / I /{
+ s,.*,import,
+ p
+ q
+ }
+ }'`
+ case $win32_nmres in
+ import*) win32_libid_type="x86 archive import";;
+ *) win32_libid_type="x86 archive static";;
+ esac
+ fi
+ ;;
+ *DLL*)
+ win32_libid_type="x86 DLL"
+ ;;
+ *executable*) # but shell scripts are "executable" too...
+ case $win32_fileres in
+ *MS\ Windows\ PE\ Intel*)
+ win32_libid_type="x86 DLL"
+ ;;
+ esac
+ ;;
+ esac
+ $echo $win32_libid_type
+}
+
+
+# func_infer_tag arg
+# Infer tagged configuration to use if any are available and
+# if one wasn't chosen via the "--tag" command line option.
+# Only attempt this if the compiler in the base compile
+# command doesn't match the default compiler.
+# arg is usually of the form 'gcc ...'
+func_infer_tag ()
+{
+ if test -n "$available_tags" && test -z "$tagname"; then
+ CC_quoted=
+ for arg in $CC; do
+ case $arg in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ arg="\"$arg\""
+ ;;
+ esac
+ CC_quoted="$CC_quoted $arg"
+ done
+ case $@ in
+ # Blanks in the command may have been stripped by the calling shell,
+ # but not from the CC environment variable when configure was run.
+ " $CC "* | "$CC "* | " `$echo $CC` "* | "`$echo $CC` "* | " $CC_quoted"* | "$CC_quoted "* | " `$echo $CC_quoted` "* | "`$echo $CC_quoted` "*) ;;
+ # Blanks at the start of $base_compile will cause this to fail
+ # if we don't check for them as well.
+ *)
+ for z in $available_tags; do
+ if grep "^# ### BEGIN LIBTOOL TAG CONFIG: $z$" < "$progpath" > /dev/null; then
+ # Evaluate the configuration.
+ eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`"
+ CC_quoted=
+ for arg in $CC; do
+ # Double-quote args containing other shell metacharacters.
+ case $arg in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ arg="\"$arg\""
+ ;;
+ esac
+ CC_quoted="$CC_quoted $arg"
+ done
+ case "$@ " in
+ " $CC "* | "$CC "* | " `$echo $CC` "* | "`$echo $CC` "* | " $CC_quoted"* | "$CC_quoted "* | " `$echo $CC_quoted` "* | "`$echo $CC_quoted` "*)
+ # The compiler in the base compile command matches
+ # the one in the tagged configuration.
+ # Assume this is the tagged configuration we want.
+ tagname=$z
+ break
+ ;;
+ esac
+ fi
+ done
+ # If $tagname still isn't set, then no tagged configuration
+ # was found and let the user know that the "--tag" command
+ # line option must be used.
+ if test -z "$tagname"; then
+ $echo "$modename: unable to infer tagged configuration"
+ $echo "$modename: specify a tag with \`--tag'" 1>&2
+ exit $EXIT_FAILURE
+# else
+# $echo "$modename: using $tagname tagged configuration"
+ fi
+ ;;
+ esac
+ fi
+}
+
+
+# func_extract_an_archive dir oldlib
+func_extract_an_archive ()
+{
+ f_ex_an_ar_dir="$1"; shift
+ f_ex_an_ar_oldlib="$1"
+
+ $show "(cd $f_ex_an_ar_dir && $AR x $f_ex_an_ar_oldlib)"
+ $run eval "(cd \$f_ex_an_ar_dir && $AR x \$f_ex_an_ar_oldlib)" || exit $?
+ if ($AR t "$f_ex_an_ar_oldlib" | sort | sort -uc >/dev/null 2>&1); then
+ :
+ else
+ $echo "$modename: ERROR: object name conflicts: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib" 1>&2
+ exit $EXIT_FAILURE
+ fi
+}
+
+# func_extract_archives gentop oldlib ...
+func_extract_archives ()
+{
+ my_gentop="$1"; shift
+ my_oldlibs=${1+"$@"}
+ my_oldobjs=""
+ my_xlib=""
+ my_xabs=""
+ my_xdir=""
+ my_status=""
+
+ $show "${rm}r $my_gentop"
+ $run ${rm}r "$my_gentop"
+ $show "$mkdir $my_gentop"
+ $run $mkdir "$my_gentop"
+ my_status=$?
+ if test "$my_status" -ne 0 && test ! -d "$my_gentop"; then
+ exit $my_status
+ fi
+
+ for my_xlib in $my_oldlibs; do
+ # Extract the objects.
+ case $my_xlib in
+ [\\/]* | [A-Za-z]:[\\/]*) my_xabs="$my_xlib" ;;
+ *) my_xabs=`pwd`"/$my_xlib" ;;
+ esac
+ my_xlib=`$echo "X$my_xlib" | $Xsed -e 's%^.*/%%'`
+ my_xlib_u=$my_xlib
+ while :; do
+ case " $extracted_archives " in
+ *" $my_xlib_u "*)
+ extracted_serial=`expr $extracted_serial + 1`
+ my_xlib_u=lt$extracted_serial-$my_xlib ;;
+ *) break ;;
+ esac
+ done
+ extracted_archives="$extracted_archives $my_xlib_u"
+ my_xdir="$my_gentop/$my_xlib_u"
+
+ $show "${rm}r $my_xdir"
+ $run ${rm}r "$my_xdir"
+ $show "$mkdir $my_xdir"
+ $run $mkdir "$my_xdir"
+ exit_status=$?
+ if test "$exit_status" -ne 0 && test ! -d "$my_xdir"; then
+ exit $exit_status
+ fi
+ case $host in
+ *-darwin*)
+ $show "Extracting $my_xabs"
+ # Do not bother doing anything if just a dry run
+ if test -z "$run"; then
+ darwin_orig_dir=`pwd`
+ cd $my_xdir || exit $?
+ darwin_archive=$my_xabs
+ darwin_curdir=`pwd`
+ darwin_base_archive=`$echo "X$darwin_archive" | $Xsed -e 's%^.*/%%'`
+ darwin_arches=`lipo -info "$darwin_archive" 2>/dev/null | $EGREP Architectures 2>/dev/null`
+ if test -n "$darwin_arches"; then
+ darwin_arches=`echo "$darwin_arches" | $SED -e 's/.*are://'`
+ darwin_arch=
+ $show "$darwin_base_archive has multiple architectures $darwin_arches"
+ for darwin_arch in $darwin_arches ; do
+ mkdir -p "unfat-$$/${darwin_base_archive}-${darwin_arch}"
+ lipo -thin $darwin_arch -output "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" "${darwin_archive}"
+ cd "unfat-$$/${darwin_base_archive}-${darwin_arch}"
+ func_extract_an_archive "`pwd`" "${darwin_base_archive}"
+ cd "$darwin_curdir"
+ $rm "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}"
+ done # $darwin_arches
+ ## Okay now we have a bunch of thin objects, gotta fatten them up :)
+ darwin_filelist=`find unfat-$$ -type f -name \*.o -print -o -name \*.lo -print| xargs basename | sort -u | $NL2SP`
+ darwin_file=
+ darwin_files=
+ for darwin_file in $darwin_filelist; do
+ darwin_files=`find unfat-$$ -name $darwin_file -print | $NL2SP`
+ lipo -create -output "$darwin_file" $darwin_files
+ done # $darwin_filelist
+ ${rm}r unfat-$$
+ cd "$darwin_orig_dir"
+ else
+ cd "$darwin_orig_dir"
+ func_extract_an_archive "$my_xdir" "$my_xabs"
+ fi # $darwin_arches
+ fi # $run
+ ;;
+ *)
+ func_extract_an_archive "$my_xdir" "$my_xabs"
+ ;;
+ esac
+ my_oldobjs="$my_oldobjs "`find $my_xdir -name \*.$objext -print -o -name \*.lo -print | $NL2SP`
+ done
+ func_extract_archives_result="$my_oldobjs"
+}
+# End of Shell function definitions
+#####################################
+
+# Darwin sucks
+eval std_shrext=\"$shrext_cmds\"
+
+disable_libs=no
+
+# Parse our command line options once, thoroughly.
+while test "$#" -gt 0
+do
+ arg="$1"
+ shift
+
+ case $arg in
+ -*=*) optarg=`$echo "X$arg" | $Xsed -e 's/[-_a-zA-Z0-9]*=//'` ;;
+ *) optarg= ;;
+ esac
+
+ # If the previous option needs an argument, assign it.
+ if test -n "$prev"; then
+ case $prev in
+ execute_dlfiles)
+ execute_dlfiles="$execute_dlfiles $arg"
+ ;;
+ tag)
+ tagname="$arg"
+ preserve_args="${preserve_args}=$arg"
+
+ # Check whether tagname contains only valid characters
+ case $tagname in
+ *[!-_A-Za-z0-9,/]*)
+ $echo "$progname: invalid tag name: $tagname" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+
+ case $tagname in
+ CC)
+ # Don't test for the "default" C tag, as we know, it's there, but
+ # not specially marked.
+ ;;
+ *)
+ if grep "^# ### BEGIN LIBTOOL TAG CONFIG: $tagname$" < "$progpath" > /dev/null; then
+ taglist="$taglist $tagname"
+ # Evaluate the configuration.
+ eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$tagname'$/,/^# ### END LIBTOOL TAG CONFIG: '$tagname'$/p' < $progpath`"
+ else
+ $echo "$progname: ignoring unknown tag $tagname" 1>&2
+ fi
+ ;;
+ esac
+ ;;
+ *)
+ eval "$prev=\$arg"
+ ;;
+ esac
+
+ prev=
+ prevopt=
+ continue
+ fi
+
+ # Have we seen a non-optional argument yet?
+ case $arg in
+ --help)
+ show_help=yes
+ ;;
+
+ --version)
+ echo "\
+$PROGRAM (GNU $PACKAGE) $VERSION$TIMESTAMP
+
+Copyright (C) 2007 Free Software Foundation, Inc.
+This is free software; see the source for copying conditions. There is NO
+warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
+ exit $?
+ ;;
+
+ --config)
+ ${SED} -e '1,/^# ### BEGIN LIBTOOL CONFIG/d' -e '/^# ### END LIBTOOL CONFIG/,$d' $progpath
+ # Now print the configurations for the tags.
+ for tagname in $taglist; do
+ ${SED} -n -e "/^# ### BEGIN LIBTOOL TAG CONFIG: $tagname$/,/^# ### END LIBTOOL TAG CONFIG: $tagname$/p" < "$progpath"
+ done
+ exit $?
+ ;;
+
+ --debug)
+ $echo "$progname: enabling shell trace mode"
+ set -x
+ preserve_args="$preserve_args $arg"
+ ;;
+
+ --dry-run | -n)
+ run=:
+ ;;
+
+ --features)
+ $echo "host: $host"
+ if test "$build_libtool_libs" = yes; then
+ $echo "enable shared libraries"
+ else
+ $echo "disable shared libraries"
+ fi
+ if test "$build_old_libs" = yes; then
+ $echo "enable static libraries"
+ else
+ $echo "disable static libraries"
+ fi
+ exit $?
+ ;;
+
+ --finish) mode="finish" ;;
+
+ --mode) prevopt="--mode" prev=mode ;;
+ --mode=*) mode="$optarg" ;;
+
+ --preserve-dup-deps) duplicate_deps="yes" ;;
+
+ --quiet | --silent)
+ show=:
+ preserve_args="$preserve_args $arg"
+ ;;
+
+ --tag)
+ prevopt="--tag"
+ prev=tag
+ preserve_args="$preserve_args --tag"
+ ;;
+ --tag=*)
+ set tag "$optarg" ${1+"$@"}
+ shift
+ prev=tag
+ preserve_args="$preserve_args --tag"
+ ;;
+
+ -dlopen)
+ prevopt="-dlopen"
+ prev=execute_dlfiles
+ ;;
+
+ -*)
+ $echo "$modename: unrecognized option \`$arg'" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+
+ *)
+ nonopt="$arg"
+ break
+ ;;
+ esac
+done
+
+if test -n "$prevopt"; then
+ $echo "$modename: option \`$prevopt' requires an argument" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+fi
+
+case $disable_libs in
+no)
+ ;;
+shared)
+ build_libtool_libs=no
+ build_old_libs=yes
+ ;;
+static)
+ build_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac`
+ ;;
+esac
+
+# If this variable is set in any of the actions, the command in it
+# will be execed at the end. This prevents here-documents from being
+# left over by shells.
+exec_cmd=
+
+if test -z "$show_help"; then
+
+ # Infer the operation mode.
+ if test -z "$mode"; then
+ $echo "*** Warning: inferring the mode of operation is deprecated." 1>&2
+ $echo "*** Future versions of Libtool will require --mode=MODE be specified." 1>&2
+ case $nonopt in
+ *cc | cc* | *++ | gcc* | *-gcc* | g++* | xlc*)
+ mode=link
+ for arg
+ do
+ case $arg in
+ -c)
+ mode=compile
+ break
+ ;;
+ esac
+ done
+ ;;
+ *db | *dbx | *strace | *truss)
+ mode=execute
+ ;;
+ *install*|cp|mv)
+ mode=install
+ ;;
+ *rm)
+ mode=uninstall
+ ;;
+ *)
+ # If we have no mode, but dlfiles were specified, then do execute mode.
+ test -n "$execute_dlfiles" && mode=execute
+
+ # Just use the default operation mode.
+ if test -z "$mode"; then
+ if test -n "$nonopt"; then
+ $echo "$modename: warning: cannot infer operation mode from \`$nonopt'" 1>&2
+ else
+ $echo "$modename: warning: cannot infer operation mode without MODE-ARGS" 1>&2
+ fi
+ fi
+ ;;
+ esac
+ fi
+
+ # Only execute mode is allowed to have -dlopen flags.
+ if test -n "$execute_dlfiles" && test "$mode" != execute; then
+ $echo "$modename: unrecognized option \`-dlopen'" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ # Change the help message to a mode-specific one.
+ generic_help="$help"
+ help="Try \`$modename --help --mode=$mode' for more information."
+
+ # These modes are in order of execution frequency so that they run quickly.
+ case $mode in
+ # libtool compile mode
+ compile)
+ modename="$modename: compile"
+ # Get the compilation command and the source file.
+ base_compile=
+ srcfile="$nonopt" # always keep a non-empty value in "srcfile"
+ suppress_opt=yes
+ suppress_output=
+ arg_mode=normal
+ libobj=
+ later=
+
+ for arg
+ do
+ case $arg_mode in
+ arg )
+ # do not "continue". Instead, add this to base_compile
+ lastarg="$arg"
+ arg_mode=normal
+ ;;
+
+ target )
+ libobj="$arg"
+ arg_mode=normal
+ continue
+ ;;
+
+ normal )
+ # Accept any command-line options.
+ case $arg in
+ -o)
+ if test -n "$libobj" ; then
+ $echo "$modename: you cannot specify \`-o' more than once" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ arg_mode=target
+ continue
+ ;;
+
+ -static | -prefer-pic | -prefer-non-pic)
+ later="$later $arg"
+ continue
+ ;;
+
+ -no-suppress)
+ suppress_opt=no
+ continue
+ ;;
+
+ -Xcompiler)
+ arg_mode=arg # the next one goes into the "base_compile" arg list
+ continue # The current "srcfile" will either be retained or
+ ;; # replaced later. I would guess that would be a bug.
+
+ -Wc,*)
+ args=`$echo "X$arg" | $Xsed -e "s/^-Wc,//"`
+ lastarg=
+ save_ifs="$IFS"; IFS=','
+ for arg in $args; do
+ IFS="$save_ifs"
+
+ # Double-quote args containing other shell metacharacters.
+ # Many Bourne shells cannot handle close brackets correctly
+ # in scan sets, so we specify it separately.
+ case $arg in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ arg="\"$arg\""
+ ;;
+ esac
+ lastarg="$lastarg $arg"
+ done
+ IFS="$save_ifs"
+ lastarg=`$echo "X$lastarg" | $Xsed -e "s/^ //"`
+
+ # Add the arguments to base_compile.
+ base_compile="$base_compile $lastarg"
+ continue
+ ;;
+
+ * )
+ # Accept the current argument as the source file.
+ # The previous "srcfile" becomes the current argument.
+ #
+ lastarg="$srcfile"
+ srcfile="$arg"
+ ;;
+ esac # case $arg
+ ;;
+ esac # case $arg_mode
+
+ # Aesthetically quote the previous argument.
+ lastarg=`$echo "X$lastarg" | $Xsed -e "$sed_quote_subst"`
+
+ case $lastarg in
+ # Double-quote args containing other shell metacharacters.
+ # Many Bourne shells cannot handle close brackets correctly
+ # in scan sets, and some SunOS ksh mistreat backslash-escaping
+ # in scan sets (worked around with variable expansion),
+ # and furthermore cannot handle '|' '&' '(' ')' in scan sets
+ # at all, so we specify them separately.
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ lastarg="\"$lastarg\""
+ ;;
+ esac
+
+ base_compile="$base_compile $lastarg"
+ done # for arg
+
+ case $arg_mode in
+ arg)
+ $echo "$modename: you must specify an argument for -Xcompile"
+ exit $EXIT_FAILURE
+ ;;
+ target)
+ $echo "$modename: you must specify a target with \`-o'" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ *)
+ # Get the name of the library object.
+ [ -z "$libobj" ] && libobj=`$echo "X$srcfile" | $Xsed -e 's%^.*/%%'`
+ ;;
+ esac
+
+ # Recognize several different file suffixes.
+ # If the user specifies -o file.o, it is replaced with file.lo
+ xform='[cCFSifmso]'
+ case $libobj in
+ *.ada) xform=ada ;;
+ *.adb) xform=adb ;;
+ *.ads) xform=ads ;;
+ *.asm) xform=asm ;;
+ *.c++) xform=c++ ;;
+ *.cc) xform=cc ;;
+ *.ii) xform=ii ;;
+ *.class) xform=class ;;
+ *.cpp) xform=cpp ;;
+ *.cxx) xform=cxx ;;
+ *.[fF][09]?) xform=[fF][09]. ;;
+ *.for) xform=for ;;
+ *.java) xform=java ;;
+ *.obj) xform=obj ;;
+ esac
+
+ libobj=`$echo "X$libobj" | $Xsed -e "s/\.$xform$/.lo/"`
+
+ case $libobj in
+ *.lo) obj=`$echo "X$libobj" | $Xsed -e "$lo2o"` ;;
+ *)
+ $echo "$modename: cannot determine name of library object from \`$libobj'" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+
+ func_infer_tag $base_compile
+
+ for arg in $later; do
+ case $arg in
+ -static)
+ build_old_libs=yes
+ continue
+ ;;
+
+ -prefer-pic)
+ pic_mode=yes
+ continue
+ ;;
+
+ -prefer-non-pic)
+ pic_mode=no
+ continue
+ ;;
+ esac
+ done
+
+ qlibobj=`$echo "X$libobj" | $Xsed -e "$sed_quote_subst"`
+ case $qlibobj in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ qlibobj="\"$qlibobj\"" ;;
+ esac
+ test "X$libobj" != "X$qlibobj" \
+ && $echo "X$libobj" | grep '[]~#^*{};<>?"'"'"' &()|`$[]' \
+ && $echo "$modename: libobj name \`$libobj' may not contain shell special characters."
+ objname=`$echo "X$obj" | $Xsed -e 's%^.*/%%'`
+ xdir=`$echo "X$obj" | $Xsed -e 's%/[^/]*$%%'`
+ if test "X$xdir" = "X$obj"; then
+ xdir=
+ else
+ xdir=$xdir/
+ fi
+ lobj=${xdir}$objdir/$objname
+
+ if test -z "$base_compile"; then
+ $echo "$modename: you must specify a compilation command" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ # Delete any leftover library objects.
+ if test "$build_old_libs" = yes; then
+ removelist="$obj $lobj $libobj ${libobj}T"
+ else
+ removelist="$lobj $libobj ${libobj}T"
+ fi
+
+ $run $rm $removelist
+ trap "$run $rm $removelist; exit $EXIT_FAILURE" 1 2 15
+
+ # On Cygwin there's no "real" PIC flag so we must build both object types
+ case $host_os in
+ cygwin* | mingw* | pw32* | os2*)
+ pic_mode=default
+ ;;
+ esac
+ if test "$pic_mode" = no && test "$deplibs_check_method" != pass_all; then
+ # non-PIC code in shared libraries is not supported
+ pic_mode=default
+ fi
+
+ # Calculate the filename of the output object if compiler does
+ # not support -o with -c
+ if test "$compiler_c_o" = no; then
+ output_obj=`$echo "X$srcfile" | $Xsed -e 's%^.*/%%' -e 's%\.[^.]*$%%'`.${objext}
+ lockfile="$output_obj.lock"
+ removelist="$removelist $output_obj $lockfile"
+ trap "$run $rm $removelist; exit $EXIT_FAILURE" 1 2 15
+ else
+ output_obj=
+ need_locks=no
+ lockfile=
+ fi
+
+ # Lock this critical section if it is needed
+ # We use this script file to make the link, it avoids creating a new file
+ if test "$need_locks" = yes; then
+ until $run ln "$progpath" "$lockfile" 2>/dev/null; do
+ $show "Waiting for $lockfile to be removed"
+ sleep 2
+ done
+ elif test "$need_locks" = warn; then
+ if test -f "$lockfile"; then
+ $echo "\
+*** ERROR, $lockfile exists and contains:
+`cat $lockfile 2>/dev/null`
+
+This indicates that another process is trying to use the same
+temporary object file, and libtool could not work around it because
+your compiler does not support \`-c' and \`-o' together. If you
+repeat this compilation, it may succeed, by chance, but you had better
+avoid parallel builds (make -j) in this platform, or get a better
+compiler."
+
+ $run $rm $removelist
+ exit $EXIT_FAILURE
+ fi
+ $echo "$srcfile" > "$lockfile"
+ fi
+
+ if test -n "$fix_srcfile_path"; then
+ eval srcfile=\"$fix_srcfile_path\"
+ fi
+ qsrcfile=`$echo "X$srcfile" | $Xsed -e "$sed_quote_subst"`
+ case $qsrcfile in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ qsrcfile="\"$qsrcfile\"" ;;
+ esac
+
+ $run $rm "$libobj" "${libobj}T"
+
+ # Create a libtool object file (analogous to a ".la" file),
+ # but don't create it if we're doing a dry run.
+ test -z "$run" && cat > ${libobj}T <<EOF
+# $libobj - a libtool object file
+# Generated by $PROGRAM - GNU $PACKAGE $VERSION$TIMESTAMP
+#
+# Please DO NOT delete this file!
+# It is necessary for linking the library.
+
+# Name of the PIC object.
+EOF
+
+ # Only build a PIC object if we are building libtool libraries.
+ if test "$build_libtool_libs" = yes; then
+ # Without this assignment, base_compile gets emptied.
+ fbsd_hideous_sh_bug=$base_compile
+
+ if test "$pic_mode" != no; then
+ command="$base_compile $qsrcfile $pic_flag"
+ else
+ # Don't build PIC code
+ command="$base_compile $qsrcfile"
+ fi
+
+ if test ! -d "${xdir}$objdir"; then
+ $show "$mkdir ${xdir}$objdir"
+ $run $mkdir ${xdir}$objdir
+ exit_status=$?
+ if test "$exit_status" -ne 0 && test ! -d "${xdir}$objdir"; then
+ exit $exit_status
+ fi
+ fi
+
+ if test -z "$output_obj"; then
+ # Place PIC objects in $objdir
+ command="$command -o $lobj"
+ fi
+
+ $run $rm "$lobj" "$output_obj"
+
+ $show "$command"
+ if $run eval "$command"; then :
+ else
+ test -n "$output_obj" && $run $rm $removelist
+ exit $EXIT_FAILURE
+ fi
+
+ if test "$need_locks" = warn &&
+ test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then
+ $echo "\
+*** ERROR, $lockfile contains:
+`cat $lockfile 2>/dev/null`
+
+but it should contain:
+$srcfile
+
+This indicates that another process is trying to use the same
+temporary object file, and libtool could not work around it because
+your compiler does not support \`-c' and \`-o' together. If you
+repeat this compilation, it may succeed, by chance, but you had better
+avoid parallel builds (make -j) in this platform, or get a better
+compiler."
+
+ $run $rm $removelist
+ exit $EXIT_FAILURE
+ fi
+
+ # Just move the object if needed, then go on to compile the next one
+ if test -n "$output_obj" && test "X$output_obj" != "X$lobj"; then
+ $show "$mv $output_obj $lobj"
+ if $run $mv $output_obj $lobj; then :
+ else
+ error=$?
+ $run $rm $removelist
+ exit $error
+ fi
+ fi
+
+ # Append the name of the PIC object to the libtool object file.
+ test -z "$run" && cat >> ${libobj}T <<EOF
+pic_object='$objdir/$objname'
+
+EOF
+
+ # Allow error messages only from the first compilation.
+ if test "$suppress_opt" = yes; then
+ suppress_output=' >/dev/null 2>&1'
+ fi
+ else
+ # No PIC object so indicate it doesn't exist in the libtool
+ # object file.
+ test -z "$run" && cat >> ${libobj}T <<EOF
+pic_object=none
+
+EOF
+ fi
+
+ # Only build a position-dependent object if we build old libraries.
+ if test "$build_old_libs" = yes; then
+ if test "$pic_mode" != yes; then
+ # Don't build PIC code
+ command="$base_compile $qsrcfile"
+ else
+ command="$base_compile $qsrcfile $pic_flag"
+ fi
+ if test "$compiler_c_o" = yes; then
+ command="$command -o $obj"
+ fi
+
+ # Suppress compiler output if we already did a PIC compilation.
+ command="$command$suppress_output"
+ $run $rm "$obj" "$output_obj"
+ $show "$command"
+ if $run eval "$command"; then :
+ else
+ $run $rm $removelist
+ exit $EXIT_FAILURE
+ fi
+
+ if test "$need_locks" = warn &&
+ test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then
+ $echo "\
+*** ERROR, $lockfile contains:
+`cat $lockfile 2>/dev/null`
+
+but it should contain:
+$srcfile
+
+This indicates that another process is trying to use the same
+temporary object file, and libtool could not work around it because
+your compiler does not support \`-c' and \`-o' together. If you
+repeat this compilation, it may succeed, by chance, but you had better
+avoid parallel builds (make -j) in this platform, or get a better
+compiler."
+
+ $run $rm $removelist
+ exit $EXIT_FAILURE
+ fi
+
+ # Just move the object if needed
+ if test -n "$output_obj" && test "X$output_obj" != "X$obj"; then
+ $show "$mv $output_obj $obj"
+ if $run $mv $output_obj $obj; then :
+ else
+ error=$?
+ $run $rm $removelist
+ exit $error
+ fi
+ fi
+
+ # Append the name of the non-PIC object the libtool object file.
+ # Only append if the libtool object file exists.
+ test -z "$run" && cat >> ${libobj}T <<EOF
+# Name of the non-PIC object.
+non_pic_object='$objname'
+
+EOF
+ else
+ # Append the name of the non-PIC object the libtool object file.
+ # Only append if the libtool object file exists.
+ test -z "$run" && cat >> ${libobj}T <<EOF
+# Name of the non-PIC object.
+non_pic_object=none
+
+EOF
+ fi
+
+ $run $mv "${libobj}T" "${libobj}"
+
+ # Unlock the critical section if it was locked
+ if test "$need_locks" != no; then
+ $run $rm "$lockfile"
+ fi
+
+ exit $EXIT_SUCCESS
+ ;;
+
+ # libtool link mode
+ link | relink)
+ modename="$modename: link"
+ case $host in
+ *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2*)
+ # It is impossible to link a dll without this setting, and
+ # we shouldn't force the makefile maintainer to figure out
+ # which system we are compiling for in order to pass an extra
+ # flag for every libtool invocation.
+ # allow_undefined=no
+
+ # FIXME: Unfortunately, there are problems with the above when trying
+ # to make a dll which has undefined symbols, in which case not
+ # even a static library is built. For now, we need to specify
+ # -no-undefined on the libtool link line when we can be certain
+ # that all symbols are satisfied, otherwise we get a static library.
+ allow_undefined=yes
+ ;;
+ *)
+ allow_undefined=yes
+ ;;
+ esac
+ libtool_args="$nonopt"
+ base_compile="$nonopt $@"
+ compile_command="$nonopt"
+ finalize_command="$nonopt"
+
+ compile_rpath=
+ finalize_rpath=
+ compile_shlibpath=
+ finalize_shlibpath=
+ convenience=
+ old_convenience=
+ deplibs=
+ old_deplibs=
+ compiler_flags=
+ linker_flags=
+ dllsearchpath=
+ lib_search_path=`pwd`
+ inst_prefix_dir=
+
+ avoid_version=no
+ dlfiles=
+ dlprefiles=
+ dlself=no
+ export_dynamic=no
+ export_symbols=
+ export_symbols_regex=
+ generated=
+ libobjs=
+ ltlibs=
+ module=no
+ no_install=no
+ objs=
+ non_pic_objects=
+ notinst_path= # paths that contain not-installed libtool libraries
+ precious_files_regex=
+ prefer_static_libs=no
+ preload=no
+ prev=
+ prevarg=
+ release=
+ rpath=
+ xrpath=
+ perm_rpath=
+ temp_rpath=
+ thread_safe=no
+ vinfo=
+ vinfo_number=no
+
+ func_infer_tag $base_compile
+
+ # We need to know -static, to get the right output filenames.
+ for arg
+ do
+ case $arg in
+ -all-static | -static | -static-libtool-libs)
+ case $arg in
+ -all-static)
+ if test "$build_libtool_libs" = yes && test -z "$link_static_flag"; then
+ $echo "$modename: warning: complete static linking is impossible in this configuration" 1>&2
+ fi
+ if test -n "$link_static_flag"; then
+ dlopen_self=$dlopen_self_static
+ fi
+ prefer_static_libs=yes
+ ;;
+ -static)
+ if test -z "$pic_flag" && test -n "$link_static_flag"; then
+ dlopen_self=$dlopen_self_static
+ fi
+ prefer_static_libs=built
+ ;;
+ -static-libtool-libs)
+ if test -z "$pic_flag" && test -n "$link_static_flag"; then
+ dlopen_self=$dlopen_self_static
+ fi
+ prefer_static_libs=yes
+ ;;
+ esac
+ build_libtool_libs=no
+ build_old_libs=yes
+ break
+ ;;
+ esac
+ done
+
+ # See if our shared archives depend on static archives.
+ test -n "$old_archive_from_new_cmds" && build_old_libs=yes
+
+ # Go through the arguments, transforming them on the way.
+ while test "$#" -gt 0; do
+ arg="$1"
+ shift
+ case $arg in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ qarg=\"`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`\" ### testsuite: skip nested quoting test
+ ;;
+ *) qarg=$arg ;;
+ esac
+ libtool_args="$libtool_args $qarg"
+
+ # If the previous option needs an argument, assign it.
+ if test -n "$prev"; then
+ case $prev in
+ output)
+ compile_command="$compile_command @OUTPUT@"
+ finalize_command="$finalize_command @OUTPUT@"
+ ;;
+ esac
+
+ case $prev in
+ dlfiles|dlprefiles)
+ if test "$preload" = no; then
+ # Add the symbol object into the linking commands.
+ compile_command="$compile_command @SYMFILE@"
+ finalize_command="$finalize_command @SYMFILE@"
+ preload=yes
+ fi
+ case $arg in
+ *.la | *.lo) ;; # We handle these cases below.
+ force)
+ if test "$dlself" = no; then
+ dlself=needless
+ export_dynamic=yes
+ fi
+ prev=
+ continue
+ ;;
+ self)
+ if test "$prev" = dlprefiles; then
+ dlself=yes
+ elif test "$prev" = dlfiles && test "$dlopen_self" != yes; then
+ dlself=yes
+ else
+ dlself=needless
+ export_dynamic=yes
+ fi
+ prev=
+ continue
+ ;;
+ *)
+ if test "$prev" = dlfiles; then
+ dlfiles="$dlfiles $arg"
+ else
+ dlprefiles="$dlprefiles $arg"
+ fi
+ prev=
+ continue
+ ;;
+ esac
+ ;;
+ expsyms)
+ export_symbols="$arg"
+ if test ! -f "$arg"; then
+ $echo "$modename: symbol file \`$arg' does not exist"
+ exit $EXIT_FAILURE
+ fi
+ prev=
+ continue
+ ;;
+ expsyms_regex)
+ export_symbols_regex="$arg"
+ prev=
+ continue
+ ;;
+ inst_prefix)
+ inst_prefix_dir="$arg"
+ prev=
+ continue
+ ;;
+ precious_regex)
+ precious_files_regex="$arg"
+ prev=
+ continue
+ ;;
+ release)
+ release="-$arg"
+ prev=
+ continue
+ ;;
+ objectlist)
+ if test -f "$arg"; then
+ save_arg=$arg
+ moreargs=
+ for fil in `cat $save_arg`
+ do
+# moreargs="$moreargs $fil"
+ arg=$fil
+ # A libtool-controlled object.
+
+ # Check to see that this really is a libtool object.
+ if (${SED} -e '2q' $arg | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then
+ pic_object=
+ non_pic_object=
+
+ # Read the .lo file
+ # If there is no directory component, then add one.
+ case $arg in
+ */* | *\\*) . $arg ;;
+ *) . ./$arg ;;
+ esac
+
+ if test -z "$pic_object" || \
+ test -z "$non_pic_object" ||
+ test "$pic_object" = none && \
+ test "$non_pic_object" = none; then
+ $echo "$modename: cannot find name of object for \`$arg'" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ # Extract subdirectory from the argument.
+ xdir=`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'`
+ if test "X$xdir" = "X$arg"; then
+ xdir=
+ else
+ xdir="$xdir/"
+ fi
+
+ if test "$pic_object" != none; then
+ # Prepend the subdirectory the object is found in.
+ pic_object="$xdir$pic_object"
+
+ if test "$prev" = dlfiles; then
+ if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then
+ dlfiles="$dlfiles $pic_object"
+ prev=
+ continue
+ else
+ # If libtool objects are unsupported, then we need to preload.
+ prev=dlprefiles
+ fi
+ fi
+
+ # CHECK ME: I think I busted this. -Ossama
+ if test "$prev" = dlprefiles; then
+ # Preload the old-style object.
+ dlprefiles="$dlprefiles $pic_object"
+ prev=
+ fi
+
+ # A PIC object.
+ libobjs="$libobjs $pic_object"
+ arg="$pic_object"
+ fi
+
+ # Non-PIC object.
+ if test "$non_pic_object" != none; then
+ # Prepend the subdirectory the object is found in.
+ non_pic_object="$xdir$non_pic_object"
+
+ # A standard non-PIC object
+ non_pic_objects="$non_pic_objects $non_pic_object"
+ if test -z "$pic_object" || test "$pic_object" = none ; then
+ arg="$non_pic_object"
+ fi
+ else
+ # If the PIC object exists, use it instead.
+ # $xdir was prepended to $pic_object above.
+ non_pic_object="$pic_object"
+ non_pic_objects="$non_pic_objects $non_pic_object"
+ fi
+ else
+ # Only an error if not doing a dry-run.
+ if test -z "$run"; then
+ $echo "$modename: \`$arg' is not a valid libtool object" 1>&2
+ exit $EXIT_FAILURE
+ else
+ # Dry-run case.
+
+ # Extract subdirectory from the argument.
+ xdir=`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'`
+ if test "X$xdir" = "X$arg"; then
+ xdir=
+ else
+ xdir="$xdir/"
+ fi
+
+ pic_object=`$echo "X${xdir}${objdir}/${arg}" | $Xsed -e "$lo2o"`
+ non_pic_object=`$echo "X${xdir}${arg}" | $Xsed -e "$lo2o"`
+ libobjs="$libobjs $pic_object"
+ non_pic_objects="$non_pic_objects $non_pic_object"
+ fi
+ fi
+ done
+ else
+ $echo "$modename: link input file \`$save_arg' does not exist"
+ exit $EXIT_FAILURE
+ fi
+ arg=$save_arg
+ prev=
+ continue
+ ;;
+ rpath | xrpath)
+ # We need an absolute path.
+ case $arg in
+ [\\/]* | [A-Za-z]:[\\/]*) ;;
+ *)
+ $echo "$modename: only absolute run-paths are allowed" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+ if test "$prev" = rpath; then
+ case "$rpath " in
+ *" $arg "*) ;;
+ *) rpath="$rpath $arg" ;;
+ esac
+ else
+ case "$xrpath " in
+ *" $arg "*) ;;
+ *) xrpath="$xrpath $arg" ;;
+ esac
+ fi
+ prev=
+ continue
+ ;;
+ xcompiler)
+ compiler_flags="$compiler_flags $qarg"
+ prev=
+ compile_command="$compile_command $qarg"
+ finalize_command="$finalize_command $qarg"
+ continue
+ ;;
+ xlinker)
+ linker_flags="$linker_flags $qarg"
+ compiler_flags="$compiler_flags $wl$qarg"
+ prev=
+ compile_command="$compile_command $wl$qarg"
+ finalize_command="$finalize_command $wl$qarg"
+ continue
+ ;;
+ xcclinker)
+ linker_flags="$linker_flags $qarg"
+ compiler_flags="$compiler_flags $qarg"
+ prev=
+ compile_command="$compile_command $qarg"
+ finalize_command="$finalize_command $qarg"
+ continue
+ ;;
+ shrext)
+ shrext_cmds="$arg"
+ prev=
+ continue
+ ;;
+ darwin_framework|darwin_framework_skip)
+ test "$prev" = "darwin_framework" && compiler_flags="$compiler_flags $arg"
+ compile_command="$compile_command $arg"
+ finalize_command="$finalize_command $arg"
+ prev=
+ continue
+ ;;
+ *)
+ eval "$prev=\"\$arg\""
+ prev=
+ continue
+ ;;
+ esac
+ fi # test -n "$prev"
+
+ prevarg="$arg"
+
+ case $arg in
+ -all-static)
+ if test -n "$link_static_flag"; then
+ compile_command="$compile_command $link_static_flag"
+ finalize_command="$finalize_command $link_static_flag"
+ fi
+ continue
+ ;;
+
+ -allow-undefined)
+ # FIXME: remove this flag sometime in the future.
+ $echo "$modename: \`-allow-undefined' is deprecated because it is the default" 1>&2
+ continue
+ ;;
+
+ -avoid-version)
+ avoid_version=yes
+ continue
+ ;;
+
+ -dlopen)
+ prev=dlfiles
+ continue
+ ;;
+
+ -dlpreopen)
+ prev=dlprefiles
+ continue
+ ;;
+
+ -export-dynamic)
+ export_dynamic=yes
+ continue
+ ;;
+
+ -export-symbols | -export-symbols-regex)
+ if test -n "$export_symbols" || test -n "$export_symbols_regex"; then
+ $echo "$modename: more than one -exported-symbols argument is not allowed"
+ exit $EXIT_FAILURE
+ fi
+ if test "X$arg" = "X-export-symbols"; then
+ prev=expsyms
+ else
+ prev=expsyms_regex
+ fi
+ continue
+ ;;
+
+ -framework|-arch|-isysroot)
+ case " $CC " in
+ *" ${arg} ${1} "* | *" ${arg} ${1} "*)
+ prev=darwin_framework_skip ;;
+ *) compiler_flags="$compiler_flags $arg"
+ prev=darwin_framework ;;
+ esac
+ compile_command="$compile_command $arg"
+ finalize_command="$finalize_command $arg"
+ continue
+ ;;
+
+ -inst-prefix-dir)
+ prev=inst_prefix
+ continue
+ ;;
+
+ # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:*
+ # so, if we see these flags be careful not to treat them like -L
+ -L[A-Z][A-Z]*:*)
+ case $with_gcc/$host in
+ no/*-*-irix* | /*-*-irix*)
+ compile_command="$compile_command $arg"
+ finalize_command="$finalize_command $arg"
+ ;;
+ esac
+ continue
+ ;;
+
+ -L*)
+ dir=`$echo "X$arg" | $Xsed -e 's/^-L//'`
+ # We need an absolute path.
+ case $dir in
+ [\\/]* | [A-Za-z]:[\\/]*) ;;
+ *)
+ absdir=`cd "$dir" && pwd`
+ if test -z "$absdir"; then
+ $echo "$modename: cannot determine absolute directory name of \`$dir'" 1>&2
+ absdir="$dir"
+ notinst_path="$notinst_path $dir"
+ fi
+ dir="$absdir"
+ ;;
+ esac
+ case "$deplibs " in
+ *" -L$dir "*) ;;
+ *)
+ deplibs="$deplibs -L$dir"
+ lib_search_path="$lib_search_path $dir"
+ ;;
+ esac
+ case $host in
+ *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2*)
+ testbindir=`$echo "X$dir" | $Xsed -e 's*/lib$*/bin*'`
+ case :$dllsearchpath: in
+ *":$dir:"*) ;;
+ *) dllsearchpath="$dllsearchpath:$dir";;
+ esac
+ case :$dllsearchpath: in
+ *":$testbindir:"*) ;;
+ *) dllsearchpath="$dllsearchpath:$testbindir";;
+ esac
+ ;;
+ esac
+ continue
+ ;;
+
+ -l*)
+ if test "X$arg" = "X-lc" || test "X$arg" = "X-lm"; then
+ case $host in
+ *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos*)
+ # These systems don't actually have a C or math library (as such)
+ continue
+ ;;
+ *-*-os2*)
+ # These systems don't actually have a C library (as such)
+ test "X$arg" = "X-lc" && continue
+ ;;
+ *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)
+ # Do not include libc due to us having libc/libc_r.
+ test "X$arg" = "X-lc" && continue
+ ;;
+ *-*-rhapsody* | *-*-darwin1.[012])
+ # Rhapsody C and math libraries are in the System framework
+ deplibs="$deplibs -framework System"
+ continue
+ ;;
+ *-*-sco3.2v5* | *-*-sco5v6*)
+ # Causes problems with __ctype
+ test "X$arg" = "X-lc" && continue
+ ;;
+ *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)
+ # Compiler inserts libc in the correct place for threads to work
+ test "X$arg" = "X-lc" && continue
+ ;;
+ esac
+ elif test "X$arg" = "X-lc_r"; then
+ case $host in
+ *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)
+ # Do not include libc_r directly, use -pthread flag.
+ continue
+ ;;
+ esac
+ fi
+ deplibs="$deplibs $arg"
+ continue
+ ;;
+
+ # Tru64 UNIX uses -model [arg] to determine the layout of C++
+ # classes, name mangling, and exception handling.
+ -model)
+ compile_command="$compile_command $arg"
+ compiler_flags="$compiler_flags $arg"
+ finalize_command="$finalize_command $arg"
+ prev=xcompiler
+ continue
+ ;;
+
+ -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe|-threads)
+ compiler_flags="$compiler_flags $arg"
+ compile_command="$compile_command $arg"
+ finalize_command="$finalize_command $arg"
+ continue
+ ;;
+
+ -module)
+ module=yes
+ continue
+ ;;
+
+ # -64, -mips[0-9] enable 64-bit mode on the SGI compiler
+ # -r[0-9][0-9]* specifies the processor on the SGI compiler
+ # -xarch=*, -xtarget=* enable 64-bit mode on the Sun compiler
+ # +DA*, +DD* enable 64-bit mode on the HP compiler
+ # -q* pass through compiler args for the IBM compiler
+ # -m* pass through architecture-specific compiler args for GCC
+ # -m*, -t[45]*, -txscale* pass through architecture-specific
+ # compiler args for GCC
+ # -p, -pg, --coverage, -fprofile-* pass through profiling flag for GCC
+ # -F/path gives path to uninstalled frameworks, gcc on darwin
+ # @file GCC response files
+ -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \
+ -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*)
+
+ # Unknown arguments in both finalize_command and compile_command need
+ # to be aesthetically quoted because they are evaled later.
+ arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`
+ case $arg in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ arg="\"$arg\""
+ ;;
+ esac
+ compile_command="$compile_command $arg"
+ finalize_command="$finalize_command $arg"
+ compiler_flags="$compiler_flags $arg"
+ continue
+ ;;
+
+ -shrext)
+ prev=shrext
+ continue
+ ;;
+
+ -no-fast-install)
+ fast_install=no
+ continue
+ ;;
+
+ -no-install)
+ case $host in
+ *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin*)
+ # The PATH hackery in wrapper scripts is required on Windows
+ # and Darwin in order for the loader to find any dlls it needs.
+ $echo "$modename: warning: \`-no-install' is ignored for $host" 1>&2
+ $echo "$modename: warning: assuming \`-no-fast-install' instead" 1>&2
+ fast_install=no
+ ;;
+ *) no_install=yes ;;
+ esac
+ continue
+ ;;
+
+ -no-undefined)
+ allow_undefined=no
+ continue
+ ;;
+
+ -objectlist)
+ prev=objectlist
+ continue
+ ;;
+
+ -o) prev=output ;;
+
+ -precious-files-regex)
+ prev=precious_regex
+ continue
+ ;;
+
+ -release)
+ prev=release
+ continue
+ ;;
+
+ -rpath)
+ prev=rpath
+ continue
+ ;;
+
+ -R)
+ prev=xrpath
+ continue
+ ;;
+
+ -R*)
+ dir=`$echo "X$arg" | $Xsed -e 's/^-R//'`
+ # We need an absolute path.
+ case $dir in
+ [\\/]* | [A-Za-z]:[\\/]*) ;;
+ *)
+ $echo "$modename: only absolute run-paths are allowed" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+ case "$xrpath " in
+ *" $dir "*) ;;
+ *) xrpath="$xrpath $dir" ;;
+ esac
+ continue
+ ;;
+
+ -static | -static-libtool-libs)
+ # The effects of -static are defined in a previous loop.
+ # We used to do the same as -all-static on platforms that
+ # didn't have a PIC flag, but the assumption that the effects
+ # would be equivalent was wrong. It would break on at least
+ # Digital Unix and AIX.
+ continue
+ ;;
+
+ -thread-safe)
+ thread_safe=yes
+ continue
+ ;;
+
+ -version-info)
+ prev=vinfo
+ continue
+ ;;
+ -version-number)
+ prev=vinfo
+ vinfo_number=yes
+ continue
+ ;;
+
+ -Wc,*)
+ args=`$echo "X$arg" | $Xsed -e "$sed_quote_subst" -e 's/^-Wc,//'`
+ arg=
+ save_ifs="$IFS"; IFS=','
+ for flag in $args; do
+ IFS="$save_ifs"
+ case $flag in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ flag="\"$flag\""
+ ;;
+ esac
+ arg="$arg $wl$flag"
+ compiler_flags="$compiler_flags $flag"
+ done
+ IFS="$save_ifs"
+ arg=`$echo "X$arg" | $Xsed -e "s/^ //"`
+ ;;
+
+ -Wl,*)
+ args=`$echo "X$arg" | $Xsed -e "$sed_quote_subst" -e 's/^-Wl,//'`
+ arg=
+ save_ifs="$IFS"; IFS=','
+ for flag in $args; do
+ IFS="$save_ifs"
+ case $flag in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ flag="\"$flag\""
+ ;;
+ esac
+ arg="$arg $wl$flag"
+ compiler_flags="$compiler_flags $wl$flag"
+ linker_flags="$linker_flags $flag"
+ done
+ IFS="$save_ifs"
+ arg=`$echo "X$arg" | $Xsed -e "s/^ //"`
+ ;;
+
+ -Xcompiler)
+ prev=xcompiler
+ continue
+ ;;
+
+ -Xlinker)
+ prev=xlinker
+ continue
+ ;;
+
+ -XCClinker)
+ prev=xcclinker
+ continue
+ ;;
+
+ # Some other compiler flag.
+ -* | +*)
+ # Unknown arguments in both finalize_command and compile_command need
+ # to be aesthetically quoted because they are evaled later.
+ arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`
+ case $arg in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ arg="\"$arg\""
+ ;;
+ esac
+ ;;
+
+ *.$objext)
+ # A standard object.
+ objs="$objs $arg"
+ ;;
+
+ *.lo)
+ # A libtool-controlled object.
+
+ # Check to see that this really is a libtool object.
+ if (${SED} -e '2q' $arg | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then
+ pic_object=
+ non_pic_object=
+
+ # Read the .lo file
+ # If there is no directory component, then add one.
+ case $arg in
+ */* | *\\*) . $arg ;;
+ *) . ./$arg ;;
+ esac
+
+ if test -z "$pic_object" || \
+ test -z "$non_pic_object" ||
+ test "$pic_object" = none && \
+ test "$non_pic_object" = none; then
+ $echo "$modename: cannot find name of object for \`$arg'" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ # Extract subdirectory from the argument.
+ xdir=`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'`
+ if test "X$xdir" = "X$arg"; then
+ xdir=
+ else
+ xdir="$xdir/"
+ fi
+
+ if test "$pic_object" != none; then
+ # Prepend the subdirectory the object is found in.
+ pic_object="$xdir$pic_object"
+
+ if test "$prev" = dlfiles; then
+ if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then
+ dlfiles="$dlfiles $pic_object"
+ prev=
+ continue
+ else
+ # If libtool objects are unsupported, then we need to preload.
+ prev=dlprefiles
+ fi
+ fi
+
+ # CHECK ME: I think I busted this. -Ossama
+ if test "$prev" = dlprefiles; then
+ # Preload the old-style object.
+ dlprefiles="$dlprefiles $pic_object"
+ prev=
+ fi
+
+ # A PIC object.
+ libobjs="$libobjs $pic_object"
+ arg="$pic_object"
+ fi
+
+ # Non-PIC object.
+ if test "$non_pic_object" != none; then
+ # Prepend the subdirectory the object is found in.
+ non_pic_object="$xdir$non_pic_object"
+
+ # A standard non-PIC object
+ non_pic_objects="$non_pic_objects $non_pic_object"
+ if test -z "$pic_object" || test "$pic_object" = none ; then
+ arg="$non_pic_object"
+ fi
+ else
+ # If the PIC object exists, use it instead.
+ # $xdir was prepended to $pic_object above.
+ non_pic_object="$pic_object"
+ non_pic_objects="$non_pic_objects $non_pic_object"
+ fi
+ else
+ # Only an error if not doing a dry-run.
+ if test -z "$run"; then
+ $echo "$modename: \`$arg' is not a valid libtool object" 1>&2
+ exit $EXIT_FAILURE
+ else
+ # Dry-run case.
+
+ # Extract subdirectory from the argument.
+ xdir=`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'`
+ if test "X$xdir" = "X$arg"; then
+ xdir=
+ else
+ xdir="$xdir/"
+ fi
+
+ pic_object=`$echo "X${xdir}${objdir}/${arg}" | $Xsed -e "$lo2o"`
+ non_pic_object=`$echo "X${xdir}${arg}" | $Xsed -e "$lo2o"`
+ libobjs="$libobjs $pic_object"
+ non_pic_objects="$non_pic_objects $non_pic_object"
+ fi
+ fi
+ ;;
+
+ *.$libext)
+ # An archive.
+ deplibs="$deplibs $arg"
+ old_deplibs="$old_deplibs $arg"
+ continue
+ ;;
+
+ *.la)
+ # A libtool-controlled library.
+
+ if test "$prev" = dlfiles; then
+ # This library was specified with -dlopen.
+ dlfiles="$dlfiles $arg"
+ prev=
+ elif test "$prev" = dlprefiles; then
+ # The library was specified with -dlpreopen.
+ dlprefiles="$dlprefiles $arg"
+ prev=
+ else
+ deplibs="$deplibs $arg"
+ fi
+ continue
+ ;;
+
+ # Some other compiler argument.
+ *)
+ # Unknown arguments in both finalize_command and compile_command need
+ # to be aesthetically quoted because they are evaled later.
+ arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`
+ case $arg in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ arg="\"$arg\""
+ ;;
+ esac
+ ;;
+ esac # arg
+
+ # Now actually substitute the argument into the commands.
+ if test -n "$arg"; then
+ compile_command="$compile_command $arg"
+ finalize_command="$finalize_command $arg"
+ fi
+ done # argument parsing loop
+
+ if test -n "$prev"; then
+ $echo "$modename: the \`$prevarg' option requires an argument" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ if test "$export_dynamic" = yes && test -n "$export_dynamic_flag_spec"; then
+ eval arg=\"$export_dynamic_flag_spec\"
+ compile_command="$compile_command $arg"
+ finalize_command="$finalize_command $arg"
+ fi
+
+ oldlibs=
+ # calculate the name of the file, without its directory
+ outputname=`$echo "X$output" | $Xsed -e 's%^.*/%%'`
+ libobjs_save="$libobjs"
+
+ if test -n "$shlibpath_var"; then
+ # get the directories listed in $shlibpath_var
+ eval shlib_search_path=\`\$echo \"X\${$shlibpath_var}\" \| \$Xsed -e \'s/:/ /g\'\`
+ else
+ shlib_search_path=
+ fi
+ eval sys_lib_search_path=\"$sys_lib_search_path_spec\"
+ eval sys_lib_dlsearch_path=\"$sys_lib_dlsearch_path_spec\"
+
+ output_objdir=`$echo "X$output" | $Xsed -e 's%/[^/]*$%%'`
+ if test "X$output_objdir" = "X$output"; then
+ output_objdir="$objdir"
+ else
+ output_objdir="$output_objdir/$objdir"
+ fi
+ # Create the object directory.
+ if test ! -d "$output_objdir"; then
+ $show "$mkdir $output_objdir"
+ $run $mkdir $output_objdir
+ exit_status=$?
+ if test "$exit_status" -ne 0 && test ! -d "$output_objdir"; then
+ exit $exit_status
+ fi
+ fi
+
+ # Determine the type of output
+ case $output in
+ "")
+ $echo "$modename: you must specify an output file" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ *.$libext) linkmode=oldlib ;;
+ *.lo | *.$objext) linkmode=obj ;;
+ *.la) linkmode=lib ;;
+ *) linkmode=prog ;; # Anything else should be a program.
+ esac
+
+ case $host in
+ *cygwin* | *mingw* | *pw32*)
+ # don't eliminate duplications in $postdeps and $predeps
+ duplicate_compiler_generated_deps=yes
+ ;;
+ *)
+ duplicate_compiler_generated_deps=$duplicate_deps
+ ;;
+ esac
+ specialdeplibs=
+
+ libs=
+ # Find all interdependent deplibs by searching for libraries
+ # that are linked more than once (e.g. -la -lb -la)
+ for deplib in $deplibs; do
+ if test "X$duplicate_deps" = "Xyes" ; then
+ case "$libs " in
+ *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;;
+ esac
+ fi
+ libs="$libs $deplib"
+ done
+
+ if test "$linkmode" = lib; then
+ libs="$predeps $libs $compiler_lib_search_path $postdeps"
+
+ # Compute libraries that are listed more than once in $predeps
+ # $postdeps and mark them as special (i.e., whose duplicates are
+ # not to be eliminated).
+ pre_post_deps=
+ if test "X$duplicate_compiler_generated_deps" = "Xyes" ; then
+ for pre_post_dep in $predeps $postdeps; do
+ case "$pre_post_deps " in
+ *" $pre_post_dep "*) specialdeplibs="$specialdeplibs $pre_post_deps" ;;
+ esac
+ pre_post_deps="$pre_post_deps $pre_post_dep"
+ done
+ fi
+ pre_post_deps=
+ fi
+
+ deplibs=
+ newdependency_libs=
+ newlib_search_path=
+ need_relink=no # whether we're linking any uninstalled libtool libraries
+ notinst_deplibs= # not-installed libtool libraries
+ case $linkmode in
+ lib)
+ passes="conv link"
+ for file in $dlfiles $dlprefiles; do
+ case $file in
+ *.la) ;;
+ *)
+ $echo "$modename: libraries can \`-dlopen' only libtool libraries: $file" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+ done
+ ;;
+ prog)
+ compile_deplibs=
+ finalize_deplibs=
+ alldeplibs=no
+ newdlfiles=
+ newdlprefiles=
+ passes="conv scan dlopen dlpreopen link"
+ ;;
+ *) passes="conv"
+ ;;
+ esac
+ for pass in $passes; do
+ if test "$linkmode,$pass" = "lib,link" ||
+ test "$linkmode,$pass" = "prog,scan"; then
+ libs="$deplibs"
+ deplibs=
+ fi
+ if test "$linkmode" = prog; then
+ case $pass in
+ dlopen) libs="$dlfiles" ;;
+ dlpreopen) libs="$dlprefiles" ;;
+ link) libs="$deplibs %DEPLIBS% $dependency_libs" ;;
+ esac
+ fi
+ if test "$pass" = dlopen; then
+ # Collect dlpreopened libraries
+ save_deplibs="$deplibs"
+ deplibs=
+ fi
+ for deplib in $libs; do
+ lib=
+ found=no
+ case $deplib in
+ -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe|-threads)
+ if test "$linkmode,$pass" = "prog,link"; then
+ compile_deplibs="$deplib $compile_deplibs"
+ finalize_deplibs="$deplib $finalize_deplibs"
+ else
+ compiler_flags="$compiler_flags $deplib"
+ fi
+ continue
+ ;;
+ -l*)
+ if test "$linkmode" != lib && test "$linkmode" != prog; then
+ $echo "$modename: warning: \`-l' is ignored for archives/objects" 1>&2
+ continue
+ fi
+ name=`$echo "X$deplib" | $Xsed -e 's/^-l//'`
+ for searchdir in $newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path; do
+ for search_ext in .la $std_shrext .so .a; do
+ # Search the libtool library
+ lib="$searchdir/lib${name}${search_ext}"
+ if test -f "$lib"; then
+ if test "$search_ext" = ".la"; then
+ found=yes
+ else
+ found=no
+ fi
+ break 2
+ fi
+ done
+ done
+ if test "$found" != yes; then
+ # deplib doesn't seem to be a libtool library
+ if test "$linkmode,$pass" = "prog,link"; then
+ compile_deplibs="$deplib $compile_deplibs"
+ finalize_deplibs="$deplib $finalize_deplibs"
+ else
+ deplibs="$deplib $deplibs"
+ test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs"
+ fi
+ continue
+ else # deplib is a libtool library
+ # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib,
+ # We need to do some special things here, and not later.
+ if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+ case " $predeps $postdeps " in
+ *" $deplib "*)
+ if (${SED} -e '2q' $lib |
+ grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then
+ library_names=
+ old_library=
+ case $lib in
+ */* | *\\*) . $lib ;;
+ *) . ./$lib ;;
+ esac
+ for l in $old_library $library_names; do
+ ll="$l"
+ done
+ if test "X$ll" = "X$old_library" ; then # only static version available
+ found=no
+ ladir=`$echo "X$lib" | $Xsed -e 's%/[^/]*$%%'`
+ test "X$ladir" = "X$lib" && ladir="."
+ lib=$ladir/$old_library
+ if test "$linkmode,$pass" = "prog,link"; then
+ compile_deplibs="$deplib $compile_deplibs"
+ finalize_deplibs="$deplib $finalize_deplibs"
+ else
+ deplibs="$deplib $deplibs"
+ test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs"
+ fi
+ continue
+ fi
+ fi
+ ;;
+ *) ;;
+ esac
+ fi
+ fi
+ ;; # -l
+ -L*)
+ case $linkmode in
+ lib)
+ deplibs="$deplib $deplibs"
+ test "$pass" = conv && continue
+ newdependency_libs="$deplib $newdependency_libs"
+ newlib_search_path="$newlib_search_path "`$echo "X$deplib" | $Xsed -e 's/^-L//'`
+ ;;
+ prog)
+ if test "$pass" = conv; then
+ deplibs="$deplib $deplibs"
+ continue
+ fi
+ if test "$pass" = scan; then
+ deplibs="$deplib $deplibs"
+ else
+ compile_deplibs="$deplib $compile_deplibs"
+ finalize_deplibs="$deplib $finalize_deplibs"
+ fi
+ newlib_search_path="$newlib_search_path "`$echo "X$deplib" | $Xsed -e 's/^-L//'`
+ ;;
+ *)
+ $echo "$modename: warning: \`-L' is ignored for archives/objects" 1>&2
+ ;;
+ esac # linkmode
+ continue
+ ;; # -L
+ -R*)
+ if test "$pass" = link; then
+ dir=`$echo "X$deplib" | $Xsed -e 's/^-R//'`
+ # Make sure the xrpath contains only unique directories.
+ case "$xrpath " in
+ *" $dir "*) ;;
+ *) xrpath="$xrpath $dir" ;;
+ esac
+ fi
+ deplibs="$deplib $deplibs"
+ continue
+ ;;
+ *.la) lib="$deplib" ;;
+ *.$libext)
+ if test "$pass" = conv; then
+ deplibs="$deplib $deplibs"
+ continue
+ fi
+ case $linkmode in
+ lib)
+ valid_a_lib=no
+ case $deplibs_check_method in
+ match_pattern*)
+ set dummy $deplibs_check_method
+ match_pattern_regex=`expr "$deplibs_check_method" : "$2 \(.*\)"`
+ if eval $echo \"$deplib\" 2>/dev/null \
+ | $SED 10q \
+ | $EGREP "$match_pattern_regex" > /dev/null; then
+ valid_a_lib=yes
+ fi
+ ;;
+ pass_all)
+ valid_a_lib=yes
+ ;;
+ esac
+ if test "$valid_a_lib" != yes; then
+ $echo
+ $echo "*** Warning: Trying to link with static lib archive $deplib."
+ $echo "*** I have the capability to make that library automatically link in when"
+ $echo "*** you link to this library. But I can only do this if you have a"
+ $echo "*** shared version of the library, which you do not appear to have"
+ $echo "*** because the file extensions .$libext of this argument makes me believe"
+ $echo "*** that it is just a static archive that I should not used here."
+ else
+ $echo
+ $echo "*** Warning: Linking the shared library $output against the"
+ $echo "*** static library $deplib is not portable!"
+ deplibs="$deplib $deplibs"
+ fi
+ continue
+ ;;
+ prog)
+ if test "$pass" != link; then
+ deplibs="$deplib $deplibs"
+ else
+ compile_deplibs="$deplib $compile_deplibs"
+ finalize_deplibs="$deplib $finalize_deplibs"
+ fi
+ continue
+ ;;
+ esac # linkmode
+ ;; # *.$libext
+ *.lo | *.$objext)
+ if test "$pass" = conv; then
+ deplibs="$deplib $deplibs"
+ elif test "$linkmode" = prog; then
+ if test "$pass" = dlpreopen || test "$dlopen_support" != yes || test "$build_libtool_libs" = no; then
+ # If there is no dlopen support or we're linking statically,
+ # we need to preload.
+ newdlprefiles="$newdlprefiles $deplib"
+ compile_deplibs="$deplib $compile_deplibs"
+ finalize_deplibs="$deplib $finalize_deplibs"
+ else
+ newdlfiles="$newdlfiles $deplib"
+ fi
+ fi
+ continue
+ ;;
+ %DEPLIBS%)
+ alldeplibs=yes
+ continue
+ ;;
+ esac # case $deplib
+ if test "$found" = yes || test -f "$lib"; then :
+ else
+ $echo "$modename: cannot find the library \`$lib' or unhandled argument \`$deplib'" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ # Check to see that this really is a libtool archive.
+ if (${SED} -e '2q' $lib | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then :
+ else
+ $echo "$modename: \`$lib' is not a valid libtool archive" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ ladir=`$echo "X$lib" | $Xsed -e 's%/[^/]*$%%'`
+ test "X$ladir" = "X$lib" && ladir="."
+
+ dlname=
+ dlopen=
+ dlpreopen=
+ libdir=
+ library_names=
+ old_library=
+ # If the library was installed with an old release of libtool,
+ # it will not redefine variables installed, or shouldnotlink
+ installed=yes
+ shouldnotlink=no
+ avoidtemprpath=
+
+
+ # Read the .la file
+ case $lib in
+ */* | *\\*) . $lib ;;
+ *) . ./$lib ;;
+ esac
+
+ if test "$linkmode,$pass" = "lib,link" ||
+ test "$linkmode,$pass" = "prog,scan" ||
+ { test "$linkmode" != prog && test "$linkmode" != lib; }; then
+ test -n "$dlopen" && dlfiles="$dlfiles $dlopen"
+ test -n "$dlpreopen" && dlprefiles="$dlprefiles $dlpreopen"
+ fi
+
+ if test "$pass" = conv; then
+ # Only check for convenience libraries
+ deplibs="$lib $deplibs"
+ if test -z "$libdir"; then
+ if test -z "$old_library"; then
+ $echo "$modename: cannot find name of link library for \`$lib'" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ # It is a libtool convenience library, so add in its objects.
+ convenience="$convenience $ladir/$objdir/$old_library"
+ old_convenience="$old_convenience $ladir/$objdir/$old_library"
+ tmp_libs=
+ for deplib in $dependency_libs; do
+ deplibs="$deplib $deplibs"
+ if test "X$duplicate_deps" = "Xyes" ; then
+ case "$tmp_libs " in
+ *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;;
+ esac
+ fi
+ tmp_libs="$tmp_libs $deplib"
+ done
+ elif test "$linkmode" != prog && test "$linkmode" != lib; then
+ $echo "$modename: \`$lib' is not a convenience library" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ continue
+ fi # $pass = conv
+
+
+ # Get the name of the library we link against.
+ linklib=
+ for l in $old_library $library_names; do
+ linklib="$l"
+ done
+ if test -z "$linklib"; then
+ $echo "$modename: cannot find name of link library for \`$lib'" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ # This library was specified with -dlopen.
+ if test "$pass" = dlopen; then
+ if test -z "$libdir"; then
+ $echo "$modename: cannot -dlopen a convenience library: \`$lib'" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ if test -z "$dlname" ||
+ test "$dlopen_support" != yes ||
+ test "$build_libtool_libs" = no; then
+ # If there is no dlname, no dlopen support or we're linking
+ # statically, we need to preload. We also need to preload any
+ # dependent libraries so libltdl's deplib preloader doesn't
+ # bomb out in the load deplibs phase.
+ dlprefiles="$dlprefiles $lib $dependency_libs"
+ else
+ newdlfiles="$newdlfiles $lib"
+ fi
+ continue
+ fi # $pass = dlopen
+
+ # We need an absolute path.
+ case $ladir in
+ [\\/]* | [A-Za-z]:[\\/]*) abs_ladir="$ladir" ;;
+ *)
+ abs_ladir=`cd "$ladir" && pwd`
+ if test -z "$abs_ladir"; then
+ $echo "$modename: warning: cannot determine absolute directory name of \`$ladir'" 1>&2
+ $echo "$modename: passing it literally to the linker, although it might fail" 1>&2
+ abs_ladir="$ladir"
+ fi
+ ;;
+ esac
+ laname=`$echo "X$lib" | $Xsed -e 's%^.*/%%'`
+
+ # Find the relevant object directory and library name.
+ if test "X$installed" = Xyes; then
+ if test ! -f "$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then
+ $echo "$modename: warning: library \`$lib' was moved." 1>&2
+ dir="$ladir"
+ absdir="$abs_ladir"
+ libdir="$abs_ladir"
+ else
+ dir="$libdir"
+ absdir="$libdir"
+ fi
+ test "X$hardcode_automatic" = Xyes && avoidtemprpath=yes
+ else
+ if test ! -f "$ladir/$objdir/$linklib" && test -f "$abs_ladir/$linklib"; then
+ dir="$ladir"
+ absdir="$abs_ladir"
+ # Remove this search path later
+ notinst_path="$notinst_path $abs_ladir"
+ else
+ dir="$ladir/$objdir"
+ absdir="$abs_ladir/$objdir"
+ # Remove this search path later
+ notinst_path="$notinst_path $abs_ladir"
+ fi
+ fi # $installed = yes
+ name=`$echo "X$laname" | $Xsed -e 's/\.la$//' -e 's/^lib//'`
+
+ # This library was specified with -dlpreopen.
+ if test "$pass" = dlpreopen; then
+ if test -z "$libdir"; then
+ $echo "$modename: cannot -dlpreopen a convenience library: \`$lib'" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ # Prefer using a static library (so that no silly _DYNAMIC symbols
+ # are required to link).
+ if test -n "$old_library"; then
+ newdlprefiles="$newdlprefiles $dir/$old_library"
+ # Otherwise, use the dlname, so that lt_dlopen finds it.
+ elif test -n "$dlname"; then
+ newdlprefiles="$newdlprefiles $dir/$dlname"
+ else
+ newdlprefiles="$newdlprefiles $dir/$linklib"
+ fi
+ fi # $pass = dlpreopen
+
+ if test -z "$libdir"; then
+ # Link the convenience library
+ if test "$linkmode" = lib; then
+ deplibs="$dir/$old_library $deplibs"
+ elif test "$linkmode,$pass" = "prog,link"; then
+ compile_deplibs="$dir/$old_library $compile_deplibs"
+ finalize_deplibs="$dir/$old_library $finalize_deplibs"
+ else
+ deplibs="$lib $deplibs" # used for prog,scan pass
+ fi
+ continue
+ fi
+
+
+ if test "$linkmode" = prog && test "$pass" != link; then
+ newlib_search_path="$newlib_search_path $ladir"
+ deplibs="$lib $deplibs"
+
+ linkalldeplibs=no
+ if test "$link_all_deplibs" != no || test -z "$library_names" ||
+ test "$build_libtool_libs" = no; then
+ linkalldeplibs=yes
+ fi
+
+ tmp_libs=
+ for deplib in $dependency_libs; do
+ case $deplib in
+ -L*) newlib_search_path="$newlib_search_path "`$echo "X$deplib" | $Xsed -e 's/^-L//'`;; ### testsuite: skip nested quoting test
+ esac
+ # Need to link against all dependency_libs?
+ if test "$linkalldeplibs" = yes; then
+ deplibs="$deplib $deplibs"
+ else
+ # Need to hardcode shared library paths
+ # or/and link against static libraries
+ newdependency_libs="$deplib $newdependency_libs"
+ fi
+ if test "X$duplicate_deps" = "Xyes" ; then
+ case "$tmp_libs " in
+ *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;;
+ esac
+ fi
+ tmp_libs="$tmp_libs $deplib"
+ done # for deplib
+ continue
+ fi # $linkmode = prog...
+
+ if test "$linkmode,$pass" = "prog,link"; then
+ if test -n "$library_names" &&
+ { { test "$prefer_static_libs" = no ||
+ test "$prefer_static_libs,$installed" = "built,yes"; } ||
+ test -z "$old_library"; }; then
+ # We need to hardcode the library path
+ if test -n "$shlibpath_var" && test -z "$avoidtemprpath" ; then
+ # Make sure the rpath contains only unique directories.
+ case "$temp_rpath " in
+ *" $dir "*) ;;
+ *" $absdir "*) ;;
+ *) temp_rpath="$temp_rpath $absdir" ;;
+ esac
+ fi
+
+ # Hardcode the library path.
+ # Skip directories that are in the system default run-time
+ # search path.
+ case " $sys_lib_dlsearch_path " in
+ *" $absdir "*) ;;
+ *)
+ case "$compile_rpath " in
+ *" $absdir "*) ;;
+ *) compile_rpath="$compile_rpath $absdir"
+ esac
+ ;;
+ esac
+ case " $sys_lib_dlsearch_path " in
+ *" $libdir "*) ;;
+ *)
+ case "$finalize_rpath " in
+ *" $libdir "*) ;;
+ *) finalize_rpath="$finalize_rpath $libdir"
+ esac
+ ;;
+ esac
+ fi # $linkmode,$pass = prog,link...
+
+ if test "$alldeplibs" = yes &&
+ { test "$deplibs_check_method" = pass_all ||
+ { test "$build_libtool_libs" = yes &&
+ test -n "$library_names"; }; }; then
+ # We only need to search for static libraries
+ continue
+ fi
+ fi
+
+ link_static=no # Whether the deplib will be linked statically
+ use_static_libs=$prefer_static_libs
+ if test "$use_static_libs" = built && test "$installed" = yes ; then
+ use_static_libs=no
+ fi
+ if test -n "$library_names" &&
+ { test "$use_static_libs" = no || test -z "$old_library"; }; then
+ if test "$installed" = no; then
+ notinst_deplibs="$notinst_deplibs $lib"
+ need_relink=yes
+ fi
+ # This is a shared library
+
+ # Warn about portability, can't link against -module's on
+ # some systems (darwin)
+ if test "$shouldnotlink" = yes && test "$pass" = link ; then
+ $echo
+ if test "$linkmode" = prog; then
+ $echo "*** Warning: Linking the executable $output against the loadable module"
+ else
+ $echo "*** Warning: Linking the shared library $output against the loadable module"
+ fi
+ $echo "*** $linklib is not portable!"
+ fi
+ if test "$linkmode" = lib &&
+ test "$hardcode_into_libs" = yes; then
+ # Hardcode the library path.
+ # Skip directories that are in the system default run-time
+ # search path.
+ case " $sys_lib_dlsearch_path " in
+ *" $absdir "*) ;;
+ *)
+ case "$compile_rpath " in
+ *" $absdir "*) ;;
+ *) compile_rpath="$compile_rpath $absdir"
+ esac
+ ;;
+ esac
+ case " $sys_lib_dlsearch_path " in
+ *" $libdir "*) ;;
+ *)
+ case "$finalize_rpath " in
+ *" $libdir "*) ;;
+ *) finalize_rpath="$finalize_rpath $libdir"
+ esac
+ ;;
+ esac
+ fi
+
+ if test -n "$old_archive_from_expsyms_cmds"; then
+ # figure out the soname
+ set dummy $library_names
+ realname="$2"
+ shift; shift
+ libname=`eval \\$echo \"$libname_spec\"`
+ # use dlname if we got it. it's perfectly good, no?
+ if test -n "$dlname"; then
+ soname="$dlname"
+ elif test -n "$soname_spec"; then
+ # bleh windows
+ case $host in
+ *cygwin* | mingw*)
+ major=`expr $current - $age`
+ versuffix="-$major"
+ ;;
+ esac
+ eval soname=\"$soname_spec\"
+ else
+ soname="$realname"
+ fi
+
+ # Make a new name for the extract_expsyms_cmds to use
+ soroot="$soname"
+ soname=`$echo $soroot | ${SED} -e 's/^.*\///'`
+ newlib="libimp-`$echo $soname | ${SED} 's/^lib//;s/\.dll$//'`.a"
+
+ # If the library has no export list, then create one now
+ if test -f "$output_objdir/$soname-def"; then :
+ else
+ $show "extracting exported symbol list from \`$soname'"
+ save_ifs="$IFS"; IFS='~'
+ cmds=$extract_expsyms_cmds
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ eval cmd=\"$cmd\"
+ $show "$cmd"
+ $run eval "$cmd" || exit $?
+ done
+ IFS="$save_ifs"
+ fi
+
+ # Create $newlib
+ if test -f "$output_objdir/$newlib"; then :; else
+ $show "generating import library for \`$soname'"
+ save_ifs="$IFS"; IFS='~'
+ cmds=$old_archive_from_expsyms_cmds
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ eval cmd=\"$cmd\"
+ $show "$cmd"
+ $run eval "$cmd" || exit $?
+ done
+ IFS="$save_ifs"
+ fi
+ # make sure the library variables are pointing to the new library
+ dir=$output_objdir
+ linklib=$newlib
+ fi # test -n "$old_archive_from_expsyms_cmds"
+
+ if test "$linkmode" = prog || test "$mode" != relink; then
+ add_shlibpath=
+ add_dir=
+ add=
+ lib_linked=yes
+ case $hardcode_action in
+ immediate | unsupported)
+ if test "$hardcode_direct" = no; then
+ add="$dir/$linklib"
+ case $host in
+ *-*-sco3.2v5.0.[024]*) add_dir="-L$dir" ;;
+ *-*-sysv4*uw2*) add_dir="-L$dir" ;;
+ *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \
+ *-*-unixware7*) add_dir="-L$dir" ;;
+ *-*-darwin* )
+ # if the lib is a module then we can not link against
+ # it, someone is ignoring the new warnings I added
+ if /usr/bin/file -L $add 2> /dev/null |
+ $EGREP ": [^:]* bundle" >/dev/null ; then
+ $echo "** Warning, lib $linklib is a module, not a shared library"
+ if test -z "$old_library" ; then
+ $echo
+ $echo "** And there doesn't seem to be a static archive available"
+ $echo "** The link will probably fail, sorry"
+ else
+ add="$dir/$old_library"
+ fi
+ fi
+ esac
+ elif test "$hardcode_minus_L" = no; then
+ case $host in
+ *-*-sunos*) add_shlibpath="$dir" ;;
+ esac
+ add_dir="-L$dir"
+ add="-l$name"
+ elif test "$hardcode_shlibpath_var" = no; then
+ add_shlibpath="$dir"
+ add="-l$name"
+ else
+ lib_linked=no
+ fi
+ ;;
+ relink)
+ if test "$hardcode_direct" = yes; then
+ add="$dir/$linklib"
+ elif test "$hardcode_minus_L" = yes; then
+ add_dir="-L$dir"
+ # Try looking first in the location we're being installed to.
+ if test -n "$inst_prefix_dir"; then
+ case $libdir in
+ [\\/]*)
+ add_dir="$add_dir -L$inst_prefix_dir$libdir"
+ ;;
+ esac
+ fi
+ add="-l$name"
+ elif test "$hardcode_shlibpath_var" = yes; then
+ add_shlibpath="$dir"
+ add="-l$name"
+ else
+ lib_linked=no
+ fi
+ ;;
+ *) lib_linked=no ;;
+ esac
+
+ if test "$lib_linked" != yes; then
+ $echo "$modename: configuration error: unsupported hardcode properties"
+ exit $EXIT_FAILURE
+ fi
+
+ if test -n "$add_shlibpath"; then
+ case :$compile_shlibpath: in
+ *":$add_shlibpath:"*) ;;
+ *) compile_shlibpath="$compile_shlibpath$add_shlibpath:" ;;
+ esac
+ fi
+ if test "$linkmode" = prog; then
+ test -n "$add_dir" && compile_deplibs="$add_dir $compile_deplibs"
+ test -n "$add" && compile_deplibs="$add $compile_deplibs"
+ else
+ test -n "$add_dir" && deplibs="$add_dir $deplibs"
+ test -n "$add" && deplibs="$add $deplibs"
+ if test "$hardcode_direct" != yes && \
+ test "$hardcode_minus_L" != yes && \
+ test "$hardcode_shlibpath_var" = yes; then
+ case :$finalize_shlibpath: in
+ *":$libdir:"*) ;;
+ *) finalize_shlibpath="$finalize_shlibpath$libdir:" ;;
+ esac
+ fi
+ fi
+ fi
+
+ if test "$linkmode" = prog || test "$mode" = relink; then
+ add_shlibpath=
+ add_dir=
+ add=
+ # Finalize command for both is simple: just hardcode it.
+ if test "$hardcode_direct" = yes; then
+ add="$libdir/$linklib"
+ elif test "$hardcode_minus_L" = yes; then
+ add_dir="-L$libdir"
+ add="-l$name"
+ elif test "$hardcode_shlibpath_var" = yes; then
+ case :$finalize_shlibpath: in
+ *":$libdir:"*) ;;
+ *) finalize_shlibpath="$finalize_shlibpath$libdir:" ;;
+ esac
+ add="-l$name"
+ elif test "$hardcode_automatic" = yes; then
+ if test -n "$inst_prefix_dir" &&
+ test -f "$inst_prefix_dir$libdir/$linklib" ; then
+ add="$inst_prefix_dir$libdir/$linklib"
+ else
+ add="$libdir/$linklib"
+ fi
+ else
+ # We cannot seem to hardcode it, guess we'll fake it.
+ add_dir="-L$libdir"
+ # Try looking first in the location we're being installed to.
+ if test -n "$inst_prefix_dir"; then
+ case $libdir in
+ [\\/]*)
+ add_dir="$add_dir -L$inst_prefix_dir$libdir"
+ ;;
+ esac
+ fi
+ add="-l$name"
+ fi
+
+ if test "$linkmode" = prog; then
+ test -n "$add_dir" && finalize_deplibs="$add_dir $finalize_deplibs"
+ test -n "$add" && finalize_deplibs="$add $finalize_deplibs"
+ else
+ test -n "$add_dir" && deplibs="$add_dir $deplibs"
+ test -n "$add" && deplibs="$add $deplibs"
+ fi
+ fi
+ elif test "$linkmode" = prog; then
+ # Here we assume that one of hardcode_direct or hardcode_minus_L
+ # is not unsupported. This is valid on all known static and
+ # shared platforms.
+ if test "$hardcode_direct" != unsupported; then
+ test -n "$old_library" && linklib="$old_library"
+ compile_deplibs="$dir/$linklib $compile_deplibs"
+ finalize_deplibs="$dir/$linklib $finalize_deplibs"
+ else
+ compile_deplibs="-l$name -L$dir $compile_deplibs"
+ finalize_deplibs="-l$name -L$dir $finalize_deplibs"
+ fi
+ elif test "$build_libtool_libs" = yes; then
+ # Not a shared library
+ if test "$deplibs_check_method" != pass_all; then
+ # We're trying link a shared library against a static one
+ # but the system doesn't support it.
+
+ # Just print a warning and add the library to dependency_libs so
+ # that the program can be linked against the static library.
+ $echo
+ $echo "*** Warning: This system can not link to static lib archive $lib."
+ $echo "*** I have the capability to make that library automatically link in when"
+ $echo "*** you link to this library. But I can only do this if you have a"
+ $echo "*** shared version of the library, which you do not appear to have."
+ if test "$module" = yes; then
+ $echo "*** But as you try to build a module library, libtool will still create "
+ $echo "*** a static module, that should work as long as the dlopening application"
+ $echo "*** is linked with the -dlopen flag to resolve symbols at runtime."
+ if test -z "$global_symbol_pipe"; then
+ $echo
+ $echo "*** However, this would only work if libtool was able to extract symbol"
+ $echo "*** lists from a program, using \`nm' or equivalent, but libtool could"
+ $echo "*** not find such a program. So, this module is probably useless."
+ $echo "*** \`nm' from GNU binutils and a full rebuild may help."
+ fi
+ if test "$build_old_libs" = no; then
+ build_libtool_libs=module
+ build_old_libs=yes
+ else
+ build_libtool_libs=no
+ fi
+ fi
+ else
+ deplibs="$dir/$old_library $deplibs"
+ link_static=yes
+ fi
+ fi # link shared/static library?
+
+ if test "$linkmode" = lib; then
+ if test -n "$dependency_libs" &&
+ { test "$hardcode_into_libs" != yes ||
+ test "$build_old_libs" = yes ||
+ test "$link_static" = yes; }; then
+ # Extract -R from dependency_libs
+ temp_deplibs=
+ for libdir in $dependency_libs; do
+ case $libdir in
+ -R*) temp_xrpath=`$echo "X$libdir" | $Xsed -e 's/^-R//'`
+ case " $xrpath " in
+ *" $temp_xrpath "*) ;;
+ *) xrpath="$xrpath $temp_xrpath";;
+ esac;;
+ *) temp_deplibs="$temp_deplibs $libdir";;
+ esac
+ done
+ dependency_libs="$temp_deplibs"
+ fi
+
+ newlib_search_path="$newlib_search_path $absdir"
+ # Link against this library
+ test "$link_static" = no && newdependency_libs="$abs_ladir/$laname $newdependency_libs"
+ # ... and its dependency_libs
+ tmp_libs=
+ for deplib in $dependency_libs; do
+ newdependency_libs="$deplib $newdependency_libs"
+ if test "X$duplicate_deps" = "Xyes" ; then
+ case "$tmp_libs " in
+ *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;;
+ esac
+ fi
+ tmp_libs="$tmp_libs $deplib"
+ done
+
+ if test "$link_all_deplibs" != no; then
+ # Add the search paths of all dependency libraries
+ for deplib in $dependency_libs; do
+ case $deplib in
+ -L*) path="$deplib" ;;
+ *.la)
+ dir=`$echo "X$deplib" | $Xsed -e 's%/[^/]*$%%'`
+ test "X$dir" = "X$deplib" && dir="."
+ # We need an absolute path.
+ case $dir in
+ [\\/]* | [A-Za-z]:[\\/]*) absdir="$dir" ;;
+ *)
+ absdir=`cd "$dir" && pwd`
+ if test -z "$absdir"; then
+ $echo "$modename: warning: cannot determine absolute directory name of \`$dir'" 1>&2
+ absdir="$dir"
+ fi
+ ;;
+ esac
+ if grep "^installed=no" $deplib > /dev/null; then
+ path="$absdir/$objdir"
+ else
+ eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib`
+ if test -z "$libdir"; then
+ $echo "$modename: \`$deplib' is not a valid libtool archive" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ if test "$absdir" != "$libdir"; then
+ $echo "$modename: warning: \`$deplib' seems to be moved" 1>&2
+ fi
+ path="$absdir"
+ fi
+ depdepl=
+ case $host in
+ *-*-darwin*)
+ # we do not want to link against static libs,
+ # but need to link against shared
+ eval deplibrary_names=`${SED} -n -e 's/^library_names=\(.*\)$/\1/p' $deplib`
+ if test -n "$deplibrary_names" ; then
+ for tmp in $deplibrary_names ; do
+ depdepl=$tmp
+ done
+ if test -f "$path/$depdepl" ; then
+ depdepl="$path/$depdepl"
+ fi
+ # do not add paths which are already there
+ case " $newlib_search_path " in
+ *" $path "*) ;;
+ *) newlib_search_path="$newlib_search_path $path";;
+ esac
+ fi
+ path=""
+ ;;
+ *)
+ path="-L$path"
+ ;;
+ esac
+ ;;
+ -l*)
+ case $host in
+ *-*-darwin*)
+ # Again, we only want to link against shared libraries
+ eval tmp_libs=`$echo "X$deplib" | $Xsed -e "s,^\-l,,"`
+ for tmp in $newlib_search_path ; do
+ if test -f "$tmp/lib$tmp_libs.dylib" ; then
+ eval depdepl="$tmp/lib$tmp_libs.dylib"
+ break
+ fi
+ done
+ path=""
+ ;;
+ *) continue ;;
+ esac
+ ;;
+ *) continue ;;
+ esac
+ case " $deplibs " in
+ *" $path "*) ;;
+ *) deplibs="$path $deplibs" ;;
+ esac
+ case " $deplibs " in
+ *" $depdepl "*) ;;
+ *) deplibs="$depdepl $deplibs" ;;
+ esac
+ done
+ fi # link_all_deplibs != no
+ fi # linkmode = lib
+ done # for deplib in $libs
+ dependency_libs="$newdependency_libs"
+ if test "$pass" = dlpreopen; then
+ # Link the dlpreopened libraries before other libraries
+ for deplib in $save_deplibs; do
+ deplibs="$deplib $deplibs"
+ done
+ fi
+ if test "$pass" != dlopen; then
+ if test "$pass" != conv; then
+ # Make sure lib_search_path contains only unique directories.
+ lib_search_path=
+ for dir in $newlib_search_path; do
+ case "$lib_search_path " in
+ *" $dir "*) ;;
+ *) lib_search_path="$lib_search_path $dir" ;;
+ esac
+ done
+ newlib_search_path=
+ fi
+
+ if test "$linkmode,$pass" != "prog,link"; then
+ vars="deplibs"
+ else
+ vars="compile_deplibs finalize_deplibs"
+ fi
+ for var in $vars dependency_libs; do
+ # Add libraries to $var in reverse order
+ eval tmp_libs=\"\$$var\"
+ new_libs=
+ for deplib in $tmp_libs; do
+ # FIXME: Pedantically, this is the right thing to do, so
+ # that some nasty dependency loop isn't accidentally
+ # broken:
+ #new_libs="$deplib $new_libs"
+ # Pragmatically, this seems to cause very few problems in
+ # practice:
+ case $deplib in
+ -L*) new_libs="$deplib $new_libs" ;;
+ -R*) ;;
+ *)
+ # And here is the reason: when a library appears more
+ # than once as an explicit dependence of a library, or
+ # is implicitly linked in more than once by the
+ # compiler, it is considered special, and multiple
+ # occurrences thereof are not removed. Compare this
+ # with having the same library being listed as a
+ # dependency of multiple other libraries: in this case,
+ # we know (pedantically, we assume) the library does not
+ # need to be listed more than once, so we keep only the
+ # last copy. This is not always right, but it is rare
+ # enough that we require users that really mean to play
+ # such unportable linking tricks to link the library
+ # using -Wl,-lname, so that libtool does not consider it
+ # for duplicate removal.
+ case " $specialdeplibs " in
+ *" $deplib "*) new_libs="$deplib $new_libs" ;;
+ *)
+ case " $new_libs " in
+ *" $deplib "*) ;;
+ *) new_libs="$deplib $new_libs" ;;
+ esac
+ ;;
+ esac
+ ;;
+ esac
+ done
+ tmp_libs=
+ for deplib in $new_libs; do
+ case $deplib in
+ -L*)
+ case " $tmp_libs " in
+ *" $deplib "*) ;;
+ *) tmp_libs="$tmp_libs $deplib" ;;
+ esac
+ ;;
+ *) tmp_libs="$tmp_libs $deplib" ;;
+ esac
+ done
+ eval $var=\"$tmp_libs\"
+ done # for var
+ fi
+ # Last step: remove runtime libs from dependency_libs
+ # (they stay in deplibs)
+ tmp_libs=
+ for i in $dependency_libs ; do
+ case " $predeps $postdeps $compiler_lib_search_path " in
+ *" $i "*)
+ i=""
+ ;;
+ esac
+ if test -n "$i" ; then
+ tmp_libs="$tmp_libs $i"
+ fi
+ done
+ dependency_libs=$tmp_libs
+ done # for pass
+ if test "$linkmode" = prog; then
+ dlfiles="$newdlfiles"
+ dlprefiles="$newdlprefiles"
+ fi
+
+ case $linkmode in
+ oldlib)
+ if test -n "$deplibs"; then
+ $echo "$modename: warning: \`-l' and \`-L' are ignored for archives" 1>&2
+ fi
+
+ if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then
+ $echo "$modename: warning: \`-dlopen' is ignored for archives" 1>&2
+ fi
+
+ if test -n "$rpath"; then
+ $echo "$modename: warning: \`-rpath' is ignored for archives" 1>&2
+ fi
+
+ if test -n "$xrpath"; then
+ $echo "$modename: warning: \`-R' is ignored for archives" 1>&2
+ fi
+
+ if test -n "$vinfo"; then
+ $echo "$modename: warning: \`-version-info/-version-number' is ignored for archives" 1>&2
+ fi
+
+ if test -n "$release"; then
+ $echo "$modename: warning: \`-release' is ignored for archives" 1>&2
+ fi
+
+ if test -n "$export_symbols" || test -n "$export_symbols_regex"; then
+ $echo "$modename: warning: \`-export-symbols' is ignored for archives" 1>&2
+ fi
+
+ # Now set the variables for building old libraries.
+ build_libtool_libs=no
+ oldlibs="$output"
+ objs="$objs$old_deplibs"
+ ;;
+
+ lib)
+ # Make sure we only generate libraries of the form `libNAME.la'.
+ case $outputname in
+ lib*)
+ name=`$echo "X$outputname" | $Xsed -e 's/\.la$//' -e 's/^lib//'`
+ eval shared_ext=\"$shrext_cmds\"
+ eval libname=\"$libname_spec\"
+ ;;
+ *)
+ if test "$module" = no; then
+ $echo "$modename: libtool library \`$output' must begin with \`lib'" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ if test "$need_lib_prefix" != no; then
+ # Add the "lib" prefix for modules if required
+ name=`$echo "X$outputname" | $Xsed -e 's/\.la$//'`
+ eval shared_ext=\"$shrext_cmds\"
+ eval libname=\"$libname_spec\"
+ else
+ libname=`$echo "X$outputname" | $Xsed -e 's/\.la$//'`
+ fi
+ ;;
+ esac
+
+ if test -n "$objs"; then
+ if test "$deplibs_check_method" != pass_all; then
+ $echo "$modename: cannot build libtool library \`$output' from non-libtool objects on this host:$objs" 2>&1
+ exit $EXIT_FAILURE
+ else
+ $echo
+ $echo "*** Warning: Linking the shared library $output against the non-libtool"
+ $echo "*** objects $objs is not portable!"
+ libobjs="$libobjs $objs"
+ fi
+ fi
+
+ if test "$dlself" != no; then
+ $echo "$modename: warning: \`-dlopen self' is ignored for libtool libraries" 1>&2
+ fi
+
+ set dummy $rpath
+ if test "$#" -gt 2; then
+ $echo "$modename: warning: ignoring multiple \`-rpath's for a libtool library" 1>&2
+ fi
+ install_libdir="$2"
+
+ oldlibs=
+ if test -z "$rpath"; then
+ if test "$build_libtool_libs" = yes; then
+ # Building a libtool convenience library.
+ # Some compilers have problems with a `.al' extension so
+ # convenience libraries should have the same extension an
+ # archive normally would.
+ oldlibs="$output_objdir/$libname.$libext $oldlibs"
+ build_libtool_libs=convenience
+ build_old_libs=yes
+ fi
+
+ if test -n "$vinfo"; then
+ $echo "$modename: warning: \`-version-info/-version-number' is ignored for convenience libraries" 1>&2
+ fi
+
+ if test -n "$release"; then
+ $echo "$modename: warning: \`-release' is ignored for convenience libraries" 1>&2
+ fi
+ else
+
+ # Parse the version information argument.
+ save_ifs="$IFS"; IFS=':'
+ set dummy $vinfo 0 0 0
+ IFS="$save_ifs"
+
+ if test -n "$8"; then
+ $echo "$modename: too many parameters to \`-version-info'" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ # convert absolute version numbers to libtool ages
+ # this retains compatibility with .la files and attempts
+ # to make the code below a bit more comprehensible
+
+ case $vinfo_number in
+ yes)
+ number_major="$2"
+ number_minor="$3"
+ number_revision="$4"
+ #
+ # There are really only two kinds -- those that
+ # use the current revision as the major version
+ # and those that subtract age and use age as
+ # a minor version. But, then there is irix
+ # which has an extra 1 added just for fun
+ #
+ case $version_type in
+ darwin|linux|osf|windows|none)
+ current=`expr $number_major + $number_minor`
+ age="$number_minor"
+ revision="$number_revision"
+ ;;
+ freebsd-aout|freebsd-elf|sunos)
+ current="$number_major"
+ revision="$number_minor"
+ age="0"
+ ;;
+ irix|nonstopux)
+ current=`expr $number_major + $number_minor`
+ age="$number_minor"
+ revision="$number_minor"
+ lt_irix_increment=no
+ ;;
+ esac
+ ;;
+ no)
+ current="$2"
+ revision="$3"
+ age="$4"
+ ;;
+ esac
+
+ # Check that each of the things are valid numbers.
+ case $current in
+ 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;
+ *)
+ $echo "$modename: CURRENT \`$current' must be a nonnegative integer" 1>&2
+ $echo "$modename: \`$vinfo' is not valid version information" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+
+ case $revision in
+ 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;
+ *)
+ $echo "$modename: REVISION \`$revision' must be a nonnegative integer" 1>&2
+ $echo "$modename: \`$vinfo' is not valid version information" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+
+ case $age in
+ 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;
+ *)
+ $echo "$modename: AGE \`$age' must be a nonnegative integer" 1>&2
+ $echo "$modename: \`$vinfo' is not valid version information" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+
+ if test "$age" -gt "$current"; then
+ $echo "$modename: AGE \`$age' is greater than the current interface number \`$current'" 1>&2
+ $echo "$modename: \`$vinfo' is not valid version information" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ # Calculate the version variables.
+ major=
+ versuffix=
+ verstring=
+ case $version_type in
+ none) ;;
+
+ darwin)
+ # Like Linux, but with the current version available in
+ # verstring for coding it into the library header
+ major=.`expr $current - $age`
+ versuffix="$major.$age.$revision"
+ # Darwin ld doesn't like 0 for these options...
+ minor_current=`expr $current + 1`
+ xlcverstring="${wl}-compatibility_version ${wl}$minor_current ${wl}-current_version ${wl}$minor_current.$revision"
+ verstring="-compatibility_version $minor_current -current_version $minor_current.$revision"
+ ;;
+
+ freebsd-aout)
+ major=".$current"
+ versuffix=".$current.$revision";
+ ;;
+
+ freebsd-elf)
+ major=".$current"
+ versuffix=".$current";
+ ;;
+
+ irix | nonstopux)
+ if test "X$lt_irix_increment" = "Xno"; then
+ major=`expr $current - $age`
+ else
+ major=`expr $current - $age + 1`
+ fi
+ case $version_type in
+ nonstopux) verstring_prefix=nonstopux ;;
+ *) verstring_prefix=sgi ;;
+ esac
+ verstring="$verstring_prefix$major.$revision"
+
+ # Add in all the interfaces that we are compatible with.
+ loop=$revision
+ while test "$loop" -ne 0; do
+ iface=`expr $revision - $loop`
+ loop=`expr $loop - 1`
+ verstring="$verstring_prefix$major.$iface:$verstring"
+ done
+
+ # Before this point, $major must not contain `.'.
+ major=.$major
+ versuffix="$major.$revision"
+ ;;
+
+ linux)
+ major=.`expr $current - $age`
+ versuffix="$major.$age.$revision"
+ ;;
+
+ osf)
+ major=.`expr $current - $age`
+ versuffix=".$current.$age.$revision"
+ verstring="$current.$age.$revision"
+
+ # Add in all the interfaces that we are compatible with.
+ loop=$age
+ while test "$loop" -ne 0; do
+ iface=`expr $current - $loop`
+ loop=`expr $loop - 1`
+ verstring="$verstring:${iface}.0"
+ done
+
+ # Make executables depend on our current version.
+ verstring="$verstring:${current}.0"
+ ;;
+
+ sunos)
+ major=".$current"
+ versuffix=".$current.$revision"
+ ;;
+
+ windows)
+ # Use '-' rather than '.', since we only want one
+ # extension on DOS 8.3 filesystems.
+ major=`expr $current - $age`
+ versuffix="-$major"
+ ;;
+
+ *)
+ $echo "$modename: unknown library version type \`$version_type'" 1>&2
+ $echo "Fatal configuration error. See the $PACKAGE docs for more information." 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+
+ # Clear the version info if we defaulted, and they specified a release.
+ if test -z "$vinfo" && test -n "$release"; then
+ major=
+ case $version_type in
+ darwin)
+ # we can't check for "0.0" in archive_cmds due to quoting
+ # problems, so we reset it completely
+ verstring=
+ ;;
+ *)
+ verstring="0.0"
+ ;;
+ esac
+ if test "$need_version" = no; then
+ versuffix=
+ else
+ versuffix=".0.0"
+ fi
+ fi
+
+ # Remove version info from name if versioning should be avoided
+ if test "$avoid_version" = yes && test "$need_version" = no; then
+ major=
+ versuffix=
+ verstring=""
+ fi
+
+ # Check to see if the archive will have undefined symbols.
+ if test "$allow_undefined" = yes; then
+ if test "$allow_undefined_flag" = unsupported; then
+ $echo "$modename: warning: undefined symbols not allowed in $host shared libraries" 1>&2
+ build_libtool_libs=no
+ build_old_libs=yes
+ fi
+ else
+ # Don't allow undefined symbols.
+ allow_undefined_flag="$no_undefined_flag"
+ fi
+ fi
+
+ if test "$mode" != relink; then
+ # Remove our outputs, but don't remove object files since they
+ # may have been created when compiling PIC objects.
+ removelist=
+ tempremovelist=`$echo "$output_objdir/*"`
+ for p in $tempremovelist; do
+ case $p in
+ *.$objext)
+ ;;
+ $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/${libname}${release}.*)
+ if test "X$precious_files_regex" != "X"; then
+ if echo $p | $EGREP -e "$precious_files_regex" >/dev/null 2>&1
+ then
+ continue
+ fi
+ fi
+ removelist="$removelist $p"
+ ;;
+ *) ;;
+ esac
+ done
+ if test -n "$removelist"; then
+ $show "${rm}r $removelist"
+ $run ${rm}r $removelist
+ fi
+ fi
+
+ # Now set the variables for building old libraries.
+ if test "$build_old_libs" = yes && test "$build_libtool_libs" != convenience ; then
+ oldlibs="$oldlibs $output_objdir/$libname.$libext"
+
+ # Transform .lo files to .o files.
+ oldobjs="$objs "`$echo "X$libobjs" | $SP2NL | $Xsed -e '/\.'${libext}'$/d' -e "$lo2o" | $NL2SP`
+ fi
+
+ # Eliminate all temporary directories.
+ #for path in $notinst_path; do
+ # lib_search_path=`$echo "$lib_search_path " | ${SED} -e "s% $path % %g"`
+ # deplibs=`$echo "$deplibs " | ${SED} -e "s% -L$path % %g"`
+ # dependency_libs=`$echo "$dependency_libs " | ${SED} -e "s% -L$path % %g"`
+ #done
+
+ if test -n "$xrpath"; then
+ # If the user specified any rpath flags, then add them.
+ temp_xrpath=
+ for libdir in $xrpath; do
+ temp_xrpath="$temp_xrpath -R$libdir"
+ case "$finalize_rpath " in
+ *" $libdir "*) ;;
+ *) finalize_rpath="$finalize_rpath $libdir" ;;
+ esac
+ done
+ if test "$hardcode_into_libs" != yes || test "$build_old_libs" = yes; then
+ dependency_libs="$temp_xrpath $dependency_libs"
+ fi
+ fi
+
+ # Make sure dlfiles contains only unique files that won't be dlpreopened
+ old_dlfiles="$dlfiles"
+ dlfiles=
+ for lib in $old_dlfiles; do
+ case " $dlprefiles $dlfiles " in
+ *" $lib "*) ;;
+ *) dlfiles="$dlfiles $lib" ;;
+ esac
+ done
+
+ # Make sure dlprefiles contains only unique files
+ old_dlprefiles="$dlprefiles"
+ dlprefiles=
+ for lib in $old_dlprefiles; do
+ case "$dlprefiles " in
+ *" $lib "*) ;;
+ *) dlprefiles="$dlprefiles $lib" ;;
+ esac
+ done
+
+ if test "$build_libtool_libs" = yes; then
+ if test -n "$rpath"; then
+ case $host in
+ *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos*)
+ # these systems don't actually have a c library (as such)!
+ ;;
+ *-*-rhapsody* | *-*-darwin1.[012])
+ # Rhapsody C library is in the System framework
+ deplibs="$deplibs -framework System"
+ ;;
+ *-*-netbsd*)
+ # Don't link with libc until the a.out ld.so is fixed.
+ ;;
+ *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)
+ # Do not include libc due to us having libc/libc_r.
+ ;;
+ *-*-sco3.2v5* | *-*-sco5v6*)
+ # Causes problems with __ctype
+ ;;
+ *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)
+ # Compiler inserts libc in the correct place for threads to work
+ ;;
+ *)
+ # Add libc to deplibs on all other systems if necessary.
+ if test "$build_libtool_need_lc" = "yes"; then
+ deplibs="$deplibs -lc"
+ fi
+ ;;
+ esac
+ fi
+
+ # Transform deplibs into only deplibs that can be linked in shared.
+ name_save=$name
+ libname_save=$libname
+ release_save=$release
+ versuffix_save=$versuffix
+ major_save=$major
+ # I'm not sure if I'm treating the release correctly. I think
+ # release should show up in the -l (ie -lgmp5) so we don't want to
+ # add it in twice. Is that correct?
+ release=""
+ versuffix=""
+ major=""
+ newdeplibs=
+ droppeddeps=no
+ case $deplibs_check_method in
+ pass_all)
+ # Don't check for shared/static. Everything works.
+ # This might be a little naive. We might want to check
+ # whether the library exists or not. But this is on
+ # osf3 & osf4 and I'm not really sure... Just
+ # implementing what was already the behavior.
+ newdeplibs=$deplibs
+ ;;
+ test_compile)
+ # This code stresses the "libraries are programs" paradigm to its
+ # limits. Maybe even breaks it. We compile a program, linking it
+ # against the deplibs as a proxy for the library. Then we can check
+ # whether they linked in statically or dynamically with ldd.
+ $rm conftest.c
+ cat > conftest.c <<EOF
+ int main() { return 0; }
+EOF
+ $rm conftest
+ if $LTCC $LTCFLAGS -o conftest conftest.c $deplibs; then
+ ldd_output=`ldd conftest`
+ for i in $deplibs; do
+ name=`expr $i : '-l\(.*\)'`
+ # If $name is empty we are operating on a -L argument.
+ if test "$name" != "" && test "$name" != "0"; then
+ if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+ case " $predeps $postdeps " in
+ *" $i "*)
+ newdeplibs="$newdeplibs $i"
+ i=""
+ ;;
+ esac
+ fi
+ if test -n "$i" ; then
+ libname=`eval \\$echo \"$libname_spec\"`
+ deplib_matches=`eval \\$echo \"$library_names_spec\"`
+ set dummy $deplib_matches
+ deplib_match=$2
+ if test `expr "$ldd_output" : ".*$deplib_match"` -ne 0 ; then
+ newdeplibs="$newdeplibs $i"
+ else
+ droppeddeps=yes
+ $echo
+ $echo "*** Warning: dynamic linker does not accept needed library $i."
+ $echo "*** I have the capability to make that library automatically link in when"
+ $echo "*** you link to this library. But I can only do this if you have a"
+ $echo "*** shared version of the library, which I believe you do not have"
+ $echo "*** because a test_compile did reveal that the linker did not use it for"
+ $echo "*** its dynamic dependency list that programs get resolved with at runtime."
+ fi
+ fi
+ else
+ newdeplibs="$newdeplibs $i"
+ fi
+ done
+ else
+ # Error occurred in the first compile. Let's try to salvage
+ # the situation: Compile a separate program for each library.
+ for i in $deplibs; do
+ name=`expr $i : '-l\(.*\)'`
+ # If $name is empty we are operating on a -L argument.
+ if test "$name" != "" && test "$name" != "0"; then
+ $rm conftest
+ if $LTCC $LTCFLAGS -o conftest conftest.c $i; then
+ ldd_output=`ldd conftest`
+ if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+ case " $predeps $postdeps " in
+ *" $i "*)
+ newdeplibs="$newdeplibs $i"
+ i=""
+ ;;
+ esac
+ fi
+ if test -n "$i" ; then
+ libname=`eval \\$echo \"$libname_spec\"`
+ deplib_matches=`eval \\$echo \"$library_names_spec\"`
+ set dummy $deplib_matches
+ deplib_match=$2
+ if test `expr "$ldd_output" : ".*$deplib_match"` -ne 0 ; then
+ newdeplibs="$newdeplibs $i"
+ else
+ droppeddeps=yes
+ $echo
+ $echo "*** Warning: dynamic linker does not accept needed library $i."
+ $echo "*** I have the capability to make that library automatically link in when"
+ $echo "*** you link to this library. But I can only do this if you have a"
+ $echo "*** shared version of the library, which you do not appear to have"
+ $echo "*** because a test_compile did reveal that the linker did not use this one"
+ $echo "*** as a dynamic dependency that programs can get resolved with at runtime."
+ fi
+ fi
+ else
+ droppeddeps=yes
+ $echo
+ $echo "*** Warning! Library $i is needed by this library but I was not able to"
+ $echo "*** make it link in! You will probably need to install it or some"
+ $echo "*** library that it depends on before this library will be fully"
+ $echo "*** functional. Installing it before continuing would be even better."
+ fi
+ else
+ newdeplibs="$newdeplibs $i"
+ fi
+ done
+ fi
+ ;;
+ file_magic*)
+ set dummy $deplibs_check_method
+ file_magic_regex=`expr "$deplibs_check_method" : "$2 \(.*\)"`
+ for a_deplib in $deplibs; do
+ name=`expr $a_deplib : '-l\(.*\)'`
+ # If $name is empty we are operating on a -L argument.
+ if test "$name" != "" && test "$name" != "0"; then
+ if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+ case " $predeps $postdeps " in
+ *" $a_deplib "*)
+ newdeplibs="$newdeplibs $a_deplib"
+ a_deplib=""
+ ;;
+ esac
+ fi
+ if test -n "$a_deplib" ; then
+ libname=`eval \\$echo \"$libname_spec\"`
+ for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do
+ potential_libs=`ls $i/$libname[.-]* 2>/dev/null`
+ for potent_lib in $potential_libs; do
+ # Follow soft links.
+ if ls -lLd "$potent_lib" 2>/dev/null \
+ | grep " -> " >/dev/null; then
+ continue
+ fi
+ # The statement above tries to avoid entering an
+ # endless loop below, in case of cyclic links.
+ # We might still enter an endless loop, since a link
+ # loop can be closed while we follow links,
+ # but so what?
+ potlib="$potent_lib"
+ while test -h "$potlib" 2>/dev/null; do
+ potliblink=`ls -ld $potlib | ${SED} 's/.* -> //'`
+ case $potliblink in
+ [\\/]* | [A-Za-z]:[\\/]*) potlib="$potliblink";;
+ *) potlib=`$echo "X$potlib" | $Xsed -e 's,[^/]*$,,'`"$potliblink";;
+ esac
+ done
+ if eval $file_magic_cmd \"\$potlib\" 2>/dev/null \
+ | ${SED} 10q \
+ | $EGREP "$file_magic_regex" > /dev/null; then
+ newdeplibs="$newdeplibs $a_deplib"
+ a_deplib=""
+ break 2
+ fi
+ done
+ done
+ fi
+ if test -n "$a_deplib" ; then
+ droppeddeps=yes
+ $echo
+ $echo "*** Warning: linker path does not have real file for library $a_deplib."
+ $echo "*** I have the capability to make that library automatically link in when"
+ $echo "*** you link to this library. But I can only do this if you have a"
+ $echo "*** shared version of the library, which you do not appear to have"
+ $echo "*** because I did check the linker path looking for a file starting"
+ if test -z "$potlib" ; then
+ $echo "*** with $libname but no candidates were found. (...for file magic test)"
+ else
+ $echo "*** with $libname and none of the candidates passed a file format test"
+ $echo "*** using a file magic. Last file checked: $potlib"
+ fi
+ fi
+ else
+ # Add a -L argument.
+ newdeplibs="$newdeplibs $a_deplib"
+ fi
+ done # Gone through all deplibs.
+ ;;
+ match_pattern*)
+ set dummy $deplibs_check_method
+ match_pattern_regex=`expr "$deplibs_check_method" : "$2 \(.*\)"`
+ for a_deplib in $deplibs; do
+ name=`expr $a_deplib : '-l\(.*\)'`
+ # If $name is empty we are operating on a -L argument.
+ if test -n "$name" && test "$name" != "0"; then
+ if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+ case " $predeps $postdeps " in
+ *" $a_deplib "*)
+ newdeplibs="$newdeplibs $a_deplib"
+ a_deplib=""
+ ;;
+ esac
+ fi
+ if test -n "$a_deplib" ; then
+ libname=`eval \\$echo \"$libname_spec\"`
+ for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do
+ potential_libs=`ls $i/$libname[.-]* 2>/dev/null`
+ for potent_lib in $potential_libs; do
+ potlib="$potent_lib" # see symlink-check above in file_magic test
+ if eval $echo \"$potent_lib\" 2>/dev/null \
+ | ${SED} 10q \
+ | $EGREP "$match_pattern_regex" > /dev/null; then
+ newdeplibs="$newdeplibs $a_deplib"
+ a_deplib=""
+ break 2
+ fi
+ done
+ done
+ fi
+ if test -n "$a_deplib" ; then
+ droppeddeps=yes
+ $echo
+ $echo "*** Warning: linker path does not have real file for library $a_deplib."
+ $echo "*** I have the capability to make that library automatically link in when"
+ $echo "*** you link to this library. But I can only do this if you have a"
+ $echo "*** shared version of the library, which you do not appear to have"
+ $echo "*** because I did check the linker path looking for a file starting"
+ if test -z "$potlib" ; then
+ $echo "*** with $libname but no candidates were found. (...for regex pattern test)"
+ else
+ $echo "*** with $libname and none of the candidates passed a file format test"
+ $echo "*** using a regex pattern. Last file checked: $potlib"
+ fi
+ fi
+ else
+ # Add a -L argument.
+ newdeplibs="$newdeplibs $a_deplib"
+ fi
+ done # Gone through all deplibs.
+ ;;
+ none | unknown | *)
+ newdeplibs=""
+ tmp_deplibs=`$echo "X $deplibs" | $Xsed -e 's/ -lc$//' \
+ -e 's/ -[LR][^ ]*//g'`
+ if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+ for i in $predeps $postdeps ; do
+ # can't use Xsed below, because $i might contain '/'
+ tmp_deplibs=`$echo "X $tmp_deplibs" | ${SED} -e "1s,^X,," -e "s,$i,,"`
+ done
+ fi
+ if $echo "X $tmp_deplibs" | $Xsed -e 's/[ ]//g' \
+ | grep . >/dev/null; then
+ $echo
+ if test "X$deplibs_check_method" = "Xnone"; then
+ $echo "*** Warning: inter-library dependencies are not supported in this platform."
+ else
+ $echo "*** Warning: inter-library dependencies are not known to be supported."
+ fi
+ $echo "*** All declared inter-library dependencies are being dropped."
+ droppeddeps=yes
+ fi
+ ;;
+ esac
+ versuffix=$versuffix_save
+ major=$major_save
+ release=$release_save
+ libname=$libname_save
+ name=$name_save
+
+ case $host in
+ *-*-rhapsody* | *-*-darwin1.[012])
+ # On Rhapsody replace the C library is the System framework
+ newdeplibs=`$echo "X $newdeplibs" | $Xsed -e 's/ -lc / -framework System /'`
+ ;;
+ esac
+
+ if test "$droppeddeps" = yes; then
+ if test "$module" = yes; then
+ $echo
+ $echo "*** Warning: libtool could not satisfy all declared inter-library"
+ $echo "*** dependencies of module $libname. Therefore, libtool will create"
+ $echo "*** a static module, that should work as long as the dlopening"
+ $echo "*** application is linked with the -dlopen flag."
+ if test -z "$global_symbol_pipe"; then
+ $echo
+ $echo "*** However, this would only work if libtool was able to extract symbol"
+ $echo "*** lists from a program, using \`nm' or equivalent, but libtool could"
+ $echo "*** not find such a program. So, this module is probably useless."
+ $echo "*** \`nm' from GNU binutils and a full rebuild may help."
+ fi
+ if test "$build_old_libs" = no; then
+ oldlibs="$output_objdir/$libname.$libext"
+ build_libtool_libs=module
+ build_old_libs=yes
+ else
+ build_libtool_libs=no
+ fi
+ else
+ $echo "*** The inter-library dependencies that have been dropped here will be"
+ $echo "*** automatically added whenever a program is linked with this library"
+ $echo "*** or is declared to -dlopen it."
+
+ if test "$allow_undefined" = no; then
+ $echo
+ $echo "*** Since this library must not contain undefined symbols,"
+ $echo "*** because either the platform does not support them or"
+ $echo "*** it was explicitly requested with -no-undefined,"
+ $echo "*** libtool will only create a static version of it."
+ if test "$build_old_libs" = no; then
+ oldlibs="$output_objdir/$libname.$libext"
+ build_libtool_libs=module
+ build_old_libs=yes
+ else
+ build_libtool_libs=no
+ fi
+ fi
+ fi
+ fi
+ # Done checking deplibs!
+ deplibs=$newdeplibs
+ fi
+
+
+ # move library search paths that coincide with paths to not yet
+ # installed libraries to the beginning of the library search list
+ new_libs=
+ for path in $notinst_path; do
+ case " $new_libs " in
+ *" -L$path/$objdir "*) ;;
+ *)
+ case " $deplibs " in
+ *" -L$path/$objdir "*)
+ new_libs="$new_libs -L$path/$objdir" ;;
+ esac
+ ;;
+ esac
+ done
+ for deplib in $deplibs; do
+ case $deplib in
+ -L*)
+ case " $new_libs " in
+ *" $deplib "*) ;;
+ *) new_libs="$new_libs $deplib" ;;
+ esac
+ ;;
+ *) new_libs="$new_libs $deplib" ;;
+ esac
+ done
+ deplibs="$new_libs"
+
+
+ # All the library-specific variables (install_libdir is set above).
+ library_names=
+ old_library=
+ dlname=
+
+ # Test again, we may have decided not to build it any more
+ if test "$build_libtool_libs" = yes; then
+ if test "$hardcode_into_libs" = yes; then
+ # Hardcode the library paths
+ hardcode_libdirs=
+ dep_rpath=
+ rpath="$finalize_rpath"
+ test "$mode" != relink && rpath="$compile_rpath$rpath"
+ for libdir in $rpath; do
+ if test -n "$hardcode_libdir_flag_spec"; then
+ if test -n "$hardcode_libdir_separator"; then
+ if test -z "$hardcode_libdirs"; then
+ hardcode_libdirs="$libdir"
+ else
+ # Just accumulate the unique libdirs.
+ case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in
+ *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*)
+ ;;
+ *)
+ hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir"
+ ;;
+ esac
+ fi
+ else
+ eval flag=\"$hardcode_libdir_flag_spec\"
+ dep_rpath="$dep_rpath $flag"
+ fi
+ elif test -n "$runpath_var"; then
+ case "$perm_rpath " in
+ *" $libdir "*) ;;
+ *) perm_rpath="$perm_rpath $libdir" ;;
+ esac
+ fi
+ done
+ # Substitute the hardcoded libdirs into the rpath.
+ if test -n "$hardcode_libdir_separator" &&
+ test -n "$hardcode_libdirs"; then
+ libdir="$hardcode_libdirs"
+ if test -n "$hardcode_libdir_flag_spec_ld"; then
+ case $archive_cmds in
+ *\$LD*) eval dep_rpath=\"$hardcode_libdir_flag_spec_ld\" ;;
+ *) eval dep_rpath=\"$hardcode_libdir_flag_spec\" ;;
+ esac
+ else
+ eval dep_rpath=\"$hardcode_libdir_flag_spec\"
+ fi
+ fi
+ if test -n "$runpath_var" && test -n "$perm_rpath"; then
+ # We should set the runpath_var.
+ rpath=
+ for dir in $perm_rpath; do
+ rpath="$rpath$dir:"
+ done
+ eval "$runpath_var='$rpath\$$runpath_var'; export $runpath_var"
+ fi
+ test -n "$dep_rpath" && deplibs="$dep_rpath $deplibs"
+ fi
+
+ shlibpath="$finalize_shlibpath"
+ test "$mode" != relink && shlibpath="$compile_shlibpath$shlibpath"
+ if test -n "$shlibpath"; then
+ eval "$shlibpath_var='$shlibpath\$$shlibpath_var'; export $shlibpath_var"
+ fi
+
+ # Get the real and link names of the library.
+ eval shared_ext=\"$shrext_cmds\"
+ eval library_names=\"$library_names_spec\"
+ set dummy $library_names
+ realname="$2"
+ shift; shift
+
+ if test -n "$soname_spec"; then
+ eval soname=\"$soname_spec\"
+ else
+ soname="$realname"
+ fi
+ if test -z "$dlname"; then
+ dlname=$soname
+ fi
+
+ lib="$output_objdir/$realname"
+ linknames=
+ for link
+ do
+ linknames="$linknames $link"
+ done
+
+ # Use standard objects if they are pic
+ test -z "$pic_flag" && libobjs=`$echo "X$libobjs" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP`
+
+ # Prepare the list of exported symbols
+ if test -z "$export_symbols"; then
+ if test "$always_export_symbols" = yes || test -n "$export_symbols_regex"; then
+ $show "generating symbol list for \`$libname.la'"
+ export_symbols="$output_objdir/$libname.exp"
+ $run $rm $export_symbols
+ cmds=$export_symbols_cmds
+ save_ifs="$IFS"; IFS='~'
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ eval cmd=\"$cmd\"
+ if len=`expr "X$cmd" : ".*"` &&
+ test "$len" -le "$max_cmd_len" || test "$max_cmd_len" -le -1; then
+ $show "$cmd"
+ $run eval "$cmd" || exit $?
+ skipped_export=false
+ else
+ # The command line is too long to execute in one step.
+ $show "using reloadable object file for export list..."
+ skipped_export=:
+ # Break out early, otherwise skipped_export may be
+ # set to false by a later but shorter cmd.
+ break
+ fi
+ done
+ IFS="$save_ifs"
+ if test -n "$export_symbols_regex"; then
+ $show "$EGREP -e \"$export_symbols_regex\" \"$export_symbols\" > \"${export_symbols}T\""
+ $run eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"'
+ $show "$mv \"${export_symbols}T\" \"$export_symbols\""
+ $run eval '$mv "${export_symbols}T" "$export_symbols"'
+ fi
+ fi
+ fi
+
+ if test -n "$export_symbols" && test -n "$include_expsyms"; then
+ $run eval '$echo "X$include_expsyms" | $SP2NL >> "$export_symbols"'
+ fi
+
+ tmp_deplibs=
+ for test_deplib in $deplibs; do
+ case " $convenience " in
+ *" $test_deplib "*) ;;
+ *)
+ tmp_deplibs="$tmp_deplibs $test_deplib"
+ ;;
+ esac
+ done
+ deplibs="$tmp_deplibs"
+
+ if test -n "$convenience"; then
+ if test -n "$whole_archive_flag_spec"; then
+ save_libobjs=$libobjs
+ eval libobjs=\"\$libobjs $whole_archive_flag_spec\"
+ else
+ gentop="$output_objdir/${outputname}x"
+ generated="$generated $gentop"
+
+ func_extract_archives $gentop $convenience
+ libobjs="$libobjs $func_extract_archives_result"
+ fi
+ fi
+
+ if test "$thread_safe" = yes && test -n "$thread_safe_flag_spec"; then
+ eval flag=\"$thread_safe_flag_spec\"
+ linker_flags="$linker_flags $flag"
+ fi
+
+ # Make a backup of the uninstalled library when relinking
+ if test "$mode" = relink; then
+ $run eval '(cd $output_objdir && $rm ${realname}U && $mv $realname ${realname}U)' || exit $?
+ fi
+
+ # Do each of the archive commands.
+ if test "$module" = yes && test -n "$module_cmds" ; then
+ if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then
+ eval test_cmds=\"$module_expsym_cmds\"
+ cmds=$module_expsym_cmds
+ else
+ eval test_cmds=\"$module_cmds\"
+ cmds=$module_cmds
+ fi
+ else
+ if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then
+ eval test_cmds=\"$archive_expsym_cmds\"
+ cmds=$archive_expsym_cmds
+ else
+ eval test_cmds=\"$archive_cmds\"
+ cmds=$archive_cmds
+ fi
+ fi
+
+ if test "X$skipped_export" != "X:" &&
+ len=`expr "X$test_cmds" : ".*" 2>/dev/null` &&
+ test "$len" -le "$max_cmd_len" || test "$max_cmd_len" -le -1; then
+ :
+ else
+ # The command line is too long to link in one step, link piecewise.
+ $echo "creating reloadable object files..."
+
+ # Save the value of $output and $libobjs because we want to
+ # use them later. If we have whole_archive_flag_spec, we
+ # want to use save_libobjs as it was before
+ # whole_archive_flag_spec was expanded, because we can't
+ # assume the linker understands whole_archive_flag_spec.
+ # This may have to be revisited, in case too many
+ # convenience libraries get linked in and end up exceeding
+ # the spec.
+ if test -z "$convenience" || test -z "$whole_archive_flag_spec"; then
+ save_libobjs=$libobjs
+ fi
+ save_output=$output
+ output_la=`$echo "X$output" | $Xsed -e "$basename"`
+
+ # Clear the reloadable object creation command queue and
+ # initialize k to one.
+ test_cmds=
+ concat_cmds=
+ objlist=
+ delfiles=
+ last_robj=
+ k=1
+ output=$output_objdir/$output_la-${k}.$objext
+ # Loop over the list of objects to be linked.
+ for obj in $save_libobjs
+ do
+ eval test_cmds=\"$reload_cmds $objlist $last_robj\"
+ if test "X$objlist" = X ||
+ { len=`expr "X$test_cmds" : ".*" 2>/dev/null` &&
+ test "$len" -le "$max_cmd_len"; }; then
+ objlist="$objlist $obj"
+ else
+ # The command $test_cmds is almost too long, add a
+ # command to the queue.
+ if test "$k" -eq 1 ; then
+ # The first file doesn't have a previous command to add.
+ eval concat_cmds=\"$reload_cmds $objlist $last_robj\"
+ else
+ # All subsequent reloadable object files will link in
+ # the last one created.
+ eval concat_cmds=\"\$concat_cmds~$reload_cmds $objlist $last_robj\"
+ fi
+ last_robj=$output_objdir/$output_la-${k}.$objext
+ k=`expr $k + 1`
+ output=$output_objdir/$output_la-${k}.$objext
+ objlist=$obj
+ len=1
+ fi
+ done
+ # Handle the remaining objects by creating one last
+ # reloadable object file. All subsequent reloadable object
+ # files will link in the last one created.
+ test -z "$concat_cmds" || concat_cmds=$concat_cmds~
+ eval concat_cmds=\"\${concat_cmds}$reload_cmds $objlist $last_robj\"
+
+ if ${skipped_export-false}; then
+ $show "generating symbol list for \`$libname.la'"
+ export_symbols="$output_objdir/$libname.exp"
+ $run $rm $export_symbols
+ libobjs=$output
+ # Append the command to create the export file.
+ eval concat_cmds=\"\$concat_cmds~$export_symbols_cmds\"
+ fi
+
+ # Set up a command to remove the reloadable object files
+ # after they are used.
+ i=0
+ while test "$i" -lt "$k"
+ do
+ i=`expr $i + 1`
+ delfiles="$delfiles $output_objdir/$output_la-${i}.$objext"
+ done
+
+ $echo "creating a temporary reloadable object file: $output"
+
+ # Loop through the commands generated above and execute them.
+ save_ifs="$IFS"; IFS='~'
+ for cmd in $concat_cmds; do
+ IFS="$save_ifs"
+ $show "$cmd"
+ $run eval "$cmd" || exit $?
+ done
+ IFS="$save_ifs"
+
+ libobjs=$output
+ # Restore the value of output.
+ output=$save_output
+
+ if test -n "$convenience" && test -n "$whole_archive_flag_spec"; then
+ eval libobjs=\"\$libobjs $whole_archive_flag_spec\"
+ fi
+ # Expand the library linking commands again to reset the
+ # value of $libobjs for piecewise linking.
+
+ # Do each of the archive commands.
+ if test "$module" = yes && test -n "$module_cmds" ; then
+ if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then
+ cmds=$module_expsym_cmds
+ else
+ cmds=$module_cmds
+ fi
+ else
+ if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then
+ cmds=$archive_expsym_cmds
+ else
+ cmds=$archive_cmds
+ fi
+ fi
+
+ # Append the command to remove the reloadable object files
+ # to the just-reset $cmds.
+ eval cmds=\"\$cmds~\$rm $delfiles\"
+ fi
+ save_ifs="$IFS"; IFS='~'
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ eval cmd=\"$cmd\"
+ $show "$cmd"
+ $run eval "$cmd" || {
+ lt_exit=$?
+
+ # Restore the uninstalled library and exit
+ if test "$mode" = relink; then
+ $run eval '(cd $output_objdir && $rm ${realname}T && $mv ${realname}U $realname)'
+ fi
+
+ exit $lt_exit
+ }
+ done
+ IFS="$save_ifs"
+
+ # Restore the uninstalled library and exit
+ if test "$mode" = relink; then
+ $run eval '(cd $output_objdir && $rm ${realname}T && $mv $realname ${realname}T && $mv "$realname"U $realname)' || exit $?
+
+ if test -n "$convenience"; then
+ if test -z "$whole_archive_flag_spec"; then
+ $show "${rm}r $gentop"
+ $run ${rm}r "$gentop"
+ fi
+ fi
+
+ exit $EXIT_SUCCESS
+ fi
+
+ # Create links to the real library.
+ for linkname in $linknames; do
+ if test "$realname" != "$linkname"; then
+ $show "(cd $output_objdir && $rm $linkname && $LN_S $realname $linkname)"
+ $run eval '(cd $output_objdir && $rm $linkname && $LN_S $realname $linkname)' || exit $?
+ fi
+ done
+
+ # If -module or -export-dynamic was specified, set the dlname.
+ if test "$module" = yes || test "$export_dynamic" = yes; then
+ # On all known operating systems, these are identical.
+ dlname="$soname"
+ fi
+ fi
+ ;;
+
+ obj)
+ if test -n "$deplibs"; then
+ $echo "$modename: warning: \`-l' and \`-L' are ignored for objects" 1>&2
+ fi
+
+ if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then
+ $echo "$modename: warning: \`-dlopen' is ignored for objects" 1>&2
+ fi
+
+ if test -n "$rpath"; then
+ $echo "$modename: warning: \`-rpath' is ignored for objects" 1>&2
+ fi
+
+ if test -n "$xrpath"; then
+ $echo "$modename: warning: \`-R' is ignored for objects" 1>&2
+ fi
+
+ if test -n "$vinfo"; then
+ $echo "$modename: warning: \`-version-info' is ignored for objects" 1>&2
+ fi
+
+ if test -n "$release"; then
+ $echo "$modename: warning: \`-release' is ignored for objects" 1>&2
+ fi
+
+ case $output in
+ *.lo)
+ if test -n "$objs$old_deplibs"; then
+ $echo "$modename: cannot build library object \`$output' from non-libtool objects" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ libobj="$output"
+ obj=`$echo "X$output" | $Xsed -e "$lo2o"`
+ ;;
+ *)
+ libobj=
+ obj="$output"
+ ;;
+ esac
+
+ # Delete the old objects.
+ $run $rm $obj $libobj
+
+ # Objects from convenience libraries. This assumes
+ # single-version convenience libraries. Whenever we create
+ # different ones for PIC/non-PIC, this we'll have to duplicate
+ # the extraction.
+ reload_conv_objs=
+ gentop=
+ # reload_cmds runs $LD directly, so let us get rid of
+ # -Wl from whole_archive_flag_spec and hope we can get by with
+ # turning comma into space..
+ wl=
+
+ if test -n "$convenience"; then
+ if test -n "$whole_archive_flag_spec"; then
+ eval tmp_whole_archive_flags=\"$whole_archive_flag_spec\"
+ reload_conv_objs=$reload_objs\ `$echo "X$tmp_whole_archive_flags" | $Xsed -e 's|,| |g'`
+ else
+ gentop="$output_objdir/${obj}x"
+ generated="$generated $gentop"
+
+ func_extract_archives $gentop $convenience
+ reload_conv_objs="$reload_objs $func_extract_archives_result"
+ fi
+ fi
+
+ # Create the old-style object.
+ reload_objs="$objs$old_deplibs "`$echo "X$libobjs" | $SP2NL | $Xsed -e '/\.'${libext}$'/d' -e '/\.lib$/d' -e "$lo2o" | $NL2SP`" $reload_conv_objs" ### testsuite: skip nested quoting test
+
+ output="$obj"
+ cmds=$reload_cmds
+ save_ifs="$IFS"; IFS='~'
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ eval cmd=\"$cmd\"
+ $show "$cmd"
+ $run eval "$cmd" || exit $?
+ done
+ IFS="$save_ifs"
+
+ # Exit if we aren't doing a library object file.
+ if test -z "$libobj"; then
+ if test -n "$gentop"; then
+ $show "${rm}r $gentop"
+ $run ${rm}r $gentop
+ fi
+
+ exit $EXIT_SUCCESS
+ fi
+
+ if test "$build_libtool_libs" != yes; then
+ if test -n "$gentop"; then
+ $show "${rm}r $gentop"
+ $run ${rm}r $gentop
+ fi
+
+ # Create an invalid libtool object if no PIC, so that we don't
+ # accidentally link it into a program.
+ # $show "echo timestamp > $libobj"
+ # $run eval "echo timestamp > $libobj" || exit $?
+ exit $EXIT_SUCCESS
+ fi
+
+ if test -n "$pic_flag" || test "$pic_mode" != default; then
+ # Only do commands if we really have different PIC objects.
+ reload_objs="$libobjs $reload_conv_objs"
+ output="$libobj"
+ cmds=$reload_cmds
+ save_ifs="$IFS"; IFS='~'
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ eval cmd=\"$cmd\"
+ $show "$cmd"
+ $run eval "$cmd" || exit $?
+ done
+ IFS="$save_ifs"
+ fi
+
+ if test -n "$gentop"; then
+ $show "${rm}r $gentop"
+ $run ${rm}r $gentop
+ fi
+
+ exit $EXIT_SUCCESS
+ ;;
+
+ prog)
+ case $host in
+ *cygwin*) output=`$echo $output | ${SED} -e 's,.exe$,,;s,$,.exe,'` ;;
+ esac
+ if test -n "$vinfo"; then
+ $echo "$modename: warning: \`-version-info' is ignored for programs" 1>&2
+ fi
+
+ if test -n "$release"; then
+ $echo "$modename: warning: \`-release' is ignored for programs" 1>&2
+ fi
+
+ if test "$preload" = yes; then
+ if test "$dlopen_support" = unknown && test "$dlopen_self" = unknown &&
+ test "$dlopen_self_static" = unknown; then
+ $echo "$modename: warning: \`AC_LIBTOOL_DLOPEN' not used. Assuming no dlopen support."
+ fi
+ fi
+
+ case $host in
+ *-*-rhapsody* | *-*-darwin1.[012])
+ # On Rhapsody replace the C library is the System framework
+ compile_deplibs=`$echo "X $compile_deplibs" | $Xsed -e 's/ -lc / -framework System /'`
+ finalize_deplibs=`$echo "X $finalize_deplibs" | $Xsed -e 's/ -lc / -framework System /'`
+ ;;
+ esac
+
+ case $host in
+ *darwin*)
+ # Don't allow lazy linking, it breaks C++ global constructors
+ if test "$tagname" = CXX ; then
+ compile_command="$compile_command ${wl}-bind_at_load"
+ finalize_command="$finalize_command ${wl}-bind_at_load"
+ fi
+ ;;
+ esac
+
+
+ # move library search paths that coincide with paths to not yet
+ # installed libraries to the beginning of the library search list
+ new_libs=
+ for path in $notinst_path; do
+ case " $new_libs " in
+ *" -L$path/$objdir "*) ;;
+ *)
+ case " $compile_deplibs " in
+ *" -L$path/$objdir "*)
+ new_libs="$new_libs -L$path/$objdir" ;;
+ esac
+ ;;
+ esac
+ done
+ for deplib in $compile_deplibs; do
+ case $deplib in
+ -L*)
+ case " $new_libs " in
+ *" $deplib "*) ;;
+ *) new_libs="$new_libs $deplib" ;;
+ esac
+ ;;
+ *) new_libs="$new_libs $deplib" ;;
+ esac
+ done
+ compile_deplibs="$new_libs"
+
+
+ compile_command="$compile_command $compile_deplibs"
+ finalize_command="$finalize_command $finalize_deplibs"
+
+ if test -n "$rpath$xrpath"; then
+ # If the user specified any rpath flags, then add them.
+ for libdir in $rpath $xrpath; do
+ # This is the magic to use -rpath.
+ case "$finalize_rpath " in
+ *" $libdir "*) ;;
+ *) finalize_rpath="$finalize_rpath $libdir" ;;
+ esac
+ done
+ fi
+
+ # Now hardcode the library paths
+ rpath=
+ hardcode_libdirs=
+ for libdir in $compile_rpath $finalize_rpath; do
+ if test -n "$hardcode_libdir_flag_spec"; then
+ if test -n "$hardcode_libdir_separator"; then
+ if test -z "$hardcode_libdirs"; then
+ hardcode_libdirs="$libdir"
+ else
+ # Just accumulate the unique libdirs.
+ case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in
+ *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*)
+ ;;
+ *)
+ hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir"
+ ;;
+ esac
+ fi
+ else
+ eval flag=\"$hardcode_libdir_flag_spec\"
+ rpath="$rpath $flag"
+ fi
+ elif test -n "$runpath_var"; then
+ case "$perm_rpath " in
+ *" $libdir "*) ;;
+ *) perm_rpath="$perm_rpath $libdir" ;;
+ esac
+ fi
+ case $host in
+ *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2*)
+ testbindir=`$echo "X$libdir" | $Xsed -e 's*/lib$*/bin*'`
+ case :$dllsearchpath: in
+ *":$libdir:"*) ;;
+ *) dllsearchpath="$dllsearchpath:$libdir";;
+ esac
+ case :$dllsearchpath: in
+ *":$testbindir:"*) ;;
+ *) dllsearchpath="$dllsearchpath:$testbindir";;
+ esac
+ ;;
+ esac
+ done
+ # Substitute the hardcoded libdirs into the rpath.
+ if test -n "$hardcode_libdir_separator" &&
+ test -n "$hardcode_libdirs"; then
+ libdir="$hardcode_libdirs"
+ eval rpath=\" $hardcode_libdir_flag_spec\"
+ fi
+ compile_rpath="$rpath"
+
+ rpath=
+ hardcode_libdirs=
+ for libdir in $finalize_rpath; do
+ if test -n "$hardcode_libdir_flag_spec"; then
+ if test -n "$hardcode_libdir_separator"; then
+ if test -z "$hardcode_libdirs"; then
+ hardcode_libdirs="$libdir"
+ else
+ # Just accumulate the unique libdirs.
+ case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in
+ *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*)
+ ;;
+ *)
+ hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir"
+ ;;
+ esac
+ fi
+ else
+ eval flag=\"$hardcode_libdir_flag_spec\"
+ rpath="$rpath $flag"
+ fi
+ elif test -n "$runpath_var"; then
+ case "$finalize_perm_rpath " in
+ *" $libdir "*) ;;
+ *) finalize_perm_rpath="$finalize_perm_rpath $libdir" ;;
+ esac
+ fi
+ done
+ # Substitute the hardcoded libdirs into the rpath.
+ if test -n "$hardcode_libdir_separator" &&
+ test -n "$hardcode_libdirs"; then
+ libdir="$hardcode_libdirs"
+ eval rpath=\" $hardcode_libdir_flag_spec\"
+ fi
+ finalize_rpath="$rpath"
+
+ if test -n "$libobjs" && test "$build_old_libs" = yes; then
+ # Transform all the library objects into standard objects.
+ compile_command=`$echo "X$compile_command" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP`
+ finalize_command=`$echo "X$finalize_command" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP`
+ fi
+
+ dlsyms=
+ if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then
+ if test -n "$NM" && test -n "$global_symbol_pipe"; then
+ dlsyms="${outputname}S.c"
+ else
+ $echo "$modename: not configured to extract global symbols from dlpreopened files" 1>&2
+ fi
+ fi
+
+ if test -n "$dlsyms"; then
+ case $dlsyms in
+ "") ;;
+ *.c)
+ # Discover the nlist of each of the dlfiles.
+ nlist="$output_objdir/${outputname}.nm"
+
+ $show "$rm $nlist ${nlist}S ${nlist}T"
+ $run $rm "$nlist" "${nlist}S" "${nlist}T"
+
+ # Parse the name list into a source file.
+ $show "creating $output_objdir/$dlsyms"
+
+ test -z "$run" && $echo > "$output_objdir/$dlsyms" "\
+/* $dlsyms - symbol resolution table for \`$outputname' dlsym emulation. */
+/* Generated by $PROGRAM - GNU $PACKAGE $VERSION$TIMESTAMP */
+
+#ifdef __cplusplus
+extern \"C\" {
+#endif
+
+/* Prevent the only kind of declaration conflicts we can make. */
+#define lt_preloaded_symbols some_other_symbol
+
+/* External symbol declarations for the compiler. */\
+"
+
+ if test "$dlself" = yes; then
+ $show "generating symbol list for \`$output'"
+
+ test -z "$run" && $echo ': @PROGRAM@ ' > "$nlist"
+
+ # Add our own program objects to the symbol list.
+ progfiles=`$echo "X$objs$old_deplibs" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP`
+ for arg in $progfiles; do
+ $show "extracting global C symbols from \`$arg'"
+ $run eval "$NM $arg | $global_symbol_pipe >> '$nlist'"
+ done
+
+ if test -n "$exclude_expsyms"; then
+ $run eval '$EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T'
+ $run eval '$mv "$nlist"T "$nlist"'
+ fi
+
+ if test -n "$export_symbols_regex"; then
+ $run eval '$EGREP -e "$export_symbols_regex" "$nlist" > "$nlist"T'
+ $run eval '$mv "$nlist"T "$nlist"'
+ fi
+
+ # Prepare the list of exported symbols
+ if test -z "$export_symbols"; then
+ export_symbols="$output_objdir/$outputname.exp"
+ $run $rm $export_symbols
+ $run eval "${SED} -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \(.*\)$/\1/p' "'< "$nlist" > "$export_symbols"'
+ case $host in
+ *cygwin* | *mingw* )
+ $run eval "echo EXPORTS "'> "$output_objdir/$outputname.def"'
+ $run eval 'cat "$export_symbols" >> "$output_objdir/$outputname.def"'
+ ;;
+ esac
+ else
+ $run eval "${SED} -e 's/\([].[*^$]\)/\\\\\1/g' -e 's/^/ /' -e 's/$/$/'"' < "$export_symbols" > "$output_objdir/$outputname.exp"'
+ $run eval 'grep -f "$output_objdir/$outputname.exp" < "$nlist" > "$nlist"T'
+ $run eval 'mv "$nlist"T "$nlist"'
+ case $host in
+ *cygwin* | *mingw* )
+ $run eval "echo EXPORTS "'> "$output_objdir/$outputname.def"'
+ $run eval 'cat "$nlist" >> "$output_objdir/$outputname.def"'
+ ;;
+ esac
+ fi
+ fi
+
+ for arg in $dlprefiles; do
+ $show "extracting global C symbols from \`$arg'"
+ name=`$echo "$arg" | ${SED} -e 's%^.*/%%'`
+ $run eval '$echo ": $name " >> "$nlist"'
+ $run eval "$NM $arg | $global_symbol_pipe >> '$nlist'"
+ done
+
+ if test -z "$run"; then
+ # Make sure we have at least an empty file.
+ test -f "$nlist" || : > "$nlist"
+
+ if test -n "$exclude_expsyms"; then
+ $EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T
+ $mv "$nlist"T "$nlist"
+ fi
+
+ # Try sorting and uniquifying the output.
+ if grep -v "^: " < "$nlist" |
+ if sort -k 3 </dev/null >/dev/null 2>&1; then
+ sort -k 3
+ else
+ sort +2
+ fi |
+ uniq > "$nlist"S; then
+ :
+ else
+ grep -v "^: " < "$nlist" > "$nlist"S
+ fi
+
+ if test -f "$nlist"S; then
+ eval "$global_symbol_to_cdecl"' < "$nlist"S >> "$output_objdir/$dlsyms"'
+ else
+ $echo '/* NONE */' >> "$output_objdir/$dlsyms"
+ fi
+
+ $echo >> "$output_objdir/$dlsyms" "\
+
+#undef lt_preloaded_symbols
+
+#if defined (__STDC__) && __STDC__
+# define lt_ptr void *
+#else
+# define lt_ptr char *
+# define const
+#endif
+
+/* The mapping between symbol names and symbols. */
+"
+
+ case $host in
+ *cygwin* | *mingw* )
+ $echo >> "$output_objdir/$dlsyms" "\
+/* DATA imports from DLLs on WIN32 can't be const, because
+ runtime relocations are performed -- see ld's documentation
+ on pseudo-relocs */
+struct {
+"
+ ;;
+ * )
+ $echo >> "$output_objdir/$dlsyms" "\
+const struct {
+"
+ ;;
+ esac
+
+
+ $echo >> "$output_objdir/$dlsyms" "\
+ const char *name;
+ lt_ptr address;
+}
+lt_preloaded_symbols[] =
+{\
+"
+
+ eval "$global_symbol_to_c_name_address" < "$nlist" >> "$output_objdir/$dlsyms"
+
+ $echo >> "$output_objdir/$dlsyms" "\
+ {0, (lt_ptr) 0}
+};
+
+/* This works around a problem in FreeBSD linker */
+#ifdef FREEBSD_WORKAROUND
+static const void *lt_preloaded_setup() {
+ return lt_preloaded_symbols;
+}
+#endif
+
+#ifdef __cplusplus
+}
+#endif\
+"
+ fi
+
+ pic_flag_for_symtable=
+ case $host in
+ # compiling the symbol table file with pic_flag works around
+ # a FreeBSD bug that causes programs to crash when -lm is
+ # linked before any other PIC object. But we must not use
+ # pic_flag when linking with -static. The problem exists in
+ # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1.
+ *-*-freebsd2*|*-*-freebsd3.0*|*-*-freebsdelf3.0*)
+ case "$compile_command " in
+ *" -static "*) ;;
+ *) pic_flag_for_symtable=" $pic_flag -DFREEBSD_WORKAROUND";;
+ esac;;
+ *-*-hpux*)
+ case "$compile_command " in
+ *" -static "*) ;;
+ *) pic_flag_for_symtable=" $pic_flag";;
+ esac
+ esac
+
+ # Now compile the dynamic symbol file.
+ $show "(cd $output_objdir && $LTCC $LTCFLAGS -c$no_builtin_flag$pic_flag_for_symtable \"$dlsyms\")"
+ $run eval '(cd $output_objdir && $LTCC $LTCFLAGS -c$no_builtin_flag$pic_flag_for_symtable "$dlsyms")' || exit $?
+
+ # Clean up the generated files.
+ $show "$rm $output_objdir/$dlsyms $nlist ${nlist}S ${nlist}T"
+ $run $rm "$output_objdir/$dlsyms" "$nlist" "${nlist}S" "${nlist}T"
+
+ # Transform the symbol file into the correct name.
+ case $host in
+ *cygwin* | *mingw* )
+ if test -f "$output_objdir/${outputname}.def" ; then
+ compile_command=`$echo "X$compile_command" | $SP2NL | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}.def $output_objdir/${outputname}S.${objext}%" | $NL2SP`
+ finalize_command=`$echo "X$finalize_command" | $SP2NL | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}.def $output_objdir/${outputname}S.${objext}%" | $NL2SP`
+ else
+ compile_command=`$echo "X$compile_command" | $SP2NL | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%" | $NL2SP`
+ finalize_command=`$echo "X$finalize_command" | $SP2NL | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%" | $NL2SP`
+ fi
+ ;;
+ * )
+ compile_command=`$echo "X$compile_command" | $SP2NL | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%" | $NL2SP`
+ finalize_command=`$echo "X$finalize_command" | $SP2NL | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%" | $NL2SP`
+ ;;
+ esac
+ ;;
+ *)
+ $echo "$modename: unknown suffix for \`$dlsyms'" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+ else
+ # We keep going just in case the user didn't refer to
+ # lt_preloaded_symbols. The linker will fail if global_symbol_pipe
+ # really was required.
+
+ # Nullify the symbol file.
+ compile_command=`$echo "X$compile_command" | $SP2NL | $Xsed -e "s% @SYMFILE@%%" | $NL2SP`
+ finalize_command=`$echo "X$finalize_command" | $SP2NL | $Xsed -e "s% @SYMFILE@%%" | $NL2SP`
+ fi
+
+ if test "$need_relink" = no || test "$build_libtool_libs" != yes; then
+ # Replace the output file specification.
+ compile_command=`$echo "X$compile_command" | $SP2NL | $Xsed -e 's%@OUTPUT@%'"$output"'%g' | $NL2SP`
+ link_command="$compile_command$compile_rpath"
+
+ # We have no uninstalled library dependencies, so finalize right now.
+ $show "$link_command"
+ $run eval "$link_command"
+ exit_status=$?
+
+ # Delete the generated files.
+ if test -n "$dlsyms"; then
+ $show "$rm $output_objdir/${outputname}S.${objext}"
+ $run $rm "$output_objdir/${outputname}S.${objext}"
+ fi
+
+ exit $exit_status
+ fi
+
+ if test -n "$shlibpath_var"; then
+ # We should set the shlibpath_var
+ rpath=
+ for dir in $temp_rpath; do
+ case $dir in
+ [\\/]* | [A-Za-z]:[\\/]*)
+ # Absolute path.
+ rpath="$rpath$dir:"
+ ;;
+ *)
+ # Relative path: add a thisdir entry.
+ rpath="$rpath\$thisdir/$dir:"
+ ;;
+ esac
+ done
+ temp_rpath="$rpath"
+ fi
+
+ if test -n "$compile_shlibpath$finalize_shlibpath"; then
+ compile_command="$shlibpath_var=\"$compile_shlibpath$finalize_shlibpath\$$shlibpath_var\" $compile_command"
+ fi
+ if test -n "$finalize_shlibpath"; then
+ finalize_command="$shlibpath_var=\"$finalize_shlibpath\$$shlibpath_var\" $finalize_command"
+ fi
+
+ compile_var=
+ finalize_var=
+ if test -n "$runpath_var"; then
+ if test -n "$perm_rpath"; then
+ # We should set the runpath_var.
+ rpath=
+ for dir in $perm_rpath; do
+ rpath="$rpath$dir:"
+ done
+ compile_var="$runpath_var=\"$rpath\$$runpath_var\" "
+ fi
+ if test -n "$finalize_perm_rpath"; then
+ # We should set the runpath_var.
+ rpath=
+ for dir in $finalize_perm_rpath; do
+ rpath="$rpath$dir:"
+ done
+ finalize_var="$runpath_var=\"$rpath\$$runpath_var\" "
+ fi
+ fi
+
+ if test "$no_install" = yes; then
+ # We don't need to create a wrapper script.
+ link_command="$compile_var$compile_command$compile_rpath"
+ # Replace the output file specification.
+ link_command=`$echo "X$link_command" | $Xsed -e 's%@OUTPUT@%'"$output"'%g'`
+ # Delete the old output file.
+ $run $rm $output
+ # Link the executable and exit
+ $show "$link_command"
+ $run eval "$link_command" || exit $?
+ exit $EXIT_SUCCESS
+ fi
+
+ if test "$hardcode_action" = relink; then
+ # Fast installation is not supported
+ link_command="$compile_var$compile_command$compile_rpath"
+ relink_command="$finalize_var$finalize_command$finalize_rpath"
+
+ $echo "$modename: warning: this platform does not like uninstalled shared libraries" 1>&2
+ $echo "$modename: \`$output' will be relinked during installation" 1>&2
+ else
+ if test "$fast_install" != no; then
+ link_command="$finalize_var$compile_command$finalize_rpath"
+ if test "$fast_install" = yes; then
+ relink_command=`$echo "X$compile_var$compile_command$compile_rpath" | $SP2NL | $Xsed -e 's%@OUTPUT@%\$progdir/\$file%g' | $NL2SP`
+ else
+ # fast_install is set to needless
+ relink_command=
+ fi
+ else
+ link_command="$compile_var$compile_command$compile_rpath"
+ relink_command="$finalize_var$finalize_command$finalize_rpath"
+ fi
+ fi
+
+ # Replace the output file specification.
+ link_command=`$echo "X$link_command" | $Xsed -e 's%@OUTPUT@%'"$output_objdir/$outputname"'%g'`
+
+ # Delete the old output files.
+ $run $rm $output $output_objdir/$outputname $output_objdir/lt-$outputname
+
+ $show "$link_command"
+ $run eval "$link_command" || exit $?
+
+ # Now create the wrapper script.
+ $show "creating $output"
+
+ # Quote the relink command for shipping.
+ if test -n "$relink_command"; then
+ # Preserve any variables that may affect compiler behavior
+ for var in $variables_saved_for_relink; do
+ if eval test -z \"\${$var+set}\"; then
+ relink_command="{ test -z \"\${$var+set}\" || unset $var || { $var=; export $var; }; }; $relink_command"
+ elif eval var_value=\$$var; test -z "$var_value"; then
+ relink_command="$var=; export $var; $relink_command"
+ else
+ var_value=`$echo "X$var_value" | $Xsed -e "$sed_quote_subst"`
+ relink_command="$var=\"$var_value\"; export $var; $relink_command"
+ fi
+ done
+ relink_command="(cd `pwd`; $relink_command)"
+ relink_command=`$echo "X$relink_command" | $SP2NL | $Xsed -e "$sed_quote_subst" | $NL2SP`
+ fi
+
+ # Quote $echo for shipping.
+ if test "X$echo" = "X$SHELL $progpath --fallback-echo"; then
+ case $progpath in
+ [\\/]* | [A-Za-z]:[\\/]*) qecho="$SHELL $progpath --fallback-echo";;
+ *) qecho="$SHELL `pwd`/$progpath --fallback-echo";;
+ esac
+ qecho=`$echo "X$qecho" | $Xsed -e "$sed_quote_subst"`
+ else
+ qecho=`$echo "X$echo" | $Xsed -e "$sed_quote_subst"`
+ fi
+
+ # Only actually do things if our run command is non-null.
+ if test -z "$run"; then
+ # win32 will think the script is a binary if it has
+ # a .exe suffix, so we strip it off here.
+ case $output in
+ *.exe) output=`$echo $output|${SED} 's,.exe$,,'` ;;
+ esac
+ # test for cygwin because mv fails w/o .exe extensions
+ case $host in
+ *cygwin*)
+ exeext=.exe
+ outputname=`$echo $outputname|${SED} 's,.exe$,,'` ;;
+ *) exeext= ;;
+ esac
+ case $host in
+ *cygwin* | *mingw* )
+ output_name=`basename $output`
+ output_path=`dirname $output`
+ cwrappersource="$output_path/$objdir/lt-$output_name.c"
+ cwrapper="$output_path/$output_name.exe"
+ $rm $cwrappersource $cwrapper
+ trap "$rm $cwrappersource $cwrapper; exit $EXIT_FAILURE" 1 2 15
+
+ cat > $cwrappersource <<EOF
+
+/* $cwrappersource - temporary wrapper executable for $objdir/$outputname
+ Generated by $PROGRAM - GNU $PACKAGE $VERSION$TIMESTAMP
+
+ The $output program cannot be directly executed until all the libtool
+ libraries that it depends on are installed.
+
+ This wrapper executable should never be moved out of the build directory.
+ If it is, it will not operate correctly.
+
+ Currently, it simply execs the wrapper *script* "/bin/sh $output",
+ but could eventually absorb all of the scripts functionality and
+ exec $objdir/$outputname directly.
+*/
+EOF
+ cat >> $cwrappersource<<"EOF"
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <malloc.h>
+#include <stdarg.h>
+#include <assert.h>
+#include <string.h>
+#include <ctype.h>
+#include <sys/stat.h>
+
+#if defined(PATH_MAX)
+# define LT_PATHMAX PATH_MAX
+#elif defined(MAXPATHLEN)
+# define LT_PATHMAX MAXPATHLEN
+#else
+# define LT_PATHMAX 1024
+#endif
+
+#ifndef DIR_SEPARATOR
+# define DIR_SEPARATOR '/'
+# define PATH_SEPARATOR ':'
+#endif
+
+#if defined (_WIN32) || defined (__MSDOS__) || defined (__DJGPP__) || \
+ defined (__OS2__)
+# define HAVE_DOS_BASED_FILE_SYSTEM
+# ifndef DIR_SEPARATOR_2
+# define DIR_SEPARATOR_2 '\\'
+# endif
+# ifndef PATH_SEPARATOR_2
+# define PATH_SEPARATOR_2 ';'
+# endif
+#endif
+
+#ifndef DIR_SEPARATOR_2
+# define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR)
+#else /* DIR_SEPARATOR_2 */
+# define IS_DIR_SEPARATOR(ch) \
+ (((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2))
+#endif /* DIR_SEPARATOR_2 */
+
+#ifndef PATH_SEPARATOR_2
+# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR)
+#else /* PATH_SEPARATOR_2 */
+# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2)
+#endif /* PATH_SEPARATOR_2 */
+
+#define XMALLOC(type, num) ((type *) xmalloc ((num) * sizeof(type)))
+#define XFREE(stale) do { \
+ if (stale) { free ((void *) stale); stale = 0; } \
+} while (0)
+
+/* -DDEBUG is fairly common in CFLAGS. */
+#undef DEBUG
+#if defined DEBUGWRAPPER
+# define DEBUG(format, ...) fprintf(stderr, format, __VA_ARGS__)
+#else
+# define DEBUG(format, ...)
+#endif
+
+const char *program_name = NULL;
+
+void * xmalloc (size_t num);
+char * xstrdup (const char *string);
+const char * base_name (const char *name);
+char * find_executable(const char *wrapper);
+int check_executable(const char *path);
+char * strendzap(char *str, const char *pat);
+void lt_fatal (const char *message, ...);
+
+int
+main (int argc, char *argv[])
+{
+ char **newargz;
+ int i;
+
+ program_name = (char *) xstrdup (base_name (argv[0]));
+ DEBUG("(main) argv[0] : %s\n",argv[0]);
+ DEBUG("(main) program_name : %s\n",program_name);
+ newargz = XMALLOC(char *, argc+2);
+EOF
+
+ cat >> $cwrappersource <<EOF
+ newargz[0] = (char *) xstrdup("$SHELL");
+EOF
+
+ cat >> $cwrappersource <<"EOF"
+ newargz[1] = find_executable(argv[0]);
+ if (newargz[1] == NULL)
+ lt_fatal("Couldn't find %s", argv[0]);
+ DEBUG("(main) found exe at : %s\n",newargz[1]);
+ /* we know the script has the same name, without the .exe */
+ /* so make sure newargz[1] doesn't end in .exe */
+ strendzap(newargz[1],".exe");
+ for (i = 1; i < argc; i++)
+ newargz[i+1] = xstrdup(argv[i]);
+ newargz[argc+1] = NULL;
+
+ for (i=0; i<argc+1; i++)
+ {
+ DEBUG("(main) newargz[%d] : %s\n",i,newargz[i]);
+ ;
+ }
+
+EOF
+
+ case $host_os in
+ mingw*)
+ cat >> $cwrappersource <<EOF
+ execv("$SHELL",(char const **)newargz);
+EOF
+ ;;
+ *)
+ cat >> $cwrappersource <<EOF
+ execv("$SHELL",newargz);
+EOF
+ ;;
+ esac
+
+ cat >> $cwrappersource <<"EOF"
+ return 127;
+}
+
+void *
+xmalloc (size_t num)
+{
+ void * p = (void *) malloc (num);
+ if (!p)
+ lt_fatal ("Memory exhausted");
+
+ return p;
+}
+
+char *
+xstrdup (const char *string)
+{
+ return string ? strcpy ((char *) xmalloc (strlen (string) + 1), string) : NULL
+;
+}
+
+const char *
+base_name (const char *name)
+{
+ const char *base;
+
+#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
+ /* Skip over the disk name in MSDOS pathnames. */
+ if (isalpha ((unsigned char)name[0]) && name[1] == ':')
+ name += 2;
+#endif
+
+ for (base = name; *name; name++)
+ if (IS_DIR_SEPARATOR (*name))
+ base = name + 1;
+ return base;
+}
+
+int
+check_executable(const char * path)
+{
+ struct stat st;
+
+ DEBUG("(check_executable) : %s\n", path ? (*path ? path : "EMPTY!") : "NULL!");
+ if ((!path) || (!*path))
+ return 0;
+
+ if ((stat (path, &st) >= 0) &&
+ (
+ /* MinGW & native WIN32 do not support S_IXOTH or S_IXGRP */
+#if defined (S_IXOTH)
+ ((st.st_mode & S_IXOTH) == S_IXOTH) ||
+#endif
+#if defined (S_IXGRP)
+ ((st.st_mode & S_IXGRP) == S_IXGRP) ||
+#endif
+ ((st.st_mode & S_IXUSR) == S_IXUSR))
+ )
+ return 1;
+ else
+ return 0;
+}
+
+/* Searches for the full path of the wrapper. Returns
+ newly allocated full path name if found, NULL otherwise */
+char *
+find_executable (const char* wrapper)
+{
+ int has_slash = 0;
+ const char* p;
+ const char* p_next;
+ /* static buffer for getcwd */
+ char tmp[LT_PATHMAX + 1];
+ int tmp_len;
+ char* concat_name;
+
+ DEBUG("(find_executable) : %s\n", wrapper ? (*wrapper ? wrapper : "EMPTY!") : "NULL!");
+
+ if ((wrapper == NULL) || (*wrapper == '\0'))
+ return NULL;
+
+ /* Absolute path? */
+#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
+ if (isalpha ((unsigned char)wrapper[0]) && wrapper[1] == ':')
+ {
+ concat_name = xstrdup (wrapper);
+ if (check_executable(concat_name))
+ return concat_name;
+ XFREE(concat_name);
+ }
+ else
+ {
+#endif
+ if (IS_DIR_SEPARATOR (wrapper[0]))
+ {
+ concat_name = xstrdup (wrapper);
+ if (check_executable(concat_name))
+ return concat_name;
+ XFREE(concat_name);
+ }
+#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
+ }
+#endif
+
+ for (p = wrapper; *p; p++)
+ if (*p == '/')
+ {
+ has_slash = 1;
+ break;
+ }
+ if (!has_slash)
+ {
+ /* no slashes; search PATH */
+ const char* path = getenv ("PATH");
+ if (path != NULL)
+ {
+ for (p = path; *p; p = p_next)
+ {
+ const char* q;
+ size_t p_len;
+ for (q = p; *q; q++)
+ if (IS_PATH_SEPARATOR(*q))
+ break;
+ p_len = q - p;
+ p_next = (*q == '\0' ? q : q + 1);
+ if (p_len == 0)
+ {
+ /* empty path: current directory */
+ if (getcwd (tmp, LT_PATHMAX) == NULL)
+ lt_fatal ("getcwd failed");
+ tmp_len = strlen(tmp);
+ concat_name = XMALLOC(char, tmp_len + 1 + strlen(wrapper) + 1);
+ memcpy (concat_name, tmp, tmp_len);
+ concat_name[tmp_len] = '/';
+ strcpy (concat_name + tmp_len + 1, wrapper);
+ }
+ else
+ {
+ concat_name = XMALLOC(char, p_len + 1 + strlen(wrapper) + 1);
+ memcpy (concat_name, p, p_len);
+ concat_name[p_len] = '/';
+ strcpy (concat_name + p_len + 1, wrapper);
+ }
+ if (check_executable(concat_name))
+ return concat_name;
+ XFREE(concat_name);
+ }
+ }
+ /* not found in PATH; assume curdir */
+ }
+ /* Relative path | not found in path: prepend cwd */
+ if (getcwd (tmp, LT_PATHMAX) == NULL)
+ lt_fatal ("getcwd failed");
+ tmp_len = strlen(tmp);
+ concat_name = XMALLOC(char, tmp_len + 1 + strlen(wrapper) + 1);
+ memcpy (concat_name, tmp, tmp_len);
+ concat_name[tmp_len] = '/';
+ strcpy (concat_name + tmp_len + 1, wrapper);
+
+ if (check_executable(concat_name))
+ return concat_name;
+ XFREE(concat_name);
+ return NULL;
+}
+
+char *
+strendzap(char *str, const char *pat)
+{
+ size_t len, patlen;
+
+ assert(str != NULL);
+ assert(pat != NULL);
+
+ len = strlen(str);
+ patlen = strlen(pat);
+
+ if (patlen <= len)
+ {
+ str += len - patlen;
+ if (strcmp(str, pat) == 0)
+ *str = '\0';
+ }
+ return str;
+}
+
+static void
+lt_error_core (int exit_status, const char * mode,
+ const char * message, va_list ap)
+{
+ fprintf (stderr, "%s: %s: ", program_name, mode);
+ vfprintf (stderr, message, ap);
+ fprintf (stderr, ".\n");
+
+ if (exit_status >= 0)
+ exit (exit_status);
+}
+
+void
+lt_fatal (const char *message, ...)
+{
+ va_list ap;
+ va_start (ap, message);
+ lt_error_core (EXIT_FAILURE, "FATAL", message, ap);
+ va_end (ap);
+}
+EOF
+ # we should really use a build-platform specific compiler
+ # here, but OTOH, the wrappers (shell script and this C one)
+ # are only useful if you want to execute the "real" binary.
+ # Since the "real" binary is built for $host, then this
+ # wrapper might as well be built for $host, too.
+ $run $LTCC $LTCFLAGS -s -o $cwrapper $cwrappersource
+ ;;
+ esac
+ $rm $output
+ trap "$rm $output; exit $EXIT_FAILURE" 1 2 15
+
+ $echo > $output "\
+#! $SHELL
+
+# $output - temporary wrapper script for $objdir/$outputname
+# Generated by $PROGRAM - GNU $PACKAGE $VERSION$TIMESTAMP
+#
+# The $output program cannot be directly executed until all the libtool
+# libraries that it depends on are installed.
+#
+# This wrapper script should never be moved out of the build directory.
+# If it is, it will not operate correctly.
+
+# Sed substitution that helps us do robust quoting. It backslashifies
+# metacharacters that are still active within double-quoted strings.
+Xsed='${SED} -e 1s/^X//'
+sed_quote_subst='$sed_quote_subst'
+
+# Be Bourne compatible (taken from Autoconf:_AS_BOURNE_COMPATIBLE).
+if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then
+ emulate sh
+ NULLCMD=:
+ # Zsh 3.x and 4.x performs word splitting on \${1+\"\$@\"}, which
+ # is contrary to our usage. Disable this feature.
+ alias -g '\${1+\"\$@\"}'='\"\$@\"'
+ setopt NO_GLOB_SUBST
+else
+ case \`(set -o) 2>/dev/null\` in *posix*) set -o posix;; esac
+fi
+BIN_SH=xpg4; export BIN_SH # for Tru64
+DUALCASE=1; export DUALCASE # for MKS sh
+
+# The HP-UX ksh and POSIX shell print the target directory to stdout
+# if CDPATH is set.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
+
+relink_command=\"$relink_command\"
+
+# This environment variable determines our operation mode.
+if test \"\$libtool_install_magic\" = \"$magic\"; then
+ # install mode needs the following variable:
+ notinst_deplibs='$notinst_deplibs'
+else
+ # When we are sourced in execute mode, \$file and \$echo are already set.
+ if test \"\$libtool_execute_magic\" != \"$magic\"; then
+ echo=\"$qecho\"
+ file=\"\$0\"
+ # Make sure echo works.
+ if test \"X\$1\" = X--no-reexec; then
+ # Discard the --no-reexec flag, and continue.
+ shift
+ elif test \"X\`(\$echo '\t') 2>/dev/null\`\" = 'X\t'; then
+ # Yippee, \$echo works!
+ :
+ else
+ # Restart under the correct shell, and then maybe \$echo will work.
+ exec $SHELL \"\$0\" --no-reexec \${1+\"\$@\"}
+ fi
+ fi\
+"
+ $echo >> $output "\
+
+ # Find the directory that this script lives in.
+ thisdir=\`\$echo \"X\$file\" | \$Xsed -e 's%/[^/]*$%%'\`
+ test \"x\$thisdir\" = \"x\$file\" && thisdir=.
+
+ # Follow symbolic links until we get to the real thisdir.
+ file=\`ls -ld \"\$file\" | ${SED} -n 's/.*-> //p'\`
+ while test -n \"\$file\"; do
+ destdir=\`\$echo \"X\$file\" | \$Xsed -e 's%/[^/]*\$%%'\`
+
+ # If there was a directory component, then change thisdir.
+ if test \"x\$destdir\" != \"x\$file\"; then
+ case \"\$destdir\" in
+ [\\\\/]* | [A-Za-z]:[\\\\/]*) thisdir=\"\$destdir\" ;;
+ *) thisdir=\"\$thisdir/\$destdir\" ;;
+ esac
+ fi
+
+ file=\`\$echo \"X\$file\" | \$Xsed -e 's%^.*/%%'\`
+ file=\`ls -ld \"\$thisdir/\$file\" | ${SED} -n 's/.*-> //p'\`
+ done
+
+ # Try to get the absolute directory name.
+ absdir=\`cd \"\$thisdir\" && pwd\`
+ test -n \"\$absdir\" && thisdir=\"\$absdir\"
+"
+
+ if test "$fast_install" = yes; then
+ $echo >> $output "\
+ program=lt-'$outputname'$exeext
+ progdir=\"\$thisdir/$objdir\"
+
+ if test ! -f \"\$progdir/\$program\" || \\
+ { file=\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\" 2>/dev/null | ${SED} 1q\`; \\
+ test \"X\$file\" != \"X\$progdir/\$program\"; }; then
+
+ file=\"\$\$-\$program\"
+
+ if test ! -d \"\$progdir\"; then
+ $mkdir \"\$progdir\"
+ else
+ $rm \"\$progdir/\$file\"
+ fi"
+
+ $echo >> $output "\
+
+ # relink executable if necessary
+ if test -n \"\$relink_command\"; then
+ if relink_command_output=\`eval \$relink_command 2>&1\`; then :
+ else
+ $echo \"\$relink_command_output\" >&2
+ $rm \"\$progdir/\$file\"
+ exit $EXIT_FAILURE
+ fi
+ fi
+
+ $mv \"\$progdir/\$file\" \"\$progdir/\$program\" 2>/dev/null ||
+ { $rm \"\$progdir/\$program\";
+ $mv \"\$progdir/\$file\" \"\$progdir/\$program\"; }
+ $rm \"\$progdir/\$file\"
+ fi"
+ else
+ $echo >> $output "\
+ program='$outputname'
+ progdir=\"\$thisdir/$objdir\"
+"
+ fi
+
+ $echo >> $output "\
+
+ if test -f \"\$progdir/\$program\"; then"
+
+ # Export our shlibpath_var if we have one.
+ if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then
+ $echo >> $output "\
+ # Add our own library path to $shlibpath_var
+ $shlibpath_var=\"$temp_rpath\$$shlibpath_var\"
+
+ # Some systems cannot cope with colon-terminated $shlibpath_var
+ # The second colon is a workaround for a bug in BeOS R4 sed
+ $shlibpath_var=\`\$echo \"X\$$shlibpath_var\" | \$Xsed -e 's/::*\$//'\`
+
+ export $shlibpath_var
+"
+ fi
+
+ # fixup the dll searchpath if we need to.
+ if test -n "$dllsearchpath"; then
+ $echo >> $output "\
+ # Add the dll search path components to the executable PATH
+ PATH=$dllsearchpath:\$PATH
+"
+ fi
+
+ $echo >> $output "\
+ if test \"\$libtool_execute_magic\" != \"$magic\"; then
+ # Run the actual program with our arguments.
+"
+ case $host in
+ # Backslashes separate directories on plain windows
+ *-*-mingw | *-*-os2*)
+ $echo >> $output "\
+ exec \"\$progdir\\\\\$program\" \${1+\"\$@\"}
+"
+ ;;
+
+ *)
+ $echo >> $output "\
+ exec \"\$progdir/\$program\" \${1+\"\$@\"}
+"
+ ;;
+ esac
+ $echo >> $output "\
+ \$echo \"\$0: cannot exec \$program \$*\"
+ exit $EXIT_FAILURE
+ fi
+ else
+ # The program doesn't exist.
+ \$echo \"\$0: error: \\\`\$progdir/\$program' does not exist\" 1>&2
+ \$echo \"This script is just a wrapper for \$program.\" 1>&2
+ $echo \"See the $PACKAGE documentation for more information.\" 1>&2
+ exit $EXIT_FAILURE
+ fi
+fi\
+"
+ chmod +x $output
+ fi
+ exit $EXIT_SUCCESS
+ ;;
+ esac
+
+ # See if we need to build an old-fashioned archive.
+ for oldlib in $oldlibs; do
+
+ if test "$build_libtool_libs" = convenience; then
+ oldobjs="$libobjs_save"
+ addlibs="$convenience"
+ build_libtool_libs=no
+ else
+ if test "$build_libtool_libs" = module; then
+ oldobjs="$libobjs_save"
+ build_libtool_libs=no
+ else
+ oldobjs="$old_deplibs $non_pic_objects"
+ fi
+ addlibs="$old_convenience"
+ fi
+
+ if test -n "$addlibs"; then
+ gentop="$output_objdir/${outputname}x"
+ generated="$generated $gentop"
+
+ func_extract_archives $gentop $addlibs
+ oldobjs="$oldobjs $func_extract_archives_result"
+ fi
+
+ # Do each command in the archive commands.
+ if test -n "$old_archive_from_new_cmds" && test "$build_libtool_libs" = yes; then
+ cmds=$old_archive_from_new_cmds
+ else
+ # POSIX demands no paths to be encoded in archives. We have
+ # to avoid creating archives with duplicate basenames if we
+ # might have to extract them afterwards, e.g., when creating a
+ # static archive out of a convenience library, or when linking
+ # the entirety of a libtool archive into another (currently
+ # not supported by libtool).
+ if (for obj in $oldobjs
+ do
+ $echo "X$obj" | $Xsed -e 's%^.*/%%'
+ done | sort | sort -uc >/dev/null 2>&1); then
+ :
+ else
+ $echo "copying selected object files to avoid basename conflicts..."
+
+ if test -z "$gentop"; then
+ gentop="$output_objdir/${outputname}x"
+ generated="$generated $gentop"
+
+ $show "${rm}r $gentop"
+ $run ${rm}r "$gentop"
+ $show "$mkdir $gentop"
+ $run $mkdir "$gentop"
+ exit_status=$?
+ if test "$exit_status" -ne 0 && test ! -d "$gentop"; then
+ exit $exit_status
+ fi
+ fi
+
+ save_oldobjs=$oldobjs
+ oldobjs=
+ counter=1
+ for obj in $save_oldobjs
+ do
+ objbase=`$echo "X$obj" | $Xsed -e 's%^.*/%%'`
+ case " $oldobjs " in
+ " ") oldobjs=$obj ;;
+ *[\ /]"$objbase "*)
+ while :; do
+ # Make sure we don't pick an alternate name that also
+ # overlaps.
+ newobj=lt$counter-$objbase
+ counter=`expr $counter + 1`
+ case " $oldobjs " in
+ *[\ /]"$newobj "*) ;;
+ *) if test ! -f "$gentop/$newobj"; then break; fi ;;
+ esac
+ done
+ $show "ln $obj $gentop/$newobj || cp $obj $gentop/$newobj"
+ $run ln "$obj" "$gentop/$newobj" ||
+ $run cp "$obj" "$gentop/$newobj"
+ oldobjs="$oldobjs $gentop/$newobj"
+ ;;
+ *) oldobjs="$oldobjs $obj" ;;
+ esac
+ done
+ fi
+
+ eval cmds=\"$old_archive_cmds\"
+
+ if len=`expr "X$cmds" : ".*"` &&
+ test "$len" -le "$max_cmd_len" || test "$max_cmd_len" -le -1; then
+ cmds=$old_archive_cmds
+ else
+ # the command line is too long to link in one step, link in parts
+ $echo "using piecewise archive linking..."
+ save_RANLIB=$RANLIB
+ RANLIB=:
+ objlist=
+ concat_cmds=
+ save_oldobjs=$oldobjs
+
+ # Is there a better way of finding the last object in the list?
+ for obj in $save_oldobjs
+ do
+ last_oldobj=$obj
+ done
+ for obj in $save_oldobjs
+ do
+ oldobjs="$objlist $obj"
+ objlist="$objlist $obj"
+ eval test_cmds=\"$old_archive_cmds\"
+ if len=`expr "X$test_cmds" : ".*" 2>/dev/null` &&
+ test "$len" -le "$max_cmd_len"; then
+ :
+ else
+ # the above command should be used before it gets too long
+ oldobjs=$objlist
+ if test "$obj" = "$last_oldobj" ; then
+ RANLIB=$save_RANLIB
+ fi
+ test -z "$concat_cmds" || concat_cmds=$concat_cmds~
+ eval concat_cmds=\"\${concat_cmds}$old_archive_cmds\"
+ objlist=
+ fi
+ done
+ RANLIB=$save_RANLIB
+ oldobjs=$objlist
+ if test "X$oldobjs" = "X" ; then
+ eval cmds=\"\$concat_cmds\"
+ else
+ eval cmds=\"\$concat_cmds~\$old_archive_cmds\"
+ fi
+ fi
+ fi
+ save_ifs="$IFS"; IFS='~'
+ for cmd in $cmds; do
+ eval cmd=\"$cmd\"
+ IFS="$save_ifs"
+ $show "$cmd"
+ $run eval "$cmd" || exit $?
+ done
+ IFS="$save_ifs"
+ done
+
+ if test -n "$generated"; then
+ $show "${rm}r$generated"
+ $run ${rm}r$generated
+ fi
+
+ # Now create the libtool archive.
+ case $output in
+ *.la)
+ old_library=
+ test "$build_old_libs" = yes && old_library="$libname.$libext"
+ $show "creating $output"
+
+ # Preserve any variables that may affect compiler behavior
+ for var in $variables_saved_for_relink; do
+ if eval test -z \"\${$var+set}\"; then
+ relink_command="{ test -z \"\${$var+set}\" || unset $var || { $var=; export $var; }; }; $relink_command"
+ elif eval var_value=\$$var; test -z "$var_value"; then
+ relink_command="$var=; export $var; $relink_command"
+ else
+ var_value=`$echo "X$var_value" | $Xsed -e "$sed_quote_subst"`
+ relink_command="$var=\"$var_value\"; export $var; $relink_command"
+ fi
+ done
+ # Quote the link command for shipping.
+ relink_command="(cd `pwd`; $SHELL $progpath $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)"
+ relink_command=`$echo "X$relink_command" | $SP2NL | $Xsed -e "$sed_quote_subst" | $NL2SP`
+ if test "$hardcode_automatic" = yes ; then
+ relink_command=
+ fi
+
+
+ # Only create the output if not a dry run.
+ if test -z "$run"; then
+ for installed in no yes; do
+ if test "$installed" = yes; then
+ if test -z "$install_libdir"; then
+ break
+ fi
+ output="$output_objdir/$outputname"i
+ # Replace all uninstalled libtool libraries with the installed ones
+ newdependency_libs=
+ for deplib in $dependency_libs; do
+ case $deplib in
+ *.la)
+ name=`$echo "X$deplib" | $Xsed -e 's%^.*/%%'`
+ eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib`
+ if test -z "$libdir"; then
+ $echo "$modename: \`$deplib' is not a valid libtool archive" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ newdependency_libs="$newdependency_libs $libdir/$name"
+ ;;
+ *) newdependency_libs="$newdependency_libs $deplib" ;;
+ esac
+ done
+ dependency_libs="$newdependency_libs"
+ newdlfiles=
+ for lib in $dlfiles; do
+ name=`$echo "X$lib" | $Xsed -e 's%^.*/%%'`
+ eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib`
+ if test -z "$libdir"; then
+ $echo "$modename: \`$lib' is not a valid libtool archive" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ newdlfiles="$newdlfiles $libdir/$name"
+ done
+ dlfiles="$newdlfiles"
+ newdlprefiles=
+ for lib in $dlprefiles; do
+ name=`$echo "X$lib" | $Xsed -e 's%^.*/%%'`
+ eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib`
+ if test -z "$libdir"; then
+ $echo "$modename: \`$lib' is not a valid libtool archive" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ newdlprefiles="$newdlprefiles $libdir/$name"
+ done
+ dlprefiles="$newdlprefiles"
+ else
+ newdlfiles=
+ for lib in $dlfiles; do
+ case $lib in
+ [\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;;
+ *) abs=`pwd`"/$lib" ;;
+ esac
+ newdlfiles="$newdlfiles $abs"
+ done
+ dlfiles="$newdlfiles"
+ newdlprefiles=
+ for lib in $dlprefiles; do
+ case $lib in
+ [\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;;
+ *) abs=`pwd`"/$lib" ;;
+ esac
+ newdlprefiles="$newdlprefiles $abs"
+ done
+ dlprefiles="$newdlprefiles"
+ fi
+ $rm $output
+ # place dlname in correct position for cygwin
+ tdlname=$dlname
+ case $host,$output,$installed,$module,$dlname in
+ *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll) tdlname=../bin/$dlname ;;
+ esac
+ $echo > $output "\
+# $outputname - a libtool library file
+# Generated by $PROGRAM - GNU $PACKAGE $VERSION$TIMESTAMP
+#
+# Please DO NOT delete this file!
+# It is necessary for linking the library.
+
+# The name that we can dlopen(3).
+dlname='$tdlname'
+
+# Names of this library.
+library_names='$library_names'
+
+# The name of the static archive.
+old_library='$old_library'
+
+# Libraries that this one depends upon.
+dependency_libs='$dependency_libs'
+
+# Version information for $libname.
+current=$current
+age=$age
+revision=$revision
+
+# Is this an already installed library?
+installed=$installed
+
+# Should we warn about portability when linking against -modules?
+shouldnotlink=$module
+
+# Files to dlopen/dlpreopen
+dlopen='$dlfiles'
+dlpreopen='$dlprefiles'
+
+# Directory that this library needs to be installed in:
+libdir='$install_libdir'"
+ if test "$installed" = no && test "$need_relink" = yes; then
+ $echo >> $output "\
+relink_command=\"$relink_command\""
+ fi
+ done
+ fi
+
+ # Do a symbolic link so that the libtool archive can be found in
+ # LD_LIBRARY_PATH before the program is installed.
+ $show "(cd $output_objdir && $rm $outputname && $LN_S ../$outputname $outputname)"
+ $run eval '(cd $output_objdir && $rm $outputname && $LN_S ../$outputname $outputname)' || exit $?
+ ;;
+ esac
+ exit $EXIT_SUCCESS
+ ;;
+
+ # libtool install mode
+ install)
+ modename="$modename: install"
+
+ # There may be an optional sh(1) argument at the beginning of
+ # install_prog (especially on Windows NT).
+ if test "$nonopt" = "$SHELL" || test "$nonopt" = /bin/sh ||
+ # Allow the use of GNU shtool's install command.
+ $echo "X$nonopt" | grep shtool > /dev/null; then
+ # Aesthetically quote it.
+ arg=`$echo "X$nonopt" | $Xsed -e "$sed_quote_subst"`
+ case $arg in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ arg="\"$arg\""
+ ;;
+ esac
+ install_prog="$arg "
+ arg="$1"
+ shift
+ else
+ install_prog=
+ arg=$nonopt
+ fi
+
+ # The real first argument should be the name of the installation program.
+ # Aesthetically quote it.
+ arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`
+ case $arg in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ arg="\"$arg\""
+ ;;
+ esac
+ install_prog="$install_prog$arg"
+
+ # We need to accept at least all the BSD install flags.
+ dest=
+ files=
+ opts=
+ prev=
+ install_type=
+ isdir=no
+ stripme=
+ for arg
+ do
+ if test -n "$dest"; then
+ files="$files $dest"
+ dest=$arg
+ continue
+ fi
+
+ case $arg in
+ -d) isdir=yes ;;
+ -f)
+ case " $install_prog " in
+ *[\\\ /]cp\ *) ;;
+ *) prev=$arg ;;
+ esac
+ ;;
+ -g | -m | -o) prev=$arg ;;
+ -s)
+ stripme=" -s"
+ continue
+ ;;
+ -*)
+ ;;
+ *)
+ # If the previous option needed an argument, then skip it.
+ if test -n "$prev"; then
+ prev=
+ else
+ dest=$arg
+ continue
+ fi
+ ;;
+ esac
+
+ # Aesthetically quote the argument.
+ arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`
+ case $arg in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ arg="\"$arg\""
+ ;;
+ esac
+ install_prog="$install_prog $arg"
+ done
+
+ if test -z "$install_prog"; then
+ $echo "$modename: you must specify an install program" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ if test -n "$prev"; then
+ $echo "$modename: the \`$prev' option requires an argument" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ if test -z "$files"; then
+ if test -z "$dest"; then
+ $echo "$modename: no file or destination specified" 1>&2
+ else
+ $echo "$modename: you must specify a destination" 1>&2
+ fi
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ # Strip any trailing slash from the destination.
+ dest=`$echo "X$dest" | $Xsed -e 's%/$%%'`
+
+ # Check to see that the destination is a directory.
+ test -d "$dest" && isdir=yes
+ if test "$isdir" = yes; then
+ destdir="$dest"
+ destname=
+ else
+ destdir=`$echo "X$dest" | $Xsed -e 's%/[^/]*$%%'`
+ test "X$destdir" = "X$dest" && destdir=.
+ destname=`$echo "X$dest" | $Xsed -e 's%^.*/%%'`
+
+ # Not a directory, so check to see that there is only one file specified.
+ set dummy $files
+ if test "$#" -gt 2; then
+ $echo "$modename: \`$dest' is not a directory" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ fi
+ case $destdir in
+ [\\/]* | [A-Za-z]:[\\/]*) ;;
+ *)
+ for file in $files; do
+ case $file in
+ *.lo) ;;
+ *)
+ $echo "$modename: \`$destdir' must be an absolute directory name" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+ done
+ ;;
+ esac
+
+ # This variable tells wrapper scripts just to set variables rather
+ # than running their programs.
+ libtool_install_magic="$magic"
+
+ staticlibs=
+ future_libdirs=
+ current_libdirs=
+ for file in $files; do
+
+ # Do each installation.
+ case $file in
+ *.$libext)
+ # Do the static libraries later.
+ staticlibs="$staticlibs $file"
+ ;;
+
+ *.la)
+ # Check to see that this really is a libtool archive.
+ if (${SED} -e '2q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then :
+ else
+ $echo "$modename: \`$file' is not a valid libtool archive" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ library_names=
+ old_library=
+ relink_command=
+ # If there is no directory component, then add one.
+ case $file in
+ */* | *\\*) . $file ;;
+ *) . ./$file ;;
+ esac
+
+ # Add the libdir to current_libdirs if it is the destination.
+ if test "X$destdir" = "X$libdir"; then
+ case "$current_libdirs " in
+ *" $libdir "*) ;;
+ *) current_libdirs="$current_libdirs $libdir" ;;
+ esac
+ else
+ # Note the libdir as a future libdir.
+ case "$future_libdirs " in
+ *" $libdir "*) ;;
+ *) future_libdirs="$future_libdirs $libdir" ;;
+ esac
+ fi
+
+ dir=`$echo "X$file" | $Xsed -e 's%/[^/]*$%%'`/
+ test "X$dir" = "X$file/" && dir=
+ dir="$dir$objdir"
+
+ if test -n "$relink_command"; then
+ # Determine the prefix the user has applied to our future dir.
+ inst_prefix_dir=`$echo "$destdir" | $SED "s%$libdir\$%%"`
+
+ # Don't allow the user to place us outside of our expected
+ # location b/c this prevents finding dependent libraries that
+ # are installed to the same prefix.
+ # At present, this check doesn't affect windows .dll's that
+ # are installed into $libdir/../bin (currently, that works fine)
+ # but it's something to keep an eye on.
+ if test "$inst_prefix_dir" = "$destdir"; then
+ $echo "$modename: error: cannot install \`$file' to a directory not ending in $libdir" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ if test -n "$inst_prefix_dir"; then
+ # Stick the inst_prefix_dir data into the link command.
+ relink_command=`$echo "$relink_command" | $SP2NL | $SED "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%" | $NL2SP`
+ else
+ relink_command=`$echo "$relink_command" | $SP2NL | $SED "s%@inst_prefix_dir@%%" | $NL2SP`
+ fi
+
+ $echo "$modename: warning: relinking \`$file'" 1>&2
+ $show "$relink_command"
+ if $run eval "$relink_command"; then :
+ else
+ $echo "$modename: error: relink \`$file' with the above command before installing it" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ fi
+
+ # See the names of the shared library.
+ set dummy $library_names
+ if test -n "$2"; then
+ realname="$2"
+ shift
+ shift
+
+ srcname="$realname"
+ test -n "$relink_command" && srcname="$realname"T
+
+ # Install the shared library and build the symlinks.
+ $show "$install_prog $dir/$srcname $destdir/$realname"
+ $run eval "$install_prog $dir/$srcname $destdir/$realname" || exit $?
+ if test -n "$stripme" && test -n "$striplib"; then
+ $show "$striplib $destdir/$realname"
+ $run eval "$striplib $destdir/$realname" || exit $?
+ fi
+
+ if test "$#" -gt 0; then
+ # Delete the old symlinks, and create new ones.
+ # Try `ln -sf' first, because the `ln' binary might depend on
+ # the symlink we replace! Solaris /bin/ln does not understand -f,
+ # so we also need to try rm && ln -s.
+ for linkname
+ do
+ if test "$linkname" != "$realname"; then
+ $show "(cd $destdir && { $LN_S -f $realname $linkname || { $rm $linkname && $LN_S $realname $linkname; }; })"
+ $run eval "(cd $destdir && { $LN_S -f $realname $linkname || { $rm $linkname && $LN_S $realname $linkname; }; })"
+ fi
+ done
+ fi
+
+ # Do each command in the postinstall commands.
+ lib="$destdir/$realname"
+ cmds=$postinstall_cmds
+ save_ifs="$IFS"; IFS='~'
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ eval cmd=\"$cmd\"
+ $show "$cmd"
+ $run eval "$cmd" || {
+ lt_exit=$?
+
+ # Restore the uninstalled library and exit
+ if test "$mode" = relink; then
+ $run eval '(cd $output_objdir && $rm ${realname}T && $mv ${realname}U $realname)'
+ fi
+
+ exit $lt_exit
+ }
+ done
+ IFS="$save_ifs"
+ fi
+
+ # Install the pseudo-library for information purposes.
+ name=`$echo "X$file" | $Xsed -e 's%^.*/%%'`
+ instname="$dir/$name"i
+ $show "$install_prog $instname $destdir/$name"
+ $run eval "$install_prog $instname $destdir/$name" || exit $?
+
+ # Maybe install the static library, too.
+ test -n "$old_library" && staticlibs="$staticlibs $dir/$old_library"
+ ;;
+
+ *.lo)
+ # Install (i.e. copy) a libtool object.
+
+ # Figure out destination file name, if it wasn't already specified.
+ if test -n "$destname"; then
+ destfile="$destdir/$destname"
+ else
+ destfile=`$echo "X$file" | $Xsed -e 's%^.*/%%'`
+ destfile="$destdir/$destfile"
+ fi
+
+ # Deduce the name of the destination old-style object file.
+ case $destfile in
+ *.lo)
+ staticdest=`$echo "X$destfile" | $Xsed -e "$lo2o"`
+ ;;
+ *.$objext)
+ staticdest="$destfile"
+ destfile=
+ ;;
+ *)
+ $echo "$modename: cannot copy a libtool object to \`$destfile'" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+
+ # Install the libtool object if requested.
+ if test -n "$destfile"; then
+ $show "$install_prog $file $destfile"
+ $run eval "$install_prog $file $destfile" || exit $?
+ fi
+
+ # Install the old object if enabled.
+ if test "$build_old_libs" = yes; then
+ # Deduce the name of the old-style object file.
+ staticobj=`$echo "X$file" | $Xsed -e "$lo2o"`
+
+ $show "$install_prog $staticobj $staticdest"
+ $run eval "$install_prog \$staticobj \$staticdest" || exit $?
+ fi
+ exit $EXIT_SUCCESS
+ ;;
+
+ *)
+ # Figure out destination file name, if it wasn't already specified.
+ if test -n "$destname"; then
+ destfile="$destdir/$destname"
+ else
+ destfile=`$echo "X$file" | $Xsed -e 's%^.*/%%'`
+ destfile="$destdir/$destfile"
+ fi
+
+ # If the file is missing, and there is a .exe on the end, strip it
+ # because it is most likely a libtool script we actually want to
+ # install
+ stripped_ext=""
+ case $file in
+ *.exe)
+ if test ! -f "$file"; then
+ file=`$echo $file|${SED} 's,.exe$,,'`
+ stripped_ext=".exe"
+ fi
+ ;;
+ esac
+
+ # Do a test to see if this is really a libtool program.
+ case $host in
+ *cygwin*|*mingw*)
+ wrapper=`$echo $file | ${SED} -e 's,.exe$,,'`
+ ;;
+ *)
+ wrapper=$file
+ ;;
+ esac
+ if (${SED} -e '4q' $wrapper | grep "^# Generated by .*$PACKAGE")>/dev/null 2>&1; then
+ notinst_deplibs=
+ relink_command=
+
+ # Note that it is not necessary on cygwin/mingw to append a dot to
+ # foo even if both foo and FILE.exe exist: automatic-append-.exe
+ # behavior happens only for exec(3), not for open(2)! Also, sourcing
+ # `FILE.' does not work on cygwin managed mounts.
+ #
+ # If there is no directory component, then add one.
+ case $wrapper in
+ */* | *\\*) . ${wrapper} ;;
+ *) . ./${wrapper} ;;
+ esac
+
+ # Check the variables that should have been set.
+ if test -z "$notinst_deplibs"; then
+ $echo "$modename: invalid libtool wrapper script \`$wrapper'" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ finalize=yes
+ for lib in $notinst_deplibs; do
+ # Check to see that each library is installed.
+ libdir=
+ if test -f "$lib"; then
+ # If there is no directory component, then add one.
+ case $lib in
+ */* | *\\*) . $lib ;;
+ *) . ./$lib ;;
+ esac
+ fi
+ libfile="$libdir/"`$echo "X$lib" | $Xsed -e 's%^.*/%%g'` ### testsuite: skip nested quoting test
+ if test -n "$libdir" && test ! -f "$libfile"; then
+ $echo "$modename: warning: \`$lib' has not been installed in \`$libdir'" 1>&2
+ finalize=no
+ fi
+ done
+
+ relink_command=
+ # Note that it is not necessary on cygwin/mingw to append a dot to
+ # foo even if both foo and FILE.exe exist: automatic-append-.exe
+ # behavior happens only for exec(3), not for open(2)! Also, sourcing
+ # `FILE.' does not work on cygwin managed mounts.
+ #
+ # If there is no directory component, then add one.
+ case $wrapper in
+ */* | *\\*) . ${wrapper} ;;
+ *) . ./${wrapper} ;;
+ esac
+
+ outputname=
+ if test "$fast_install" = no && test -n "$relink_command"; then
+ if test "$finalize" = yes && test -z "$run"; then
+ tmpdir=`func_mktempdir`
+ file=`$echo "X$file$stripped_ext" | $Xsed -e 's%^.*/%%'`
+ outputname="$tmpdir/$file"
+ # Replace the output file specification.
+ relink_command=`$echo "X$relink_command" | $SP2NL | $Xsed -e 's%@OUTPUT@%'"$outputname"'%g' | $NL2SP`
+
+ $show "$relink_command"
+ if $run eval "$relink_command"; then :
+ else
+ $echo "$modename: error: relink \`$file' with the above command before installing it" 1>&2
+ ${rm}r "$tmpdir"
+ continue
+ fi
+ file="$outputname"
+ else
+ $echo "$modename: warning: cannot relink \`$file'" 1>&2
+ fi
+ else
+ # Install the binary that we compiled earlier.
+ file=`$echo "X$file$stripped_ext" | $Xsed -e "s%\([^/]*\)$%$objdir/\1%"`
+ fi
+ fi
+
+ # remove .exe since cygwin /usr/bin/install will append another
+ # one anyway
+ case $install_prog,$host in
+ */usr/bin/install*,*cygwin*)
+ case $file:$destfile in
+ *.exe:*.exe)
+ # this is ok
+ ;;
+ *.exe:*)
+ destfile=$destfile.exe
+ ;;
+ *:*.exe)
+ destfile=`$echo $destfile | ${SED} -e 's,.exe$,,'`
+ ;;
+ esac
+ ;;
+ esac
+ $show "$install_prog$stripme $file $destfile"
+ $run eval "$install_prog\$stripme \$file \$destfile" || exit $?
+ test -n "$outputname" && ${rm}r "$tmpdir"
+ ;;
+ esac
+ done
+
+ for file in $staticlibs; do
+ name=`$echo "X$file" | $Xsed -e 's%^.*/%%'`
+
+ # Set up the ranlib parameters.
+ oldlib="$destdir/$name"
+
+ $show "$install_prog $file $oldlib"
+ $run eval "$install_prog \$file \$oldlib" || exit $?
+
+ if test -n "$stripme" && test -n "$old_striplib"; then
+ $show "$old_striplib $oldlib"
+ $run eval "$old_striplib $oldlib" || exit $?
+ fi
+
+ # Do each command in the postinstall commands.
+ cmds=$old_postinstall_cmds
+ save_ifs="$IFS"; IFS='~'
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ eval cmd=\"$cmd\"
+ $show "$cmd"
+ $run eval "$cmd" || exit $?
+ done
+ IFS="$save_ifs"
+ done
+
+ if test -n "$future_libdirs"; then
+ $echo "$modename: warning: remember to run \`$progname --finish$future_libdirs'" 1>&2
+ fi
+
+ if test -n "$current_libdirs"; then
+ # Maybe just do a dry run.
+ test -n "$run" && current_libdirs=" -n$current_libdirs"
+ exec_cmd='$SHELL $progpath $preserve_args --finish$current_libdirs'
+ else
+ exit $EXIT_SUCCESS
+ fi
+ ;;
+
+ # libtool finish mode
+ finish)
+ modename="$modename: finish"
+ libdirs="$nonopt"
+ admincmds=
+
+ if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then
+ for dir
+ do
+ libdirs="$libdirs $dir"
+ done
+
+ for libdir in $libdirs; do
+ if test -n "$finish_cmds"; then
+ # Do each command in the finish commands.
+ cmds=$finish_cmds
+ save_ifs="$IFS"; IFS='~'
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ eval cmd=\"$cmd\"
+ $show "$cmd"
+ $run eval "$cmd" || admincmds="$admincmds
+ $cmd"
+ done
+ IFS="$save_ifs"
+ fi
+ if test -n "$finish_eval"; then
+ # Do the single finish_eval.
+ eval cmds=\"$finish_eval\"
+ $run eval "$cmds" || admincmds="$admincmds
+ $cmds"
+ fi
+ done
+ fi
+
+ # Exit here if they wanted silent mode.
+ test "$show" = : && exit $EXIT_SUCCESS
+
+ $echo "X----------------------------------------------------------------------" | $Xsed
+ $echo "Libraries have been installed in:"
+ for libdir in $libdirs; do
+ $echo " $libdir"
+ done
+ $echo
+ $echo "If you ever happen to want to link against installed libraries"
+ $echo "in a given directory, LIBDIR, you must either use libtool, and"
+ $echo "specify the full pathname of the library, or use the \`-LLIBDIR'"
+ $echo "flag during linking and do at least one of the following:"
+ if test -n "$shlibpath_var"; then
+ $echo " - add LIBDIR to the \`$shlibpath_var' environment variable"
+ $echo " during execution"
+ fi
+ if test -n "$runpath_var"; then
+ $echo " - add LIBDIR to the \`$runpath_var' environment variable"
+ $echo " during linking"
+ fi
+ if test -n "$hardcode_libdir_flag_spec"; then
+ libdir=LIBDIR
+ eval flag=\"$hardcode_libdir_flag_spec\"
+
+ $echo " - use the \`$flag' linker flag"
+ fi
+ if test -n "$admincmds"; then
+ $echo " - have your system administrator run these commands:$admincmds"
+ fi
+ if test -f /etc/ld.so.conf; then
+ $echo " - have your system administrator add LIBDIR to \`/etc/ld.so.conf'"
+ fi
+ $echo
+ $echo "See any operating system documentation about shared libraries for"
+ $echo "more information, such as the ld(1) and ld.so(8) manual pages."
+ $echo "X----------------------------------------------------------------------" | $Xsed
+ exit $EXIT_SUCCESS
+ ;;
+
+ # libtool execute mode
+ execute)
+ modename="$modename: execute"
+
+ # The first argument is the command name.
+ cmd="$nonopt"
+ if test -z "$cmd"; then
+ $echo "$modename: you must specify a COMMAND" 1>&2
+ $echo "$help"
+ exit $EXIT_FAILURE
+ fi
+
+ # Handle -dlopen flags immediately.
+ for file in $execute_dlfiles; do
+ if test ! -f "$file"; then
+ $echo "$modename: \`$file' is not a file" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ dir=
+ case $file in
+ *.la)
+ # Check to see that this really is a libtool archive.
+ if (${SED} -e '2q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then :
+ else
+ $echo "$modename: \`$lib' is not a valid libtool archive" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ # Read the libtool library.
+ dlname=
+ library_names=
+
+ # If there is no directory component, then add one.
+ case $file in
+ */* | *\\*) . $file ;;
+ *) . ./$file ;;
+ esac
+
+ # Skip this library if it cannot be dlopened.
+ if test -z "$dlname"; then
+ # Warn if it was a shared library.
+ test -n "$library_names" && $echo "$modename: warning: \`$file' was not linked with \`-export-dynamic'"
+ continue
+ fi
+
+ dir=`$echo "X$file" | $Xsed -e 's%/[^/]*$%%'`
+ test "X$dir" = "X$file" && dir=.
+
+ if test -f "$dir/$objdir/$dlname"; then
+ dir="$dir/$objdir"
+ else
+ if test ! -f "$dir/$dlname"; then
+ $echo "$modename: cannot find \`$dlname' in \`$dir' or \`$dir/$objdir'" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ fi
+ ;;
+
+ *.lo)
+ # Just add the directory containing the .lo file.
+ dir=`$echo "X$file" | $Xsed -e 's%/[^/]*$%%'`
+ test "X$dir" = "X$file" && dir=.
+ ;;
+
+ *)
+ $echo "$modename: warning \`-dlopen' is ignored for non-libtool libraries and objects" 1>&2
+ continue
+ ;;
+ esac
+
+ # Get the absolute pathname.
+ absdir=`cd "$dir" && pwd`
+ test -n "$absdir" && dir="$absdir"
+
+ # Now add the directory to shlibpath_var.
+ if eval "test -z \"\$$shlibpath_var\""; then
+ eval "$shlibpath_var=\"\$dir\""
+ else
+ eval "$shlibpath_var=\"\$dir:\$$shlibpath_var\""
+ fi
+ done
+
+ # This variable tells wrapper scripts just to set shlibpath_var
+ # rather than running their programs.
+ libtool_execute_magic="$magic"
+
+ # Check if any of the arguments is a wrapper script.
+ args=
+ for file
+ do
+ case $file in
+ -*) ;;
+ *)
+ # Do a test to see if this is really a libtool program.
+ if (${SED} -e '4q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then
+ # If there is no directory component, then add one.
+ case $file in
+ */* | *\\*) . $file ;;
+ *) . ./$file ;;
+ esac
+
+ # Transform arg to wrapped name.
+ file="$progdir/$program"
+ fi
+ ;;
+ esac
+ # Quote arguments (to preserve shell metacharacters).
+ file=`$echo "X$file" | $Xsed -e "$sed_quote_subst"`
+ args="$args \"$file\""
+ done
+
+ if test -z "$run"; then
+ if test -n "$shlibpath_var"; then
+ # Export the shlibpath_var.
+ eval "export $shlibpath_var"
+ fi
+
+ # Restore saved environment variables
+ for lt_var in LANG LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES
+ do
+ eval "if test \"\${save_$lt_var+set}\" = set; then
+ $lt_var=\$save_$lt_var; export $lt_var
+ fi"
+ done
+
+ # Now prepare to actually exec the command.
+ exec_cmd="\$cmd$args"
+ else
+ # Display what would be done.
+ if test -n "$shlibpath_var"; then
+ eval "\$echo \"\$shlibpath_var=\$$shlibpath_var\""
+ $echo "export $shlibpath_var"
+ fi
+ $echo "$cmd$args"
+ exit $EXIT_SUCCESS
+ fi
+ ;;
+
+ # libtool clean and uninstall mode
+ clean | uninstall)
+ modename="$modename: $mode"
+ rm="$nonopt"
+ files=
+ rmforce=
+ exit_status=0
+
+ # This variable tells wrapper scripts just to set variables rather
+ # than running their programs.
+ libtool_install_magic="$magic"
+
+ for arg
+ do
+ case $arg in
+ -f) rm="$rm $arg"; rmforce=yes ;;
+ -*) rm="$rm $arg" ;;
+ *) files="$files $arg" ;;
+ esac
+ done
+
+ if test -z "$rm"; then
+ $echo "$modename: you must specify an RM program" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ rmdirs=
+
+ origobjdir="$objdir"
+ for file in $files; do
+ dir=`$echo "X$file" | $Xsed -e 's%/[^/]*$%%'`
+ if test "X$dir" = "X$file"; then
+ dir=.
+ objdir="$origobjdir"
+ else
+ objdir="$dir/$origobjdir"
+ fi
+ name=`$echo "X$file" | $Xsed -e 's%^.*/%%'`
+ test "$mode" = uninstall && objdir="$dir"
+
+ # Remember objdir for removal later, being careful to avoid duplicates
+ if test "$mode" = clean; then
+ case " $rmdirs " in
+ *" $objdir "*) ;;
+ *) rmdirs="$rmdirs $objdir" ;;
+ esac
+ fi
+
+ # Don't error if the file doesn't exist and rm -f was used.
+ if (test -L "$file") >/dev/null 2>&1 \
+ || (test -h "$file") >/dev/null 2>&1 \
+ || test -f "$file"; then
+ :
+ elif test -d "$file"; then
+ exit_status=1
+ continue
+ elif test "$rmforce" = yes; then
+ continue
+ fi
+
+ rmfiles="$file"
+
+ case $name in
+ *.la)
+ # Possibly a libtool archive, so verify it.
+ if (${SED} -e '2q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then
+ . $dir/$name
+
+ # Delete the libtool libraries and symlinks.
+ for n in $library_names; do
+ rmfiles="$rmfiles $objdir/$n"
+ done
+ test -n "$old_library" && rmfiles="$rmfiles $objdir/$old_library"
+
+ case "$mode" in
+ clean)
+ case " $library_names " in
+ # " " in the beginning catches empty $dlname
+ *" $dlname "*) ;;
+ *) rmfiles="$rmfiles $objdir/$dlname" ;;
+ esac
+ test -n "$libdir" && rmfiles="$rmfiles $objdir/$name $objdir/${name}i"
+ ;;
+ uninstall)
+ if test -n "$library_names"; then
+ # Do each command in the postuninstall commands.
+ cmds=$postuninstall_cmds
+ save_ifs="$IFS"; IFS='~'
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ eval cmd=\"$cmd\"
+ $show "$cmd"
+ $run eval "$cmd"
+ if test "$?" -ne 0 && test "$rmforce" != yes; then
+ exit_status=1
+ fi
+ done
+ IFS="$save_ifs"
+ fi
+
+ if test -n "$old_library"; then
+ # Do each command in the old_postuninstall commands.
+ cmds=$old_postuninstall_cmds
+ save_ifs="$IFS"; IFS='~'
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ eval cmd=\"$cmd\"
+ $show "$cmd"
+ $run eval "$cmd"
+ if test "$?" -ne 0 && test "$rmforce" != yes; then
+ exit_status=1
+ fi
+ done
+ IFS="$save_ifs"
+ fi
+ # FIXME: should reinstall the best remaining shared library.
+ ;;
+ esac
+ fi
+ ;;
+
+ *.lo)
+ # Possibly a libtool object, so verify it.
+ if (${SED} -e '2q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then
+
+ # Read the .lo file
+ . $dir/$name
+
+ # Add PIC object to the list of files to remove.
+ if test -n "$pic_object" \
+ && test "$pic_object" != none; then
+ rmfiles="$rmfiles $dir/$pic_object"
+ fi
+
+ # Add non-PIC object to the list of files to remove.
+ if test -n "$non_pic_object" \
+ && test "$non_pic_object" != none; then
+ rmfiles="$rmfiles $dir/$non_pic_object"
+ fi
+ fi
+ ;;
+
+ *)
+ if test "$mode" = clean ; then
+ noexename=$name
+ case $file in
+ *.exe)
+ file=`$echo $file|${SED} 's,.exe$,,'`
+ noexename=`$echo $name|${SED} 's,.exe$,,'`
+ # $file with .exe has already been added to rmfiles,
+ # add $file without .exe
+ rmfiles="$rmfiles $file"
+ ;;
+ esac
+ # Do a test to see if this is a libtool program.
+ if (${SED} -e '4q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then
+ relink_command=
+ . $dir/$noexename
+
+ # note $name still contains .exe if it was in $file originally
+ # as does the version of $file that was added into $rmfiles
+ rmfiles="$rmfiles $objdir/$name $objdir/${name}S.${objext}"
+ if test "$fast_install" = yes && test -n "$relink_command"; then
+ rmfiles="$rmfiles $objdir/lt-$name"
+ fi
+ if test "X$noexename" != "X$name" ; then
+ rmfiles="$rmfiles $objdir/lt-${noexename}.c"
+ fi
+ fi
+ fi
+ ;;
+ esac
+ $show "$rm $rmfiles"
+ $run $rm $rmfiles || exit_status=1
+ done
+ objdir="$origobjdir"
+
+ # Try to remove the ${objdir}s in the directories where we deleted files
+ for dir in $rmdirs; do
+ if test -d "$dir"; then
+ $show "rmdir $dir"
+ $run rmdir $dir >/dev/null 2>&1
+ fi
+ done
+
+ exit $exit_status
+ ;;
+
+ "")
+ $echo "$modename: you must specify a MODE" 1>&2
+ $echo "$generic_help" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+
+ if test -z "$exec_cmd"; then
+ $echo "$modename: invalid operation mode \`$mode'" 1>&2
+ $echo "$generic_help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+fi # test -z "$show_help"
+
+if test -n "$exec_cmd"; then
+ eval exec $exec_cmd
+ exit $EXIT_FAILURE
+fi
+
+# We need to display help for each of the modes.
+case $mode in
+"") $echo \
+"Usage: $modename [OPTION]... [MODE-ARG]...
+
+Provide generalized library-building support services.
+
+ --config show all configuration variables
+ --debug enable verbose shell tracing
+-n, --dry-run display commands without modifying any files
+ --features display basic configuration information and exit
+ --finish same as \`--mode=finish'
+ --help display this help message and exit
+ --mode=MODE use operation mode MODE [default=inferred from MODE-ARGS]
+ --quiet same as \`--silent'
+ --silent don't print informational messages
+ --tag=TAG use configuration variables from tag TAG
+ --version print version information
+
+MODE must be one of the following:
+
+ clean remove files from the build directory
+ compile compile a source file into a libtool object
+ execute automatically set library path, then run a program
+ finish complete the installation of libtool libraries
+ install install libraries or executables
+ link create a library or an executable
+ uninstall remove libraries from an installed directory
+
+MODE-ARGS vary depending on the MODE. Try \`$modename --help --mode=MODE' for
+a more detailed description of MODE.
+
+Report bugs to <[email protected]>."
+ exit $EXIT_SUCCESS
+ ;;
+
+clean)
+ $echo \
+"Usage: $modename [OPTION]... --mode=clean RM [RM-OPTION]... FILE...
+
+Remove files from the build directory.
+
+RM is the name of the program to use to delete files associated with each FILE
+(typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed
+to RM.
+
+If FILE is a libtool library, object or program, all the files associated
+with it are deleted. Otherwise, only FILE itself is deleted using RM."
+ ;;
+
+compile)
+ $echo \
+"Usage: $modename [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE
+
+Compile a source file into a libtool library object.
+
+This mode accepts the following additional options:
+
+ -o OUTPUT-FILE set the output file name to OUTPUT-FILE
+ -prefer-pic try to building PIC objects only
+ -prefer-non-pic try to building non-PIC objects only
+ -static always build a \`.o' file suitable for static linking
+
+COMPILE-COMMAND is a command to be used in creating a \`standard' object file
+from the given SOURCEFILE.
+
+The output file name is determined by removing the directory component from
+SOURCEFILE, then substituting the C source code suffix \`.c' with the
+library object suffix, \`.lo'."
+ ;;
+
+execute)
+ $echo \
+"Usage: $modename [OPTION]... --mode=execute COMMAND [ARGS]...
+
+Automatically set library path, then run a program.
+
+This mode accepts the following additional options:
+
+ -dlopen FILE add the directory containing FILE to the library path
+
+This mode sets the library path environment variable according to \`-dlopen'
+flags.
+
+If any of the ARGS are libtool executable wrappers, then they are translated
+into their corresponding uninstalled binary, and any of their required library
+directories are added to the library path.
+
+Then, COMMAND is executed, with ARGS as arguments."
+ ;;
+
+finish)
+ $echo \
+"Usage: $modename [OPTION]... --mode=finish [LIBDIR]...
+
+Complete the installation of libtool libraries.
+
+Each LIBDIR is a directory that contains libtool libraries.
+
+The commands that this mode executes may require superuser privileges. Use
+the \`--dry-run' option if you just want to see what would be executed."
+ ;;
+
+install)
+ $echo \
+"Usage: $modename [OPTION]... --mode=install INSTALL-COMMAND...
+
+Install executables or libraries.
+
+INSTALL-COMMAND is the installation command. The first component should be
+either the \`install' or \`cp' program.
+
+The rest of the components are interpreted as arguments to that command (only
+BSD-compatible install options are recognized)."
+ ;;
+
+link)
+ $echo \
+"Usage: $modename [OPTION]... --mode=link LINK-COMMAND...
+
+Link object files or libraries together to form another library, or to
+create an executable program.
+
+LINK-COMMAND is a command using the C compiler that you would use to create
+a program from several object files.
+
+The following components of LINK-COMMAND are treated specially:
+
+ -all-static do not do any dynamic linking at all
+ -avoid-version do not add a version suffix if possible
+ -dlopen FILE \`-dlpreopen' FILE if it cannot be dlopened at runtime
+ -dlpreopen FILE link in FILE and add its symbols to lt_preloaded_symbols
+ -export-dynamic allow symbols from OUTPUT-FILE to be resolved with dlsym(3)
+ -export-symbols SYMFILE
+ try to export only the symbols listed in SYMFILE
+ -export-symbols-regex REGEX
+ try to export only the symbols matching REGEX
+ -LLIBDIR search LIBDIR for required installed libraries
+ -lNAME OUTPUT-FILE requires the installed library libNAME
+ -module build a library that can dlopened
+ -no-fast-install disable the fast-install mode
+ -no-install link a not-installable executable
+ -no-undefined declare that a library does not refer to external symbols
+ -o OUTPUT-FILE create OUTPUT-FILE from the specified objects
+ -objectlist FILE Use a list of object files found in FILE to specify objects
+ -precious-files-regex REGEX
+ don't remove output files matching REGEX
+ -release RELEASE specify package release information
+ -rpath LIBDIR the created library will eventually be installed in LIBDIR
+ -R[ ]LIBDIR add LIBDIR to the runtime path of programs and libraries
+ -static do not do any dynamic linking of uninstalled libtool libraries
+ -static-libtool-libs
+ do not do any dynamic linking of libtool libraries
+ -version-info CURRENT[:REVISION[:AGE]]
+ specify library version info [each variable defaults to 0]
+
+All other options (arguments beginning with \`-') are ignored.
+
+Every other argument is treated as a filename. Files ending in \`.la' are
+treated as uninstalled libtool libraries, other files are standard or library
+object files.
+
+If the OUTPUT-FILE ends in \`.la', then a libtool library is created,
+only library objects (\`.lo' files) may be specified, and \`-rpath' is
+required, except when creating a convenience library.
+
+If OUTPUT-FILE ends in \`.a' or \`.lib', then a standard library is created
+using \`ar' and \`ranlib', or on Windows using \`lib'.
+
+If OUTPUT-FILE ends in \`.lo' or \`.${objext}', then a reloadable object file
+is created, otherwise an executable program is created."
+ ;;
+
+uninstall)
+ $echo \
+"Usage: $modename [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE...
+
+Remove libraries from an installation directory.
+
+RM is the name of the program to use to delete files associated with each FILE
+(typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed
+to RM.
+
+If FILE is a libtool library, all the files associated with it are deleted.
+Otherwise, only FILE itself is deleted using RM."
+ ;;
+
+*)
+ $echo "$modename: invalid operation mode \`$mode'" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+esac
+
+$echo
+$echo "Try \`$modename --help' for more information about other modes."
+
+exit $?
+
+# The TAGs below are defined such that we never get into a situation
+# in which we disable both kinds of libraries. Given conflicting
+# choices, we go for a static library, that is the most portable,
+# since we can't tell whether shared libraries were disabled because
+# the user asked for that or because the platform doesn't support
+# them. This is particularly important on AIX, because we don't
+# support having both static and shared libraries enabled at the same
+# time on that platform, so we default to a shared-only configuration.
+# If a disable-shared tag is given, we'll fallback to a static-only
+# configuration. But we'll never go from static-only to shared-only.
+
+# ### BEGIN LIBTOOL TAG CONFIG: disable-shared
+disable_libs=shared
+# ### END LIBTOOL TAG CONFIG: disable-shared
+
+# ### BEGIN LIBTOOL TAG CONFIG: disable-static
+disable_libs=static
+# ### END LIBTOOL TAG CONFIG: disable-static
+
+# Local Variables:
+# mode:shell-script
+# sh-indentation:2
+# End:
|
jeromer/modmemcachedinclude
|
dac7f7c2b8cb3f0d9fe3214b55e824f52a8ef011
|
- removed --tag=CC arg in configure.ac - update FAQ to explain that adding --tag=CC applies for mod_memcached_include as well as some systems already include the correct argument
|
diff --git a/FAQ b/FAQ
index 2a07f60..8a282a6 100644
--- a/FAQ
+++ b/FAQ
@@ -1,13 +1,15 @@
When compiling apr_memcache, I get the following error message : "unable to infer tagged configuration"
------------------------------------------------------------------------------------------------------
Open configure.ac and change the following line
LIBTOOL="`${APR_CONFIG} --apr-libtool`"
By the following one :
LIBTOOL="`${APR_CONFIG} --apr-libtool` --tag=CC"
And then run 'autoconf'.
Run make clean and restart the configuration process
+
+Note: this advice applies for mod_memcached_include as well
diff --git a/configure.ac b/configure.ac
index d3922f5..322df39 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1,51 +1,51 @@
AC_INIT(mod_memcached_include, 1.0)
MAKE_CONFIG_NICE(config.nice)
AC_PREREQ(2.53)
AC_CONFIG_SRCDIR([src/mod_memcached_include.c])
AC_CONFIG_AUX_DIR(config)
AC_PROG_LIBTOOL
AM_MAINTAINER_MODE
AC_CANONICAL_TARGET
AM_INIT_AUTOMAKE(AC_PACKAGE_NAME, AC_PACKAGE_VERSION)
AM_CONFIG_HEADER([src/mod_memcached_include_config.h:config.in])
AC_PROG_CC
AC_PROG_CXX
AC_PROG_LD
AC_PROG_INSTALL
CHECK_APR_MEMCACHE()
AP_VERSION=2.2.9
CHECK_APACHE(,$AP_VERSION,
:,:,
AC_MSG_ERROR([*** Apache version $AP_VERSION not found!])
)
prefix=${AP_PREFIX}
-LIBTOOL="`${APR_CONFIG} --apr-libtool` --tag=CC"
+LIBTOOL="`${APR_CONFIG} --apr-libtool`"
AC_SUBST(LIBTOOL)
MODULE_CFLAGS="${APXS_CFLAGS} ${AP_INCLUDES} ${APR_INCLUDES} ${APU_INCLUDES}"
AC_SUBST(MODULE_CFLAGS)
MODULE_LDFLAGS=" `${APR_CONFIG} --link-libtool` `${APU_CONFIG} --link-libtool`"
AC_SUBST(MODULE_LDFLAGS)
BIN_LDFLAGS=" `${APR_CONFIG} --link-libtool` `${APU_CONFIG} --link-libtool` `${APU_CONFIG} --ldflags --libs` `${APR_CONFIG} --ldflags --libs`"
AC_SUBST(BIN_LDFLAGS)
dnl this should be a list to all of the makefiles you expect to be generated
AC_CONFIG_FILES([Makefile src/Makefile])
AC_OUTPUT
dnl whatever you want here, or nothing
echo "---"
echo "Configuration summary for mod_memcached_include"
echo ""
echo " * Apache Modules Directory: $AP_LIBEXECDIR"
echo ""
echo "---"
|
jeromer/modmemcachedinclude
|
7648cd37405d08ba8e802f5173c47e902c550749
|
- set Apache 2.2.9 a mininal required version for Apache
|
diff --git a/configure.ac b/configure.ac
index 7e9dcea..d3922f5 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1,51 +1,51 @@
AC_INIT(mod_memcached_include, 1.0)
MAKE_CONFIG_NICE(config.nice)
AC_PREREQ(2.53)
AC_CONFIG_SRCDIR([src/mod_memcached_include.c])
AC_CONFIG_AUX_DIR(config)
AC_PROG_LIBTOOL
AM_MAINTAINER_MODE
AC_CANONICAL_TARGET
AM_INIT_AUTOMAKE(AC_PACKAGE_NAME, AC_PACKAGE_VERSION)
AM_CONFIG_HEADER([src/mod_memcached_include_config.h:config.in])
AC_PROG_CC
AC_PROG_CXX
AC_PROG_LD
AC_PROG_INSTALL
CHECK_APR_MEMCACHE()
-AP_VERSION=2.2.4
+AP_VERSION=2.2.9
CHECK_APACHE(,$AP_VERSION,
:,:,
AC_MSG_ERROR([*** Apache version $AP_VERSION not found!])
)
prefix=${AP_PREFIX}
LIBTOOL="`${APR_CONFIG} --apr-libtool` --tag=CC"
AC_SUBST(LIBTOOL)
MODULE_CFLAGS="${APXS_CFLAGS} ${AP_INCLUDES} ${APR_INCLUDES} ${APU_INCLUDES}"
AC_SUBST(MODULE_CFLAGS)
MODULE_LDFLAGS=" `${APR_CONFIG} --link-libtool` `${APU_CONFIG} --link-libtool`"
AC_SUBST(MODULE_LDFLAGS)
BIN_LDFLAGS=" `${APR_CONFIG} --link-libtool` `${APU_CONFIG} --link-libtool` `${APU_CONFIG} --ldflags --libs` `${APR_CONFIG} --ldflags --libs`"
AC_SUBST(BIN_LDFLAGS)
dnl this should be a list to all of the makefiles you expect to be generated
AC_CONFIG_FILES([Makefile src/Makefile])
AC_OUTPUT
dnl whatever you want here, or nothing
echo "---"
echo "Configuration summary for mod_memcached_include"
echo ""
echo " * Apache Modules Directory: $AP_LIBEXECDIR"
echo ""
echo "---"
|
jeromer/modmemcachedinclude
|
c29b6c8d52732fab494e8a715e0c5d8a6407fbde
|
- added tag to avoir compilation errors
|
diff --git a/configure.ac b/configure.ac
index 05f6750..7e9dcea 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1,51 +1,51 @@
AC_INIT(mod_memcached_include, 1.0)
MAKE_CONFIG_NICE(config.nice)
AC_PREREQ(2.53)
AC_CONFIG_SRCDIR([src/mod_memcached_include.c])
AC_CONFIG_AUX_DIR(config)
AC_PROG_LIBTOOL
AM_MAINTAINER_MODE
AC_CANONICAL_TARGET
AM_INIT_AUTOMAKE(AC_PACKAGE_NAME, AC_PACKAGE_VERSION)
AM_CONFIG_HEADER([src/mod_memcached_include_config.h:config.in])
AC_PROG_CC
AC_PROG_CXX
AC_PROG_LD
AC_PROG_INSTALL
CHECK_APR_MEMCACHE()
AP_VERSION=2.2.4
CHECK_APACHE(,$AP_VERSION,
:,:,
AC_MSG_ERROR([*** Apache version $AP_VERSION not found!])
)
prefix=${AP_PREFIX}
-LIBTOOL="`${APR_CONFIG} --apr-libtool`"
+LIBTOOL="`${APR_CONFIG} --apr-libtool` --tag=CC"
AC_SUBST(LIBTOOL)
MODULE_CFLAGS="${APXS_CFLAGS} ${AP_INCLUDES} ${APR_INCLUDES} ${APU_INCLUDES}"
AC_SUBST(MODULE_CFLAGS)
MODULE_LDFLAGS=" `${APR_CONFIG} --link-libtool` `${APU_CONFIG} --link-libtool`"
AC_SUBST(MODULE_LDFLAGS)
BIN_LDFLAGS=" `${APR_CONFIG} --link-libtool` `${APU_CONFIG} --link-libtool` `${APU_CONFIG} --ldflags --libs` `${APR_CONFIG} --ldflags --libs`"
AC_SUBST(BIN_LDFLAGS)
dnl this should be a list to all of the makefiles you expect to be generated
AC_CONFIG_FILES([Makefile src/Makefile])
AC_OUTPUT
dnl whatever you want here, or nothing
echo "---"
echo "Configuration summary for mod_memcached_include"
echo ""
echo " * Apache Modules Directory: $AP_LIBEXECDIR"
echo ""
echo "---"
|
jeromer/modmemcachedinclude
|
f6532c4470d0aa2aab96aaf714664bc7921c9714
|
- added FAQ
|
diff --git a/FAQ b/FAQ
new file mode 100644
index 0000000..2a07f60
--- /dev/null
+++ b/FAQ
@@ -0,0 +1,13 @@
+When compiling apr_memcache, I get the following error message : "unable to infer tagged configuration"
+------------------------------------------------------------------------------------------------------
+
+Open configure.ac and change the following line
+
+LIBTOOL="`${APR_CONFIG} --apr-libtool`"
+
+By the following one :
+
+LIBTOOL="`${APR_CONFIG} --apr-libtool` --tag=CC"
+
+And then run 'autoconf'.
+Run make clean and restart the configuration process
|
jeromer/modmemcachedinclude
|
8770265650aacb9496d4ea219150436b857f9ec8
|
- delete doc directory - moved INSTALL to root directory - moved source files to src - fixed issue 2 - deletes original Makefile - added empty 'config' dir
|
diff --git a/doc/INSTALL b/INSTALL
similarity index 54%
rename from doc/INSTALL
rename to INSTALL
index ae94e7f..04e4c8f 100644
--- a/doc/INSTALL
+++ b/INSTALL
@@ -1,91 +1,72 @@
What is this extension made for ?
=================================
This module may be used with any file that is pushed
in Memcached and meant to be fetched from an SSI tag.
How to compile this extension ?
===============================
You will have to install and compiler apr_memcache first.
This module uses version 0.7.0 do not use older versions.
apr_memcache may be downloaded here :
- http://www.outoforder.cc/projects/libs/apr_memcache/
- http://www.outoforder.cc/downloads/apr_memcache/apr_memcache-0.7.0.tar.bz2
Once apr_memcache is downloaded, extract it and compile it.
Note the path where it has been installed, you will need it.
-Unfortunately I did not had time to create a configure script.
-I wish I had some spare time to fix this issue as soon as possible.
-
-In order to compile the extension you will have to edit the Makefile.
-
-Change the following contents :
+Run
::
- builddir=.
- top_srcdir=/usr/local/apache-2.2.9
- top_builddir=/usr/local/apache-2.2.9
- include /usr/local/apache-2.2.9/build/special.mk
+ ./autogen.sh
+ ./configure
+ make
+ sudo make install
- # the used tools
- APXS=apxs
- APACHECTL=apache2ctl
+Depending on your system and your apr_memcache installation path
+you may need to specify the following arguments for the configure script:
- # additional defines, includes and libraries
- #DEFS=-DDEBUG_MEMCACHED_INCLUDE
- DEFS=
- INCLUDES=-I/usr/local/apache-2.2.9/include/apr_memcache-0
- LIBS=-L/usr/local/apache-2.2.9/lib -lapr_memcache
-
-By the following :
+--with-apxs=/path/to/apache/bin/apxs
+--with-apr-memcache=/path/to/apr_memcache/
+
+For example here is my configuration
::
- builddir=.
- top_srcdir=/path/to/your/apache/installtion/directory
- top_builddir=/path/to/your/apache/installation/directory
- include /path/to/your/apache/installation/build/special.mk
-
- # the used tools
- APXS=apxs
- APACHECTL=apachectl
+ ./configure --with-apxs=/usr/local/apache-2.2.9/bin/apxs \
+ --with-apr-memcache=/opt/local/
- # additional defines, includes and libraries
- #DEFS=-DDEBUG_MEMCACHED_INCLUDE
- DEFS=
- INCLUDES=-I/path/to/apr_memcache/installation/directory/apr_memcache-0
- LIBS=-L/path/to/your/apr_memcache/installation/directory/lib -lapr_memcache
+Once everything is compiled, restart Apache
How to test this extension ?
============================
In order to test the extension you have to first compile
the module and install it, once you are done you have to
launch test/push.php to store some contents in Memcached.
You can configure your Memcached host by editing push.php
After that you may create the following configuration
for Apache :
::
LoadModule memcached_include_module modules/mod_memcached_include.so
<Directory /path/to/mod_memcached_include/tests/>
AddType text/html .shtml
AddOutputFilter INCLUDES .shtml
Options +Includes
MemcachedHost localhost:11211
</Directory>
Once the file is stored in Memcached, you can ``test/pull-*.shtml``
files.
..
Local Variables:
mode: rst
fill-column: 79
End:
vim: et syn=rst tw=79
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..e69de29
diff --git a/Makefile b/Makefile
deleted file mode 100644
index 0b0586a..0000000
--- a/Makefile
+++ /dev/null
@@ -1,49 +0,0 @@
-##
-## Makefile -- Build procedure for sample memcached_include Apache module
-## Autogenerated via ``apxs -n memcached_include -g''.
-##
-
-## apxs -c -lapr_memcache -L/opt/local/lib -I/opt/local/include/apr_memcache-0 -DDEBUG_INCLUDE mod_memcached_include.c
-
-builddir=.
-top_srcdir=/usr/local/apache-2.2.9
-top_builddir=/usr/local/apache-2.2.9
-include /usr/local/apache-2.2.9/build/special.mk
-
-# the used tools
-APXS=apxs
-APACHECTL=apache2ctl
-
-# additional defines, includes and libraries
-#DEFS=-DDEBUG_MEMCACHED_INCLUDE
-DEFS=
-INCLUDES=-I/usr/local/apache-2.2.9/include/apr_memcache-0
-LIBS=-L/usr/local/apache-2.2.9/lib -lapr_memcache
-
-# the default target
-all: local-shared-build
-
-# install the shared object file into Apache
-install: install-modules-yes
-
-# cleanup
-clean:
- -rm -f mod_memcached_include.o mod_memcached_include.lo mod_memcached_include.slo mod_memcached_include.la
-
-# simple test
-test: reload
- lynx -mime_header http://localhost/memcached_include
-
-# install and activate shared object by reloading Apache to
-# force a reload of the shared object file
-reload: install restart
-
-# the general Apache start/restart/stop
-# procedures
-start:
- $(APACHECTL) start
-restart:
- $(APACHECTL) restart
-stop:
- $(APACHECTL) stop
-
diff --git a/Makefile.am b/Makefile.am
new file mode 100644
index 0000000..8c06be2
--- /dev/null
+++ b/Makefile.am
@@ -0,0 +1,12 @@
+AUTOMAKE_OPTIONS = foreign dist-bzip2
+
+EXTRA_DIST = m4/apache.m4 \
+ m4/apache_test.m4 \
+ m4/apr_memcache.m4 \
+ m4/config_nice.m4 \
+ LICENSE \
+ README \
+ INSTALL \
+ TODO
+
+SUBDIRS = src
diff --git a/README b/README
new file mode 100644
index 0000000..e69de29
diff --git a/STATUS b/STATUS
new file mode 100644
index 0000000..e69de29
diff --git a/TODO b/TODO
new file mode 100644
index 0000000..e69de29
diff --git a/autogen.sh b/autogen.sh
new file mode 100755
index 0000000..39f4e93
--- /dev/null
+++ b/autogen.sh
@@ -0,0 +1,60 @@
+#!/bin/sh
+
+export WANT_AUTOCONF=2.5
+
+LIBTOOLIZE=libtoolize
+AUTOMAKE=automake-1.9
+ACLOCAL=aclocal-1.9
+
+# Find the first extant libtoolize on the path out of a number of platform
+# specific possibilities.
+for l in libtoolize libtoolize15 libtoolize14 glibtoolize;
+do
+ ($l --version) < /dev/null > /dev/null 2>&1 && {
+ LIBTOOLIZE=$l
+ break
+ }
+done
+
+# Same for aclocal
+for a in aclocal aclocal-1.9 aclocal19 aclocal15 aclocal14;
+do
+ ($a --version) < /dev/null > /dev/null 2>&1 && {
+ ACLOCAL=$a
+ break
+ }
+done
+
+# Same for automake
+for m in automake automake-1.9 automake19 automake15 automake14;
+do
+ ($m --version) < /dev/null > /dev/null 2>&1 && {
+ AUTOMAKE=$m
+ break
+ }
+done
+
+for h in autoheader autoheader259 autoheader253;
+do
+ ($h --version) < /dev/null > /dev/null 2>&1 && {
+ AUTOHEADER=$h
+ break
+ }
+done
+
+for c in autoconf autoconf259 autoconf253;
+do
+ ($c --version) < /dev/null > /dev/null 2>&1 && {
+ AUTOCONF=$c
+ break
+ }
+done
+
+
+$ACLOCAL -I m4
+$AUTOHEADER
+$LIBTOOLIZE --force --copy
+$AUTOMAKE --add-missing --copy --foreign
+$AUTOCONF
+
+rm -rf autom4te.cache
diff --git a/configure.ac b/configure.ac
new file mode 100644
index 0000000..05f6750
--- /dev/null
+++ b/configure.ac
@@ -0,0 +1,51 @@
+AC_INIT(mod_memcached_include, 1.0)
+MAKE_CONFIG_NICE(config.nice)
+AC_PREREQ(2.53)
+
+AC_CONFIG_SRCDIR([src/mod_memcached_include.c])
+AC_CONFIG_AUX_DIR(config)
+AC_PROG_LIBTOOL
+AM_MAINTAINER_MODE
+AC_CANONICAL_TARGET
+AM_INIT_AUTOMAKE(AC_PACKAGE_NAME, AC_PACKAGE_VERSION)
+
+AM_CONFIG_HEADER([src/mod_memcached_include_config.h:config.in])
+
+AC_PROG_CC
+AC_PROG_CXX
+AC_PROG_LD
+AC_PROG_INSTALL
+
+CHECK_APR_MEMCACHE()
+
+AP_VERSION=2.2.4
+CHECK_APACHE(,$AP_VERSION,
+ :,:,
+ AC_MSG_ERROR([*** Apache version $AP_VERSION not found!])
+)
+
+prefix=${AP_PREFIX}
+
+LIBTOOL="`${APR_CONFIG} --apr-libtool`"
+AC_SUBST(LIBTOOL)
+
+MODULE_CFLAGS="${APXS_CFLAGS} ${AP_INCLUDES} ${APR_INCLUDES} ${APU_INCLUDES}"
+AC_SUBST(MODULE_CFLAGS)
+
+MODULE_LDFLAGS=" `${APR_CONFIG} --link-libtool` `${APU_CONFIG} --link-libtool`"
+AC_SUBST(MODULE_LDFLAGS)
+
+BIN_LDFLAGS=" `${APR_CONFIG} --link-libtool` `${APU_CONFIG} --link-libtool` `${APU_CONFIG} --ldflags --libs` `${APR_CONFIG} --ldflags --libs`"
+AC_SUBST(BIN_LDFLAGS)
+
+dnl this should be a list to all of the makefiles you expect to be generated
+AC_CONFIG_FILES([Makefile src/Makefile])
+AC_OUTPUT
+
+dnl whatever you want here, or nothing
+echo "---"
+echo "Configuration summary for mod_memcached_include"
+echo ""
+echo " * Apache Modules Directory: $AP_LIBEXECDIR"
+echo ""
+echo "---"
diff --git a/m4/apache.m4 b/m4/apache.m4
new file mode 100644
index 0000000..7d4bafa
--- /dev/null
+++ b/m4/apache.m4
@@ -0,0 +1,137 @@
+dnl -------------------------------------------------------- -*- autoconf -*-
+dnl Copyright 2005 The Apache Software Foundation
+dnl
+dnl Licensed under the Apache License, Version 2.0 (the "License");
+dnl you may not use this file except in compliance with the License.
+dnl You may obtain a copy of the License at
+dnl
+dnl http://www.apache.org/licenses/LICENSE-2.0
+dnl
+dnl Unless required by applicable law or agreed to in writing, software
+dnl distributed under the License is distributed on an "AS IS" BASIS,
+dnl WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+dnl See the License for the specific language governing permissions and
+dnl limitations under the License.
+
+dnl CHECK_APACHE([MINIMUM13-VERSION [, MINIMUM20-VERSION [,
+dnl ACTION-IF-FOUND13 [, ACTION-IF-FOUND20 [, ACTION-IF-NOT-FOUND]]])
+dnl Test for Apache apxs, APR, and APU
+
+AC_DEFUN([CHECK_APACHE],
+[dnl
+AC_ARG_WITH(
+ apxs,
+ [AC_HELP_STRING([--with-apxs=PATH],[Path to apxs])],
+ apxs_prefix="$withval",
+ apxs_prefix="/usr"
+ )
+
+AC_ARG_ENABLE(
+ apachetest,
+ [AC_HELP_STRING([--disable-apxstest],[Do not try to compile and run apache version test program])],
+ ,
+ enable_apachetest=yes
+ )
+
+ if test -x $apxs_prefix -a ! -d $apxs_prefix; then
+ APXS_BIN=$apxs_prefix
+ else
+ test_paths="$apxs_prefix:$apxs_prefix/bin:$apxs_prefix/sbin"
+ test_paths="${test_paths}:/usr/bin:/usr/sbin"
+ test_paths="${test_paths}:/usr/local/bin:/usr/local/sbin:/usr/local/apache2/bin"
+ AC_PATH_PROG(APXS_BIN, apxs, no, [$test_paths])
+ fi
+ min_apache13_version=ifelse([$1], ,no,$1)
+ min_apache20_version=ifelse([$2], ,no,$2)
+ no_apxs=""
+ if test "$APXS_BIN" = "no"; then
+ AC_MSG_ERROR([*** The apxs binary installed by apache could not be found!])
+ AC_MSG_ERROR([*** Use the --with-apxs option with the full path to apxs])
+ else
+ AP_INCLUDES="-I`$APXS_BIN -q INCLUDEDIR 2>/dev/null`"
+ AP_INCLUDEDIR="`$APXS_BIN -q INCLUDEDIR 2>/dev/null`"
+
+ AP_PREFIX="`$APXS_BIN -q prefix 2>/dev/null`"
+
+ AP_BINDIR="`$APXS_BIN -q bindir 2>/dev/null`"
+ AP_SBINDIR="`$APXS_BIN -q sbindir 2>/dev/null`"
+
+ APXS_CFLAGS=""
+ for flag in CFLAGS EXTRA_CFLAGS EXTRA_CPPFLAGS NOTEST_CFLAGS; do
+ APXS_CFLAGS="$APXS_CFLAGS `$APXS_BIN -q $flag 2>/dev/null`"
+ done
+
+ AP_CPPFLAGS="$APXS_CPPFLAGS $AP_INCLUDES"
+ AP_CFLAGS="$APXS_CFLAGS $AP_INCLUDES"
+
+ AP_LIBEXECDIR=`$APXS_BIN -q LIBEXECDIR 2>/dev/null`
+
+ if test "x$enable_apachetest" = "xyes" ; then
+ if test "$min_apache20_version" != "no"; then
+ APR_CONFIG="`$APXS_BIN -q APR_BINDIR 2>/dev/null`/apr-1-config"
+ if test ! -x $APR_CONFIG; then
+ APR_CONFIG="`$APXS_BIN -q APR_BINDIR 2>/dev/null`/apr-config"
+ fi
+ APR_INCLUDES=`$APR_CONFIG --includes 2>/dev/null`
+ APR_VERSION=`$APR_CONFIG --version 2>/dev/null`
+ APU_CONFIG="`$APXS_BIN -q APU_BINDIR 2>/dev/null`/apu-1-config"
+ if test ! -x $APU_CONFIG; then
+ APU_CONFIG="`$APXS_BIN -q APU_BINDIR 2>/dev/null`/apu-config"
+ fi
+ APU_INCLUDES=`$APU_CONFIG --includes 2>/dev/null`
+ APU_VERSION=`$APU_CONFIG --version 2>/dev/null`
+
+ AC_MSG_CHECKING(for Apache 2.0 version >= $min_apache20_version)
+ TEST_APACHE_VERSION(20,$min_apache20_version,
+ AC_MSG_RESULT(yes)
+ AC_DEFINE(WITH_APACHE20,1,[Define to 1 if we are compiling with Apache 2.0.x])
+ AP_VERSION="2.0"
+ APXS_EXTENSION=.la
+ AP_CFLAGS="$AP_CFLAGS $APU_INCLUDES $APR_INCLUDES"
+ AP_CPPFLAGS="$AP_CPPFLAGS $APU_INCLUDES $APR_INCLUDES"
+ AP_DEFS="-DWITH_APACHE20"
+ ifelse([$4], , , $4),
+ AC_MSG_RESULT(no)
+ if test "x$min_apache13_version" = "xno"; then
+ ifelse([$5], , , $5)
+ fi
+ )
+ fi
+ if test "$min_apache13_version" != "no" -a "x$AP_VERSION" = "x"; then
+ APR_INCLUDES=""
+ APR_VERSION=""
+ APU_INCLUDES=""
+ APU_VERSION=""
+ AC_MSG_CHECKING(for Apache 1.3 version >= $min_apache13_version)
+ TEST_APACHE_VERSION(13,$min_apache13_version,
+ AC_MSG_RESULT(yes)
+ AC_DEFINE(WITH_APACHE13,1,[Define to 1 if we are compiling with Apache 1.3.x])
+ AP_VERSION="1.3"
+ APXS_EXTENSION=.so
+ AP_CFLAGS="-g $AP_CFLAGS"
+ AP_DEFS="-DWITH_APACHE13"
+ ifelse([$3], , , $3),
+ AC_MSG_RESULT(no)
+ ifelse([$5], , , $5)
+ )
+ fi
+ fi
+ AC_SUBST(AP_DEFS)
+ AC_SUBST(AP_PREFIX)
+ AC_SUBST(AP_CFLAGS)
+ AC_SUBST(AP_CPPFLAGS)
+ AC_SUBST(AP_INCLUDES)
+ AC_SUBST(AP_INCLUDEDIR)
+ AC_SUBST(AP_LIBEXECDIR)
+ AC_SUBST(AP_VERSION)
+ AC_SUBST(AP_BINDIR)
+ AC_SUBST(AP_SBINDIR)
+ AC_SUBST(APR_CONFIG)
+ AC_SUBST(APU_CONFIG)
+ AC_SUBST(APR_INCLUDES)
+ AC_SUBST(APU_INCLUDES)
+ AC_SUBST(APXS_EXTENSION)
+ AC_SUBST(APXS_BIN)
+ AC_SUBST(APXS_CFLAGS)
+ fi
+])
diff --git a/m4/apache_test.m4 b/m4/apache_test.m4
new file mode 100644
index 0000000..1df6e0d
--- /dev/null
+++ b/m4/apache_test.m4
@@ -0,0 +1,112 @@
+dnl -------------------------------------------------------- -*- autoconf -*-
+dnl Copyright 2005 The Apache Software Foundation
+dnl
+dnl Licensed under the Apache License, Version 2.0 (the "License");
+dnl you may not use this file except in compliance with the License.
+dnl You may obtain a copy of the License at
+dnl
+dnl http://www.apache.org/licenses/LICENSE-2.0
+dnl
+dnl Unless required by applicable law or agreed to in writing, software
+dnl distributed under the License is distributed on an "AS IS" BASIS,
+dnl WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+dnl See the License for the specific language governing permissions and
+dnl limitations under the License.
+
+
+dnl TEST_APACHE_VERSION(RELEASE, [MINIMUM-VERSION [, ACTION-IF-FOUND [, ACTION-IF-NOT-FOUND]]])
+dnl Test for Apache
+dnl
+AC_DEFUN([TEST_APACHE_VERSION],
+[dnl
+ AC_REQUIRE([AC_CANONICAL_TARGET])
+ releasetest=$1
+ min_apache_version="$2"
+ no_apache=""
+ ac_save_CFLAGS="$CFLAGS"
+ CFLAGS="$CFLAGS $AP_CFLAGS"
+ if test $releasetest -eq 20; then
+ CFLAGS="$CFLAGS $APU_INCLUDES $APR_INCLUDES"
+ fi
+ AC_TRY_RUN([
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "httpd.h"
+
+#ifndef AP_SERVER_BASEREVISION
+ #define AP_SERVER_BASEREVISION SERVER_BASEREVISION
+#endif
+
+char* my_strdup (char *str)
+{
+ char *new_str;
+
+ if (str) {
+ new_str = (char *)malloc ((strlen (str) + 1) * sizeof(char));
+ strcpy (new_str, str);
+ } else
+ new_str = NULL;
+
+ return new_str;
+}
+
+int main (int argc, char *argv[])
+{
+ int major1, minor1, micro1;
+ int major2, minor2, micro2;
+ char *tmp_version;
+
+ { FILE *fp = fopen("conf.apachetest", "a"); if ( fp ) fclose(fp); }
+
+ tmp_version = my_strdup("$min_apache_version");
+ if (sscanf(tmp_version, "%d.%d.%d", &major1, &minor1, µ1) != 3) {
+ printf("%s, bad version string\n", "$min_apache_version");
+ exit(1);
+ }
+ tmp_version = my_strdup(AP_SERVER_BASEREVISION);
+ if (sscanf(tmp_version, "%d.%d.%d", &major2, &minor2, µ2) != 3) {
+ printf("%s, bad version string\n", AP_SERVER_BASEREVISION);
+ exit(1);
+ }
+
+ if ( (major2 == major1) &&
+ ( (minor2 > minor1) ||
+ ((minor2 == minor1) && (micro2 >= micro1)) ) ) {
+ exit(0);
+ } else {
+ exit(1);
+ }
+}
+
+],, no_apache=yes,[echo $ac_n "cross compiling; assumed OK... $ac_c"])
+ CFLAGS="$ac_save_CFLAGS"
+
+ if test "x$no_apache" = x ; then
+ ifelse([$3], , :, [$3])
+ else
+ if test -f conf.apachetest ; then
+ :
+ else
+ echo "*** Could not run Apache test program, checking why..."
+ CFLAGS="$CFLAGS $AP_CFLAGS"
+ if test $releasetest -eq 20; then
+ CFLAGS="$CFLAGS $APU_INCLUDES $APR_INCLUDES"
+ fi
+ AC_TRY_LINK([
+#include <stdio.h>
+#include "httpd.h"
+
+int main(int argc, char *argv[])
+{ return 0; }
+#undef main
+#define main K_and_R_C_main
+], [ return 0; ],
+ [ echo "*** The test program compiled, but failed to run. Check config.log" ],
+ [ echo "*** The test program failed to compile or link. Check config.log" ])
+ CFLAGS="$ac_save_CFLAGS"
+ fi
+ ifelse([$4], , :, [$4])
+ fi
+ rm -f conf.apachetest
+])
diff --git a/m4/apr_memcache.m4 b/m4/apr_memcache.m4
new file mode 100644
index 0000000..512c073
--- /dev/null
+++ b/m4/apr_memcache.m4
@@ -0,0 +1,59 @@
+dnl -------------------------------------------------------- -*- autoconf -*-
+dnl Copyright 2005 The Apache Software Foundation
+dnl
+dnl Licensed under the Apache License, Version 2.0 (the "License");
+dnl you may not use this file except in compliance with the License.
+dnl You may obtain a copy of the License at
+dnl
+dnl http://www.apache.org/licenses/LICENSE-2.0
+dnl
+dnl Unless required by applicable law or agreed to in writing, software
+dnl distributed under the License is distributed on an "AS IS" BASIS,
+dnl WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+dnl See the License for the specific language governing permissions and
+dnl limitations under the License.
+
+dnl Check for apr_memcache
+
+dnl CHECK_APR_MEMCACHE(ACTION-IF-FOUND [, ACTION-IF-NOT-FOUND])
+AC_DEFUN([CHECK_APR_MEMCACHE],
+[dnl
+
+APR_MEMCACHE_URL="http://www.outoforder.cc/projects/libs/apr_memcache/"
+AC_ARG_WITH(
+ apr_memcache,
+ [AC_HELP_STRING([--with-apr-memcache=PATH],[Path to apr_memcache library])],
+ mc_path="$withval",
+ :)
+
+if test -z $mc_path; then
+ test_paths="/usr/local/apr_memcache /usr/local /usr /opt/local"
+else
+ test_paths="${mc_path}"
+fi
+
+for x in $test_paths ; do
+ AC_MSG_CHECKING([for apr_memcache library in ${x}])
+ if test -f ${x}/include/apr_memcache-0/apr_memcache.h; then
+ AC_MSG_RESULT([yes])
+ APR_MEMCACHE_LIBS="-R${x}/lib -L${x}/lib -lapr_memcache"
+ APR_MEMCACHE_CFLAGS="-I${x}/include/apr_memcache-0"
+ break
+ else
+ AC_MSG_RESULT([no])
+ fi
+done
+
+AC_SUBST(APR_MEMCACHE_LIBS)
+AC_SUBST(APR_MEMCACHE_CFLAGS)
+
+if test -z "${APR_MEMCACHE_LIBS}"; then
+ AC_MSG_NOTICE([*** apr_memcache library not found.])
+ ifelse([$2], , AC_MSG_ERROR([The apr_memcache library is required.
+ See $APR_MEMCACHE_URL]), [$2])
+else
+ AC_MSG_NOTICE([found apr_memcache.])
+ ifelse([$1], , , [$1])
+fi
+])
+
diff --git a/m4/config_nice.m4 b/m4/config_nice.m4
new file mode 100644
index 0000000..3e0065d
--- /dev/null
+++ b/m4/config_nice.m4
@@ -0,0 +1,37 @@
+dnl -------------------------------------------------------- -*- autoconf -*-
+dnl Copyright 2005 The Apache Software Foundation
+dnl
+dnl Licensed under the Apache License, Version 2.0 (the "License");
+dnl you may not use this file except in compliance with the License.
+dnl You may obtain a copy of the License at
+dnl
+dnl http://www.apache.org/licenses/LICENSE-2.0
+dnl
+dnl Unless required by applicable law or agreed to in writing, software
+dnl distributed under the License is distributed on an "AS IS" BASIS,
+dnl WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+dnl See the License for the specific language governing permissions and
+dnl limitations under the License.
+
+dnl this writes a "config.nice" file which reinvokes ./configure with all
+dnl of the arguments. this is different from config.status which simply
+dnl regenerates the output files. config.nice is useful after you rebuild
+dnl ./configure (via autoconf or autogen.sh)
+AC_DEFUN([MAKE_CONFIG_NICE],[
+ echo configure: creating $1
+ rm -f $1
+ cat >$1<<EOF
+#! /bin/sh
+#
+# Created by configure
+
+EOF
+
+ for arg in [$]0 "[$]@"; do
+ if test "[$]arg" != "--no-create" -a "[$]arg" != "--no-recursion"; then
+ echo "\"[$]arg\" \\" >> $1
+ fi
+ done
+ echo '"[$]@"' >> $1
+ chmod +x $1
+])
diff --git a/modules.mk b/modules.mk
deleted file mode 100644
index 5259fbe..0000000
--- a/modules.mk
+++ /dev/null
@@ -1,4 +0,0 @@
-mod_memcached_include.la: mod_memcached_include.slo
- $(SH_LINK) -rpath $(libexecdir) -module -avoid-version mod_memcached_include.lo
-DISTCLEAN_TARGETS = modules.mk
-shared = mod_memcached_include.la
diff --git a/src/Makefile.am b/src/Makefile.am
new file mode 100644
index 0000000..bc0183d
--- /dev/null
+++ b/src/Makefile.am
@@ -0,0 +1,10 @@
+mod_memcached_include_la_SOURCES = mod_memcached_include.c mod_memcached_include.h
+mod_memcached_include_la_CFLAGS = -Wall ${MODULE_CFLAGS}
+mod_memcached_include_la_LDFLAGS = -rpath ${AP_LIBEXECDIR} -module -avoid-version ${MODULE_LDFLAGS}
+
+mod_LTLIBRARIES = mod_memcached_include.la
+moddir=${AP_LIBEXECDIR}
+
+install: install-am
+ rm -f $(DESTDIR)${AP_LIBEXECDIR}/mod_memcached_include.a
+ rm -f $(DESTDIR)${AP_LIBEXECDIR}/mod_memcached_include.la
diff --git a/mod_memcached_include.c b/src/mod_memcached_include.c
similarity index 100%
rename from mod_memcached_include.c
rename to src/mod_memcached_include.c
diff --git a/mod_memcached_include.h b/src/mod_memcached_include.h
similarity index 100%
rename from mod_memcached_include.h
rename to src/mod_memcached_include.h
|
jeromer/modmemcachedinclude
|
0421293080bfeec5c66c345b56856f6abd497526
|
- fixed bug #1
|
diff --git a/mod_memcached_include.c b/mod_memcached_include.c
index c6ff9d0..f5c5889 100644
--- a/mod_memcached_include.c
+++ b/mod_memcached_include.c
@@ -1216,1069 +1216,1057 @@ static int parse_expr(include_ctx_t *ctx, const char *expr, int *was_error)
default:
new->parent = current;
current = current->right = new;
continue;
}
break;
case TOKEN_RE:
switch (current->token.type) {
case TOKEN_EQ:
case TOKEN_NE:
new->parent = current;
current = current->right = new;
++regex;
continue;
default:
break;
}
break;
case TOKEN_AND:
case TOKEN_OR:
switch (current->token.type) {
case TOKEN_STRING:
case TOKEN_RE:
case TOKEN_GROUP:
current = current->parent;
while (current) {
switch (current->token.type) {
case TOKEN_AND:
case TOKEN_OR:
case TOKEN_LBRACE:
break;
default:
current = current->parent;
continue;
}
break;
}
if (!current) {
new->left = root;
root->parent = new;
current = root = new;
continue;
}
new->left = current->right;
new->left->parent = new;
new->parent = current;
current = current->right = new;
continue;
default:
break;
}
break;
case TOKEN_EQ:
case TOKEN_NE:
case TOKEN_GE:
case TOKEN_GT:
case TOKEN_LE:
case TOKEN_LT:
if (current->token.type == TOKEN_STRING) {
current = current->parent;
if (!current) {
new->left = root;
root->parent = new;
current = root = new;
continue;
}
switch (current->token.type) {
case TOKEN_LBRACE:
case TOKEN_AND:
case TOKEN_OR:
new->left = current->right;
new->left->parent = new;
new->parent = current;
current = current->right = new;
continue;
default:
break;
}
}
break;
case TOKEN_RBRACE:
while (current && current->token.type != TOKEN_LBRACE) {
current = current->parent;
}
if (current) {
TYPE_TOKEN(¤t->token, TOKEN_GROUP);
continue;
}
error = "Unmatched ')' in \"%s\" in file %s";
break;
case TOKEN_NOT:
case TOKEN_ACCESS:
case TOKEN_LBRACE:
switch (current->token.type) {
case TOKEN_STRING:
case TOKEN_RE:
case TOKEN_RBRACE:
case TOKEN_GROUP:
break;
default:
current->right = new;
new->parent = current;
current = new;
continue;
}
break;
default:
break;
}
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, error, expr, r->filename);
*was_error = 1;
return 0;
}
DEBUG_DUMP_TREE(ctx, root);
/* Evaluate Parse Tree */
current = root;
error = NULL;
while (current) {
switch (current->token.type) {
case TOKEN_STRING:
current->token.value =
ap_ssi_parse_string(ctx, current->token.value, NULL, 0,
SSI_EXPAND_DROP_NAME);
current->value = !!*current->token.value;
break;
case TOKEN_AND:
case TOKEN_OR:
if (!current->left || !current->right) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
"Invalid expression \"%s\" in file %s",
expr, r->filename);
*was_error = 1;
return 0;
}
if (!current->left->done) {
switch (current->left->token.type) {
case TOKEN_STRING:
current->left->token.value =
ap_ssi_parse_string(ctx, current->left->token.value,
NULL, 0, SSI_EXPAND_DROP_NAME);
current->left->value = !!*current->left->token.value;
DEBUG_DUMP_EVAL(ctx, current->left);
current->left->done = 1;
break;
default:
current = current->left;
continue;
}
}
/* short circuit evaluation */
if (!current->right->done && !regex &&
((current->token.type == TOKEN_AND && !current->left->value) ||
(current->token.type == TOKEN_OR && current->left->value))) {
current->value = current->left->value;
}
else {
if (!current->right->done) {
switch (current->right->token.type) {
case TOKEN_STRING:
current->right->token.value =
ap_ssi_parse_string(ctx,current->right->token.value,
NULL, 0, SSI_EXPAND_DROP_NAME);
current->right->value = !!*current->right->token.value;
DEBUG_DUMP_EVAL(ctx, current->right);
current->right->done = 1;
break;
default:
current = current->right;
continue;
}
}
if (current->token.type == TOKEN_AND) {
current->value = current->left->value &&
current->right->value;
}
else {
current->value = current->left->value ||
current->right->value;
}
}
break;
case TOKEN_EQ:
case TOKEN_NE:
if (!current->left || !current->right ||
current->left->token.type != TOKEN_STRING ||
(current->right->token.type != TOKEN_STRING &&
current->right->token.type != TOKEN_RE)) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
"Invalid expression \"%s\" in file %s",
expr, r->filename);
*was_error = 1;
return 0;
}
current->left->token.value =
ap_ssi_parse_string(ctx, current->left->token.value, NULL, 0,
SSI_EXPAND_DROP_NAME);
current->right->token.value =
ap_ssi_parse_string(ctx, current->right->token.value, NULL, 0,
SSI_EXPAND_DROP_NAME);
if (current->right->token.type == TOKEN_RE) {
current->value = re_check(ctx, current->left->token.value,
current->right->token.value);
--regex;
}
else {
current->value = !strcmp(current->left->token.value,
current->right->token.value);
}
if (current->token.type == TOKEN_NE) {
current->value = !current->value;
}
break;
case TOKEN_GE:
case TOKEN_GT:
case TOKEN_LE:
case TOKEN_LT:
if (!current->left || !current->right ||
current->left->token.type != TOKEN_STRING ||
current->right->token.type != TOKEN_STRING) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
"Invalid expression \"%s\" in file %s",
expr, r->filename);
*was_error = 1;
return 0;
}
current->left->token.value =
ap_ssi_parse_string(ctx, current->left->token.value, NULL, 0,
SSI_EXPAND_DROP_NAME);
current->right->token.value =
ap_ssi_parse_string(ctx, current->right->token.value, NULL, 0,
SSI_EXPAND_DROP_NAME);
current->value = strcmp(current->left->token.value,
current->right->token.value);
switch (current->token.type) {
case TOKEN_GE: current->value = current->value >= 0; break;
case TOKEN_GT: current->value = current->value > 0; break;
case TOKEN_LE: current->value = current->value <= 0; break;
case TOKEN_LT: current->value = current->value < 0; break;
default: current->value = 0; break; /* should not happen */
}
break;
case TOKEN_NOT:
case TOKEN_GROUP:
if (current->right) {
if (!current->right->done) {
current = current->right;
continue;
}
current->value = current->right->value;
}
else {
current->value = 1;
}
if (current->token.type == TOKEN_NOT) {
current->value = !current->value;
}
break;
case TOKEN_ACCESS:
if (current->left || !current->right ||
(current->right->token.type != TOKEN_STRING &&
current->right->token.type != TOKEN_RE)) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
"Invalid expression \"%s\" in file %s: Token '-A' must be followed by a URI string.",
expr, r->filename);
*was_error = 1;
return 0;
}
current->right->token.value =
ap_ssi_parse_string(ctx, current->right->token.value, NULL, 0,
SSI_EXPAND_DROP_NAME);
rr = ap_sub_req_lookup_uri(current->right->token.value, r, NULL);
/* 400 and higher are considered access denied */
if (rr->status < HTTP_BAD_REQUEST) {
current->value = 1;
}
else {
current->value = 0;
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, rr->status, r,
"mod_include: The tested "
"subrequest -A \"%s\" returned an error code.",
current->right->token.value);
}
ap_destroy_sub_req(rr);
break;
case TOKEN_RE:
if (!error) {
error = "No operator before regex in expr \"%s\" in file %s";
}
case TOKEN_LBRACE:
if (!error) {
error = "Unmatched '(' in \"%s\" in file %s";
}
default:
if (!error) {
error = "internal parser error in \"%s\" in file %s";
}
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, error, expr,r->filename);
*was_error = 1;
return 0;
}
DEBUG_DUMP_EVAL(ctx, current);
current->done = 1;
current = current->parent;
}
return (root ? root->value : 0);
}
/*
* +-------------------------------------------------------+
* | |
* | Action Handlers
* | |
* +-------------------------------------------------------+
*/
/*
* Extract the next tag name and value.
* If there are no more tags, set the tag name to NULL.
* The tag value is html decoded if dodecode is non-zero.
* The tag value may be NULL if there is no tag value..
*/
static void ap_ssi_get_tag_and_value(include_ctx_t *ctx, char **tag,
char **tag_val, int dodecode)
{
if (!ctx->intern->argv) {
*tag = NULL;
*tag_val = NULL;
return;
}
*tag_val = ctx->intern->argv->value;
*tag = ctx->intern->argv->name;
ctx->intern->argv = ctx->intern->argv->next;
if (dodecode && *tag_val) {
decodehtml(*tag_val);
}
return;
}
static int find_file(request_rec *r, const char *directive, const char *tag,
char *tag_val, apr_finfo_t *finfo)
{
char *to_send = tag_val;
request_rec *rr = NULL;
int ret=0;
char *error_fmt = NULL;
apr_status_t rv = APR_SUCCESS;
if (!strcmp(tag, "file")) {
char *newpath;
/* be safe; only files in this directory or below allowed */
rv = apr_filepath_merge(&newpath, NULL, tag_val,
APR_FILEPATH_SECUREROOTTEST |
APR_FILEPATH_NOTABSOLUTE, r->pool);
if (rv != APR_SUCCESS) {
error_fmt = "unable to access file \"%s\" "
"in parsed file %s";
}
else {
/* note: it is okay to pass NULL for the "next filter" since
we never attempt to "run" this sub request. */
rr = ap_sub_req_lookup_file(newpath, r, NULL);
if (rr->status == HTTP_OK && rr->finfo.filetype != 0) {
to_send = rr->filename;
if ((rv = apr_stat(finfo, to_send,
APR_FINFO_GPROT | APR_FINFO_MIN, rr->pool)) != APR_SUCCESS
&& rv != APR_INCOMPLETE) {
error_fmt = "unable to get information about \"%s\" "
"in parsed file %s";
}
}
else {
error_fmt = "unable to lookup information about \"%s\" "
"in parsed file %s";
}
}
if (error_fmt) {
ret = -1;
ap_log_rerror(APLOG_MARK, APLOG_ERR,
rv, r, error_fmt, to_send, r->filename);
}
if (rr) ap_destroy_sub_req(rr);
return ret;
}
else if (!strcmp(tag, "virtual")) {
/* note: it is okay to pass NULL for the "next filter" since
we never attempt to "run" this sub request. */
rr = ap_sub_req_lookup_uri(tag_val, r, NULL);
if (rr->status == HTTP_OK && rr->finfo.filetype != 0) {
memcpy((char *) finfo, (const char *) &rr->finfo,
sizeof(rr->finfo));
ap_destroy_sub_req(rr);
return 0;
}
else {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unable to get "
"information about \"%s\" in parsed file %s",
tag_val, r->filename);
ap_destroy_sub_req(rr);
return -1;
}
}
else {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unknown parameter \"%s\" "
"to tag %s in %s", tag, directive, r->filename);
return -1;
}
}
/*
* <!--#include virtual|file="..." [virtual|file="..."] ... -->
*/
static apr_status_t handle_include(include_ctx_t *ctx, ap_filter_t *f,
apr_bucket_brigade *bb)
{
request_rec *r = f->r;
if (!ctx->argc) {
ap_log_rerror(APLOG_MARK,
(ctx->flags & SSI_FLAG_PRINTING)
? APLOG_ERR : APLOG_WARNING,
0, r, "missing argument for include element in %s",
r->filename);
}
if (!(ctx->flags & SSI_FLAG_PRINTING)) {
return APR_SUCCESS;
}
if (!ctx->argc) {
SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
return APR_SUCCESS;
}
while (1) {
char *tag = NULL;
char *tag_val = NULL;
request_rec *rr = NULL;
char *error_fmt = NULL;
char *parsed_string;
ap_ssi_get_tag_and_value(ctx, &tag, &tag_val, SSI_VALUE_DECODED);
if (!tag || !tag_val) {
break;
}
if (strcmp(tag, "virtual") && strcmp(tag, "file") && strcmp(tag, "memcached")) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unknown parameter "
"\"%s\" to tag include in %s", tag, r->filename);
SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
break;
}
parsed_string = ap_ssi_parse_string(ctx, tag_val, NULL, 0,
SSI_EXPAND_DROP_NAME);
/* Fetching files from Memcached */
if (tag[0] == 'm') {
-#ifdef DEBUG_MEMCACHED_INCLUDE
- ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Found tag : %s", "memcached");
-#endif
include_server_config *conf;
apr_uint16_t flags;
char *strkey = NULL;
char *value;
apr_size_t value_len;
apr_status_t rv;
strkey = ap_escape_uri(r->pool, parsed_string);
conf = (include_server_config *)ap_get_module_config(r->server->module_config, &memcached_include_module);
#ifdef DEBUG_MEMCACHED_INCLUDE
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Fetching the file with key : %s", strkey);
#endif
rv = apr_memcache_getp(conf->memcached, r->pool, strkey, &value, &value_len, &flags);
if( rv == APR_SUCCESS ) {
#ifdef DEBUG_MEMCACHED_INCLUDE
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, rv, r, "File found with key %s, value : %s", strkey, value);
#endif
APR_BRIGADE_INSERT_TAIL(bb,
apr_bucket_pool_create(apr_pmemdup(ctx->pool, value, value_len),
value_len,
ctx->pool,
f->c->bucket_alloc));
+ return APR_SUCCESS;
}
-
- if (rv == APR_NOTFOUND) {
- ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, "File not found with key : %s", strkey);
- SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
- }
-
- if (rv != APR_SUCCESS) {
- ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, "Unable to fetch the file with key : %s", strkey);
- SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
+ else {
+ error_fmt = "Unable to fetch file with key '%s' in parsed file %s";
}
-
- return APR_SUCCESS;
}
-
- if (tag[0] == 'f') {
+ else if (tag[0] == 'f') {
char *newpath;
apr_status_t rv;
/* be safe only files in this directory or below allowed */
rv = apr_filepath_merge(&newpath, NULL, parsed_string,
APR_FILEPATH_SECUREROOTTEST |
APR_FILEPATH_NOTABSOLUTE, ctx->dpool);
if (rv != APR_SUCCESS) {
error_fmt = "unable to include file \"%s\" in parsed file %s";
}
else {
rr = ap_sub_req_lookup_file(newpath, r, f->next);
}
}
else {
rr = ap_sub_req_lookup_uri(parsed_string, r, f->next);
}
if (!error_fmt && rr->status != HTTP_OK) {
error_fmt = "unable to include \"%s\" in parsed file %s";
}
if (!error_fmt && (ctx->flags & SSI_FLAG_NO_EXEC) &&
rr->content_type && strncmp(rr->content_type, "text/", 5)) {
error_fmt = "unable to include potential exec \"%s\" in parsed "
"file %s";
}
/* See the Kludge in includes_filter for why.
* Basically, it puts a bread crumb in here, then looks
* for the crumb later to see if its been here.
*/
if (rr) {
ap_set_module_config(rr->request_config, &memcached_include_module, r);
}
if (!error_fmt && ap_run_sub_req(rr)) {
error_fmt = "unable to include \"%s\" in parsed file %s";
}
if (error_fmt) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, error_fmt, tag_val,
r->filename);
SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
}
/* Do *not* destroy the subrequest here; it may have allocated
* variables in this r->subprocess_env in the subrequest's
* r->pool, so that pool must survive as long as this request.
* Yes, this is a memory leak. */
if (error_fmt) {
break;
}
}
return APR_SUCCESS;
}
/*
* <!--#echo [encoding="..."] var="..." [encoding="..."] var="..." ... -->
*/
static apr_status_t handle_echo(include_ctx_t *ctx, ap_filter_t *f,
apr_bucket_brigade *bb)
{
enum {E_NONE, E_URL, E_ENTITY} encode;
request_rec *r = f->r;
if (!ctx->argc) {
ap_log_rerror(APLOG_MARK,
(ctx->flags & SSI_FLAG_PRINTING)
? APLOG_ERR : APLOG_WARNING,
0, r, "missing argument for echo element in %s",
r->filename);
}
if (!(ctx->flags & SSI_FLAG_PRINTING)) {
return APR_SUCCESS;
}
if (!ctx->argc) {
SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
return APR_SUCCESS;
}
encode = E_ENTITY;
while (1) {
char *tag = NULL;
char *tag_val = NULL;
ap_ssi_get_tag_and_value(ctx, &tag, &tag_val, SSI_VALUE_DECODED);
if (!tag || !tag_val) {
break;
}
if (!strcmp(tag, "var")) {
const char *val;
const char *echo_text = NULL;
apr_size_t e_len;
val = get_include_var(ap_ssi_parse_string(ctx, tag_val, NULL,
0, SSI_EXPAND_DROP_NAME),
ctx);
if (val) {
switch(encode) {
case E_NONE:
echo_text = val;
break;
case E_URL:
echo_text = ap_escape_uri(ctx->dpool, val);
break;
case E_ENTITY:
echo_text = ap_escape_html(ctx->dpool, val);
break;
}
e_len = strlen(echo_text);
}
else {
echo_text = ctx->intern->undefined_echo;
e_len = ctx->intern->undefined_echo_len;
}
APR_BRIGADE_INSERT_TAIL(bb, apr_bucket_pool_create(
apr_pmemdup(ctx->pool, echo_text, e_len),
e_len, ctx->pool, f->c->bucket_alloc));
}
else if (!strcmp(tag, "encoding")) {
if (!strcasecmp(tag_val, "none")) {
encode = E_NONE;
}
else if (!strcasecmp(tag_val, "url")) {
encode = E_URL;
}
else if (!strcasecmp(tag_val, "entity")) {
encode = E_ENTITY;
}
else {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unknown value "
"\"%s\" to parameter \"encoding\" of tag echo in "
"%s", tag_val, r->filename);
SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
break;
}
}
else {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unknown parameter "
"\"%s\" in tag echo of %s", tag, r->filename);
SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
break;
}
}
return APR_SUCCESS;
}
/*
* <!--#config [timefmt="..."] [sizefmt="..."] [errmsg="..."]
* [echomsg="..."] -->
*/
static apr_status_t handle_config(include_ctx_t *ctx, ap_filter_t *f,
apr_bucket_brigade *bb)
{
request_rec *r = f->r;
apr_table_t *env = r->subprocess_env;
if (!ctx->argc) {
ap_log_rerror(APLOG_MARK,
(ctx->flags & SSI_FLAG_PRINTING)
? APLOG_ERR : APLOG_WARNING,
0, r, "missing argument for config element in %s",
r->filename);
}
if (!(ctx->flags & SSI_FLAG_PRINTING)) {
return APR_SUCCESS;
}
if (!ctx->argc) {
SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
return APR_SUCCESS;
}
while (1) {
char *tag = NULL;
char *tag_val = NULL;
ap_ssi_get_tag_and_value(ctx, &tag, &tag_val, SSI_VALUE_RAW);
if (!tag || !tag_val) {
break;
}
if (!strcmp(tag, "errmsg")) {
ctx->error_str = ap_ssi_parse_string(ctx, tag_val, NULL, 0,
SSI_EXPAND_DROP_NAME);
}
else if (!strcmp(tag, "echomsg")) {
ctx->intern->undefined_echo =
ap_ssi_parse_string(ctx, tag_val, NULL, 0,SSI_EXPAND_DROP_NAME);
ctx->intern->undefined_echo_len=strlen(ctx->intern->undefined_echo);
}
else if (!strcmp(tag, "timefmt")) {
apr_time_t date = r->request_time;
ctx->time_str = ap_ssi_parse_string(ctx, tag_val, NULL, 0,
SSI_EXPAND_DROP_NAME);
apr_table_setn(env, "DATE_LOCAL", ap_ht_time(r->pool, date,
ctx->time_str, 0));
apr_table_setn(env, "DATE_GMT", ap_ht_time(r->pool, date,
ctx->time_str, 1));
apr_table_setn(env, "LAST_MODIFIED",
ap_ht_time(r->pool, r->finfo.mtime,
ctx->time_str, 0));
}
else if (!strcmp(tag, "sizefmt")) {
char *parsed_string;
parsed_string = ap_ssi_parse_string(ctx, tag_val, NULL, 0,
SSI_EXPAND_DROP_NAME);
if (!strcmp(parsed_string, "bytes")) {
ctx->flags |= SSI_FLAG_SIZE_IN_BYTES;
}
else if (!strcmp(parsed_string, "abbrev")) {
ctx->flags &= SSI_FLAG_SIZE_ABBREV;
}
else {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unknown value "
"\"%s\" to parameter \"sizefmt\" of tag config "
"in %s", parsed_string, r->filename);
SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
break;
}
}
else {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unknown parameter "
"\"%s\" to tag config in %s", tag, r->filename);
SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
break;
}
}
return APR_SUCCESS;
}
/*
* <!--#fsize virtual|file="..." [virtual|file="..."] ... -->
*/
static apr_status_t handle_fsize(include_ctx_t *ctx, ap_filter_t *f,
apr_bucket_brigade *bb)
{
request_rec *r = f->r;
if (!ctx->argc) {
ap_log_rerror(APLOG_MARK,
(ctx->flags & SSI_FLAG_PRINTING)
? APLOG_ERR : APLOG_WARNING,
0, r, "missing argument for fsize element in %s",
r->filename);
}
if (!(ctx->flags & SSI_FLAG_PRINTING)) {
return APR_SUCCESS;
}
if (!ctx->argc) {
SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
return APR_SUCCESS;
}
while (1) {
char *tag = NULL;
char *tag_val = NULL;
apr_finfo_t finfo;
char *parsed_string;
ap_ssi_get_tag_and_value(ctx, &tag, &tag_val, SSI_VALUE_DECODED);
if (!tag || !tag_val) {
break;
}
parsed_string = ap_ssi_parse_string(ctx, tag_val, NULL, 0,
SSI_EXPAND_DROP_NAME);
if (!find_file(r, "fsize", tag, parsed_string, &finfo)) {
char *buf;
apr_size_t len;
if (!(ctx->flags & SSI_FLAG_SIZE_IN_BYTES)) {
buf = apr_strfsize(finfo.size, apr_palloc(ctx->pool, 5));
len = 4; /* omit the \0 terminator */
}
else {
apr_size_t l, x, pos;
char *tmp;
tmp = apr_psprintf(ctx->dpool, "%" APR_OFF_T_FMT, finfo.size);
len = l = strlen(tmp);
for (x = 0; x < l; ++x) {
if (x && !((l - x) % 3)) {
++len;
}
}
if (len == l) {
buf = apr_pstrmemdup(ctx->pool, tmp, len);
}
else {
buf = apr_palloc(ctx->pool, len);
for (pos = x = 0; x < l; ++x) {
if (x && !((l - x) % 3)) {
buf[pos++] = ',';
}
buf[pos++] = tmp[x];
}
}
}
APR_BRIGADE_INSERT_TAIL(bb, apr_bucket_pool_create(buf, len,
ctx->pool, f->c->bucket_alloc));
}
else {
SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
break;
}
}
return APR_SUCCESS;
}
/*
* <!--#flastmod virtual|file="..." [virtual|file="..."] ... -->
*/
static apr_status_t handle_flastmod(include_ctx_t *ctx, ap_filter_t *f,
apr_bucket_brigade *bb)
{
request_rec *r = f->r;
if (!ctx->argc) {
ap_log_rerror(APLOG_MARK,
(ctx->flags & SSI_FLAG_PRINTING)
? APLOG_ERR : APLOG_WARNING,
0, r, "missing argument for flastmod element in %s",
r->filename);
}
if (!(ctx->flags & SSI_FLAG_PRINTING)) {
return APR_SUCCESS;
}
if (!ctx->argc) {
SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
return APR_SUCCESS;
}
while (1) {
char *tag = NULL;
char *tag_val = NULL;
apr_finfo_t finfo;
char *parsed_string;
ap_ssi_get_tag_and_value(ctx, &tag, &tag_val, SSI_VALUE_DECODED);
if (!tag || !tag_val) {
break;
}
parsed_string = ap_ssi_parse_string(ctx, tag_val, NULL, 0,
SSI_EXPAND_DROP_NAME);
if (!find_file(r, "flastmod", tag, parsed_string, &finfo)) {
char *t_val;
apr_size_t t_len;
t_val = ap_ht_time(ctx->pool, finfo.mtime, ctx->time_str, 0);
t_len = strlen(t_val);
APR_BRIGADE_INSERT_TAIL(bb, apr_bucket_pool_create(t_val, t_len,
ctx->pool, f->c->bucket_alloc));
}
else {
SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
break;
}
}
return APR_SUCCESS;
}
/*
* <!--#if expr="..." -->
*/
static apr_status_t handle_if(include_ctx_t *ctx, ap_filter_t *f,
apr_bucket_brigade *bb)
{
char *tag = NULL;
char *expr = NULL;
request_rec *r = f->r;
int expr_ret, was_error;
if (ctx->argc != 1) {
ap_log_rerror(APLOG_MARK,
(ctx->flags & SSI_FLAG_PRINTING)
? APLOG_ERR : APLOG_WARNING,
0, r, (ctx->argc)
? "too many arguments for if element in %s"
: "missing expr argument for if element in %s",
r->filename);
}
if (!(ctx->flags & SSI_FLAG_PRINTING)) {
++(ctx->if_nesting_level);
return APR_SUCCESS;
}
if (ctx->argc != 1) {
SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
return APR_SUCCESS;
}
ap_ssi_get_tag_and_value(ctx, &tag, &expr, SSI_VALUE_RAW);
if (strcmp(tag, "expr")) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unknown parameter \"%s\" "
"to tag if in %s", tag, r->filename);
SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
return APR_SUCCESS;
}
if (!expr) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "missing expr value for if "
"element in %s", r->filename);
SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
return APR_SUCCESS;
}
DEBUG_PRINTF((ctx, "**** if expr=\"%s\"\n", expr));
expr_ret = parse_expr(ctx, expr, &was_error);
if (was_error) {
SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
return APR_SUCCESS;
}
if (expr_ret) {
ctx->flags |= (SSI_FLAG_PRINTING | SSI_FLAG_COND_TRUE);
}
else {
ctx->flags &= SSI_FLAG_CLEAR_PRINT_COND;
}
DEBUG_DUMP_COND(ctx, " if");
ctx->if_nesting_level = 0;
return APR_SUCCESS;
}
/*
* <!--#elif expr="..." -->
*/
static apr_status_t handle_elif(include_ctx_t *ctx, ap_filter_t *f,
apr_bucket_brigade *bb)
{
char *tag = NULL;
char *expr = NULL;
request_rec *r = f->r;
int expr_ret, was_error;
if (ctx->argc != 1) {
ap_log_rerror(APLOG_MARK,
(!(ctx->if_nesting_level)) ? APLOG_ERR : APLOG_WARNING,
0, r, (ctx->argc)
? "too many arguments for if element in %s"
: "missing expr argument for if element in %s",
r->filename);
}
if (ctx->if_nesting_level) {
return APR_SUCCESS;
}
if (ctx->argc != 1) {
SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
return APR_SUCCESS;
}
ap_ssi_get_tag_and_value(ctx, &tag, &expr, SSI_VALUE_RAW);
if (strcmp(tag, "expr")) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unknown parameter \"%s\" "
"to tag if in %s", tag, r->filename);
SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
return APR_SUCCESS;
}
if (!expr) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "missing expr in elif "
"statement: %s", r->filename);
SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
return APR_SUCCESS;
}
DEBUG_PRINTF((ctx, "**** elif expr=\"%s\"\n", expr));
DEBUG_DUMP_COND(ctx, " elif");
if (ctx->flags & SSI_FLAG_COND_TRUE) {
@@ -3486,604 +3474,598 @@ static apr_status_t send_parsed_content(ap_filter_t *f, apr_bucket_brigade *bb)
* start again with PARSE_PRE_HEAD
*/
case PARSE_EXECUTE:
/* if there was an error, it was already logged; just stop here */
if (intern->error) {
if (ctx->flags & SSI_FLAG_PRINTING) {
SSI_CREATE_ERROR_BUCKET(ctx, f, pass_bb);
intern->error = 0;
}
}
else {
include_handler_fn_t *handle_func;
handle_func =
(include_handler_fn_t *)apr_hash_get(include_handlers, intern->directive,
intern->directive_len);
if (handle_func) {
DEBUG_INIT(ctx, f, pass_bb);
rv = handle_func(ctx, f, pass_bb);
if (rv != APR_SUCCESS) {
apr_brigade_destroy(pass_bb);
return rv;
}
}
else {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
"unknown directive \"%s\" in parsed doc %s",
apr_pstrmemdup(r->pool, intern->directive,
intern->directive_len),
r->filename);
if (ctx->flags & SSI_FLAG_PRINTING) {
SSI_CREATE_ERROR_BUCKET(ctx, f, pass_bb);
}
}
}
/* cleanup */
apr_pool_clear(ctx->dpool);
apr_brigade_cleanup(intern->tmp_bb);
/* Oooof. Done here, start next round */
intern->state = PARSE_PRE_HEAD;
break;
} /* switch(ctx->state) */
} /* while(brigade) */
/* End of stream. Final cleanup */
if (intern->seen_eos) {
if (PARSE_HEAD == intern->state) {
if (ctx->flags & SSI_FLAG_PRINTING) {
char *to_release = apr_pmemdup(ctx->pool, intern->start_seq,
intern->parse_pos);
APR_BRIGADE_INSERT_TAIL(pass_bb,
apr_bucket_pool_create(to_release,
intern->parse_pos, ctx->pool,
f->c->bucket_alloc));
}
}
else if (PARSE_PRE_HEAD != intern->state) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
"SSI directive was not properly finished at the end "
"of parsed document %s", r->filename);
if (ctx->flags & SSI_FLAG_PRINTING) {
SSI_CREATE_ERROR_BUCKET(ctx, f, pass_bb);
}
}
if (!(ctx->flags & SSI_FLAG_PRINTING)) {
ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
"missing closing endif directive in parsed document"
" %s", r->filename);
}
/* cleanup our temporary memory */
apr_brigade_destroy(intern->tmp_bb);
apr_pool_destroy(ctx->dpool);
/* don't forget to finally insert the EOS bucket */
APR_BRIGADE_INSERT_TAIL(pass_bb, b);
}
/* if something's left over, pass it along */
if (!APR_BRIGADE_EMPTY(pass_bb)) {
rv = ap_pass_brigade(f->next, pass_bb);
}
else {
rv = APR_SUCCESS;
apr_brigade_destroy(pass_bb);
}
return rv;
}
/*
* +-------------------------------------------------------+
* | |
* | Runtime Hooks
* | |
* +-------------------------------------------------------+
*/
static int includes_setup(ap_filter_t *f)
{
include_dir_config *conf = ap_get_module_config(f->r->per_dir_config,
&memcached_include_module);
/* When our xbithack value isn't set to full or our platform isn't
* providing group-level protection bits or our group-level bits do not
* have group-execite on, we will set the no_local_copy value to 1 so
* that we will not send 304s.
*/
if ((conf->xbithack != XBITHACK_FULL)
|| !(f->r->finfo.valid & APR_FINFO_GPROT)
|| !(f->r->finfo.protection & APR_GEXECUTE)) {
f->r->no_local_copy = 1;
}
/* Don't allow ETag headers to be generated - see RFC2616 - 13.3.4.
* We don't know if we are going to be including a file or executing
* a program - in either case a strong ETag header will likely be invalid.
*/
apr_table_setn(f->r->notes, "no-etag", "");
return OK;
}
static apr_status_t includes_filter(ap_filter_t *f, apr_bucket_brigade *b)
{
request_rec *r = f->r;
include_ctx_t *ctx = f->ctx;
request_rec *parent;
include_dir_config *conf = ap_get_module_config(r->per_dir_config,
&memcached_include_module);
include_server_config *sconf= ap_get_module_config(r->server->module_config,
&memcached_include_module);
if (!(ap_allow_options(r) & OPT_INCLUDES)) {
ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
"mod_include: Options +Includes (or IncludesNoExec) "
"wasn't set, INCLUDES filter removed");
ap_remove_output_filter(f);
return ap_pass_brigade(f->next, b);
}
if (!f->ctx) {
struct ssi_internal_ctx *intern;
/* create context for this filter */
f->ctx = ctx = apr_palloc(r->pool, sizeof(*ctx));
ctx->intern = intern = apr_palloc(r->pool, sizeof(*ctx->intern));
ctx->pool = r->pool;
apr_pool_create(&ctx->dpool, ctx->pool);
/* runtime data */
intern->tmp_bb = apr_brigade_create(ctx->pool, f->c->bucket_alloc);
intern->seen_eos = 0;
intern->state = PARSE_PRE_HEAD;
ctx->flags = (SSI_FLAG_PRINTING | SSI_FLAG_COND_TRUE);
if (ap_allow_options(r) & OPT_INCNOEXEC) {
ctx->flags |= SSI_FLAG_NO_EXEC;
}
intern->accessenable = conf->accessenable;
ctx->if_nesting_level = 0;
intern->re = NULL;
ctx->error_str = conf->default_error_msg;
ctx->time_str = conf->default_time_fmt;
intern->start_seq = sconf->default_start_tag;
intern->start_seq_pat = bndm_compile(ctx->pool, intern->start_seq,
strlen(intern->start_seq));
intern->end_seq = sconf->default_end_tag;
intern->end_seq_len = strlen(intern->end_seq);
intern->undefined_echo = conf->undefined_echo;
intern->undefined_echo_len = strlen(conf->undefined_echo);
}
if ((parent = ap_get_module_config(r->request_config, &memcached_include_module))) {
/* Kludge --- for nested includes, we want to keep the subprocess
* environment of the base document (for compatibility); that means
* torquing our own last_modified date as well so that the
* LAST_MODIFIED variable gets reset to the proper value if the
* nested document resets <!--#config timefmt -->.
*/
r->subprocess_env = r->main->subprocess_env;
apr_pool_join(r->main->pool, r->pool);
r->finfo.mtime = r->main->finfo.mtime;
}
else {
/* we're not a nested include, so we create an initial
* environment */
ap_add_common_vars(r);
ap_add_cgi_vars(r);
add_include_vars(r, conf->default_time_fmt);
}
/* Always unset the content-length. There is no way to know if
* the content will be modified at some point by send_parsed_content.
* It is very possible for us to not find any content in the first
* 9k of the file, but still have to modify the content of the file.
* If we are going to pass the file through send_parsed_content, then
* the content-length should just be unset.
*/
apr_table_unset(f->r->headers_out, "Content-Length");
/* Always unset the Last-Modified field - see RFC2616 - 13.3.4.
* We don't know if we are going to be including a file or executing
* a program which may change the Last-Modified header or make the
* content completely dynamic. Therefore, we can't support these
* headers.
* Exception: XBitHack full means we *should* set the Last-Modified field.
*/
/* Assure the platform supports Group protections */
if ((conf->xbithack == XBITHACK_FULL)
&& (r->finfo.valid & APR_FINFO_GPROT)
&& (r->finfo.protection & APR_GEXECUTE)) {
ap_update_mtime(r, r->finfo.mtime);
ap_set_last_modified(r);
}
else {
apr_table_unset(f->r->headers_out, "Last-Modified");
}
/* add QUERY stuff to env cause it ain't yet */
if (r->args) {
char *arg_copy = apr_pstrdup(r->pool, r->args);
apr_table_setn(r->subprocess_env, "QUERY_STRING", r->args);
ap_unescape_url(arg_copy);
apr_table_setn(r->subprocess_env, "QUERY_STRING_UNESCAPED",
ap_escape_shell_cmd(r->pool, arg_copy));
}
return send_parsed_content(f, b);
}
static int include_fixup(request_rec *r)
{
include_dir_config *conf;
conf = ap_get_module_config(r->per_dir_config, &memcached_include_module);
if (r->handler && (strcmp(r->handler, "server-parsed") == 0))
{
if (!r->content_type || !*r->content_type) {
ap_set_content_type(r, "text/html");
}
r->handler = "default-handler";
}
else
#if defined(OS2) || defined(WIN32) || defined(NETWARE)
/* These OS's don't support xbithack. This is being worked on. */
{
return DECLINED;
}
#else
{
if (conf->xbithack == XBITHACK_OFF) {
return DECLINED;
}
if (!(r->finfo.protection & APR_UEXECUTE)) {
return DECLINED;
}
if (!r->content_type || strcmp(r->content_type, "text/html")) {
return DECLINED;
}
}
#endif
/* We always return declined, because the default handler actually
* serves the file. All we have to do is add the filter.
*/
ap_add_output_filter("INCLUDES", NULL, r, r->connection);
return DECLINED;
}
/*
* +-------------------------------------------------------+
* | |
* | Configuration Handling
* | |
* +-------------------------------------------------------+
*/
static void *create_includes_dir_config(apr_pool_t *p, char *dummy)
{
include_dir_config *result = apr_palloc(p, sizeof(include_dir_config));
result->default_error_msg = DEFAULT_ERROR_MSG;
result->default_time_fmt = DEFAULT_TIME_FORMAT;
result->undefined_echo = DEFAULT_UNDEFINED_ECHO;
result->xbithack = DEFAULT_XBITHACK;
return result;
}
static void *create_includes_server_config(apr_pool_t *p, server_rec *server)
{
include_server_config *result;
result = apr_palloc(p, sizeof(include_server_config));
result->default_end_tag = DEFAULT_END_SEQUENCE;
result->default_start_tag = DEFAULT_START_SEQUENCE;
result->servers = apr_array_make(p, 1, sizeof(memcached_include_server_t));
result->max_servers = DEFAULT_MAX_SERVERS;
result->min_size = DEFAULT_MIN_SIZE;
result->max_size = DEFAULT_MAX_SIZE;
result->conn_min = DEFAULT_MIN_CONN;
result->conn_smax = DEFAULT_SMAX;
result->conn_max = DEFAULT_MAX;
result->conn_ttl = DEFAULT_TTL;
return result;
}
static const char *set_memcached_host(cmd_parms *cmd, void *mconfig, const char *arg)
{
char *host, *port;
memcached_include_server_t *memcached_server = NULL;
include_server_config *conf = ap_get_module_config(cmd->server->module_config, &memcached_include_module);
/*
* I should consider using apr_parse_addr_port instead
* [http://apr.apache.org/docs/apr/1.3/group__apr__network__io.html#g90c31b2f012c6b1e2d842a96c4431de3]
*/
host = apr_pstrdup(cmd->pool, arg);
port = strchr(host, ':');
if(port) {
*(port++) = '\0';
}
if(!*host || host == NULL || !*port || port == NULL) {
return "MemcachedCacheServer should be in the correct format : host:port";
}
memcached_server = apr_array_push(conf->servers);
memcached_server->host = host;
memcached_server->port = apr_atoi64(port);
/* ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, cmd->server, "Arg : %s Host : %s, Port : %d", arg, memcached_server->host, memcached_server->port); */
return NULL;
}
static const char *set_memcached_timeout(cmd_parms *cmd, void *mconfig, const char *arg)
{
include_server_config *conf = ap_get_module_config(cmd->server->module_config, &memcached_include_module);
conf->conn_ttl = atoi(arg);
return NULL;
}
static const char *set_memcached_soft_max_conn(cmd_parms *cmd, void *mconfig, const char *arg)
{
include_server_config *conf = ap_get_module_config(cmd->server->module_config, &memcached_include_module);
conf->conn_smax = atoi(arg);
return NULL;
}
static const char *set_memcached_hard_max_conn(cmd_parms *cmd, void *mconfig, const char *arg)
{
include_server_config *conf = ap_get_module_config(cmd->server->module_config, &memcached_include_module);
conf->conn_max = atoi(arg);
return NULL;
}
static const char *set_xbithack(cmd_parms *cmd, void *mconfig, const char *arg)
{
include_dir_config *conf = mconfig;
if (!strcasecmp(arg, "off")) {
conf->xbithack = XBITHACK_OFF;
}
else if (!strcasecmp(arg, "on")) {
conf->xbithack = XBITHACK_ON;
}
else if (!strcasecmp(arg, "full")) {
conf->xbithack = XBITHACK_FULL;
}
else {
return "XBitHack must be set to Off, On, or Full";
}
return NULL;
}
static const char *set_default_start_tag(cmd_parms *cmd, void *mconfig,
const char *tag)
{
include_server_config *conf;
const char *p = tag;
/* be consistent. (See below in set_default_end_tag) */
while (*p) {
if (apr_isspace(*p)) {
return "SSIStartTag may not contain any whitespaces";
}
++p;
}
conf= ap_get_module_config(cmd->server->module_config , &memcached_include_module);
conf->default_start_tag = tag;
return NULL;
}
static const char *set_default_end_tag(cmd_parms *cmd, void *mconfig,
const char *tag)
{
include_server_config *conf;
const char *p = tag;
/* sanity check. The parser may fail otherwise */
while (*p) {
if (apr_isspace(*p)) {
return "SSIEndTag may not contain any whitespaces";
}
++p;
}
conf= ap_get_module_config(cmd->server->module_config , &memcached_include_module);
conf->default_end_tag = tag;
return NULL;
}
static const char *set_undefined_echo(cmd_parms *cmd, void *mconfig,
const char *msg)
{
include_dir_config *conf = mconfig;
conf->undefined_echo = msg;
return NULL;
}
static const char *set_default_error_msg(cmd_parms *cmd, void *mconfig,
const char *msg)
{
include_dir_config *conf = mconfig;
conf->default_error_msg = msg;
return NULL;
}
static const char *set_default_time_fmt(cmd_parms *cmd, void *mconfig,
const char *fmt)
{
include_dir_config *conf = mconfig;
conf->default_time_fmt = fmt;
return NULL;
}
/*
* +-------------------------------------------------------+
* | |
* | Module Initialization and Configuration
* | |
* +-------------------------------------------------------+
*/
static int include_post_config(apr_pool_t *p, apr_pool_t *plog,
apr_pool_t *ptemp, server_rec *s)
{
include_handlers = apr_hash_make(p);
ssi_pfn_register = APR_RETRIEVE_OPTIONAL_FN(ap_register_memcached_include_handler);
if(ssi_pfn_register) {
ssi_pfn_register("if", handle_if);
ssi_pfn_register("set", handle_set);
ssi_pfn_register("else", handle_else);
ssi_pfn_register("elif", handle_elif);
ssi_pfn_register("echo", handle_echo);
ssi_pfn_register("endif", handle_endif);
ssi_pfn_register("fsize", handle_fsize);
ssi_pfn_register("config", handle_config);
ssi_pfn_register("include", handle_include);
ssi_pfn_register("flastmod", handle_flastmod);
ssi_pfn_register("printenv", handle_printenv);
}
include_server_config *conf;
memcached_include_server_t *svr;
apr_status_t rv;
int i;
conf = (include_server_config *)ap_get_module_config(s->module_config, &memcached_include_module);
rv = apr_memcache_create(p, conf->max_servers, 0, &(conf->memcached));
if(rv != APR_SUCCESS) {
ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, s, "Unable to create memcached structure");
}
-#ifdef DEBUG_MEMCACHED_INCLUDE
- else {
- ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, s, "Memcached struct successfully created");
- }
-#endif
-
svr = (memcached_include_server_t *)conf->servers->elts;
for(i = 0; i < conf->servers->nelts; i++) {
rv = apr_memcache_server_create(p, svr[i].host, svr[i].port,
conf->conn_min, conf->conn_smax,
conf->conn_max, conf->conn_ttl,
&(svr[i].server));
if(rv != APR_SUCCESS) {
ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, s, "Unable to create memcache server for %s:%d is Memcached running ?", svr[i].host, svr[i].port);
continue;
}
rv = apr_memcache_add_server(conf->memcached, svr[i].server);
if(rv != APR_SUCCESS) {
ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, s, "Unable to add memcache server for %s:%d", svr[i].host, svr[i].port);
}
#ifdef DEBUG_MEMCACHED_INCLUDE
ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, s, "Memcached server successfully created %s:%d %d %d %d", svr[i].host, svr[i].port, conf->conn_smax, conf->conn_max, conf->conn_ttl);
#endif
}
return OK;
}
static const command_rec includes_cmds[] =
{
AP_INIT_TAKE1("MemcachedHost", set_memcached_host, NULL, OR_OPTIONS,
"Memcached hostname or IP address with portnumber, like this, 127.0.0.1:11211"),
AP_INIT_TAKE1("MemcachedTTL", set_memcached_timeout, NULL, OR_OPTIONS,
"Memcached timeout (in seconds)"),
AP_INIT_TAKE1("MemcachedSoftMaxConn", set_memcached_soft_max_conn, NULL, OR_OPTIONS,
"Memcached low max connexions"),
AP_INIT_TAKE1("MemcachedHardMaxConn", set_memcached_hard_max_conn, NULL, OR_OPTIONS,
"Memcached high maximum connexions"),
AP_INIT_TAKE1("XBitHack", set_xbithack, NULL, OR_OPTIONS,
"Off, On, or Full"),
AP_INIT_TAKE1("SSIErrorMsg", set_default_error_msg, NULL, OR_ALL,
"a string"),
AP_INIT_TAKE1("SSITimeFormat", set_default_time_fmt, NULL, OR_ALL,
"a strftime(3) formatted string"),
AP_INIT_TAKE1("SSIStartTag", set_default_start_tag, NULL, RSRC_CONF,
"SSI Start String Tag"),
AP_INIT_TAKE1("SSIEndTag", set_default_end_tag, NULL, RSRC_CONF,
"SSI End String Tag"),
AP_INIT_TAKE1("SSIUndefinedEcho", set_undefined_echo, NULL, OR_ALL,
"String to be displayed if an echoed variable is undefined"),
AP_INIT_FLAG("SSIAccessEnable", ap_set_flag_slot,
(void *)APR_OFFSETOF(include_dir_config, accessenable),
OR_LIMIT, "Whether testing access is enabled. Limited to 'on' or 'off'"),
{NULL}
};
static void ap_register_memcached_include_handler(char *tag, include_handler_fn_t *func)
{
apr_hash_set(include_handlers, tag, strlen(tag), (const void *)func);
}
static void register_hooks(apr_pool_t *p)
{
APR_REGISTER_OPTIONAL_FN(ap_ssi_get_tag_and_value);
APR_REGISTER_OPTIONAL_FN(ap_ssi_parse_string);
APR_REGISTER_OPTIONAL_FN(ap_register_memcached_include_handler);
ap_hook_post_config(include_post_config, NULL, NULL, APR_HOOK_REALLY_FIRST);
ap_hook_fixups(include_fixup, NULL, NULL, APR_HOOK_LAST);
ap_register_output_filter("INCLUDES", includes_filter, includes_setup,
AP_FTYPE_RESOURCE);
/* ap_hook_handler(memcached_include_handler, NULL, NULL, APR_HOOK_MIDDLE); */
}
module AP_MODULE_DECLARE_DATA memcached_include_module =
{
STANDARD20_MODULE_STUFF,
create_includes_dir_config, /* dir config creater */
NULL, /* dir merger --- default is to override */
create_includes_server_config,/* server config */
NULL, /* merge server config */
includes_cmds, /* command apr_table_t */
register_hooks /* register hooks */
};
|
jeromer/modmemcachedinclude
|
2e935bd7b18a1383a9cb688dbb1759956ab8d8b0
|
- mixed memcached and local SSI
|
diff --git a/tests/pull-memcached.shtml b/tests/pull-memcached.shtml
index 6ec5778..d0de05f 100644
--- a/tests/pull-memcached.shtml
+++ b/tests/pull-memcached.shtml
@@ -1,7 +1,11 @@
<html>
<head></head>
<body>
<h1>Memcached tests</h1>
- <!--#include memcached="mod_memcached_include_tests" -->
+ <!--#include file="mod_memcached_include_tests" -->
+ <br/>
+ <!--#include memcached="mod_memcached_include_tests_1" -->
+ <br/>
+ <!--#include memcached="mod_memcached_include_tests_2" -->
</body>
</html>
|
jeromer/modmemcachedinclude
|
e8ca2ec76d4f2d871853c82f7fe5fd01ed55d58b
|
- updated push test
|
diff --git a/tests/push.php b/tests/push.php
index d827183..99bf266 100755
--- a/tests/push.php
+++ b/tests/push.php
@@ -1,29 +1,37 @@
<?php
define( MEMCACHED_HOST, '127.0.0.1' );
define( MEMCACHED_PORT, '11211' );
define( MEMCACHED_TIMEOUT, '10' );
if( !extension_loaded( 'memcache' ) )
{
die( 'Extension not loaded' );
}
if( $cr = memcache_connect( MEMCACHED_HOST, MEMCACHED_PORT, MEMCACHED_TIMEOUT ) )
{
$key = 'mod_memcached_include_tests';
$fileContents = 'SSI block added at ' . date( 'Y/m/d H:i:s', time( ) );
$flag = false;
- //the file does not exists
- if( !memcache_replace( $cr, $key, $fileContents, $flag, 0 ) )
+ for( $i = 1; $i < 3; $i++)
{
- if( !memcache_add( $cr, $key, $fileContents, $flag, 0 ) )
+ $finalKey = $key . '_' . $i;
+ $fileFinalContents = $fileContents . '::' . $i;
+
+ print( 'Adding file : ' . $finalKey . ' with contents '. $fileFinalContents . chr( 10 ) );
+
+ //the file does not exists
+ if( !memcache_replace( $cr, $finalKey, $fileFinalContents, $flag, 0 ) )
{
- print( 'Unable to add file' );
+ if( !memcache_add( $cr, $finalKey, $fileFinalContents, $flag, 0 ) )
+ {
+ print( 'Unable to add file' );
+ }
}
}
}
else
{
print( 'unable to connect to memcached' );
}
?>
|
jeromer/modmemcachedinclude
|
f1ac4e21319fd7a029407929061de41ae143fe1e
|
- added configuration variables
|
diff --git a/mod_memcached_include.c b/mod_memcached_include.c
index 7dcfe0a..c6ff9d0 100644
--- a/mod_memcached_include.c
+++ b/mod_memcached_include.c
@@ -1,642 +1,642 @@
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "apr.h"
#include "apr_strings.h"
#include "apr_thread_proc.h"
#include "apr_hash.h"
#include "apr_user.h"
#include "apr_lib.h"
#include "apr_optional.h"
#define APR_WANT_STRFUNC
#define APR_WANT_MEMFUNC
#include "apr_want.h"
#include "ap_config.h"
#include "util_filter.h"
#include "httpd.h"
#include "http_config.h"
#include "http_core.h"
#include "http_request.h"
#include "http_core.h"
#include "http_protocol.h"
#include "http_log.h"
#include "http_main.h"
#include "util_script.h"
#include "http_core.h"
#include "mod_memcached_include.h"
#include "apr_memcache.h"
/* helper for Latin1 <-> entity encoding */
#if APR_CHARSET_EBCDIC
#include "util_ebcdic.h"
#define RAW_ASCII_CHAR(ch) apr_xlate_conv_byte(ap_hdrs_from_ascii, \
(unsigned char)ch)
#else /* APR_CHARSET_EBCDIC */
#define RAW_ASCII_CHAR(ch) (ch)
#endif /* !APR_CHARSET_EBCDIC */
/*
* +-------------------------------------------------------+
* | |
* | Types and Structures
* | |
* +-------------------------------------------------------+
*/
/* sll used for string expansion */
typedef struct result_item {
struct result_item *next;
apr_size_t len;
const char *string;
} result_item_t;
/* conditional expression parser stuff */
typedef enum {
TOKEN_STRING,
TOKEN_RE,
TOKEN_AND,
TOKEN_OR,
TOKEN_NOT,
TOKEN_EQ,
TOKEN_NE,
TOKEN_RBRACE,
TOKEN_LBRACE,
TOKEN_GROUP,
TOKEN_GE,
TOKEN_LE,
TOKEN_GT,
TOKEN_LT,
TOKEN_ACCESS
} token_type_t;
typedef struct {
token_type_t type;
const char *value;
#ifdef DEBUG_INCLUDE
const char *s;
#endif
} token_t;
typedef struct parse_node {
struct parse_node *parent;
struct parse_node *left;
struct parse_node *right;
token_t token;
int value;
int done;
#ifdef DEBUG_INCLUDE
int dump_done;
#endif
} parse_node_t;
typedef enum {
XBITHACK_OFF,
XBITHACK_ON,
XBITHACK_FULL
} xbithack_t;
typedef struct {
const char *default_error_msg;
const char *default_time_fmt;
const char *undefined_echo;
xbithack_t xbithack;
const int accessenable;
} include_dir_config;
typedef struct {
const char *host;
apr_port_t port;
apr_memcache_server_t *server;
} memcached_include_server_t;
#define DEFAULT_MAX_SERVERS 1
-#define DEFAULT_MIN 5
+#define DEFAULT_MIN_CONN 1
#define DEFAULT_SMAX 10
#define DEFAULT_MAX 15
#define DEFAULT_TTL 10
#define DEFAULT_MIN_SIZE 1
#define DEFAULT_MAX_SIZE 1048576
typedef struct {
const char *default_start_tag;
const char *default_end_tag;
apr_memcache_t *memcached;
apr_array_header_t *servers;
apr_uint32_t conn_min;
apr_uint32_t conn_smax;
apr_uint32_t conn_max;
apr_uint32_t conn_ttl;
apr_uint16_t max_servers;
apr_off_t min_size;
apr_off_t max_size;
} include_server_config;
/* main parser states */
typedef enum {
PARSE_PRE_HEAD,
PARSE_HEAD,
PARSE_DIRECTIVE,
PARSE_DIRECTIVE_POSTNAME,
PARSE_DIRECTIVE_TAIL,
PARSE_DIRECTIVE_POSTTAIL,
PARSE_PRE_ARG,
PARSE_ARG,
PARSE_ARG_NAME,
PARSE_ARG_POSTNAME,
PARSE_ARG_EQ,
PARSE_ARG_PREVAL,
PARSE_ARG_VAL,
PARSE_ARG_VAL_ESC,
PARSE_ARG_POSTVAL,
PARSE_TAIL,
PARSE_TAIL_SEQ,
PARSE_EXECUTE
} parse_state_t;
typedef struct arg_item {
struct arg_item *next;
char *name;
apr_size_t name_len;
char *value;
apr_size_t value_len;
} arg_item_t;
typedef struct {
const char *source;
const char *rexp;
apr_size_t nsub;
ap_regmatch_t match[AP_MAX_REG_MATCH];
} backref_t;
typedef struct {
unsigned int T[256];
unsigned int x;
apr_size_t pattern_len;
} bndm_t;
struct ssi_internal_ctx {
parse_state_t state;
int seen_eos;
int error;
char quote; /* quote character value (or \0) */
apr_size_t parse_pos; /* parse position of partial matches */
apr_size_t bytes_read;
apr_bucket_brigade *tmp_bb;
request_rec *r;
const char *start_seq;
bndm_t *start_seq_pat;
const char *end_seq;
apr_size_t end_seq_len;
char *directive; /* name of the current directive */
apr_size_t directive_len; /* length of the current directive name */
arg_item_t *current_arg; /* currently parsed argument */
arg_item_t *argv; /* all arguments */
backref_t *re; /* NULL if there wasn't a regex yet */
const char *undefined_echo;
apr_size_t undefined_echo_len;
int accessenable; /* is using the access tests allowed? */
#ifdef DEBUG_INCLUDE
struct {
ap_filter_t *f;
apr_bucket_brigade *bb;
} debug;
#endif
};
/*
* +-------------------------------------------------------+
* | |
* | Debugging Utilities
* | |
* +-------------------------------------------------------+
*/
#ifdef DEBUG_INCLUDE
#define TYPE_TOKEN(token, ttype) do { \
(token)->type = ttype; \
(token)->s = #ttype; \
} while(0)
#define CREATE_NODE(ctx, name) do { \
(name) = apr_palloc((ctx)->dpool, sizeof(*(name))); \
(name)->parent = (name)->left = (name)->right = NULL; \
(name)->done = 0; \
(name)->dump_done = 0; \
} while(0)
static void debug_printf(include_ctx_t *ctx, const char *fmt, ...)
{
va_list ap;
char *debug__str;
va_start(ap, fmt);
debug__str = apr_pvsprintf(ctx->pool, fmt, ap);
va_end(ap);
APR_BRIGADE_INSERT_TAIL(ctx->intern->debug.bb, apr_bucket_pool_create(
debug__str, strlen(debug__str), ctx->pool,
ctx->intern->debug.f->c->bucket_alloc));
}
#define DUMP__CHILD(ctx, is, node, child) if (1) { \
parse_node_t *d__c = node->child; \
if (d__c) { \
if (!d__c->dump_done) { \
if (d__c->parent != node) { \
debug_printf(ctx, "!!! Parse tree is not consistent !!!\n"); \
if (!d__c->parent) { \
debug_printf(ctx, "Parent of " #child " child node is " \
"NULL.\n"); \
} \
else { \
debug_printf(ctx, "Parent of " #child " child node " \
"points to another node (of type %s)!\n", \
d__c->parent->token.s); \
} \
return; \
} \
node = d__c; \
continue; \
} \
} \
else { \
debug_printf(ctx, "%s(missing)\n", is); \
} \
}
static void debug_dump_tree(include_ctx_t *ctx, parse_node_t *root)
{
parse_node_t *current;
char *is;
if (!root) {
debug_printf(ctx, " -- Parse Tree empty --\n\n");
return;
}
debug_printf(ctx, " ----- Parse Tree -----\n");
current = root;
is = " ";
while (current) {
switch (current->token.type) {
case TOKEN_STRING:
case TOKEN_RE:
debug_printf(ctx, "%s%s (%s)\n", is, current->token.s,
current->token.value);
current->dump_done = 1;
current = current->parent;
continue;
case TOKEN_NOT:
case TOKEN_GROUP:
case TOKEN_RBRACE:
case TOKEN_LBRACE:
if (!current->dump_done) {
debug_printf(ctx, "%s%s\n", is, current->token.s);
is = apr_pstrcat(ctx->dpool, is, " ", NULL);
current->dump_done = 1;
}
DUMP__CHILD(ctx, is, current, right)
if (!current->right || current->right->dump_done) {
is = apr_pstrmemdup(ctx->dpool, is, strlen(is) - 4);
if (current->right) current->right->dump_done = 0;
current = current->parent;
}
continue;
default:
if (!current->dump_done) {
debug_printf(ctx, "%s%s\n", is, current->token.s);
is = apr_pstrcat(ctx->dpool, is, " ", NULL);
current->dump_done = 1;
}
DUMP__CHILD(ctx, is, current, left)
DUMP__CHILD(ctx, is, current, right)
if ((!current->left || current->left->dump_done) &&
(!current->right || current->right->dump_done)) {
is = apr_pstrmemdup(ctx->dpool, is, strlen(is) - 4);
if (current->left) current->left->dump_done = 0;
if (current->right) current->right->dump_done = 0;
current = current->parent;
}
continue;
}
}
/* it is possible to call this function within the parser loop, to see
* how the tree is built. That way, we must cleanup after us to dump
* always the whole tree
*/
root->dump_done = 0;
if (root->left) root->left->dump_done = 0;
if (root->right) root->right->dump_done = 0;
debug_printf(ctx, " --- End Parse Tree ---\n\n");
return;
}
#define DEBUG_INIT(ctx, filter, brigade) do { \
(ctx)->intern->debug.f = filter; \
(ctx)->intern->debug.bb = brigade; \
} while(0)
#define DEBUG_PRINTF(arg) debug_printf arg
#define DEBUG_DUMP_TOKEN(ctx, token) do { \
token_t *d__t = (token); \
\
if (d__t->type == TOKEN_STRING || d__t->type == TOKEN_RE) { \
DEBUG_PRINTF(((ctx), " Found: %s (%s)\n", d__t->s, d__t->value)); \
} \
else { \
DEBUG_PRINTF((ctx, " Found: %s\n", d__t->s)); \
} \
} while(0)
#define DEBUG_DUMP_EVAL(ctx, node) do { \
char c = '"'; \
switch ((node)->token.type) { \
case TOKEN_STRING: \
debug_printf((ctx), " Evaluate: %s (%s) -> %c\n", (node)->token.s,\
(node)->token.value, ((node)->value) ? '1':'0'); \
break; \
case TOKEN_AND: \
case TOKEN_OR: \
debug_printf((ctx), " Evaluate: %s (Left: %s; Right: %s) -> %c\n",\
(node)->token.s, \
(((node)->left->done) ? ((node)->left->value ?"1":"0") \
: "short circuited"), \
(((node)->right->done) ? ((node)->right->value?"1":"0") \
: "short circuited"), \
(node)->value ? '1' : '0'); \
break; \
case TOKEN_EQ: \
case TOKEN_NE: \
case TOKEN_GT: \
case TOKEN_GE: \
case TOKEN_LT: \
case TOKEN_LE: \
if ((node)->right->token.type == TOKEN_RE) c = '/'; \
debug_printf((ctx), " Compare: %s (\"%s\" with %c%s%c) -> %c\n", \
(node)->token.s, \
(node)->left->token.value, \
c, (node)->right->token.value, c, \
(node)->value ? '1' : '0'); \
break; \
default: \
debug_printf((ctx), " Evaluate: %s -> %c\n", (node)->token.s, \
(node)->value ? '1' : '0'); \
break; \
} \
} while(0)
#define DEBUG_DUMP_UNMATCHED(ctx, unmatched) do { \
if (unmatched) { \
DEBUG_PRINTF(((ctx), " Unmatched %c\n", (char)(unmatched))); \
} \
} while(0)
#define DEBUG_DUMP_COND(ctx, text) \
DEBUG_PRINTF(((ctx), "**** %s cond status=\"%c\"\n", (text), \
((ctx)->flags & SSI_FLAG_COND_TRUE) ? '1' : '0'))
#define DEBUG_DUMP_TREE(ctx, root) debug_dump_tree(ctx, root)
#else /* DEBUG_INCLUDE */
#define TYPE_TOKEN(token, ttype) (token)->type = ttype
#define CREATE_NODE(ctx, name) do { \
(name) = apr_palloc((ctx)->dpool, sizeof(*(name))); \
(name)->parent = (name)->left = (name)->right = NULL; \
(name)->done = 0; \
} while(0)
#define DEBUG_INIT(ctx, f, bb)
#define DEBUG_PRINTF(arg)
#define DEBUG_DUMP_TOKEN(ctx, token)
#define DEBUG_DUMP_EVAL(ctx, node)
#define DEBUG_DUMP_UNMATCHED(ctx, unmatched)
#define DEBUG_DUMP_COND(ctx, text)
#define DEBUG_DUMP_TREE(ctx, root)
#endif /* !DEBUG_INCLUDE */
/*
* +-------------------------------------------------------+
* | |
* | Static Module Data
* | |
* +-------------------------------------------------------+
*/
/* global module structure */
module AP_MODULE_DECLARE_DATA memcached_include_module;
/* function handlers for include directives */
static apr_hash_t *include_handlers;
/* forward declaration of handler registry */
static APR_OPTIONAL_FN_TYPE(ap_register_memcached_include_handler) *ssi_pfn_register;
/* Sentinel value to store in subprocess_env for items that
* shouldn't be evaluated until/unless they're actually used
*/
static const char lazy_eval_sentinel;
#define LAZY_VALUE (&lazy_eval_sentinel)
/* default values */
#define DEFAULT_START_SEQUENCE "<!--#"
#define DEFAULT_END_SEQUENCE "-->"
#define DEFAULT_ERROR_MSG "[an error occurred while processing this directive]"
#define DEFAULT_TIME_FORMAT "%A, %d-%b-%Y %H:%M:%S %Z"
#define DEFAULT_UNDEFINED_ECHO "(none)"
#ifdef XBITHACK
#define DEFAULT_XBITHACK XBITHACK_FULL
#else
#define DEFAULT_XBITHACK XBITHACK_OFF
#endif
/*
* +-------------------------------------------------------+
* | |
* | Environment/Expansion Functions
* | |
* +-------------------------------------------------------+
*/
/*
* decodes a string containing html entities or numeric character references.
* 's' is overwritten with the decoded string.
* If 's' is syntatically incorrect, then the followed fixups will be made:
* unknown entities will be left undecoded;
* references to unused numeric characters will be deleted.
* In particular, � will not be decoded, but will be deleted.
*/
/* maximum length of any ISO-LATIN-1 HTML entity name. */
#define MAXENTLEN (6)
/* The following is a shrinking transformation, therefore safe. */
static void decodehtml(char *s)
{
int val, i, j;
char *p;
const char *ents;
static const char * const entlist[MAXENTLEN + 1] =
{
NULL, /* 0 */
NULL, /* 1 */
"lt\074gt\076", /* 2 */
"amp\046ETH\320eth\360", /* 3 */
"quot\042Auml\304Euml\313Iuml\317Ouml\326Uuml\334auml\344euml"
"\353iuml\357ouml\366uuml\374yuml\377", /* 4 */
"Acirc\302Aring\305AElig\306Ecirc\312Icirc\316Ocirc\324Ucirc"
"\333THORN\336szlig\337acirc\342aring\345aelig\346ecirc\352"
"icirc\356ocirc\364ucirc\373thorn\376", /* 5 */
"Agrave\300Aacute\301Atilde\303Ccedil\307Egrave\310Eacute\311"
"Igrave\314Iacute\315Ntilde\321Ograve\322Oacute\323Otilde"
"\325Oslash\330Ugrave\331Uacute\332Yacute\335agrave\340"
"aacute\341atilde\343ccedil\347egrave\350eacute\351igrave"
"\354iacute\355ntilde\361ograve\362oacute\363otilde\365"
"oslash\370ugrave\371uacute\372yacute\375" /* 6 */
};
/* Do a fast scan through the string until we find anything
* that needs more complicated handling
*/
for (; *s != '&'; s++) {
if (*s == '\0') {
return;
}
}
for (p = s; *s != '\0'; s++, p++) {
if (*s != '&') {
*p = *s;
continue;
}
/* find end of entity */
for (i = 1; s[i] != ';' && s[i] != '\0'; i++) {
continue;
}
if (s[i] == '\0') { /* treat as normal data */
*p = *s;
continue;
}
/* is it numeric ? */
if (s[1] == '#') {
for (j = 2, val = 0; j < i && apr_isdigit(s[j]); j++) {
val = val * 10 + s[j] - '0';
}
s += i;
if (j < i || val <= 8 || (val >= 11 && val <= 31) ||
(val >= 127 && val <= 160) || val >= 256) {
p--; /* no data to output */
}
else {
*p = RAW_ASCII_CHAR(val);
}
}
else {
j = i - 1;
if (j > MAXENTLEN || entlist[j] == NULL) {
/* wrong length */
*p = '&';
continue; /* skip it */
}
for (ents = entlist[j]; *ents != '\0'; ents += i) {
if (strncmp(s + 1, ents, j) == 0) {
break;
}
}
if (*ents == '\0') {
*p = '&'; /* unknown */
}
else {
*p = RAW_ASCII_CHAR(((const unsigned char *) ents)[j]);
s += i;
}
}
}
*p = '\0';
}
static void add_include_vars(request_rec *r, const char *timefmt)
{
apr_table_t *e = r->subprocess_env;
char *t;
apr_table_setn(e, "DATE_LOCAL", LAZY_VALUE);
apr_table_setn(e, "DATE_GMT", LAZY_VALUE);
apr_table_setn(e, "LAST_MODIFIED", LAZY_VALUE);
apr_table_setn(e, "DOCUMENT_URI", r->uri);
if (r->path_info && *r->path_info) {
apr_table_setn(e, "DOCUMENT_PATH_INFO", r->path_info);
}
apr_table_setn(e, "USER_NAME", LAZY_VALUE);
if (r->filename && (t = strrchr(r->filename, '/'))) {
apr_table_setn(e, "DOCUMENT_NAME", ++t);
}
else {
apr_table_setn(e, "DOCUMENT_NAME", r->uri);
}
if (r->args) {
char *arg_copy = apr_pstrdup(r->pool, r->args);
ap_unescape_url(arg_copy);
apr_table_setn(e, "QUERY_STRING_UNESCAPED",
ap_escape_shell_cmd(r->pool, arg_copy));
}
}
static const char *add_include_vars_lazy(request_rec *r, const char *var)
{
char *val;
if (!strcasecmp(var, "DATE_LOCAL")) {
include_dir_config *conf =
@@ -3291,763 +3291,799 @@ static apr_status_t send_parsed_content(ap_filter_t *f, apr_bucket_brigade *bb)
apr_brigade_destroy(pass_bb);
return rv;
}
intern->bytes_read += len;
}
/* zero length bucket, fetch next one */
if (!len && !intern->seen_eos) {
b = APR_BUCKET_NEXT(b);
continue;
}
/*
* it's actually a data containing bucket, start/continue parsing
*/
switch (intern->state) {
/* no current tag; search for start sequence */
case PARSE_PRE_HEAD:
index = find_start_sequence(ctx, data, len);
if (index < len) {
apr_bucket_split(b, index);
}
newb = APR_BUCKET_NEXT(b);
if (ctx->flags & SSI_FLAG_PRINTING) {
APR_BUCKET_REMOVE(b);
APR_BRIGADE_INSERT_TAIL(pass_bb, b);
}
else {
apr_bucket_delete(b);
}
if (index < len) {
/* now delete the start_seq stuff from the remaining bucket */
if (PARSE_DIRECTIVE == intern->state) { /* full match */
apr_bucket_split(newb, intern->start_seq_pat->pattern_len);
ctx->flush_now = 1; /* pass pre-tag stuff */
}
b = APR_BUCKET_NEXT(newb);
apr_bucket_delete(newb);
}
else {
b = newb;
}
break;
/* we're currently looking for the end of the start sequence */
case PARSE_HEAD:
index = find_partial_start_sequence(ctx, data, len, &release);
/* check if we mismatched earlier and have to release some chars */
if (release && (ctx->flags & SSI_FLAG_PRINTING)) {
char *to_release = apr_pmemdup(ctx->pool, intern->start_seq, release);
newb = apr_bucket_pool_create(to_release, release, ctx->pool,
f->c->bucket_alloc);
APR_BRIGADE_INSERT_TAIL(pass_bb, newb);
}
if (index) { /* any match */
/* now delete the start_seq stuff from the remaining bucket */
if (PARSE_DIRECTIVE == intern->state) { /* final match */
apr_bucket_split(b, index);
ctx->flush_now = 1; /* pass pre-tag stuff */
}
newb = APR_BUCKET_NEXT(b);
apr_bucket_delete(b);
b = newb;
}
break;
/* we're currently grabbing the directive name */
case PARSE_DIRECTIVE:
case PARSE_DIRECTIVE_POSTNAME:
case PARSE_DIRECTIVE_TAIL:
case PARSE_DIRECTIVE_POSTTAIL:
index = find_directive(ctx, data, len, &store, &store_len);
if (index) {
apr_bucket_split(b, index);
newb = APR_BUCKET_NEXT(b);
}
if (store) {
if (index) {
APR_BUCKET_REMOVE(b);
apr_bucket_setaside(b, r->pool);
APR_BRIGADE_INSERT_TAIL(intern->tmp_bb, b);
b = newb;
}
/* time for cleanup? */
if (store != &magic) {
apr_brigade_pflatten(intern->tmp_bb, store, store_len,
ctx->dpool);
apr_brigade_cleanup(intern->tmp_bb);
}
}
else if (index) {
apr_bucket_delete(b);
b = newb;
}
break;
/* skip WS and find out what comes next (arg or end_seq) */
case PARSE_PRE_ARG:
index = find_arg_or_tail(ctx, data, len);
if (index) { /* skipped whitespaces */
if (index < len) {
apr_bucket_split(b, index);
}
newb = APR_BUCKET_NEXT(b);
apr_bucket_delete(b);
b = newb;
}
break;
/* currently parsing name[=val] */
case PARSE_ARG:
case PARSE_ARG_NAME:
case PARSE_ARG_POSTNAME:
case PARSE_ARG_EQ:
case PARSE_ARG_PREVAL:
case PARSE_ARG_VAL:
case PARSE_ARG_VAL_ESC:
case PARSE_ARG_POSTVAL:
index = find_argument(ctx, data, len, &store, &store_len);
if (index) {
apr_bucket_split(b, index);
newb = APR_BUCKET_NEXT(b);
}
if (store) {
if (index) {
APR_BUCKET_REMOVE(b);
apr_bucket_setaside(b, r->pool);
APR_BRIGADE_INSERT_TAIL(intern->tmp_bb, b);
b = newb;
}
/* time for cleanup? */
if (store != &magic) {
apr_brigade_pflatten(intern->tmp_bb, store, store_len,
ctx->dpool);
apr_brigade_cleanup(intern->tmp_bb);
}
}
else if (index) {
apr_bucket_delete(b);
b = newb;
}
break;
/* try to match end_seq at current pos. */
case PARSE_TAIL:
case PARSE_TAIL_SEQ:
index = find_tail(ctx, data, len);
switch (intern->state) {
case PARSE_EXECUTE: /* full match */
apr_bucket_split(b, index);
newb = APR_BUCKET_NEXT(b);
apr_bucket_delete(b);
b = newb;
break;
case PARSE_ARG: /* no match */
/* PARSE_ARG must reparse at the beginning */
APR_BRIGADE_PREPEND(bb, intern->tmp_bb);
b = APR_BRIGADE_FIRST(bb);
break;
default: /* partial match */
newb = APR_BUCKET_NEXT(b);
APR_BUCKET_REMOVE(b);
apr_bucket_setaside(b, r->pool);
APR_BRIGADE_INSERT_TAIL(intern->tmp_bb, b);
b = newb;
break;
}
break;
/* now execute the parsed directive, cleanup the space and
* start again with PARSE_PRE_HEAD
*/
case PARSE_EXECUTE:
/* if there was an error, it was already logged; just stop here */
if (intern->error) {
if (ctx->flags & SSI_FLAG_PRINTING) {
SSI_CREATE_ERROR_BUCKET(ctx, f, pass_bb);
intern->error = 0;
}
}
else {
include_handler_fn_t *handle_func;
handle_func =
(include_handler_fn_t *)apr_hash_get(include_handlers, intern->directive,
intern->directive_len);
if (handle_func) {
DEBUG_INIT(ctx, f, pass_bb);
rv = handle_func(ctx, f, pass_bb);
if (rv != APR_SUCCESS) {
apr_brigade_destroy(pass_bb);
return rv;
}
}
else {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
"unknown directive \"%s\" in parsed doc %s",
apr_pstrmemdup(r->pool, intern->directive,
intern->directive_len),
r->filename);
if (ctx->flags & SSI_FLAG_PRINTING) {
SSI_CREATE_ERROR_BUCKET(ctx, f, pass_bb);
}
}
}
/* cleanup */
apr_pool_clear(ctx->dpool);
apr_brigade_cleanup(intern->tmp_bb);
/* Oooof. Done here, start next round */
intern->state = PARSE_PRE_HEAD;
break;
} /* switch(ctx->state) */
} /* while(brigade) */
/* End of stream. Final cleanup */
if (intern->seen_eos) {
if (PARSE_HEAD == intern->state) {
if (ctx->flags & SSI_FLAG_PRINTING) {
char *to_release = apr_pmemdup(ctx->pool, intern->start_seq,
intern->parse_pos);
APR_BRIGADE_INSERT_TAIL(pass_bb,
apr_bucket_pool_create(to_release,
intern->parse_pos, ctx->pool,
f->c->bucket_alloc));
}
}
else if (PARSE_PRE_HEAD != intern->state) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
"SSI directive was not properly finished at the end "
"of parsed document %s", r->filename);
if (ctx->flags & SSI_FLAG_PRINTING) {
SSI_CREATE_ERROR_BUCKET(ctx, f, pass_bb);
}
}
if (!(ctx->flags & SSI_FLAG_PRINTING)) {
ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
"missing closing endif directive in parsed document"
" %s", r->filename);
}
/* cleanup our temporary memory */
apr_brigade_destroy(intern->tmp_bb);
apr_pool_destroy(ctx->dpool);
/* don't forget to finally insert the EOS bucket */
APR_BRIGADE_INSERT_TAIL(pass_bb, b);
}
/* if something's left over, pass it along */
if (!APR_BRIGADE_EMPTY(pass_bb)) {
rv = ap_pass_brigade(f->next, pass_bb);
}
else {
rv = APR_SUCCESS;
apr_brigade_destroy(pass_bb);
}
return rv;
}
/*
* +-------------------------------------------------------+
* | |
* | Runtime Hooks
* | |
* +-------------------------------------------------------+
*/
static int includes_setup(ap_filter_t *f)
{
include_dir_config *conf = ap_get_module_config(f->r->per_dir_config,
&memcached_include_module);
/* When our xbithack value isn't set to full or our platform isn't
* providing group-level protection bits or our group-level bits do not
* have group-execite on, we will set the no_local_copy value to 1 so
* that we will not send 304s.
*/
if ((conf->xbithack != XBITHACK_FULL)
|| !(f->r->finfo.valid & APR_FINFO_GPROT)
|| !(f->r->finfo.protection & APR_GEXECUTE)) {
f->r->no_local_copy = 1;
}
/* Don't allow ETag headers to be generated - see RFC2616 - 13.3.4.
* We don't know if we are going to be including a file or executing
* a program - in either case a strong ETag header will likely be invalid.
*/
apr_table_setn(f->r->notes, "no-etag", "");
return OK;
}
static apr_status_t includes_filter(ap_filter_t *f, apr_bucket_brigade *b)
{
request_rec *r = f->r;
include_ctx_t *ctx = f->ctx;
request_rec *parent;
include_dir_config *conf = ap_get_module_config(r->per_dir_config,
&memcached_include_module);
include_server_config *sconf= ap_get_module_config(r->server->module_config,
&memcached_include_module);
if (!(ap_allow_options(r) & OPT_INCLUDES)) {
ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
"mod_include: Options +Includes (or IncludesNoExec) "
"wasn't set, INCLUDES filter removed");
ap_remove_output_filter(f);
return ap_pass_brigade(f->next, b);
}
if (!f->ctx) {
struct ssi_internal_ctx *intern;
/* create context for this filter */
f->ctx = ctx = apr_palloc(r->pool, sizeof(*ctx));
ctx->intern = intern = apr_palloc(r->pool, sizeof(*ctx->intern));
ctx->pool = r->pool;
apr_pool_create(&ctx->dpool, ctx->pool);
/* runtime data */
intern->tmp_bb = apr_brigade_create(ctx->pool, f->c->bucket_alloc);
intern->seen_eos = 0;
intern->state = PARSE_PRE_HEAD;
ctx->flags = (SSI_FLAG_PRINTING | SSI_FLAG_COND_TRUE);
if (ap_allow_options(r) & OPT_INCNOEXEC) {
ctx->flags |= SSI_FLAG_NO_EXEC;
}
intern->accessenable = conf->accessenable;
ctx->if_nesting_level = 0;
intern->re = NULL;
ctx->error_str = conf->default_error_msg;
ctx->time_str = conf->default_time_fmt;
intern->start_seq = sconf->default_start_tag;
intern->start_seq_pat = bndm_compile(ctx->pool, intern->start_seq,
strlen(intern->start_seq));
intern->end_seq = sconf->default_end_tag;
intern->end_seq_len = strlen(intern->end_seq);
intern->undefined_echo = conf->undefined_echo;
intern->undefined_echo_len = strlen(conf->undefined_echo);
}
if ((parent = ap_get_module_config(r->request_config, &memcached_include_module))) {
/* Kludge --- for nested includes, we want to keep the subprocess
* environment of the base document (for compatibility); that means
* torquing our own last_modified date as well so that the
* LAST_MODIFIED variable gets reset to the proper value if the
* nested document resets <!--#config timefmt -->.
*/
r->subprocess_env = r->main->subprocess_env;
apr_pool_join(r->main->pool, r->pool);
r->finfo.mtime = r->main->finfo.mtime;
}
else {
/* we're not a nested include, so we create an initial
* environment */
ap_add_common_vars(r);
ap_add_cgi_vars(r);
add_include_vars(r, conf->default_time_fmt);
}
/* Always unset the content-length. There is no way to know if
* the content will be modified at some point by send_parsed_content.
* It is very possible for us to not find any content in the first
* 9k of the file, but still have to modify the content of the file.
* If we are going to pass the file through send_parsed_content, then
* the content-length should just be unset.
*/
apr_table_unset(f->r->headers_out, "Content-Length");
/* Always unset the Last-Modified field - see RFC2616 - 13.3.4.
* We don't know if we are going to be including a file or executing
* a program which may change the Last-Modified header or make the
* content completely dynamic. Therefore, we can't support these
* headers.
* Exception: XBitHack full means we *should* set the Last-Modified field.
*/
/* Assure the platform supports Group protections */
if ((conf->xbithack == XBITHACK_FULL)
&& (r->finfo.valid & APR_FINFO_GPROT)
&& (r->finfo.protection & APR_GEXECUTE)) {
ap_update_mtime(r, r->finfo.mtime);
ap_set_last_modified(r);
}
else {
apr_table_unset(f->r->headers_out, "Last-Modified");
}
/* add QUERY stuff to env cause it ain't yet */
if (r->args) {
char *arg_copy = apr_pstrdup(r->pool, r->args);
apr_table_setn(r->subprocess_env, "QUERY_STRING", r->args);
ap_unescape_url(arg_copy);
apr_table_setn(r->subprocess_env, "QUERY_STRING_UNESCAPED",
ap_escape_shell_cmd(r->pool, arg_copy));
}
return send_parsed_content(f, b);
}
static int include_fixup(request_rec *r)
{
include_dir_config *conf;
conf = ap_get_module_config(r->per_dir_config, &memcached_include_module);
if (r->handler && (strcmp(r->handler, "server-parsed") == 0))
{
if (!r->content_type || !*r->content_type) {
ap_set_content_type(r, "text/html");
}
r->handler = "default-handler";
}
else
#if defined(OS2) || defined(WIN32) || defined(NETWARE)
/* These OS's don't support xbithack. This is being worked on. */
{
return DECLINED;
}
#else
{
if (conf->xbithack == XBITHACK_OFF) {
return DECLINED;
}
if (!(r->finfo.protection & APR_UEXECUTE)) {
return DECLINED;
}
if (!r->content_type || strcmp(r->content_type, "text/html")) {
return DECLINED;
}
}
#endif
/* We always return declined, because the default handler actually
* serves the file. All we have to do is add the filter.
*/
ap_add_output_filter("INCLUDES", NULL, r, r->connection);
return DECLINED;
}
/*
* +-------------------------------------------------------+
* | |
* | Configuration Handling
* | |
* +-------------------------------------------------------+
*/
static void *create_includes_dir_config(apr_pool_t *p, char *dummy)
{
include_dir_config *result = apr_palloc(p, sizeof(include_dir_config));
result->default_error_msg = DEFAULT_ERROR_MSG;
result->default_time_fmt = DEFAULT_TIME_FORMAT;
result->undefined_echo = DEFAULT_UNDEFINED_ECHO;
result->xbithack = DEFAULT_XBITHACK;
return result;
}
static void *create_includes_server_config(apr_pool_t *p, server_rec *server)
{
include_server_config *result;
result = apr_palloc(p, sizeof(include_server_config));
result->default_end_tag = DEFAULT_END_SEQUENCE;
result->default_start_tag = DEFAULT_START_SEQUENCE;
result->servers = apr_array_make(p, 1, sizeof(memcached_include_server_t));
result->max_servers = DEFAULT_MAX_SERVERS;
result->min_size = DEFAULT_MIN_SIZE;
result->max_size = DEFAULT_MAX_SIZE;
- result->conn_min = DEFAULT_MIN;
+ result->conn_min = DEFAULT_MIN_CONN;
result->conn_smax = DEFAULT_SMAX;
result->conn_max = DEFAULT_MAX;
result->conn_ttl = DEFAULT_TTL;
return result;
}
static const char *set_memcached_host(cmd_parms *cmd, void *mconfig, const char *arg)
{
char *host, *port;
memcached_include_server_t *memcached_server = NULL;
include_server_config *conf = ap_get_module_config(cmd->server->module_config, &memcached_include_module);
/*
* I should consider using apr_parse_addr_port instead
* [http://apr.apache.org/docs/apr/1.3/group__apr__network__io.html#g90c31b2f012c6b1e2d842a96c4431de3]
*/
host = apr_pstrdup(cmd->pool, arg);
port = strchr(host, ':');
if(port) {
*(port++) = '\0';
}
if(!*host || host == NULL || !*port || port == NULL) {
return "MemcachedCacheServer should be in the correct format : host:port";
}
memcached_server = apr_array_push(conf->servers);
memcached_server->host = host;
memcached_server->port = apr_atoi64(port);
/* ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, cmd->server, "Arg : %s Host : %s, Port : %d", arg, memcached_server->host, memcached_server->port); */
return NULL;
}
+static const char *set_memcached_timeout(cmd_parms *cmd, void *mconfig, const char *arg)
+{
+ include_server_config *conf = ap_get_module_config(cmd->server->module_config, &memcached_include_module);
+
+ conf->conn_ttl = atoi(arg);
+
+ return NULL;
+}
+
+static const char *set_memcached_soft_max_conn(cmd_parms *cmd, void *mconfig, const char *arg)
+{
+ include_server_config *conf = ap_get_module_config(cmd->server->module_config, &memcached_include_module);
+
+ conf->conn_smax = atoi(arg);
+
+ return NULL;
+}
+
+static const char *set_memcached_hard_max_conn(cmd_parms *cmd, void *mconfig, const char *arg)
+{
+ include_server_config *conf = ap_get_module_config(cmd->server->module_config, &memcached_include_module);
+
+ conf->conn_max = atoi(arg);
+
+ return NULL;
+}
+
static const char *set_xbithack(cmd_parms *cmd, void *mconfig, const char *arg)
{
include_dir_config *conf = mconfig;
if (!strcasecmp(arg, "off")) {
conf->xbithack = XBITHACK_OFF;
}
else if (!strcasecmp(arg, "on")) {
conf->xbithack = XBITHACK_ON;
}
else if (!strcasecmp(arg, "full")) {
conf->xbithack = XBITHACK_FULL;
}
else {
return "XBitHack must be set to Off, On, or Full";
}
return NULL;
}
static const char *set_default_start_tag(cmd_parms *cmd, void *mconfig,
const char *tag)
{
include_server_config *conf;
const char *p = tag;
/* be consistent. (See below in set_default_end_tag) */
while (*p) {
if (apr_isspace(*p)) {
return "SSIStartTag may not contain any whitespaces";
}
++p;
}
conf= ap_get_module_config(cmd->server->module_config , &memcached_include_module);
conf->default_start_tag = tag;
return NULL;
}
static const char *set_default_end_tag(cmd_parms *cmd, void *mconfig,
const char *tag)
{
include_server_config *conf;
const char *p = tag;
/* sanity check. The parser may fail otherwise */
while (*p) {
if (apr_isspace(*p)) {
return "SSIEndTag may not contain any whitespaces";
}
++p;
}
conf= ap_get_module_config(cmd->server->module_config , &memcached_include_module);
conf->default_end_tag = tag;
return NULL;
}
static const char *set_undefined_echo(cmd_parms *cmd, void *mconfig,
const char *msg)
{
include_dir_config *conf = mconfig;
conf->undefined_echo = msg;
return NULL;
}
static const char *set_default_error_msg(cmd_parms *cmd, void *mconfig,
const char *msg)
{
include_dir_config *conf = mconfig;
conf->default_error_msg = msg;
return NULL;
}
static const char *set_default_time_fmt(cmd_parms *cmd, void *mconfig,
const char *fmt)
{
include_dir_config *conf = mconfig;
conf->default_time_fmt = fmt;
return NULL;
}
/*
* +-------------------------------------------------------+
* | |
* | Module Initialization and Configuration
* | |
* +-------------------------------------------------------+
*/
static int include_post_config(apr_pool_t *p, apr_pool_t *plog,
apr_pool_t *ptemp, server_rec *s)
{
include_handlers = apr_hash_make(p);
ssi_pfn_register = APR_RETRIEVE_OPTIONAL_FN(ap_register_memcached_include_handler);
if(ssi_pfn_register) {
ssi_pfn_register("if", handle_if);
ssi_pfn_register("set", handle_set);
ssi_pfn_register("else", handle_else);
ssi_pfn_register("elif", handle_elif);
ssi_pfn_register("echo", handle_echo);
ssi_pfn_register("endif", handle_endif);
ssi_pfn_register("fsize", handle_fsize);
ssi_pfn_register("config", handle_config);
ssi_pfn_register("include", handle_include);
ssi_pfn_register("flastmod", handle_flastmod);
ssi_pfn_register("printenv", handle_printenv);
}
include_server_config *conf;
memcached_include_server_t *svr;
apr_status_t rv;
int i;
conf = (include_server_config *)ap_get_module_config(s->module_config, &memcached_include_module);
- /* ap_log_error(APLOG_MARK, APLOG_INFO, 0, s, "Function: %pp, max_servers: %d", apr_memcache_create, conf->max_servers); */
-
rv = apr_memcache_create(p, conf->max_servers, 0, &(conf->memcached));
if(rv != APR_SUCCESS) {
ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, s, "Unable to create memcached structure");
- } else {
+ }
+
+#ifdef DEBUG_MEMCACHED_INCLUDE
+ else {
ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, s, "Memcached struct successfully created");
}
+#endif
svr = (memcached_include_server_t *)conf->servers->elts;
- ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, "conf->servers->nelts : %d", conf->servers->nelts);
-
for(i = 0; i < conf->servers->nelts; i++) {
rv = apr_memcache_server_create(p, svr[i].host, svr[i].port,
conf->conn_min, conf->conn_smax,
conf->conn_max, conf->conn_ttl,
&(svr[i].server));
if(rv != APR_SUCCESS) {
- ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, s, "Unable to create memcache server for %s:%d", svr[i].host, svr[i].port);
+ ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, s, "Unable to create memcache server for %s:%d is Memcached running ?", svr[i].host, svr[i].port);
continue;
}
rv = apr_memcache_add_server(conf->memcached, svr[i].server);
if(rv != APR_SUCCESS) {
ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, s, "Unable to add memcache server for %s:%d", svr[i].host, svr[i].port);
}
- ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, s, "Memcached server successfully created %s:%d", svr[i].host, svr[i].port);
+#ifdef DEBUG_MEMCACHED_INCLUDE
+ ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, s, "Memcached server successfully created %s:%d %d %d %d", svr[i].host, svr[i].port, conf->conn_smax, conf->conn_max, conf->conn_ttl);
+#endif
}
return OK;
}
static const command_rec includes_cmds[] =
{
AP_INIT_TAKE1("MemcachedHost", set_memcached_host, NULL, OR_OPTIONS,
"Memcached hostname or IP address with portnumber, like this, 127.0.0.1:11211"),
- /*
- AP_INIT_TAKE1("MemcachedTimeOut", set_memcached_timeout, NULL, OR_OPTIONS,
+
+ AP_INIT_TAKE1("MemcachedTTL", set_memcached_timeout, NULL, OR_OPTIONS,
"Memcached timeout (in seconds)"),
- */
+
+ AP_INIT_TAKE1("MemcachedSoftMaxConn", set_memcached_soft_max_conn, NULL, OR_OPTIONS,
+ "Memcached low max connexions"),
+
+ AP_INIT_TAKE1("MemcachedHardMaxConn", set_memcached_hard_max_conn, NULL, OR_OPTIONS,
+ "Memcached high maximum connexions"),
+
AP_INIT_TAKE1("XBitHack", set_xbithack, NULL, OR_OPTIONS,
"Off, On, or Full"),
AP_INIT_TAKE1("SSIErrorMsg", set_default_error_msg, NULL, OR_ALL,
"a string"),
AP_INIT_TAKE1("SSITimeFormat", set_default_time_fmt, NULL, OR_ALL,
"a strftime(3) formatted string"),
AP_INIT_TAKE1("SSIStartTag", set_default_start_tag, NULL, RSRC_CONF,
"SSI Start String Tag"),
AP_INIT_TAKE1("SSIEndTag", set_default_end_tag, NULL, RSRC_CONF,
"SSI End String Tag"),
AP_INIT_TAKE1("SSIUndefinedEcho", set_undefined_echo, NULL, OR_ALL,
"String to be displayed if an echoed variable is undefined"),
AP_INIT_FLAG("SSIAccessEnable", ap_set_flag_slot,
(void *)APR_OFFSETOF(include_dir_config, accessenable),
OR_LIMIT, "Whether testing access is enabled. Limited to 'on' or 'off'"),
{NULL}
};
static void ap_register_memcached_include_handler(char *tag, include_handler_fn_t *func)
{
apr_hash_set(include_handlers, tag, strlen(tag), (const void *)func);
}
static void register_hooks(apr_pool_t *p)
{
APR_REGISTER_OPTIONAL_FN(ap_ssi_get_tag_and_value);
APR_REGISTER_OPTIONAL_FN(ap_ssi_parse_string);
APR_REGISTER_OPTIONAL_FN(ap_register_memcached_include_handler);
ap_hook_post_config(include_post_config, NULL, NULL, APR_HOOK_REALLY_FIRST);
ap_hook_fixups(include_fixup, NULL, NULL, APR_HOOK_LAST);
ap_register_output_filter("INCLUDES", includes_filter, includes_setup,
AP_FTYPE_RESOURCE);
+ /* ap_hook_handler(memcached_include_handler, NULL, NULL, APR_HOOK_MIDDLE); */
}
module AP_MODULE_DECLARE_DATA memcached_include_module =
{
STANDARD20_MODULE_STUFF,
create_includes_dir_config, /* dir config creater */
NULL, /* dir merger --- default is to override */
create_includes_server_config,/* server config */
NULL, /* merge server config */
includes_cmds, /* command apr_table_t */
register_hooks /* register hooks */
};
|
jeromer/modmemcachedinclude
|
9c365ebe3f64472a2432544b83c3335898193323
|
- corrected documentation
|
diff --git a/doc/INSTALL b/doc/INSTALL
index 7ebd02c..ae94e7f 100644
--- a/doc/INSTALL
+++ b/doc/INSTALL
@@ -1,95 +1,91 @@
What is this extension made for ?
=================================
-This extension has been primarily created for a customer
-project this module had to be coupled with an eZ Publish
-extension called eZSI.
-
-Anyway this module may be used with any file that is pushed
+This module may be used with any file that is pushed
in Memcached and meant to be fetched from an SSI tag.
How to compile this extension ?
===============================
You will have to install and compiler apr_memcache first.
This module uses version 0.7.0 do not use older versions.
apr_memcache may be downloaded here :
- http://www.outoforder.cc/projects/libs/apr_memcache/
- http://www.outoforder.cc/downloads/apr_memcache/apr_memcache-0.7.0.tar.bz2
Once apr_memcache is downloaded, extract it and compile it.
Note the path where it has been installed, you will need it.
Unfortunately I did not had time to create a configure script.
I wish I had some spare time to fix this issue as soon as possible.
In order to compile the extension you will have to edit the Makefile.
Change the following contents :
::
builddir=.
top_srcdir=/usr/local/apache-2.2.9
top_builddir=/usr/local/apache-2.2.9
include /usr/local/apache-2.2.9/build/special.mk
# the used tools
APXS=apxs
APACHECTL=apache2ctl
# additional defines, includes and libraries
#DEFS=-DDEBUG_MEMCACHED_INCLUDE
DEFS=
INCLUDES=-I/usr/local/apache-2.2.9/include/apr_memcache-0
LIBS=-L/usr/local/apache-2.2.9/lib -lapr_memcache
By the following :
::
builddir=.
top_srcdir=/path/to/your/apache/installtion/directory
top_builddir=/path/to/your/apache/installation/directory
include /path/to/your/apache/installation/build/special.mk
# the used tools
APXS=apxs
APACHECTL=apachectl
# additional defines, includes and libraries
#DEFS=-DDEBUG_MEMCACHED_INCLUDE
DEFS=
INCLUDES=-I/path/to/apr_memcache/installation/directory/apr_memcache-0
LIBS=-L/path/to/your/apr_memcache/installation/directory/lib -lapr_memcache
How to test this extension ?
============================
In order to test the extension you have to first compile
the module and install it, once you are done you have to
launch test/push.php to store some contents in Memcached.
You can configure your Memcached host by editing push.php
After that you may create the following configuration
for Apache :
::
LoadModule memcached_include_module modules/mod_memcached_include.so
<Directory /path/to/mod_memcached_include/tests/>
AddType text/html .shtml
AddOutputFilter INCLUDES .shtml
Options +Includes
MemcachedHost localhost:11211
</Directory>
Once the file is stored in Memcached, you can ``test/pull-*.shtml``
files.
..
Local Variables:
mode: rst
fill-column: 79
End:
vim: et syn=rst tw=79
|
jeromer/modmemcachedinclude
|
37f197c8ca1dfa54558911542f4e8e69885b2298
|
- added first version of the documentation
|
diff --git a/doc/INSTALL b/doc/INSTALL
new file mode 100644
index 0000000..7ebd02c
--- /dev/null
+++ b/doc/INSTALL
@@ -0,0 +1,95 @@
+What is this extension made for ?
+=================================
+
+This extension has been primarily created for a customer
+project this module had to be coupled with an eZ Publish
+extension called eZSI.
+
+Anyway this module may be used with any file that is pushed
+in Memcached and meant to be fetched from an SSI tag.
+
+How to compile this extension ?
+===============================
+You will have to install and compiler apr_memcache first.
+This module uses version 0.7.0 do not use older versions.
+apr_memcache may be downloaded here :
+
+- http://www.outoforder.cc/projects/libs/apr_memcache/
+- http://www.outoforder.cc/downloads/apr_memcache/apr_memcache-0.7.0.tar.bz2
+
+Once apr_memcache is downloaded, extract it and compile it.
+
+Note the path where it has been installed, you will need it.
+
+Unfortunately I did not had time to create a configure script.
+I wish I had some spare time to fix this issue as soon as possible.
+
+In order to compile the extension you will have to edit the Makefile.
+
+Change the following contents :
+
+::
+
+ builddir=.
+ top_srcdir=/usr/local/apache-2.2.9
+ top_builddir=/usr/local/apache-2.2.9
+ include /usr/local/apache-2.2.9/build/special.mk
+
+ # the used tools
+ APXS=apxs
+ APACHECTL=apache2ctl
+
+ # additional defines, includes and libraries
+ #DEFS=-DDEBUG_MEMCACHED_INCLUDE
+ DEFS=
+ INCLUDES=-I/usr/local/apache-2.2.9/include/apr_memcache-0
+ LIBS=-L/usr/local/apache-2.2.9/lib -lapr_memcache
+
+By the following :
+
+::
+
+ builddir=.
+ top_srcdir=/path/to/your/apache/installtion/directory
+ top_builddir=/path/to/your/apache/installation/directory
+ include /path/to/your/apache/installation/build/special.mk
+
+ # the used tools
+ APXS=apxs
+ APACHECTL=apachectl
+
+ # additional defines, includes and libraries
+ #DEFS=-DDEBUG_MEMCACHED_INCLUDE
+ DEFS=
+ INCLUDES=-I/path/to/apr_memcache/installation/directory/apr_memcache-0
+ LIBS=-L/path/to/your/apr_memcache/installation/directory/lib -lapr_memcache
+
+How to test this extension ?
+============================
+In order to test the extension you have to first compile
+the module and install it, once you are done you have to
+launch test/push.php to store some contents in Memcached.
+You can configure your Memcached host by editing push.php
+
+After that you may create the following configuration
+for Apache :
+
+::
+
+ LoadModule memcached_include_module modules/mod_memcached_include.so
+ <Directory /path/to/mod_memcached_include/tests/>
+ AddType text/html .shtml
+ AddOutputFilter INCLUDES .shtml
+ Options +Includes
+ MemcachedHost localhost:11211
+ </Directory>
+
+Once the file is stored in Memcached, you can ``test/pull-*.shtml``
+files.
+
+..
+ Local Variables:
+ mode: rst
+ fill-column: 79
+ End:
+ vim: et syn=rst tw=79
|
jeromer/modmemcachedinclude
|
ccdce9046f528ce3e461ae277be437651f841553
|
- translated test file in english
|
diff --git a/tests/mod_memcached_include_tests b/tests/mod_memcached_include_tests
index b13cc19..605ea75 100644
--- a/tests/mod_memcached_include_tests
+++ b/tests/mod_memcached_include_tests
@@ -1 +1 @@
-<b>contenu de mod_memcached_include_test LOCAL</b>
+mod_memcached_include test : <b>LOCAL</b>
|
jeromer/modmemcachedinclude
|
fd54ad32a57c437c796d6d52d138c7043b1aceaa
|
-initial import
|
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..0b0586a
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,49 @@
+##
+## Makefile -- Build procedure for sample memcached_include Apache module
+## Autogenerated via ``apxs -n memcached_include -g''.
+##
+
+## apxs -c -lapr_memcache -L/opt/local/lib -I/opt/local/include/apr_memcache-0 -DDEBUG_INCLUDE mod_memcached_include.c
+
+builddir=.
+top_srcdir=/usr/local/apache-2.2.9
+top_builddir=/usr/local/apache-2.2.9
+include /usr/local/apache-2.2.9/build/special.mk
+
+# the used tools
+APXS=apxs
+APACHECTL=apache2ctl
+
+# additional defines, includes and libraries
+#DEFS=-DDEBUG_MEMCACHED_INCLUDE
+DEFS=
+INCLUDES=-I/usr/local/apache-2.2.9/include/apr_memcache-0
+LIBS=-L/usr/local/apache-2.2.9/lib -lapr_memcache
+
+# the default target
+all: local-shared-build
+
+# install the shared object file into Apache
+install: install-modules-yes
+
+# cleanup
+clean:
+ -rm -f mod_memcached_include.o mod_memcached_include.lo mod_memcached_include.slo mod_memcached_include.la
+
+# simple test
+test: reload
+ lynx -mime_header http://localhost/memcached_include
+
+# install and activate shared object by reloading Apache to
+# force a reload of the shared object file
+reload: install restart
+
+# the general Apache start/restart/stop
+# procedures
+start:
+ $(APACHECTL) start
+restart:
+ $(APACHECTL) restart
+stop:
+ $(APACHECTL) stop
+
diff --git a/mod_memcached_include.c b/mod_memcached_include.c
new file mode 100644
index 0000000..7dcfe0a
--- /dev/null
+++ b/mod_memcached_include.c
@@ -0,0 +1,4053 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "apr.h"
+#include "apr_strings.h"
+#include "apr_thread_proc.h"
+#include "apr_hash.h"
+#include "apr_user.h"
+#include "apr_lib.h"
+#include "apr_optional.h"
+
+#define APR_WANT_STRFUNC
+#define APR_WANT_MEMFUNC
+#include "apr_want.h"
+
+#include "ap_config.h"
+#include "util_filter.h"
+#include "httpd.h"
+#include "http_config.h"
+#include "http_core.h"
+#include "http_request.h"
+#include "http_core.h"
+#include "http_protocol.h"
+#include "http_log.h"
+#include "http_main.h"
+#include "util_script.h"
+#include "http_core.h"
+#include "mod_memcached_include.h"
+
+#include "apr_memcache.h"
+
+/* helper for Latin1 <-> entity encoding */
+#if APR_CHARSET_EBCDIC
+#include "util_ebcdic.h"
+#define RAW_ASCII_CHAR(ch) apr_xlate_conv_byte(ap_hdrs_from_ascii, \
+ (unsigned char)ch)
+#else /* APR_CHARSET_EBCDIC */
+#define RAW_ASCII_CHAR(ch) (ch)
+#endif /* !APR_CHARSET_EBCDIC */
+
+
+/*
+ * +-------------------------------------------------------+
+ * | |
+ * | Types and Structures
+ * | |
+ * +-------------------------------------------------------+
+ */
+
+/* sll used for string expansion */
+typedef struct result_item {
+ struct result_item *next;
+ apr_size_t len;
+ const char *string;
+} result_item_t;
+
+/* conditional expression parser stuff */
+typedef enum {
+ TOKEN_STRING,
+ TOKEN_RE,
+ TOKEN_AND,
+ TOKEN_OR,
+ TOKEN_NOT,
+ TOKEN_EQ,
+ TOKEN_NE,
+ TOKEN_RBRACE,
+ TOKEN_LBRACE,
+ TOKEN_GROUP,
+ TOKEN_GE,
+ TOKEN_LE,
+ TOKEN_GT,
+ TOKEN_LT,
+ TOKEN_ACCESS
+} token_type_t;
+
+typedef struct {
+ token_type_t type;
+ const char *value;
+#ifdef DEBUG_INCLUDE
+ const char *s;
+#endif
+} token_t;
+
+typedef struct parse_node {
+ struct parse_node *parent;
+ struct parse_node *left;
+ struct parse_node *right;
+ token_t token;
+ int value;
+ int done;
+#ifdef DEBUG_INCLUDE
+ int dump_done;
+#endif
+} parse_node_t;
+
+typedef enum {
+ XBITHACK_OFF,
+ XBITHACK_ON,
+ XBITHACK_FULL
+} xbithack_t;
+
+typedef struct {
+ const char *default_error_msg;
+ const char *default_time_fmt;
+ const char *undefined_echo;
+ xbithack_t xbithack;
+ const int accessenable;
+} include_dir_config;
+
+typedef struct {
+ const char *host;
+ apr_port_t port;
+ apr_memcache_server_t *server;
+} memcached_include_server_t;
+
+#define DEFAULT_MAX_SERVERS 1
+#define DEFAULT_MIN 5
+#define DEFAULT_SMAX 10
+#define DEFAULT_MAX 15
+#define DEFAULT_TTL 10
+#define DEFAULT_MIN_SIZE 1
+#define DEFAULT_MAX_SIZE 1048576
+
+typedef struct {
+ const char *default_start_tag;
+ const char *default_end_tag;
+
+ apr_memcache_t *memcached;
+ apr_array_header_t *servers;
+
+ apr_uint32_t conn_min;
+ apr_uint32_t conn_smax;
+ apr_uint32_t conn_max;
+ apr_uint32_t conn_ttl;
+ apr_uint16_t max_servers;
+ apr_off_t min_size;
+ apr_off_t max_size;
+} include_server_config;
+
+/* main parser states */
+typedef enum {
+ PARSE_PRE_HEAD,
+ PARSE_HEAD,
+ PARSE_DIRECTIVE,
+ PARSE_DIRECTIVE_POSTNAME,
+ PARSE_DIRECTIVE_TAIL,
+ PARSE_DIRECTIVE_POSTTAIL,
+ PARSE_PRE_ARG,
+ PARSE_ARG,
+ PARSE_ARG_NAME,
+ PARSE_ARG_POSTNAME,
+ PARSE_ARG_EQ,
+ PARSE_ARG_PREVAL,
+ PARSE_ARG_VAL,
+ PARSE_ARG_VAL_ESC,
+ PARSE_ARG_POSTVAL,
+ PARSE_TAIL,
+ PARSE_TAIL_SEQ,
+ PARSE_EXECUTE
+} parse_state_t;
+
+typedef struct arg_item {
+ struct arg_item *next;
+ char *name;
+ apr_size_t name_len;
+ char *value;
+ apr_size_t value_len;
+} arg_item_t;
+
+typedef struct {
+ const char *source;
+ const char *rexp;
+ apr_size_t nsub;
+ ap_regmatch_t match[AP_MAX_REG_MATCH];
+} backref_t;
+
+typedef struct {
+ unsigned int T[256];
+ unsigned int x;
+ apr_size_t pattern_len;
+} bndm_t;
+
+struct ssi_internal_ctx {
+ parse_state_t state;
+ int seen_eos;
+ int error;
+ char quote; /* quote character value (or \0) */
+ apr_size_t parse_pos; /* parse position of partial matches */
+ apr_size_t bytes_read;
+
+ apr_bucket_brigade *tmp_bb;
+
+ request_rec *r;
+ const char *start_seq;
+ bndm_t *start_seq_pat;
+ const char *end_seq;
+ apr_size_t end_seq_len;
+ char *directive; /* name of the current directive */
+ apr_size_t directive_len; /* length of the current directive name */
+
+ arg_item_t *current_arg; /* currently parsed argument */
+ arg_item_t *argv; /* all arguments */
+
+ backref_t *re; /* NULL if there wasn't a regex yet */
+
+ const char *undefined_echo;
+ apr_size_t undefined_echo_len;
+
+ int accessenable; /* is using the access tests allowed? */
+
+#ifdef DEBUG_INCLUDE
+ struct {
+ ap_filter_t *f;
+ apr_bucket_brigade *bb;
+ } debug;
+#endif
+};
+
+
+/*
+ * +-------------------------------------------------------+
+ * | |
+ * | Debugging Utilities
+ * | |
+ * +-------------------------------------------------------+
+ */
+
+#ifdef DEBUG_INCLUDE
+
+#define TYPE_TOKEN(token, ttype) do { \
+ (token)->type = ttype; \
+ (token)->s = #ttype; \
+} while(0)
+
+#define CREATE_NODE(ctx, name) do { \
+ (name) = apr_palloc((ctx)->dpool, sizeof(*(name))); \
+ (name)->parent = (name)->left = (name)->right = NULL; \
+ (name)->done = 0; \
+ (name)->dump_done = 0; \
+} while(0)
+
+static void debug_printf(include_ctx_t *ctx, const char *fmt, ...)
+{
+ va_list ap;
+ char *debug__str;
+
+ va_start(ap, fmt);
+ debug__str = apr_pvsprintf(ctx->pool, fmt, ap);
+ va_end(ap);
+
+ APR_BRIGADE_INSERT_TAIL(ctx->intern->debug.bb, apr_bucket_pool_create(
+ debug__str, strlen(debug__str), ctx->pool,
+ ctx->intern->debug.f->c->bucket_alloc));
+}
+
+#define DUMP__CHILD(ctx, is, node, child) if (1) { \
+ parse_node_t *d__c = node->child; \
+ if (d__c) { \
+ if (!d__c->dump_done) { \
+ if (d__c->parent != node) { \
+ debug_printf(ctx, "!!! Parse tree is not consistent !!!\n"); \
+ if (!d__c->parent) { \
+ debug_printf(ctx, "Parent of " #child " child node is " \
+ "NULL.\n"); \
+ } \
+ else { \
+ debug_printf(ctx, "Parent of " #child " child node " \
+ "points to another node (of type %s)!\n", \
+ d__c->parent->token.s); \
+ } \
+ return; \
+ } \
+ node = d__c; \
+ continue; \
+ } \
+ } \
+ else { \
+ debug_printf(ctx, "%s(missing)\n", is); \
+ } \
+}
+
+static void debug_dump_tree(include_ctx_t *ctx, parse_node_t *root)
+{
+ parse_node_t *current;
+ char *is;
+
+ if (!root) {
+ debug_printf(ctx, " -- Parse Tree empty --\n\n");
+ return;
+ }
+
+ debug_printf(ctx, " ----- Parse Tree -----\n");
+ current = root;
+ is = " ";
+
+ while (current) {
+ switch (current->token.type) {
+ case TOKEN_STRING:
+ case TOKEN_RE:
+ debug_printf(ctx, "%s%s (%s)\n", is, current->token.s,
+ current->token.value);
+ current->dump_done = 1;
+ current = current->parent;
+ continue;
+
+ case TOKEN_NOT:
+ case TOKEN_GROUP:
+ case TOKEN_RBRACE:
+ case TOKEN_LBRACE:
+ if (!current->dump_done) {
+ debug_printf(ctx, "%s%s\n", is, current->token.s);
+ is = apr_pstrcat(ctx->dpool, is, " ", NULL);
+ current->dump_done = 1;
+ }
+
+ DUMP__CHILD(ctx, is, current, right)
+
+ if (!current->right || current->right->dump_done) {
+ is = apr_pstrmemdup(ctx->dpool, is, strlen(is) - 4);
+ if (current->right) current->right->dump_done = 0;
+ current = current->parent;
+ }
+ continue;
+
+ default:
+ if (!current->dump_done) {
+ debug_printf(ctx, "%s%s\n", is, current->token.s);
+ is = apr_pstrcat(ctx->dpool, is, " ", NULL);
+ current->dump_done = 1;
+ }
+
+ DUMP__CHILD(ctx, is, current, left)
+ DUMP__CHILD(ctx, is, current, right)
+
+ if ((!current->left || current->left->dump_done) &&
+ (!current->right || current->right->dump_done)) {
+
+ is = apr_pstrmemdup(ctx->dpool, is, strlen(is) - 4);
+ if (current->left) current->left->dump_done = 0;
+ if (current->right) current->right->dump_done = 0;
+ current = current->parent;
+ }
+ continue;
+ }
+ }
+
+ /* it is possible to call this function within the parser loop, to see
+ * how the tree is built. That way, we must cleanup after us to dump
+ * always the whole tree
+ */
+ root->dump_done = 0;
+ if (root->left) root->left->dump_done = 0;
+ if (root->right) root->right->dump_done = 0;
+
+ debug_printf(ctx, " --- End Parse Tree ---\n\n");
+
+ return;
+}
+
+#define DEBUG_INIT(ctx, filter, brigade) do { \
+ (ctx)->intern->debug.f = filter; \
+ (ctx)->intern->debug.bb = brigade; \
+} while(0)
+
+#define DEBUG_PRINTF(arg) debug_printf arg
+
+#define DEBUG_DUMP_TOKEN(ctx, token) do { \
+ token_t *d__t = (token); \
+ \
+ if (d__t->type == TOKEN_STRING || d__t->type == TOKEN_RE) { \
+ DEBUG_PRINTF(((ctx), " Found: %s (%s)\n", d__t->s, d__t->value)); \
+ } \
+ else { \
+ DEBUG_PRINTF((ctx, " Found: %s\n", d__t->s)); \
+ } \
+} while(0)
+
+#define DEBUG_DUMP_EVAL(ctx, node) do { \
+ char c = '"'; \
+ switch ((node)->token.type) { \
+ case TOKEN_STRING: \
+ debug_printf((ctx), " Evaluate: %s (%s) -> %c\n", (node)->token.s,\
+ (node)->token.value, ((node)->value) ? '1':'0'); \
+ break; \
+ case TOKEN_AND: \
+ case TOKEN_OR: \
+ debug_printf((ctx), " Evaluate: %s (Left: %s; Right: %s) -> %c\n",\
+ (node)->token.s, \
+ (((node)->left->done) ? ((node)->left->value ?"1":"0") \
+ : "short circuited"), \
+ (((node)->right->done) ? ((node)->right->value?"1":"0") \
+ : "short circuited"), \
+ (node)->value ? '1' : '0'); \
+ break; \
+ case TOKEN_EQ: \
+ case TOKEN_NE: \
+ case TOKEN_GT: \
+ case TOKEN_GE: \
+ case TOKEN_LT: \
+ case TOKEN_LE: \
+ if ((node)->right->token.type == TOKEN_RE) c = '/'; \
+ debug_printf((ctx), " Compare: %s (\"%s\" with %c%s%c) -> %c\n", \
+ (node)->token.s, \
+ (node)->left->token.value, \
+ c, (node)->right->token.value, c, \
+ (node)->value ? '1' : '0'); \
+ break; \
+ default: \
+ debug_printf((ctx), " Evaluate: %s -> %c\n", (node)->token.s, \
+ (node)->value ? '1' : '0'); \
+ break; \
+ } \
+} while(0)
+
+#define DEBUG_DUMP_UNMATCHED(ctx, unmatched) do { \
+ if (unmatched) { \
+ DEBUG_PRINTF(((ctx), " Unmatched %c\n", (char)(unmatched))); \
+ } \
+} while(0)
+
+#define DEBUG_DUMP_COND(ctx, text) \
+ DEBUG_PRINTF(((ctx), "**** %s cond status=\"%c\"\n", (text), \
+ ((ctx)->flags & SSI_FLAG_COND_TRUE) ? '1' : '0'))
+
+#define DEBUG_DUMP_TREE(ctx, root) debug_dump_tree(ctx, root)
+
+#else /* DEBUG_INCLUDE */
+
+#define TYPE_TOKEN(token, ttype) (token)->type = ttype
+
+#define CREATE_NODE(ctx, name) do { \
+ (name) = apr_palloc((ctx)->dpool, sizeof(*(name))); \
+ (name)->parent = (name)->left = (name)->right = NULL; \
+ (name)->done = 0; \
+} while(0)
+
+#define DEBUG_INIT(ctx, f, bb)
+#define DEBUG_PRINTF(arg)
+#define DEBUG_DUMP_TOKEN(ctx, token)
+#define DEBUG_DUMP_EVAL(ctx, node)
+#define DEBUG_DUMP_UNMATCHED(ctx, unmatched)
+#define DEBUG_DUMP_COND(ctx, text)
+#define DEBUG_DUMP_TREE(ctx, root)
+
+#endif /* !DEBUG_INCLUDE */
+
+
+/*
+ * +-------------------------------------------------------+
+ * | |
+ * | Static Module Data
+ * | |
+ * +-------------------------------------------------------+
+ */
+
+/* global module structure */
+module AP_MODULE_DECLARE_DATA memcached_include_module;
+
+/* function handlers for include directives */
+static apr_hash_t *include_handlers;
+
+/* forward declaration of handler registry */
+static APR_OPTIONAL_FN_TYPE(ap_register_memcached_include_handler) *ssi_pfn_register;
+
+/* Sentinel value to store in subprocess_env for items that
+ * shouldn't be evaluated until/unless they're actually used
+ */
+static const char lazy_eval_sentinel;
+#define LAZY_VALUE (&lazy_eval_sentinel)
+
+/* default values */
+#define DEFAULT_START_SEQUENCE "<!--#"
+#define DEFAULT_END_SEQUENCE "-->"
+#define DEFAULT_ERROR_MSG "[an error occurred while processing this directive]"
+#define DEFAULT_TIME_FORMAT "%A, %d-%b-%Y %H:%M:%S %Z"
+#define DEFAULT_UNDEFINED_ECHO "(none)"
+
+#ifdef XBITHACK
+#define DEFAULT_XBITHACK XBITHACK_FULL
+#else
+#define DEFAULT_XBITHACK XBITHACK_OFF
+#endif
+
+
+/*
+ * +-------------------------------------------------------+
+ * | |
+ * | Environment/Expansion Functions
+ * | |
+ * +-------------------------------------------------------+
+ */
+
+/*
+ * decodes a string containing html entities or numeric character references.
+ * 's' is overwritten with the decoded string.
+ * If 's' is syntatically incorrect, then the followed fixups will be made:
+ * unknown entities will be left undecoded;
+ * references to unused numeric characters will be deleted.
+ * In particular, � will not be decoded, but will be deleted.
+ */
+
+/* maximum length of any ISO-LATIN-1 HTML entity name. */
+#define MAXENTLEN (6)
+
+/* The following is a shrinking transformation, therefore safe. */
+
+static void decodehtml(char *s)
+{
+ int val, i, j;
+ char *p;
+ const char *ents;
+ static const char * const entlist[MAXENTLEN + 1] =
+ {
+ NULL, /* 0 */
+ NULL, /* 1 */
+ "lt\074gt\076", /* 2 */
+ "amp\046ETH\320eth\360", /* 3 */
+ "quot\042Auml\304Euml\313Iuml\317Ouml\326Uuml\334auml\344euml"
+ "\353iuml\357ouml\366uuml\374yuml\377", /* 4 */
+
+ "Acirc\302Aring\305AElig\306Ecirc\312Icirc\316Ocirc\324Ucirc"
+ "\333THORN\336szlig\337acirc\342aring\345aelig\346ecirc\352"
+ "icirc\356ocirc\364ucirc\373thorn\376", /* 5 */
+
+ "Agrave\300Aacute\301Atilde\303Ccedil\307Egrave\310Eacute\311"
+ "Igrave\314Iacute\315Ntilde\321Ograve\322Oacute\323Otilde"
+ "\325Oslash\330Ugrave\331Uacute\332Yacute\335agrave\340"
+ "aacute\341atilde\343ccedil\347egrave\350eacute\351igrave"
+ "\354iacute\355ntilde\361ograve\362oacute\363otilde\365"
+ "oslash\370ugrave\371uacute\372yacute\375" /* 6 */
+ };
+
+ /* Do a fast scan through the string until we find anything
+ * that needs more complicated handling
+ */
+ for (; *s != '&'; s++) {
+ if (*s == '\0') {
+ return;
+ }
+ }
+
+ for (p = s; *s != '\0'; s++, p++) {
+ if (*s != '&') {
+ *p = *s;
+ continue;
+ }
+ /* find end of entity */
+ for (i = 1; s[i] != ';' && s[i] != '\0'; i++) {
+ continue;
+ }
+
+ if (s[i] == '\0') { /* treat as normal data */
+ *p = *s;
+ continue;
+ }
+
+ /* is it numeric ? */
+ if (s[1] == '#') {
+ for (j = 2, val = 0; j < i && apr_isdigit(s[j]); j++) {
+ val = val * 10 + s[j] - '0';
+ }
+ s += i;
+ if (j < i || val <= 8 || (val >= 11 && val <= 31) ||
+ (val >= 127 && val <= 160) || val >= 256) {
+ p--; /* no data to output */
+ }
+ else {
+ *p = RAW_ASCII_CHAR(val);
+ }
+ }
+ else {
+ j = i - 1;
+ if (j > MAXENTLEN || entlist[j] == NULL) {
+ /* wrong length */
+ *p = '&';
+ continue; /* skip it */
+ }
+ for (ents = entlist[j]; *ents != '\0'; ents += i) {
+ if (strncmp(s + 1, ents, j) == 0) {
+ break;
+ }
+ }
+
+ if (*ents == '\0') {
+ *p = '&'; /* unknown */
+ }
+ else {
+ *p = RAW_ASCII_CHAR(((const unsigned char *) ents)[j]);
+ s += i;
+ }
+ }
+ }
+
+ *p = '\0';
+}
+
+static void add_include_vars(request_rec *r, const char *timefmt)
+{
+ apr_table_t *e = r->subprocess_env;
+ char *t;
+
+ apr_table_setn(e, "DATE_LOCAL", LAZY_VALUE);
+ apr_table_setn(e, "DATE_GMT", LAZY_VALUE);
+ apr_table_setn(e, "LAST_MODIFIED", LAZY_VALUE);
+ apr_table_setn(e, "DOCUMENT_URI", r->uri);
+ if (r->path_info && *r->path_info) {
+ apr_table_setn(e, "DOCUMENT_PATH_INFO", r->path_info);
+ }
+ apr_table_setn(e, "USER_NAME", LAZY_VALUE);
+ if (r->filename && (t = strrchr(r->filename, '/'))) {
+ apr_table_setn(e, "DOCUMENT_NAME", ++t);
+ }
+ else {
+ apr_table_setn(e, "DOCUMENT_NAME", r->uri);
+ }
+ if (r->args) {
+ char *arg_copy = apr_pstrdup(r->pool, r->args);
+
+ ap_unescape_url(arg_copy);
+ apr_table_setn(e, "QUERY_STRING_UNESCAPED",
+ ap_escape_shell_cmd(r->pool, arg_copy));
+ }
+}
+
+static const char *add_include_vars_lazy(request_rec *r, const char *var)
+{
+ char *val;
+ if (!strcasecmp(var, "DATE_LOCAL")) {
+ include_dir_config *conf =
+ (include_dir_config *)ap_get_module_config(r->per_dir_config,
+ &memcached_include_module);
+ val = ap_ht_time(r->pool, r->request_time, conf->default_time_fmt, 0);
+ }
+ else if (!strcasecmp(var, "DATE_GMT")) {
+ include_dir_config *conf =
+ (include_dir_config *)ap_get_module_config(r->per_dir_config,
+ &memcached_include_module);
+ val = ap_ht_time(r->pool, r->request_time, conf->default_time_fmt, 1);
+ }
+ else if (!strcasecmp(var, "LAST_MODIFIED")) {
+ include_dir_config *conf =
+ (include_dir_config *)ap_get_module_config(r->per_dir_config,
+ &memcached_include_module);
+ val = ap_ht_time(r->pool, r->finfo.mtime, conf->default_time_fmt, 0);
+ }
+ else if (!strcasecmp(var, "USER_NAME")) {
+ if (apr_uid_name_get(&val, r->finfo.user, r->pool) != APR_SUCCESS) {
+ val = "<unknown>";
+ }
+ }
+ else {
+ val = NULL;
+ }
+
+ if (val) {
+ apr_table_setn(r->subprocess_env, var, val);
+ }
+ return val;
+}
+
+static const char *get_include_var(const char *var, include_ctx_t *ctx)
+{
+ const char *val;
+ request_rec *r = ctx->intern->r;
+
+ if (apr_isdigit(*var) && !var[1]) {
+ apr_size_t idx = *var - '0';
+ backref_t *re = ctx->intern->re;
+
+ /* Handle $0 .. $9 from the last regex evaluated.
+ * The choice of returning NULL strings on not-found,
+ * v.s. empty strings on an empty match is deliberate.
+ */
+ if (!re) {
+ ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
+ "regex capture $%" APR_SIZE_T_FMT " refers to no regex in %s",
+ idx, r->filename);
+ return NULL;
+ }
+ else {
+ if (re->nsub < idx || idx >= AP_MAX_REG_MATCH) {
+ ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
+ "regex capture $%" APR_SIZE_T_FMT
+ " is out of range (last regex was: '%s') in %s",
+ idx, re->rexp, r->filename);
+ return NULL;
+ }
+
+ if (re->match[idx].rm_so < 0 || re->match[idx].rm_eo < 0) {
+ return NULL;
+ }
+
+ val = apr_pstrmemdup(ctx->dpool, re->source + re->match[idx].rm_so,
+ re->match[idx].rm_eo - re->match[idx].rm_so);
+ }
+ }
+ else {
+ val = apr_table_get(r->subprocess_env, var);
+
+ if (val == LAZY_VALUE) {
+ val = add_include_vars_lazy(r, var);
+ }
+ }
+
+ return val;
+}
+
+/*
+ * Do variable substitution on strings
+ *
+ * (Note: If out==NULL, this function allocs a buffer for the resulting
+ * string from ctx->pool. The return value is always the parsed string)
+ */
+static char *ap_ssi_parse_string(include_ctx_t *ctx, const char *in, char *out,
+ apr_size_t length, int leave_name)
+{
+ request_rec *r = ctx->intern->r;
+ result_item_t *result = NULL, *current = NULL;
+ apr_size_t outlen = 0, inlen, span;
+ char *ret = NULL, *eout = NULL;
+ const char *p;
+
+ if (out) {
+ /* sanity check, out && !length is not supported */
+ ap_assert(out && length);
+
+ ret = out;
+ eout = out + length - 1;
+ }
+
+ span = strcspn(in, "\\$");
+ inlen = strlen(in);
+
+ /* fast exit */
+ if (inlen == span) {
+ if (out) {
+ apr_cpystrn(out, in, length);
+ }
+ else {
+ ret = apr_pstrmemdup(ctx->pool, in, (length && length <= inlen)
+ ? length - 1 : inlen);
+ }
+
+ return ret;
+ }
+
+ /* well, actually something to do */
+ p = in + span;
+
+ if (out) {
+ if (span) {
+ memcpy(out, in, (out+span <= eout) ? span : (eout-out));
+ out += span;
+ }
+ }
+ else {
+ current = result = apr_palloc(ctx->dpool, sizeof(*result));
+ current->next = NULL;
+ current->string = in;
+ current->len = span;
+ outlen = span;
+ }
+
+ /* loop for specials */
+ do {
+ if ((out && out >= eout) || (length && outlen >= length)) {
+ break;
+ }
+
+ /* prepare next entry */
+ if (!out && current->len) {
+ current->next = apr_palloc(ctx->dpool, sizeof(*current->next));
+ current = current->next;
+ current->next = NULL;
+ current->len = 0;
+ }
+
+ /*
+ * escaped character
+ */
+ if (*p == '\\') {
+ if (out) {
+ *out++ = (p[1] == '$') ? *++p : *p;
+ ++p;
+ }
+ else {
+ current->len = 1;
+ current->string = (p[1] == '$') ? ++p : p;
+ ++p;
+ ++outlen;
+ }
+ }
+
+ /*
+ * variable expansion
+ */
+ else { /* *p == '$' */
+ const char *newp = NULL, *ep, *key = NULL;
+
+ if (*++p == '{') {
+ ep = ap_strchr_c(++p, '}');
+ if (!ep) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Missing '}' on "
+ "variable \"%s\" in %s", p, r->filename);
+ break;
+ }
+
+ if (p < ep) {
+ key = apr_pstrmemdup(ctx->dpool, p, ep - p);
+ newp = ep + 1;
+ }
+ p -= 2;
+ }
+ else {
+ ep = p;
+ while (*ep == '_' || apr_isalnum(*ep)) {
+ ++ep;
+ }
+
+ if (p < ep) {
+ key = apr_pstrmemdup(ctx->dpool, p, ep - p);
+ newp = ep;
+ }
+ --p;
+ }
+
+ /* empty name results in a copy of '$' in the output string */
+ if (!key) {
+ if (out) {
+ *out++ = *p++;
+ }
+ else {
+ current->len = 1;
+ current->string = p++;
+ ++outlen;
+ }
+ }
+ else {
+ const char *val = get_include_var(key, ctx);
+ apr_size_t len = 0;
+
+ if (val) {
+ len = strlen(val);
+ }
+ else if (leave_name) {
+ val = p;
+ len = ep - p;
+ }
+
+ if (val && len) {
+ if (out) {
+ memcpy(out, val, (out+len <= eout) ? len : (eout-out));
+ out += len;
+ }
+ else {
+ current->len = len;
+ current->string = val;
+ outlen += len;
+ }
+ }
+
+ p = newp;
+ }
+ }
+
+ if ((out && out >= eout) || (length && outlen >= length)) {
+ break;
+ }
+
+ /* check the remainder */
+ if (*p && (span = strcspn(p, "\\$")) > 0) {
+ if (!out && current->len) {
+ current->next = apr_palloc(ctx->dpool, sizeof(*current->next));
+ current = current->next;
+ current->next = NULL;
+ }
+
+ if (out) {
+ memcpy(out, p, (out+span <= eout) ? span : (eout-out));
+ out += span;
+ }
+ else {
+ current->len = span;
+ current->string = p;
+ outlen += span;
+ }
+
+ p += span;
+ }
+ } while (p < in+inlen);
+
+ /* assemble result */
+ if (out) {
+ if (out > eout) {
+ *eout = '\0';
+ }
+ else {
+ *out = '\0';
+ }
+ }
+ else {
+ const char *ep;
+
+ if (length && outlen > length) {
+ outlen = length - 1;
+ }
+
+ ret = out = apr_palloc(ctx->pool, outlen + 1);
+ ep = ret + outlen;
+
+ do {
+ if (result->len) {
+ memcpy(out, result->string, (out+result->len <= ep)
+ ? result->len : (ep-out));
+ out += result->len;
+ }
+ result = result->next;
+ } while (result && out < ep);
+
+ ret[outlen] = '\0';
+ }
+
+ return ret;
+}
+
+
+/*
+ * +-------------------------------------------------------+
+ * | |
+ * | Conditional Expression Parser
+ * | |
+ * +-------------------------------------------------------+
+ */
+
+static APR_INLINE int re_check(include_ctx_t *ctx, const char *string,
+ const char *rexp)
+{
+ ap_regex_t *compiled;
+ backref_t *re = ctx->intern->re;
+ int rc;
+
+ compiled = ap_pregcomp(ctx->dpool, rexp, AP_REG_EXTENDED);
+ if (!compiled) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, ctx->intern->r, "unable to "
+ "compile pattern \"%s\"", rexp);
+ return -1;
+ }
+
+ if (!re) {
+ re = ctx->intern->re = apr_palloc(ctx->pool, sizeof(*re));
+ }
+
+ re->source = apr_pstrdup(ctx->pool, string);
+ re->rexp = apr_pstrdup(ctx->pool, rexp);
+ re->nsub = compiled->re_nsub;
+ rc = !ap_regexec(compiled, string, AP_MAX_REG_MATCH, re->match, 0);
+
+ ap_pregfree(ctx->dpool, compiled);
+ return rc;
+}
+
+static int get_ptoken(include_ctx_t *ctx, const char **parse, token_t *token, token_t *previous)
+{
+ const char *p;
+ apr_size_t shift;
+ int unmatched;
+
+ token->value = NULL;
+
+ if (!*parse) {
+ return 0;
+ }
+
+ /* Skip leading white space */
+ while (apr_isspace(**parse)) {
+ ++*parse;
+ }
+
+ if (!**parse) {
+ *parse = NULL;
+ return 0;
+ }
+
+ TYPE_TOKEN(token, TOKEN_STRING); /* the default type */
+ p = *parse;
+ unmatched = 0;
+
+ switch (*(*parse)++) {
+ case '(':
+ TYPE_TOKEN(token, TOKEN_LBRACE);
+ return 0;
+ case ')':
+ TYPE_TOKEN(token, TOKEN_RBRACE);
+ return 0;
+ case '=':
+ if (**parse == '=') ++*parse;
+ TYPE_TOKEN(token, TOKEN_EQ);
+ return 0;
+ case '!':
+ if (**parse == '=') {
+ TYPE_TOKEN(token, TOKEN_NE);
+ ++*parse;
+ return 0;
+ }
+ TYPE_TOKEN(token, TOKEN_NOT);
+ return 0;
+ case '\'':
+ unmatched = '\'';
+ break;
+ case '/':
+ /* if last token was ACCESS, this token is STRING */
+ if (previous != NULL && TOKEN_ACCESS == previous->type) {
+ break;
+ }
+ TYPE_TOKEN(token, TOKEN_RE);
+ unmatched = '/';
+ break;
+ case '|':
+ if (**parse == '|') {
+ TYPE_TOKEN(token, TOKEN_OR);
+ ++*parse;
+ return 0;
+ }
+ break;
+ case '&':
+ if (**parse == '&') {
+ TYPE_TOKEN(token, TOKEN_AND);
+ ++*parse;
+ return 0;
+ }
+ break;
+ case '>':
+ if (**parse == '=') {
+ TYPE_TOKEN(token, TOKEN_GE);
+ ++*parse;
+ return 0;
+ }
+ TYPE_TOKEN(token, TOKEN_GT);
+ return 0;
+ case '<':
+ if (**parse == '=') {
+ TYPE_TOKEN(token, TOKEN_LE);
+ ++*parse;
+ return 0;
+ }
+ TYPE_TOKEN(token, TOKEN_LT);
+ return 0;
+ case '-':
+ if (**parse == 'A' && (ctx->intern->accessenable)) {
+ TYPE_TOKEN(token, TOKEN_ACCESS);
+ ++*parse;
+ return 0;
+ }
+ break;
+ }
+
+ /* It's a string or regex token
+ * Now search for the next token, which finishes this string
+ */
+ shift = 0;
+ p = *parse = token->value = unmatched ? *parse : p;
+
+ for (; **parse; p = ++*parse) {
+ if (**parse == '\\') {
+ if (!*(++*parse)) {
+ p = *parse;
+ break;
+ }
+
+ ++shift;
+ }
+ else {
+ if (unmatched) {
+ if (**parse == unmatched) {
+ unmatched = 0;
+ ++*parse;
+ break;
+ }
+ } else if (apr_isspace(**parse)) {
+ break;
+ }
+ else {
+ int found = 0;
+
+ switch (**parse) {
+ case '(':
+ case ')':
+ case '=':
+ case '!':
+ case '<':
+ case '>':
+ ++found;
+ break;
+
+ case '|':
+ case '&':
+ if ((*parse)[1] == **parse) {
+ ++found;
+ }
+ break;
+ }
+
+ if (found) {
+ break;
+ }
+ }
+ }
+ }
+
+ if (unmatched) {
+ token->value = apr_pstrdup(ctx->dpool, "");
+ }
+ else {
+ apr_size_t len = p - token->value - shift;
+ char *c = apr_palloc(ctx->dpool, len + 1);
+
+ p = token->value;
+ token->value = c;
+
+ while (shift--) {
+ const char *e = ap_strchr_c(p, '\\');
+
+ memcpy(c, p, e-p);
+ c += e-p;
+ *c++ = *++e;
+ len -= e-p;
+ p = e+1;
+ }
+
+ if (len) {
+ memcpy(c, p, len);
+ }
+ c[len] = '\0';
+ }
+
+ return unmatched;
+}
+
+static int parse_expr(include_ctx_t *ctx, const char *expr, int *was_error)
+{
+ parse_node_t *new, *root = NULL, *current = NULL;
+ request_rec *r = ctx->intern->r;
+ request_rec *rr = NULL;
+ const char *error = "Invalid expression \"%s\" in file %s";
+ const char *parse = expr;
+ int was_unmatched = 0;
+ unsigned regex = 0;
+
+ *was_error = 0;
+
+ if (!parse) {
+ return 0;
+ }
+
+ /* Create Parse Tree */
+ while (1) {
+ /* uncomment this to see how the tree a built:
+ *
+ * DEBUG_DUMP_TREE(ctx, root);
+ */
+ CREATE_NODE(ctx, new);
+
+ was_unmatched = get_ptoken(ctx, &parse, &new->token,
+ (current != NULL ? ¤t->token : NULL));
+ if (!parse) {
+ break;
+ }
+
+ DEBUG_DUMP_UNMATCHED(ctx, was_unmatched);
+ DEBUG_DUMP_TOKEN(ctx, &new->token);
+
+ if (!current) {
+ switch (new->token.type) {
+ case TOKEN_STRING:
+ case TOKEN_NOT:
+ case TOKEN_ACCESS:
+ case TOKEN_LBRACE:
+ root = current = new;
+ continue;
+
+ default:
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, error, expr,
+ r->filename);
+ *was_error = 1;
+ return 0;
+ }
+ }
+
+ switch (new->token.type) {
+ case TOKEN_STRING:
+ switch (current->token.type) {
+ case TOKEN_STRING:
+ current->token.value =
+ apr_pstrcat(ctx->dpool, current->token.value,
+ *current->token.value ? " " : "",
+ new->token.value, NULL);
+ continue;
+
+ case TOKEN_RE:
+ case TOKEN_RBRACE:
+ case TOKEN_GROUP:
+ break;
+
+ default:
+ new->parent = current;
+ current = current->right = new;
+ continue;
+ }
+ break;
+
+ case TOKEN_RE:
+ switch (current->token.type) {
+ case TOKEN_EQ:
+ case TOKEN_NE:
+ new->parent = current;
+ current = current->right = new;
+ ++regex;
+ continue;
+
+ default:
+ break;
+ }
+ break;
+
+ case TOKEN_AND:
+ case TOKEN_OR:
+ switch (current->token.type) {
+ case TOKEN_STRING:
+ case TOKEN_RE:
+ case TOKEN_GROUP:
+ current = current->parent;
+
+ while (current) {
+ switch (current->token.type) {
+ case TOKEN_AND:
+ case TOKEN_OR:
+ case TOKEN_LBRACE:
+ break;
+
+ default:
+ current = current->parent;
+ continue;
+ }
+ break;
+ }
+
+ if (!current) {
+ new->left = root;
+ root->parent = new;
+ current = root = new;
+ continue;
+ }
+
+ new->left = current->right;
+ new->left->parent = new;
+ new->parent = current;
+ current = current->right = new;
+ continue;
+
+ default:
+ break;
+ }
+ break;
+
+ case TOKEN_EQ:
+ case TOKEN_NE:
+ case TOKEN_GE:
+ case TOKEN_GT:
+ case TOKEN_LE:
+ case TOKEN_LT:
+ if (current->token.type == TOKEN_STRING) {
+ current = current->parent;
+
+ if (!current) {
+ new->left = root;
+ root->parent = new;
+ current = root = new;
+ continue;
+ }
+
+ switch (current->token.type) {
+ case TOKEN_LBRACE:
+ case TOKEN_AND:
+ case TOKEN_OR:
+ new->left = current->right;
+ new->left->parent = new;
+ new->parent = current;
+ current = current->right = new;
+ continue;
+
+ default:
+ break;
+ }
+ }
+ break;
+
+ case TOKEN_RBRACE:
+ while (current && current->token.type != TOKEN_LBRACE) {
+ current = current->parent;
+ }
+
+ if (current) {
+ TYPE_TOKEN(¤t->token, TOKEN_GROUP);
+ continue;
+ }
+
+ error = "Unmatched ')' in \"%s\" in file %s";
+ break;
+
+ case TOKEN_NOT:
+ case TOKEN_ACCESS:
+ case TOKEN_LBRACE:
+ switch (current->token.type) {
+ case TOKEN_STRING:
+ case TOKEN_RE:
+ case TOKEN_RBRACE:
+ case TOKEN_GROUP:
+ break;
+
+ default:
+ current->right = new;
+ new->parent = current;
+ current = new;
+ continue;
+ }
+ break;
+
+ default:
+ break;
+ }
+
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, error, expr, r->filename);
+ *was_error = 1;
+ return 0;
+ }
+
+ DEBUG_DUMP_TREE(ctx, root);
+
+ /* Evaluate Parse Tree */
+ current = root;
+ error = NULL;
+ while (current) {
+ switch (current->token.type) {
+ case TOKEN_STRING:
+ current->token.value =
+ ap_ssi_parse_string(ctx, current->token.value, NULL, 0,
+ SSI_EXPAND_DROP_NAME);
+ current->value = !!*current->token.value;
+ break;
+
+ case TOKEN_AND:
+ case TOKEN_OR:
+ if (!current->left || !current->right) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
+ "Invalid expression \"%s\" in file %s",
+ expr, r->filename);
+ *was_error = 1;
+ return 0;
+ }
+
+ if (!current->left->done) {
+ switch (current->left->token.type) {
+ case TOKEN_STRING:
+ current->left->token.value =
+ ap_ssi_parse_string(ctx, current->left->token.value,
+ NULL, 0, SSI_EXPAND_DROP_NAME);
+ current->left->value = !!*current->left->token.value;
+ DEBUG_DUMP_EVAL(ctx, current->left);
+ current->left->done = 1;
+ break;
+
+ default:
+ current = current->left;
+ continue;
+ }
+ }
+
+ /* short circuit evaluation */
+ if (!current->right->done && !regex &&
+ ((current->token.type == TOKEN_AND && !current->left->value) ||
+ (current->token.type == TOKEN_OR && current->left->value))) {
+ current->value = current->left->value;
+ }
+ else {
+ if (!current->right->done) {
+ switch (current->right->token.type) {
+ case TOKEN_STRING:
+ current->right->token.value =
+ ap_ssi_parse_string(ctx,current->right->token.value,
+ NULL, 0, SSI_EXPAND_DROP_NAME);
+ current->right->value = !!*current->right->token.value;
+ DEBUG_DUMP_EVAL(ctx, current->right);
+ current->right->done = 1;
+ break;
+
+ default:
+ current = current->right;
+ continue;
+ }
+ }
+
+ if (current->token.type == TOKEN_AND) {
+ current->value = current->left->value &&
+ current->right->value;
+ }
+ else {
+ current->value = current->left->value ||
+ current->right->value;
+ }
+ }
+ break;
+
+ case TOKEN_EQ:
+ case TOKEN_NE:
+ if (!current->left || !current->right ||
+ current->left->token.type != TOKEN_STRING ||
+ (current->right->token.type != TOKEN_STRING &&
+ current->right->token.type != TOKEN_RE)) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
+ "Invalid expression \"%s\" in file %s",
+ expr, r->filename);
+ *was_error = 1;
+ return 0;
+ }
+ current->left->token.value =
+ ap_ssi_parse_string(ctx, current->left->token.value, NULL, 0,
+ SSI_EXPAND_DROP_NAME);
+ current->right->token.value =
+ ap_ssi_parse_string(ctx, current->right->token.value, NULL, 0,
+ SSI_EXPAND_DROP_NAME);
+
+ if (current->right->token.type == TOKEN_RE) {
+ current->value = re_check(ctx, current->left->token.value,
+ current->right->token.value);
+ --regex;
+ }
+ else {
+ current->value = !strcmp(current->left->token.value,
+ current->right->token.value);
+ }
+
+ if (current->token.type == TOKEN_NE) {
+ current->value = !current->value;
+ }
+ break;
+
+ case TOKEN_GE:
+ case TOKEN_GT:
+ case TOKEN_LE:
+ case TOKEN_LT:
+ if (!current->left || !current->right ||
+ current->left->token.type != TOKEN_STRING ||
+ current->right->token.type != TOKEN_STRING) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
+ "Invalid expression \"%s\" in file %s",
+ expr, r->filename);
+ *was_error = 1;
+ return 0;
+ }
+
+ current->left->token.value =
+ ap_ssi_parse_string(ctx, current->left->token.value, NULL, 0,
+ SSI_EXPAND_DROP_NAME);
+ current->right->token.value =
+ ap_ssi_parse_string(ctx, current->right->token.value, NULL, 0,
+ SSI_EXPAND_DROP_NAME);
+
+ current->value = strcmp(current->left->token.value,
+ current->right->token.value);
+
+ switch (current->token.type) {
+ case TOKEN_GE: current->value = current->value >= 0; break;
+ case TOKEN_GT: current->value = current->value > 0; break;
+ case TOKEN_LE: current->value = current->value <= 0; break;
+ case TOKEN_LT: current->value = current->value < 0; break;
+ default: current->value = 0; break; /* should not happen */
+ }
+ break;
+
+ case TOKEN_NOT:
+ case TOKEN_GROUP:
+ if (current->right) {
+ if (!current->right->done) {
+ current = current->right;
+ continue;
+ }
+ current->value = current->right->value;
+ }
+ else {
+ current->value = 1;
+ }
+
+ if (current->token.type == TOKEN_NOT) {
+ current->value = !current->value;
+ }
+ break;
+
+ case TOKEN_ACCESS:
+ if (current->left || !current->right ||
+ (current->right->token.type != TOKEN_STRING &&
+ current->right->token.type != TOKEN_RE)) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
+ "Invalid expression \"%s\" in file %s: Token '-A' must be followed by a URI string.",
+ expr, r->filename);
+ *was_error = 1;
+ return 0;
+ }
+ current->right->token.value =
+ ap_ssi_parse_string(ctx, current->right->token.value, NULL, 0,
+ SSI_EXPAND_DROP_NAME);
+ rr = ap_sub_req_lookup_uri(current->right->token.value, r, NULL);
+ /* 400 and higher are considered access denied */
+ if (rr->status < HTTP_BAD_REQUEST) {
+ current->value = 1;
+ }
+ else {
+ current->value = 0;
+ ap_log_rerror(APLOG_MARK, APLOG_DEBUG, rr->status, r,
+ "mod_include: The tested "
+ "subrequest -A \"%s\" returned an error code.",
+ current->right->token.value);
+ }
+ ap_destroy_sub_req(rr);
+ break;
+
+ case TOKEN_RE:
+ if (!error) {
+ error = "No operator before regex in expr \"%s\" in file %s";
+ }
+ case TOKEN_LBRACE:
+ if (!error) {
+ error = "Unmatched '(' in \"%s\" in file %s";
+ }
+ default:
+ if (!error) {
+ error = "internal parser error in \"%s\" in file %s";
+ }
+
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, error, expr,r->filename);
+ *was_error = 1;
+ return 0;
+ }
+
+ DEBUG_DUMP_EVAL(ctx, current);
+ current->done = 1;
+ current = current->parent;
+ }
+
+ return (root ? root->value : 0);
+}
+
+
+/*
+ * +-------------------------------------------------------+
+ * | |
+ * | Action Handlers
+ * | |
+ * +-------------------------------------------------------+
+ */
+
+/*
+ * Extract the next tag name and value.
+ * If there are no more tags, set the tag name to NULL.
+ * The tag value is html decoded if dodecode is non-zero.
+ * The tag value may be NULL if there is no tag value..
+ */
+static void ap_ssi_get_tag_and_value(include_ctx_t *ctx, char **tag,
+ char **tag_val, int dodecode)
+{
+ if (!ctx->intern->argv) {
+ *tag = NULL;
+ *tag_val = NULL;
+
+ return;
+ }
+
+ *tag_val = ctx->intern->argv->value;
+ *tag = ctx->intern->argv->name;
+
+ ctx->intern->argv = ctx->intern->argv->next;
+
+ if (dodecode && *tag_val) {
+ decodehtml(*tag_val);
+ }
+
+ return;
+}
+
+static int find_file(request_rec *r, const char *directive, const char *tag,
+ char *tag_val, apr_finfo_t *finfo)
+{
+ char *to_send = tag_val;
+ request_rec *rr = NULL;
+ int ret=0;
+ char *error_fmt = NULL;
+ apr_status_t rv = APR_SUCCESS;
+
+ if (!strcmp(tag, "file")) {
+ char *newpath;
+
+ /* be safe; only files in this directory or below allowed */
+ rv = apr_filepath_merge(&newpath, NULL, tag_val,
+ APR_FILEPATH_SECUREROOTTEST |
+ APR_FILEPATH_NOTABSOLUTE, r->pool);
+
+ if (rv != APR_SUCCESS) {
+ error_fmt = "unable to access file \"%s\" "
+ "in parsed file %s";
+ }
+ else {
+ /* note: it is okay to pass NULL for the "next filter" since
+ we never attempt to "run" this sub request. */
+ rr = ap_sub_req_lookup_file(newpath, r, NULL);
+
+ if (rr->status == HTTP_OK && rr->finfo.filetype != 0) {
+ to_send = rr->filename;
+ if ((rv = apr_stat(finfo, to_send,
+ APR_FINFO_GPROT | APR_FINFO_MIN, rr->pool)) != APR_SUCCESS
+ && rv != APR_INCOMPLETE) {
+ error_fmt = "unable to get information about \"%s\" "
+ "in parsed file %s";
+ }
+ }
+ else {
+ error_fmt = "unable to lookup information about \"%s\" "
+ "in parsed file %s";
+ }
+ }
+
+ if (error_fmt) {
+ ret = -1;
+ ap_log_rerror(APLOG_MARK, APLOG_ERR,
+ rv, r, error_fmt, to_send, r->filename);
+ }
+
+ if (rr) ap_destroy_sub_req(rr);
+
+ return ret;
+ }
+ else if (!strcmp(tag, "virtual")) {
+ /* note: it is okay to pass NULL for the "next filter" since
+ we never attempt to "run" this sub request. */
+ rr = ap_sub_req_lookup_uri(tag_val, r, NULL);
+
+ if (rr->status == HTTP_OK && rr->finfo.filetype != 0) {
+ memcpy((char *) finfo, (const char *) &rr->finfo,
+ sizeof(rr->finfo));
+ ap_destroy_sub_req(rr);
+ return 0;
+ }
+ else {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unable to get "
+ "information about \"%s\" in parsed file %s",
+ tag_val, r->filename);
+ ap_destroy_sub_req(rr);
+ return -1;
+ }
+ }
+ else {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unknown parameter \"%s\" "
+ "to tag %s in %s", tag, directive, r->filename);
+ return -1;
+ }
+}
+
+/*
+ * <!--#include virtual|file="..." [virtual|file="..."] ... -->
+ */
+static apr_status_t handle_include(include_ctx_t *ctx, ap_filter_t *f,
+ apr_bucket_brigade *bb)
+{
+ request_rec *r = f->r;
+
+ if (!ctx->argc) {
+ ap_log_rerror(APLOG_MARK,
+ (ctx->flags & SSI_FLAG_PRINTING)
+ ? APLOG_ERR : APLOG_WARNING,
+ 0, r, "missing argument for include element in %s",
+ r->filename);
+ }
+
+ if (!(ctx->flags & SSI_FLAG_PRINTING)) {
+ return APR_SUCCESS;
+ }
+
+ if (!ctx->argc) {
+ SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
+ return APR_SUCCESS;
+ }
+
+ while (1) {
+ char *tag = NULL;
+ char *tag_val = NULL;
+ request_rec *rr = NULL;
+ char *error_fmt = NULL;
+ char *parsed_string;
+
+ ap_ssi_get_tag_and_value(ctx, &tag, &tag_val, SSI_VALUE_DECODED);
+ if (!tag || !tag_val) {
+ break;
+ }
+
+ if (strcmp(tag, "virtual") && strcmp(tag, "file") && strcmp(tag, "memcached")) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unknown parameter "
+ "\"%s\" to tag include in %s", tag, r->filename);
+ SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
+ break;
+ }
+
+ parsed_string = ap_ssi_parse_string(ctx, tag_val, NULL, 0,
+ SSI_EXPAND_DROP_NAME);
+
+ /* Fetching files from Memcached */
+ if (tag[0] == 'm') {
+#ifdef DEBUG_MEMCACHED_INCLUDE
+ ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Found tag : %s", "memcached");
+#endif
+ include_server_config *conf;
+ apr_uint16_t flags;
+ char *strkey = NULL;
+ char *value;
+ apr_size_t value_len;
+ apr_status_t rv;
+
+ strkey = ap_escape_uri(r->pool, parsed_string);
+
+ conf = (include_server_config *)ap_get_module_config(r->server->module_config, &memcached_include_module);
+
+#ifdef DEBUG_MEMCACHED_INCLUDE
+ ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Fetching the file with key : %s", strkey);
+#endif
+
+ rv = apr_memcache_getp(conf->memcached, r->pool, strkey, &value, &value_len, &flags);
+
+ if( rv == APR_SUCCESS ) {
+#ifdef DEBUG_MEMCACHED_INCLUDE
+ ap_log_rerror(APLOG_MARK, APLOG_DEBUG, rv, r, "File found with key %s, value : %s", strkey, value);
+#endif
+ APR_BRIGADE_INSERT_TAIL(bb,
+ apr_bucket_pool_create(apr_pmemdup(ctx->pool, value, value_len),
+ value_len,
+ ctx->pool,
+ f->c->bucket_alloc));
+ }
+
+ if (rv == APR_NOTFOUND) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, "File not found with key : %s", strkey);
+ SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
+ }
+
+ if (rv != APR_SUCCESS) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, "Unable to fetch the file with key : %s", strkey);
+ SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
+ }
+
+ return APR_SUCCESS;
+ }
+
+ if (tag[0] == 'f') {
+ char *newpath;
+ apr_status_t rv;
+
+ /* be safe only files in this directory or below allowed */
+ rv = apr_filepath_merge(&newpath, NULL, parsed_string,
+ APR_FILEPATH_SECUREROOTTEST |
+ APR_FILEPATH_NOTABSOLUTE, ctx->dpool);
+
+ if (rv != APR_SUCCESS) {
+ error_fmt = "unable to include file \"%s\" in parsed file %s";
+ }
+ else {
+ rr = ap_sub_req_lookup_file(newpath, r, f->next);
+ }
+ }
+ else {
+ rr = ap_sub_req_lookup_uri(parsed_string, r, f->next);
+ }
+
+ if (!error_fmt && rr->status != HTTP_OK) {
+ error_fmt = "unable to include \"%s\" in parsed file %s";
+ }
+
+ if (!error_fmt && (ctx->flags & SSI_FLAG_NO_EXEC) &&
+ rr->content_type && strncmp(rr->content_type, "text/", 5)) {
+
+ error_fmt = "unable to include potential exec \"%s\" in parsed "
+ "file %s";
+ }
+
+ /* See the Kludge in includes_filter for why.
+ * Basically, it puts a bread crumb in here, then looks
+ * for the crumb later to see if its been here.
+ */
+ if (rr) {
+ ap_set_module_config(rr->request_config, &memcached_include_module, r);
+ }
+
+ if (!error_fmt && ap_run_sub_req(rr)) {
+ error_fmt = "unable to include \"%s\" in parsed file %s";
+ }
+
+ if (error_fmt) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, error_fmt, tag_val,
+ r->filename);
+ SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
+ }
+
+ /* Do *not* destroy the subrequest here; it may have allocated
+ * variables in this r->subprocess_env in the subrequest's
+ * r->pool, so that pool must survive as long as this request.
+ * Yes, this is a memory leak. */
+ if (error_fmt) {
+ break;
+ }
+ }
+
+ return APR_SUCCESS;
+}
+
+/*
+ * <!--#echo [encoding="..."] var="..." [encoding="..."] var="..." ... -->
+ */
+static apr_status_t handle_echo(include_ctx_t *ctx, ap_filter_t *f,
+ apr_bucket_brigade *bb)
+{
+ enum {E_NONE, E_URL, E_ENTITY} encode;
+ request_rec *r = f->r;
+
+ if (!ctx->argc) {
+ ap_log_rerror(APLOG_MARK,
+ (ctx->flags & SSI_FLAG_PRINTING)
+ ? APLOG_ERR : APLOG_WARNING,
+ 0, r, "missing argument for echo element in %s",
+ r->filename);
+ }
+
+ if (!(ctx->flags & SSI_FLAG_PRINTING)) {
+ return APR_SUCCESS;
+ }
+
+ if (!ctx->argc) {
+ SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
+ return APR_SUCCESS;
+ }
+
+ encode = E_ENTITY;
+
+ while (1) {
+ char *tag = NULL;
+ char *tag_val = NULL;
+
+ ap_ssi_get_tag_and_value(ctx, &tag, &tag_val, SSI_VALUE_DECODED);
+ if (!tag || !tag_val) {
+ break;
+ }
+
+ if (!strcmp(tag, "var")) {
+ const char *val;
+ const char *echo_text = NULL;
+ apr_size_t e_len;
+
+ val = get_include_var(ap_ssi_parse_string(ctx, tag_val, NULL,
+ 0, SSI_EXPAND_DROP_NAME),
+ ctx);
+
+ if (val) {
+ switch(encode) {
+ case E_NONE:
+ echo_text = val;
+ break;
+ case E_URL:
+ echo_text = ap_escape_uri(ctx->dpool, val);
+ break;
+ case E_ENTITY:
+ echo_text = ap_escape_html(ctx->dpool, val);
+ break;
+ }
+
+ e_len = strlen(echo_text);
+ }
+ else {
+ echo_text = ctx->intern->undefined_echo;
+ e_len = ctx->intern->undefined_echo_len;
+ }
+
+ APR_BRIGADE_INSERT_TAIL(bb, apr_bucket_pool_create(
+ apr_pmemdup(ctx->pool, echo_text, e_len),
+ e_len, ctx->pool, f->c->bucket_alloc));
+ }
+ else if (!strcmp(tag, "encoding")) {
+ if (!strcasecmp(tag_val, "none")) {
+ encode = E_NONE;
+ }
+ else if (!strcasecmp(tag_val, "url")) {
+ encode = E_URL;
+ }
+ else if (!strcasecmp(tag_val, "entity")) {
+ encode = E_ENTITY;
+ }
+ else {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unknown value "
+ "\"%s\" to parameter \"encoding\" of tag echo in "
+ "%s", tag_val, r->filename);
+ SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
+ break;
+ }
+ }
+ else {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unknown parameter "
+ "\"%s\" in tag echo of %s", tag, r->filename);
+ SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
+ break;
+ }
+ }
+
+ return APR_SUCCESS;
+}
+
+/*
+ * <!--#config [timefmt="..."] [sizefmt="..."] [errmsg="..."]
+ * [echomsg="..."] -->
+ */
+static apr_status_t handle_config(include_ctx_t *ctx, ap_filter_t *f,
+ apr_bucket_brigade *bb)
+{
+ request_rec *r = f->r;
+ apr_table_t *env = r->subprocess_env;
+
+ if (!ctx->argc) {
+ ap_log_rerror(APLOG_MARK,
+ (ctx->flags & SSI_FLAG_PRINTING)
+ ? APLOG_ERR : APLOG_WARNING,
+ 0, r, "missing argument for config element in %s",
+ r->filename);
+ }
+
+ if (!(ctx->flags & SSI_FLAG_PRINTING)) {
+ return APR_SUCCESS;
+ }
+
+ if (!ctx->argc) {
+ SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
+ return APR_SUCCESS;
+ }
+
+ while (1) {
+ char *tag = NULL;
+ char *tag_val = NULL;
+
+ ap_ssi_get_tag_and_value(ctx, &tag, &tag_val, SSI_VALUE_RAW);
+ if (!tag || !tag_val) {
+ break;
+ }
+
+ if (!strcmp(tag, "errmsg")) {
+ ctx->error_str = ap_ssi_parse_string(ctx, tag_val, NULL, 0,
+ SSI_EXPAND_DROP_NAME);
+ }
+ else if (!strcmp(tag, "echomsg")) {
+ ctx->intern->undefined_echo =
+ ap_ssi_parse_string(ctx, tag_val, NULL, 0,SSI_EXPAND_DROP_NAME);
+ ctx->intern->undefined_echo_len=strlen(ctx->intern->undefined_echo);
+ }
+ else if (!strcmp(tag, "timefmt")) {
+ apr_time_t date = r->request_time;
+
+ ctx->time_str = ap_ssi_parse_string(ctx, tag_val, NULL, 0,
+ SSI_EXPAND_DROP_NAME);
+
+ apr_table_setn(env, "DATE_LOCAL", ap_ht_time(r->pool, date,
+ ctx->time_str, 0));
+ apr_table_setn(env, "DATE_GMT", ap_ht_time(r->pool, date,
+ ctx->time_str, 1));
+ apr_table_setn(env, "LAST_MODIFIED",
+ ap_ht_time(r->pool, r->finfo.mtime,
+ ctx->time_str, 0));
+ }
+ else if (!strcmp(tag, "sizefmt")) {
+ char *parsed_string;
+
+ parsed_string = ap_ssi_parse_string(ctx, tag_val, NULL, 0,
+ SSI_EXPAND_DROP_NAME);
+ if (!strcmp(parsed_string, "bytes")) {
+ ctx->flags |= SSI_FLAG_SIZE_IN_BYTES;
+ }
+ else if (!strcmp(parsed_string, "abbrev")) {
+ ctx->flags &= SSI_FLAG_SIZE_ABBREV;
+ }
+ else {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unknown value "
+ "\"%s\" to parameter \"sizefmt\" of tag config "
+ "in %s", parsed_string, r->filename);
+ SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
+ break;
+ }
+ }
+ else {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unknown parameter "
+ "\"%s\" to tag config in %s", tag, r->filename);
+ SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
+ break;
+ }
+ }
+
+ return APR_SUCCESS;
+}
+
+/*
+ * <!--#fsize virtual|file="..." [virtual|file="..."] ... -->
+ */
+static apr_status_t handle_fsize(include_ctx_t *ctx, ap_filter_t *f,
+ apr_bucket_brigade *bb)
+{
+ request_rec *r = f->r;
+
+ if (!ctx->argc) {
+ ap_log_rerror(APLOG_MARK,
+ (ctx->flags & SSI_FLAG_PRINTING)
+ ? APLOG_ERR : APLOG_WARNING,
+ 0, r, "missing argument for fsize element in %s",
+ r->filename);
+ }
+
+ if (!(ctx->flags & SSI_FLAG_PRINTING)) {
+ return APR_SUCCESS;
+ }
+
+ if (!ctx->argc) {
+ SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
+ return APR_SUCCESS;
+ }
+
+ while (1) {
+ char *tag = NULL;
+ char *tag_val = NULL;
+ apr_finfo_t finfo;
+ char *parsed_string;
+
+ ap_ssi_get_tag_and_value(ctx, &tag, &tag_val, SSI_VALUE_DECODED);
+ if (!tag || !tag_val) {
+ break;
+ }
+
+ parsed_string = ap_ssi_parse_string(ctx, tag_val, NULL, 0,
+ SSI_EXPAND_DROP_NAME);
+
+ if (!find_file(r, "fsize", tag, parsed_string, &finfo)) {
+ char *buf;
+ apr_size_t len;
+
+ if (!(ctx->flags & SSI_FLAG_SIZE_IN_BYTES)) {
+ buf = apr_strfsize(finfo.size, apr_palloc(ctx->pool, 5));
+ len = 4; /* omit the \0 terminator */
+ }
+ else {
+ apr_size_t l, x, pos;
+ char *tmp;
+
+ tmp = apr_psprintf(ctx->dpool, "%" APR_OFF_T_FMT, finfo.size);
+ len = l = strlen(tmp);
+
+ for (x = 0; x < l; ++x) {
+ if (x && !((l - x) % 3)) {
+ ++len;
+ }
+ }
+
+ if (len == l) {
+ buf = apr_pstrmemdup(ctx->pool, tmp, len);
+ }
+ else {
+ buf = apr_palloc(ctx->pool, len);
+
+ for (pos = x = 0; x < l; ++x) {
+ if (x && !((l - x) % 3)) {
+ buf[pos++] = ',';
+ }
+ buf[pos++] = tmp[x];
+ }
+ }
+ }
+
+ APR_BRIGADE_INSERT_TAIL(bb, apr_bucket_pool_create(buf, len,
+ ctx->pool, f->c->bucket_alloc));
+ }
+ else {
+ SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
+ break;
+ }
+ }
+
+ return APR_SUCCESS;
+}
+
+/*
+ * <!--#flastmod virtual|file="..." [virtual|file="..."] ... -->
+ */
+static apr_status_t handle_flastmod(include_ctx_t *ctx, ap_filter_t *f,
+ apr_bucket_brigade *bb)
+{
+ request_rec *r = f->r;
+
+ if (!ctx->argc) {
+ ap_log_rerror(APLOG_MARK,
+ (ctx->flags & SSI_FLAG_PRINTING)
+ ? APLOG_ERR : APLOG_WARNING,
+ 0, r, "missing argument for flastmod element in %s",
+ r->filename);
+ }
+
+ if (!(ctx->flags & SSI_FLAG_PRINTING)) {
+ return APR_SUCCESS;
+ }
+
+ if (!ctx->argc) {
+ SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
+ return APR_SUCCESS;
+ }
+
+ while (1) {
+ char *tag = NULL;
+ char *tag_val = NULL;
+ apr_finfo_t finfo;
+ char *parsed_string;
+
+ ap_ssi_get_tag_and_value(ctx, &tag, &tag_val, SSI_VALUE_DECODED);
+ if (!tag || !tag_val) {
+ break;
+ }
+
+ parsed_string = ap_ssi_parse_string(ctx, tag_val, NULL, 0,
+ SSI_EXPAND_DROP_NAME);
+
+ if (!find_file(r, "flastmod", tag, parsed_string, &finfo)) {
+ char *t_val;
+ apr_size_t t_len;
+
+ t_val = ap_ht_time(ctx->pool, finfo.mtime, ctx->time_str, 0);
+ t_len = strlen(t_val);
+
+ APR_BRIGADE_INSERT_TAIL(bb, apr_bucket_pool_create(t_val, t_len,
+ ctx->pool, f->c->bucket_alloc));
+ }
+ else {
+ SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
+ break;
+ }
+ }
+
+ return APR_SUCCESS;
+}
+
+/*
+ * <!--#if expr="..." -->
+ */
+static apr_status_t handle_if(include_ctx_t *ctx, ap_filter_t *f,
+ apr_bucket_brigade *bb)
+{
+ char *tag = NULL;
+ char *expr = NULL;
+ request_rec *r = f->r;
+ int expr_ret, was_error;
+
+ if (ctx->argc != 1) {
+ ap_log_rerror(APLOG_MARK,
+ (ctx->flags & SSI_FLAG_PRINTING)
+ ? APLOG_ERR : APLOG_WARNING,
+ 0, r, (ctx->argc)
+ ? "too many arguments for if element in %s"
+ : "missing expr argument for if element in %s",
+ r->filename);
+ }
+
+ if (!(ctx->flags & SSI_FLAG_PRINTING)) {
+ ++(ctx->if_nesting_level);
+ return APR_SUCCESS;
+ }
+
+ if (ctx->argc != 1) {
+ SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
+ return APR_SUCCESS;
+ }
+
+ ap_ssi_get_tag_and_value(ctx, &tag, &expr, SSI_VALUE_RAW);
+
+ if (strcmp(tag, "expr")) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unknown parameter \"%s\" "
+ "to tag if in %s", tag, r->filename);
+ SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
+ return APR_SUCCESS;
+ }
+
+ if (!expr) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "missing expr value for if "
+ "element in %s", r->filename);
+ SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
+ return APR_SUCCESS;
+ }
+
+ DEBUG_PRINTF((ctx, "**** if expr=\"%s\"\n", expr));
+
+ expr_ret = parse_expr(ctx, expr, &was_error);
+
+ if (was_error) {
+ SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
+ return APR_SUCCESS;
+ }
+
+ if (expr_ret) {
+ ctx->flags |= (SSI_FLAG_PRINTING | SSI_FLAG_COND_TRUE);
+ }
+ else {
+ ctx->flags &= SSI_FLAG_CLEAR_PRINT_COND;
+ }
+
+ DEBUG_DUMP_COND(ctx, " if");
+
+ ctx->if_nesting_level = 0;
+
+ return APR_SUCCESS;
+}
+
+/*
+ * <!--#elif expr="..." -->
+ */
+static apr_status_t handle_elif(include_ctx_t *ctx, ap_filter_t *f,
+ apr_bucket_brigade *bb)
+{
+ char *tag = NULL;
+ char *expr = NULL;
+ request_rec *r = f->r;
+ int expr_ret, was_error;
+
+ if (ctx->argc != 1) {
+ ap_log_rerror(APLOG_MARK,
+ (!(ctx->if_nesting_level)) ? APLOG_ERR : APLOG_WARNING,
+ 0, r, (ctx->argc)
+ ? "too many arguments for if element in %s"
+ : "missing expr argument for if element in %s",
+ r->filename);
+ }
+
+ if (ctx->if_nesting_level) {
+ return APR_SUCCESS;
+ }
+
+ if (ctx->argc != 1) {
+ SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
+ return APR_SUCCESS;
+ }
+
+ ap_ssi_get_tag_and_value(ctx, &tag, &expr, SSI_VALUE_RAW);
+
+ if (strcmp(tag, "expr")) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unknown parameter \"%s\" "
+ "to tag if in %s", tag, r->filename);
+ SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
+ return APR_SUCCESS;
+ }
+
+ if (!expr) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "missing expr in elif "
+ "statement: %s", r->filename);
+ SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
+ return APR_SUCCESS;
+ }
+
+ DEBUG_PRINTF((ctx, "**** elif expr=\"%s\"\n", expr));
+ DEBUG_DUMP_COND(ctx, " elif");
+
+ if (ctx->flags & SSI_FLAG_COND_TRUE) {
+ ctx->flags &= SSI_FLAG_CLEAR_PRINTING;
+ return APR_SUCCESS;
+ }
+
+ expr_ret = parse_expr(ctx, expr, &was_error);
+
+ if (was_error) {
+ SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
+ return APR_SUCCESS;
+ }
+
+ if (expr_ret) {
+ ctx->flags |= (SSI_FLAG_PRINTING | SSI_FLAG_COND_TRUE);
+ }
+ else {
+ ctx->flags &= SSI_FLAG_CLEAR_PRINT_COND;
+ }
+
+ DEBUG_DUMP_COND(ctx, " elif");
+
+ return APR_SUCCESS;
+}
+
+/*
+ * <!--#else -->
+ */
+static apr_status_t handle_else(include_ctx_t *ctx, ap_filter_t *f,
+ apr_bucket_brigade *bb)
+{
+ request_rec *r = f->r;
+
+ if (ctx->argc) {
+ ap_log_rerror(APLOG_MARK,
+ (!(ctx->if_nesting_level)) ? APLOG_ERR : APLOG_WARNING,
+ 0, r, "else directive does not take tags in %s",
+ r->filename);
+ }
+
+ if (ctx->if_nesting_level) {
+ return APR_SUCCESS;
+ }
+
+ if (ctx->argc) {
+ if (ctx->flags & SSI_FLAG_PRINTING) {
+ SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
+ }
+
+ return APR_SUCCESS;
+ }
+
+ DEBUG_DUMP_COND(ctx, " else");
+
+ if (ctx->flags & SSI_FLAG_COND_TRUE) {
+ ctx->flags &= SSI_FLAG_CLEAR_PRINTING;
+ }
+ else {
+ ctx->flags |= (SSI_FLAG_PRINTING | SSI_FLAG_COND_TRUE);
+ }
+
+ return APR_SUCCESS;
+}
+
+/*
+ * <!--#endif -->
+ */
+static apr_status_t handle_endif(include_ctx_t *ctx, ap_filter_t *f,
+ apr_bucket_brigade *bb)
+{
+ request_rec *r = f->r;
+
+ if (ctx->argc) {
+ ap_log_rerror(APLOG_MARK,
+ (!(ctx->if_nesting_level)) ? APLOG_ERR : APLOG_WARNING,
+ 0, r, "endif directive does not take tags in %s",
+ r->filename);
+ }
+
+ if (ctx->if_nesting_level) {
+ --(ctx->if_nesting_level);
+ return APR_SUCCESS;
+ }
+
+ if (ctx->argc) {
+ SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
+ return APR_SUCCESS;
+ }
+
+ DEBUG_DUMP_COND(ctx, "endif");
+
+ ctx->flags |= (SSI_FLAG_PRINTING | SSI_FLAG_COND_TRUE);
+
+ return APR_SUCCESS;
+}
+
+/*
+ * <!--#set var="..." value="..." ... -->
+ */
+static apr_status_t handle_set(include_ctx_t *ctx, ap_filter_t *f,
+ apr_bucket_brigade *bb)
+{
+ char *var = NULL;
+ request_rec *r = f->r;
+ request_rec *sub = r->main;
+ apr_pool_t *p = r->pool;
+
+ if (ctx->argc < 2) {
+ ap_log_rerror(APLOG_MARK,
+ (ctx->flags & SSI_FLAG_PRINTING)
+ ? APLOG_ERR : APLOG_WARNING,
+ 0, r, "missing argument for set element in %s",
+ r->filename);
+ }
+
+ if (!(ctx->flags & SSI_FLAG_PRINTING)) {
+ return APR_SUCCESS;
+ }
+
+ if (ctx->argc < 2) {
+ SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
+ return APR_SUCCESS;
+ }
+
+ /* we need to use the 'main' request pool to set notes as that is
+ * a notes lifetime
+ */
+ while (sub) {
+ p = sub->pool;
+ sub = sub->main;
+ }
+
+ while (1) {
+ char *tag = NULL;
+ char *tag_val = NULL;
+
+ ap_ssi_get_tag_and_value(ctx, &tag, &tag_val, SSI_VALUE_DECODED);
+
+ if (!tag || !tag_val) {
+ break;
+ }
+
+ if (!strcmp(tag, "var")) {
+ var = ap_ssi_parse_string(ctx, tag_val, NULL, 0,
+ SSI_EXPAND_DROP_NAME);
+ }
+ else if (!strcmp(tag, "value")) {
+ char *parsed_string;
+
+ if (!var) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "variable must "
+ "precede value in set directive in %s",
+ r->filename);
+ SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
+ break;
+ }
+
+ parsed_string = ap_ssi_parse_string(ctx, tag_val, NULL, 0,
+ SSI_EXPAND_DROP_NAME);
+ apr_table_setn(r->subprocess_env, apr_pstrdup(p, var),
+ apr_pstrdup(p, parsed_string));
+ }
+ else {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Invalid tag for set "
+ "directive in %s", r->filename);
+ SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
+ break;
+ }
+ }
+
+ return APR_SUCCESS;
+}
+
+/*
+ * <!--#printenv -->
+ */
+static apr_status_t handle_printenv(include_ctx_t *ctx, ap_filter_t *f,
+ apr_bucket_brigade *bb)
+{
+ request_rec *r = f->r;
+ const apr_array_header_t *arr;
+ const apr_table_entry_t *elts;
+ int i;
+
+ if (ctx->argc) {
+ ap_log_rerror(APLOG_MARK,
+ (ctx->flags & SSI_FLAG_PRINTING)
+ ? APLOG_ERR : APLOG_WARNING,
+ 0, r, "printenv directive does not take tags in %s",
+ r->filename);
+ }
+
+ if (!(ctx->flags & SSI_FLAG_PRINTING)) {
+ return APR_SUCCESS;
+ }
+
+ if (ctx->argc) {
+ SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
+ return APR_SUCCESS;
+ }
+
+ arr = apr_table_elts(r->subprocess_env);
+ elts = (apr_table_entry_t *)arr->elts;
+
+ for (i = 0; i < arr->nelts; ++i) {
+ const char *key_text, *val_text;
+ char *key_val, *next;
+ apr_size_t k_len, v_len, kv_length;
+
+ /* get key */
+ key_text = ap_escape_html(ctx->dpool, elts[i].key);
+ k_len = strlen(key_text);
+
+ /* get value */
+ val_text = elts[i].val;
+ if (val_text == LAZY_VALUE) {
+ val_text = add_include_vars_lazy(r, elts[i].key);
+ }
+ val_text = ap_escape_html(ctx->dpool, elts[i].val);
+ v_len = strlen(val_text);
+
+ /* assemble result */
+ kv_length = k_len + v_len + sizeof("=\n");
+ key_val = apr_palloc(ctx->pool, kv_length);
+ next = key_val;
+
+ memcpy(next, key_text, k_len);
+ next += k_len;
+ *next++ = '=';
+ memcpy(next, val_text, v_len);
+ next += v_len;
+ *next++ = '\n';
+ *next = 0;
+
+ APR_BRIGADE_INSERT_TAIL(bb, apr_bucket_pool_create(key_val, kv_length-1,
+ ctx->pool, f->c->bucket_alloc));
+ }
+
+ ctx->flush_now = 1;
+ return APR_SUCCESS;
+}
+
+
+/*
+ * +-------------------------------------------------------+
+ * | |
+ * | Main Includes-Filter Engine
+ * | |
+ * +-------------------------------------------------------+
+ */
+
+/* This is an implementation of the BNDM search algorithm.
+ *
+ * Fast and Flexible String Matching by Combining Bit-parallelism and
+ * Suffix Automata (2001)
+ * Gonzalo Navarro, Mathieu Raffinot
+ *
+ * http://www-igm.univ-mlv.fr/~raffinot/ftp/jea2001.ps.gz
+ *
+ * Initial code submitted by Sascha Schumann.
+ */
+
+/* Precompile the bndm_t data structure. */
+static bndm_t *bndm_compile(apr_pool_t *pool, const char *n, apr_size_t nl)
+{
+ unsigned int x;
+ const char *ne = n + nl;
+ bndm_t *t = apr_palloc(pool, sizeof(*t));
+
+ memset(t->T, 0, sizeof(unsigned int) * 256);
+ t->pattern_len = nl;
+
+ for (x = 1; n < ne; x <<= 1) {
+ t->T[(unsigned char) *n++] |= x;
+ }
+
+ t->x = x - 1;
+
+ return t;
+}
+
+/* Implements the BNDM search algorithm (as described above).
+ *
+ * h - the string to look in
+ * hl - length of the string to look for
+ * t - precompiled bndm structure against the pattern
+ *
+ * Returns the count of character that is the first match or hl if no
+ * match is found.
+ */
+static apr_size_t bndm(bndm_t *t, const char *h, apr_size_t hl)
+{
+ const char *skip;
+ const char *he, *p, *pi;
+ unsigned int *T, x, d;
+ apr_size_t nl;
+
+ he = h + hl;
+
+ T = t->T;
+ x = t->x;
+ nl = t->pattern_len;
+
+ pi = h - 1; /* pi: p initial */
+ p = pi + nl; /* compare window right to left. point to the first char */
+
+ while (p < he) {
+ skip = p;
+ d = x;
+ do {
+ d &= T[(unsigned char) *p--];
+ if (!d) {
+ break;
+ }
+ if ((d & 1)) {
+ if (p != pi) {
+ skip = p;
+ }
+ else {
+ return p - h + 1;
+ }
+ }
+ d >>= 1;
+ } while (d);
+
+ pi = skip;
+ p = pi + nl;
+ }
+
+ return hl;
+}
+
+/*
+ * returns the index position of the first byte of start_seq (or the len of
+ * the buffer as non-match)
+ */
+static apr_size_t find_start_sequence(include_ctx_t *ctx, const char *data,
+ apr_size_t len)
+{
+ struct ssi_internal_ctx *intern = ctx->intern;
+ apr_size_t slen = intern->start_seq_pat->pattern_len;
+ apr_size_t index;
+ const char *p, *ep;
+
+ if (len < slen) {
+ p = data; /* try partial match at the end of the buffer (below) */
+ }
+ else {
+ /* try fast bndm search over the buffer
+ * (hopefully the whole start sequence can be found in this buffer)
+ */
+ index = bndm(intern->start_seq_pat, data, len);
+
+ /* wow, found it. ready. */
+ if (index < len) {
+ intern->state = PARSE_DIRECTIVE;
+ return index;
+ }
+ else {
+ /* ok, the pattern can't be found as whole in the buffer,
+ * check the end for a partial match
+ */
+ p = data + len - slen + 1;
+ }
+ }
+
+ ep = data + len;
+ do {
+ while (p < ep && *p != *intern->start_seq) {
+ ++p;
+ }
+
+ index = p - data;
+
+ /* found a possible start_seq start */
+ if (p < ep) {
+ apr_size_t pos = 1;
+
+ ++p;
+ while (p < ep && *p == intern->start_seq[pos]) {
+ ++p;
+ ++pos;
+ }
+
+ /* partial match found. Store the info for the next round */
+ if (p == ep) {
+ intern->state = PARSE_HEAD;
+ intern->parse_pos = pos;
+ return index;
+ }
+ }
+
+ /* we must try all combinations; consider (e.g.) SSIStartTag "--->"
+ * and a string data of "--.-" and the end of the buffer
+ */
+ p = data + index + 1;
+ } while (p < ep);
+
+ /* no match */
+ return len;
+}
+
+/*
+ * returns the first byte *after* the partial (or final) match.
+ *
+ * If we had to trick with the start_seq start, 'release' returns the
+ * number of chars of the start_seq which appeared not to be part of a
+ * full tag and may have to be passed down the filter chain.
+ */
+static apr_size_t find_partial_start_sequence(include_ctx_t *ctx,
+ const char *data,
+ apr_size_t len,
+ apr_size_t *release)
+{
+ struct ssi_internal_ctx *intern = ctx->intern;
+ apr_size_t pos, spos = 0;
+ apr_size_t slen = intern->start_seq_pat->pattern_len;
+ const char *p, *ep;
+
+ pos = intern->parse_pos;
+ ep = data + len;
+ *release = 0;
+
+ do {
+ p = data;
+
+ while (p < ep && pos < slen && *p == intern->start_seq[pos]) {
+ ++p;
+ ++pos;
+ }
+
+ /* full match */
+ if (pos == slen) {
+ intern->state = PARSE_DIRECTIVE;
+ return (p - data);
+ }
+
+ /* the whole buffer is a partial match */
+ if (p == ep) {
+ intern->parse_pos = pos;
+ return (p - data);
+ }
+
+ /* No match so far, but again:
+ * We must try all combinations, since the start_seq is a random
+ * user supplied string
+ *
+ * So: look if the first char of start_seq appears somewhere within
+ * the current partial match. If it does, try to start a match that
+ * begins with this offset. (This can happen, if a strange
+ * start_seq like "---->" spans buffers)
+ */
+ if (spos < intern->parse_pos) {
+ do {
+ ++spos;
+ ++*release;
+ p = intern->start_seq + spos;
+ pos = intern->parse_pos - spos;
+
+ while (pos && *p != *intern->start_seq) {
+ ++p;
+ ++spos;
+ ++*release;
+ --pos;
+ }
+
+ /* if a matching beginning char was found, try to match the
+ * remainder of the old buffer.
+ */
+ if (pos > 1) {
+ apr_size_t t = 1;
+
+ ++p;
+ while (t < pos && *p == intern->start_seq[t]) {
+ ++p;
+ ++t;
+ }
+
+ if (t == pos) {
+ /* yeah, another partial match found in the *old*
+ * buffer, now test the *current* buffer for
+ * continuing match
+ */
+ break;
+ }
+ }
+ } while (pos > 1);
+
+ if (pos) {
+ continue;
+ }
+ }
+
+ break;
+ } while (1); /* work hard to find a match ;-) */
+
+ /* no match at all, release all (wrongly) matched chars so far */
+ *release = intern->parse_pos;
+ intern->state = PARSE_PRE_HEAD;
+ return 0;
+}
+
+/*
+ * returns the position after the directive
+ */
+static apr_size_t find_directive(include_ctx_t *ctx, const char *data,
+ apr_size_t len, char ***store,
+ apr_size_t **store_len)
+{
+ struct ssi_internal_ctx *intern = ctx->intern;
+ const char *p = data;
+ const char *ep = data + len;
+ apr_size_t pos;
+
+ switch (intern->state) {
+ case PARSE_DIRECTIVE:
+ while (p < ep && !apr_isspace(*p)) {
+ /* we have to consider the case of missing space between directive
+ * and end_seq (be somewhat lenient), e.g. <!--#printenv-->
+ */
+ if (*p == *intern->end_seq) {
+ intern->state = PARSE_DIRECTIVE_TAIL;
+ intern->parse_pos = 1;
+ ++p;
+ return (p - data);
+ }
+ ++p;
+ }
+
+ if (p < ep) { /* found delimiter whitespace */
+ intern->state = PARSE_DIRECTIVE_POSTNAME;
+ *store = &intern->directive;
+ *store_len = &intern->directive_len;
+ }
+
+ break;
+
+ case PARSE_DIRECTIVE_TAIL:
+ pos = intern->parse_pos;
+
+ while (p < ep && pos < intern->end_seq_len &&
+ *p == intern->end_seq[pos]) {
+ ++p;
+ ++pos;
+ }
+
+ /* full match, we're done */
+ if (pos == intern->end_seq_len) {
+ intern->state = PARSE_DIRECTIVE_POSTTAIL;
+ *store = &intern->directive;
+ *store_len = &intern->directive_len;
+ break;
+ }
+
+ /* partial match, the buffer is too small to match fully */
+ if (p == ep) {
+ intern->parse_pos = pos;
+ break;
+ }
+
+ /* no match. continue normal parsing */
+ intern->state = PARSE_DIRECTIVE;
+ return 0;
+
+ case PARSE_DIRECTIVE_POSTTAIL:
+ intern->state = PARSE_EXECUTE;
+ intern->directive_len -= intern->end_seq_len;
+ /* continue immediately with the next state */
+
+ case PARSE_DIRECTIVE_POSTNAME:
+ if (PARSE_DIRECTIVE_POSTNAME == intern->state) {
+ intern->state = PARSE_PRE_ARG;
+ }
+ ctx->argc = 0;
+ intern->argv = NULL;
+
+ if (!intern->directive_len) {
+ intern->error = 1;
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, intern->r, "missing "
+ "directive name in parsed document %s",
+ intern->r->filename);
+ }
+ else {
+ char *sp = intern->directive;
+ char *sep = intern->directive + intern->directive_len;
+
+ /* normalize directive name */
+ for (; sp < sep; ++sp) {
+ *sp = apr_tolower(*sp);
+ }
+ }
+
+ return 0;
+
+ default:
+ /* get a rid of a gcc warning about unhandled enumerations */
+ break;
+ }
+
+ return (p - data);
+}
+
+/*
+ * find out whether the next token is (a possible) end_seq or an argument
+ */
+static apr_size_t find_arg_or_tail(include_ctx_t *ctx, const char *data,
+ apr_size_t len)
+{
+ struct ssi_internal_ctx *intern = ctx->intern;
+ const char *p = data;
+ const char *ep = data + len;
+
+ /* skip leading WS */
+ while (p < ep && apr_isspace(*p)) {
+ ++p;
+ }
+
+ /* buffer doesn't consist of whitespaces only */
+ if (p < ep) {
+ intern->state = (*p == *intern->end_seq) ? PARSE_TAIL : PARSE_ARG;
+ }
+
+ return (p - data);
+}
+
+/*
+ * test the stream for end_seq. If it doesn't match at all, it must be an
+ * argument
+ */
+static apr_size_t find_tail(include_ctx_t *ctx, const char *data,
+ apr_size_t len)
+{
+ struct ssi_internal_ctx *intern = ctx->intern;
+ const char *p = data;
+ const char *ep = data + len;
+ apr_size_t pos = intern->parse_pos;
+
+ if (PARSE_TAIL == intern->state) {
+ intern->state = PARSE_TAIL_SEQ;
+ pos = intern->parse_pos = 0;
+ }
+
+ while (p < ep && pos < intern->end_seq_len && *p == intern->end_seq[pos]) {
+ ++p;
+ ++pos;
+ }
+
+ /* bingo, full match */
+ if (pos == intern->end_seq_len) {
+ intern->state = PARSE_EXECUTE;
+ return (p - data);
+ }
+
+ /* partial match, the buffer is too small to match fully */
+ if (p == ep) {
+ intern->parse_pos = pos;
+ return (p - data);
+ }
+
+ /* no match. It must be an argument string then
+ * The caller should cleanup and rewind to the reparse point
+ */
+ intern->state = PARSE_ARG;
+ return 0;
+}
+
+/*
+ * extract name=value from the buffer
+ * A pcre-pattern could look (similar to):
+ * name\s*(?:=\s*(["'`]?)value\1(?>\s*))?
+ */
+static apr_size_t find_argument(include_ctx_t *ctx, const char *data,
+ apr_size_t len, char ***store,
+ apr_size_t **store_len)
+{
+ struct ssi_internal_ctx *intern = ctx->intern;
+ const char *p = data;
+ const char *ep = data + len;
+
+ switch (intern->state) {
+ case PARSE_ARG:
+ /*
+ * create argument structure and append it to the current list
+ */
+ intern->current_arg = apr_palloc(ctx->dpool,
+ sizeof(*intern->current_arg));
+ intern->current_arg->next = NULL;
+
+ ++(ctx->argc);
+ if (!intern->argv) {
+ intern->argv = intern->current_arg;
+ }
+ else {
+ arg_item_t *newarg = intern->argv;
+
+ while (newarg->next) {
+ newarg = newarg->next;
+ }
+ newarg->next = intern->current_arg;
+ }
+
+ /* check whether it's a valid one. If it begins with a quote, we
+ * can safely assume, someone forgot the name of the argument
+ */
+ switch (*p) {
+ case '"': case '\'': case '`':
+ *store = NULL;
+
+ intern->state = PARSE_ARG_VAL;
+ intern->quote = *p++;
+ intern->current_arg->name = NULL;
+ intern->current_arg->name_len = 0;
+ intern->error = 1;
+
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, intern->r, "missing "
+ "argument name for value to tag %s in %s",
+ apr_pstrmemdup(intern->r->pool, intern->directive,
+ intern->directive_len),
+ intern->r->filename);
+
+ return (p - data);
+
+ default:
+ intern->state = PARSE_ARG_NAME;
+ }
+ /* continue immediately with next state */
+
+ case PARSE_ARG_NAME:
+ while (p < ep && !apr_isspace(*p) && *p != '=') {
+ ++p;
+ }
+
+ if (p < ep) {
+ intern->state = PARSE_ARG_POSTNAME;
+ *store = &intern->current_arg->name;
+ *store_len = &intern->current_arg->name_len;
+ return (p - data);
+ }
+ break;
+
+ case PARSE_ARG_POSTNAME:
+ intern->current_arg->name = apr_pstrmemdup(ctx->dpool,
+ intern->current_arg->name,
+ intern->current_arg->name_len);
+ if (!intern->current_arg->name_len) {
+ intern->error = 1;
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, intern->r, "missing "
+ "argument name for value to tag %s in %s",
+ apr_pstrmemdup(intern->r->pool, intern->directive,
+ intern->directive_len),
+ intern->r->filename);
+ }
+ else {
+ char *sp = intern->current_arg->name;
+
+ /* normalize the name */
+ while (*sp) {
+ *sp = apr_tolower(*sp);
+ ++sp;
+ }
+ }
+
+ intern->state = PARSE_ARG_EQ;
+ /* continue with next state immediately */
+
+ case PARSE_ARG_EQ:
+ *store = NULL;
+
+ while (p < ep && apr_isspace(*p)) {
+ ++p;
+ }
+
+ if (p < ep) {
+ if (*p == '=') {
+ intern->state = PARSE_ARG_PREVAL;
+ ++p;
+ }
+ else { /* no value */
+ intern->current_arg->value = NULL;
+ intern->state = PARSE_PRE_ARG;
+ }
+
+ return (p - data);
+ }
+ break;
+
+ case PARSE_ARG_PREVAL:
+ *store = NULL;
+
+ while (p < ep && apr_isspace(*p)) {
+ ++p;
+ }
+
+ /* buffer doesn't consist of whitespaces only */
+ if (p < ep) {
+ intern->state = PARSE_ARG_VAL;
+ switch (*p) {
+ case '"': case '\'': case '`':
+ intern->quote = *p++;
+ break;
+ default:
+ intern->quote = '\0';
+ break;
+ }
+
+ return (p - data);
+ }
+ break;
+
+ case PARSE_ARG_VAL_ESC:
+ if (*p == intern->quote) {
+ ++p;
+ }
+ intern->state = PARSE_ARG_VAL;
+ /* continue with next state immediately */
+
+ case PARSE_ARG_VAL:
+ for (; p < ep; ++p) {
+ if (intern->quote && *p == '\\') {
+ ++p;
+ if (p == ep) {
+ intern->state = PARSE_ARG_VAL_ESC;
+ break;
+ }
+
+ if (*p != intern->quote) {
+ --p;
+ }
+ }
+ else if (intern->quote && *p == intern->quote) {
+ ++p;
+ *store = &intern->current_arg->value;
+ *store_len = &intern->current_arg->value_len;
+ intern->state = PARSE_ARG_POSTVAL;
+ break;
+ }
+ else if (!intern->quote && apr_isspace(*p)) {
+ ++p;
+ *store = &intern->current_arg->value;
+ *store_len = &intern->current_arg->value_len;
+ intern->state = PARSE_ARG_POSTVAL;
+ break;
+ }
+ }
+
+ return (p - data);
+
+ case PARSE_ARG_POSTVAL:
+ /*
+ * The value is still the raw input string. Finally clean it up.
+ */
+ --(intern->current_arg->value_len);
+
+ /* strip quote escaping \ from the string */
+ if (intern->quote) {
+ apr_size_t shift = 0;
+ char *sp;
+
+ sp = intern->current_arg->value;
+ ep = intern->current_arg->value + intern->current_arg->value_len;
+ while (sp < ep && *sp != '\\') {
+ ++sp;
+ }
+ for (; sp < ep; ++sp) {
+ if (*sp == '\\' && sp[1] == intern->quote) {
+ ++sp;
+ ++shift;
+ }
+ if (shift) {
+ *(sp-shift) = *sp;
+ }
+ }
+
+ intern->current_arg->value_len -= shift;
+ }
+
+ intern->current_arg->value[intern->current_arg->value_len] = '\0';
+ intern->state = PARSE_PRE_ARG;
+
+ return 0;
+
+ default:
+ /* get a rid of a gcc warning about unhandled enumerations */
+ break;
+ }
+
+ return len; /* partial match of something */
+}
+
+/*
+ * This is the main loop over the current bucket brigade.
+ */
+static apr_status_t send_parsed_content(ap_filter_t *f, apr_bucket_brigade *bb)
+{
+ include_ctx_t *ctx = f->ctx;
+ struct ssi_internal_ctx *intern = ctx->intern;
+ request_rec *r = f->r;
+ apr_bucket *b = APR_BRIGADE_FIRST(bb);
+ apr_bucket_brigade *pass_bb;
+ apr_status_t rv = APR_SUCCESS;
+ char *magic; /* magic pointer for sentinel use */
+
+ /* fast exit */
+ if (APR_BRIGADE_EMPTY(bb)) {
+ return APR_SUCCESS;
+ }
+
+ /* we may crash, since already cleaned up; hand over the responsibility
+ * to the next filter;-)
+ */
+ if (intern->seen_eos) {
+ return ap_pass_brigade(f->next, bb);
+ }
+
+ /* All stuff passed along has to be put into that brigade */
+ pass_bb = apr_brigade_create(ctx->pool, f->c->bucket_alloc);
+
+ /* initialization for this loop */
+ intern->bytes_read = 0;
+ intern->error = 0;
+ intern->r = r;
+ ctx->flush_now = 0;
+
+ /* loop over the current bucket brigade */
+ while (b != APR_BRIGADE_SENTINEL(bb)) {
+ const char *data = NULL;
+ apr_size_t len, index, release;
+ apr_bucket *newb = NULL;
+ char **store = &magic;
+ apr_size_t *store_len = NULL;
+
+ /* handle meta buckets before reading any data */
+ if (APR_BUCKET_IS_METADATA(b)) {
+ newb = APR_BUCKET_NEXT(b);
+
+ APR_BUCKET_REMOVE(b);
+
+ if (APR_BUCKET_IS_EOS(b)) {
+ intern->seen_eos = 1;
+
+ /* Hit end of stream, time for cleanup ... But wait!
+ * Perhaps we're not ready yet. We may have to loop one or
+ * two times again to finish our work. In that case, we
+ * just re-insert the EOS bucket to allow for an extra loop.
+ *
+ * PARSE_EXECUTE means, we've hit a directive just before the
+ * EOS, which is now waiting for execution.
+ *
+ * PARSE_DIRECTIVE_POSTTAIL means, we've hit a directive with
+ * no argument and no space between directive and end_seq
+ * just before the EOS. (consider <!--#printenv--> as last
+ * or only string within the stream). This state, however,
+ * just cleans up and turns itself to PARSE_EXECUTE, which
+ * will be passed through within the next (and actually
+ * last) round.
+ */
+ if (PARSE_EXECUTE == intern->state ||
+ PARSE_DIRECTIVE_POSTTAIL == intern->state) {
+ APR_BUCKET_INSERT_BEFORE(newb, b);
+ }
+ else {
+ break; /* END OF STREAM */
+ }
+ }
+ else {
+ APR_BRIGADE_INSERT_TAIL(pass_bb, b);
+
+ if (APR_BUCKET_IS_FLUSH(b)) {
+ ctx->flush_now = 1;
+ }
+
+ b = newb;
+ continue;
+ }
+ }
+
+ /* enough is enough ... */
+ if (ctx->flush_now ||
+ intern->bytes_read > AP_MIN_BYTES_TO_WRITE) {
+
+ if (!APR_BRIGADE_EMPTY(pass_bb)) {
+ rv = ap_pass_brigade(f->next, pass_bb);
+ if (rv != APR_SUCCESS) {
+ apr_brigade_destroy(pass_bb);
+ return rv;
+ }
+ }
+
+ ctx->flush_now = 0;
+ intern->bytes_read = 0;
+ }
+
+ /* read the current bucket data */
+ len = 0;
+ if (!intern->seen_eos) {
+ if (intern->bytes_read > 0) {
+ rv = apr_bucket_read(b, &data, &len, APR_NONBLOCK_READ);
+ if (APR_STATUS_IS_EAGAIN(rv)) {
+ ctx->flush_now = 1;
+ continue;
+ }
+ }
+
+ if (!len || rv != APR_SUCCESS) {
+ rv = apr_bucket_read(b, &data, &len, APR_BLOCK_READ);
+ }
+
+ if (rv != APR_SUCCESS) {
+ apr_brigade_destroy(pass_bb);
+ return rv;
+ }
+
+ intern->bytes_read += len;
+ }
+
+ /* zero length bucket, fetch next one */
+ if (!len && !intern->seen_eos) {
+ b = APR_BUCKET_NEXT(b);
+ continue;
+ }
+
+ /*
+ * it's actually a data containing bucket, start/continue parsing
+ */
+
+ switch (intern->state) {
+ /* no current tag; search for start sequence */
+ case PARSE_PRE_HEAD:
+ index = find_start_sequence(ctx, data, len);
+
+ if (index < len) {
+ apr_bucket_split(b, index);
+ }
+
+ newb = APR_BUCKET_NEXT(b);
+ if (ctx->flags & SSI_FLAG_PRINTING) {
+ APR_BUCKET_REMOVE(b);
+ APR_BRIGADE_INSERT_TAIL(pass_bb, b);
+ }
+ else {
+ apr_bucket_delete(b);
+ }
+
+ if (index < len) {
+ /* now delete the start_seq stuff from the remaining bucket */
+ if (PARSE_DIRECTIVE == intern->state) { /* full match */
+ apr_bucket_split(newb, intern->start_seq_pat->pattern_len);
+ ctx->flush_now = 1; /* pass pre-tag stuff */
+ }
+
+ b = APR_BUCKET_NEXT(newb);
+ apr_bucket_delete(newb);
+ }
+ else {
+ b = newb;
+ }
+
+ break;
+
+ /* we're currently looking for the end of the start sequence */
+ case PARSE_HEAD:
+ index = find_partial_start_sequence(ctx, data, len, &release);
+
+ /* check if we mismatched earlier and have to release some chars */
+ if (release && (ctx->flags & SSI_FLAG_PRINTING)) {
+ char *to_release = apr_pmemdup(ctx->pool, intern->start_seq, release);
+
+ newb = apr_bucket_pool_create(to_release, release, ctx->pool,
+ f->c->bucket_alloc);
+ APR_BRIGADE_INSERT_TAIL(pass_bb, newb);
+ }
+
+ if (index) { /* any match */
+ /* now delete the start_seq stuff from the remaining bucket */
+ if (PARSE_DIRECTIVE == intern->state) { /* final match */
+ apr_bucket_split(b, index);
+ ctx->flush_now = 1; /* pass pre-tag stuff */
+ }
+ newb = APR_BUCKET_NEXT(b);
+ apr_bucket_delete(b);
+ b = newb;
+ }
+
+ break;
+
+ /* we're currently grabbing the directive name */
+ case PARSE_DIRECTIVE:
+ case PARSE_DIRECTIVE_POSTNAME:
+ case PARSE_DIRECTIVE_TAIL:
+ case PARSE_DIRECTIVE_POSTTAIL:
+ index = find_directive(ctx, data, len, &store, &store_len);
+
+ if (index) {
+ apr_bucket_split(b, index);
+ newb = APR_BUCKET_NEXT(b);
+ }
+
+ if (store) {
+ if (index) {
+ APR_BUCKET_REMOVE(b);
+ apr_bucket_setaside(b, r->pool);
+ APR_BRIGADE_INSERT_TAIL(intern->tmp_bb, b);
+ b = newb;
+ }
+
+ /* time for cleanup? */
+ if (store != &magic) {
+ apr_brigade_pflatten(intern->tmp_bb, store, store_len,
+ ctx->dpool);
+ apr_brigade_cleanup(intern->tmp_bb);
+ }
+ }
+ else if (index) {
+ apr_bucket_delete(b);
+ b = newb;
+ }
+
+ break;
+
+ /* skip WS and find out what comes next (arg or end_seq) */
+ case PARSE_PRE_ARG:
+ index = find_arg_or_tail(ctx, data, len);
+
+ if (index) { /* skipped whitespaces */
+ if (index < len) {
+ apr_bucket_split(b, index);
+ }
+ newb = APR_BUCKET_NEXT(b);
+ apr_bucket_delete(b);
+ b = newb;
+ }
+
+ break;
+
+ /* currently parsing name[=val] */
+ case PARSE_ARG:
+ case PARSE_ARG_NAME:
+ case PARSE_ARG_POSTNAME:
+ case PARSE_ARG_EQ:
+ case PARSE_ARG_PREVAL:
+ case PARSE_ARG_VAL:
+ case PARSE_ARG_VAL_ESC:
+ case PARSE_ARG_POSTVAL:
+ index = find_argument(ctx, data, len, &store, &store_len);
+
+ if (index) {
+ apr_bucket_split(b, index);
+ newb = APR_BUCKET_NEXT(b);
+ }
+
+ if (store) {
+ if (index) {
+ APR_BUCKET_REMOVE(b);
+ apr_bucket_setaside(b, r->pool);
+ APR_BRIGADE_INSERT_TAIL(intern->tmp_bb, b);
+ b = newb;
+ }
+
+ /* time for cleanup? */
+ if (store != &magic) {
+ apr_brigade_pflatten(intern->tmp_bb, store, store_len,
+ ctx->dpool);
+ apr_brigade_cleanup(intern->tmp_bb);
+ }
+ }
+ else if (index) {
+ apr_bucket_delete(b);
+ b = newb;
+ }
+
+ break;
+
+ /* try to match end_seq at current pos. */
+ case PARSE_TAIL:
+ case PARSE_TAIL_SEQ:
+ index = find_tail(ctx, data, len);
+
+ switch (intern->state) {
+ case PARSE_EXECUTE: /* full match */
+ apr_bucket_split(b, index);
+ newb = APR_BUCKET_NEXT(b);
+ apr_bucket_delete(b);
+ b = newb;
+ break;
+
+ case PARSE_ARG: /* no match */
+ /* PARSE_ARG must reparse at the beginning */
+ APR_BRIGADE_PREPEND(bb, intern->tmp_bb);
+ b = APR_BRIGADE_FIRST(bb);
+ break;
+
+ default: /* partial match */
+ newb = APR_BUCKET_NEXT(b);
+ APR_BUCKET_REMOVE(b);
+ apr_bucket_setaside(b, r->pool);
+ APR_BRIGADE_INSERT_TAIL(intern->tmp_bb, b);
+ b = newb;
+ break;
+ }
+
+ break;
+
+ /* now execute the parsed directive, cleanup the space and
+ * start again with PARSE_PRE_HEAD
+ */
+ case PARSE_EXECUTE:
+ /* if there was an error, it was already logged; just stop here */
+ if (intern->error) {
+ if (ctx->flags & SSI_FLAG_PRINTING) {
+ SSI_CREATE_ERROR_BUCKET(ctx, f, pass_bb);
+ intern->error = 0;
+ }
+ }
+ else {
+ include_handler_fn_t *handle_func;
+
+ handle_func =
+ (include_handler_fn_t *)apr_hash_get(include_handlers, intern->directive,
+ intern->directive_len);
+
+ if (handle_func) {
+ DEBUG_INIT(ctx, f, pass_bb);
+ rv = handle_func(ctx, f, pass_bb);
+ if (rv != APR_SUCCESS) {
+ apr_brigade_destroy(pass_bb);
+ return rv;
+ }
+ }
+ else {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
+ "unknown directive \"%s\" in parsed doc %s",
+ apr_pstrmemdup(r->pool, intern->directive,
+ intern->directive_len),
+ r->filename);
+ if (ctx->flags & SSI_FLAG_PRINTING) {
+ SSI_CREATE_ERROR_BUCKET(ctx, f, pass_bb);
+ }
+ }
+ }
+
+ /* cleanup */
+ apr_pool_clear(ctx->dpool);
+ apr_brigade_cleanup(intern->tmp_bb);
+
+ /* Oooof. Done here, start next round */
+ intern->state = PARSE_PRE_HEAD;
+ break;
+
+ } /* switch(ctx->state) */
+
+ } /* while(brigade) */
+
+ /* End of stream. Final cleanup */
+ if (intern->seen_eos) {
+ if (PARSE_HEAD == intern->state) {
+ if (ctx->flags & SSI_FLAG_PRINTING) {
+ char *to_release = apr_pmemdup(ctx->pool, intern->start_seq,
+ intern->parse_pos);
+
+ APR_BRIGADE_INSERT_TAIL(pass_bb,
+ apr_bucket_pool_create(to_release,
+ intern->parse_pos, ctx->pool,
+ f->c->bucket_alloc));
+ }
+ }
+ else if (PARSE_PRE_HEAD != intern->state) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
+ "SSI directive was not properly finished at the end "
+ "of parsed document %s", r->filename);
+ if (ctx->flags & SSI_FLAG_PRINTING) {
+ SSI_CREATE_ERROR_BUCKET(ctx, f, pass_bb);
+ }
+ }
+
+ if (!(ctx->flags & SSI_FLAG_PRINTING)) {
+ ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
+ "missing closing endif directive in parsed document"
+ " %s", r->filename);
+ }
+
+ /* cleanup our temporary memory */
+ apr_brigade_destroy(intern->tmp_bb);
+ apr_pool_destroy(ctx->dpool);
+
+ /* don't forget to finally insert the EOS bucket */
+ APR_BRIGADE_INSERT_TAIL(pass_bb, b);
+ }
+
+ /* if something's left over, pass it along */
+ if (!APR_BRIGADE_EMPTY(pass_bb)) {
+ rv = ap_pass_brigade(f->next, pass_bb);
+ }
+ else {
+ rv = APR_SUCCESS;
+ apr_brigade_destroy(pass_bb);
+ }
+ return rv;
+}
+
+
+/*
+ * +-------------------------------------------------------+
+ * | |
+ * | Runtime Hooks
+ * | |
+ * +-------------------------------------------------------+
+ */
+
+static int includes_setup(ap_filter_t *f)
+{
+ include_dir_config *conf = ap_get_module_config(f->r->per_dir_config,
+ &memcached_include_module);
+
+ /* When our xbithack value isn't set to full or our platform isn't
+ * providing group-level protection bits or our group-level bits do not
+ * have group-execite on, we will set the no_local_copy value to 1 so
+ * that we will not send 304s.
+ */
+ if ((conf->xbithack != XBITHACK_FULL)
+ || !(f->r->finfo.valid & APR_FINFO_GPROT)
+ || !(f->r->finfo.protection & APR_GEXECUTE)) {
+ f->r->no_local_copy = 1;
+ }
+
+ /* Don't allow ETag headers to be generated - see RFC2616 - 13.3.4.
+ * We don't know if we are going to be including a file or executing
+ * a program - in either case a strong ETag header will likely be invalid.
+ */
+ apr_table_setn(f->r->notes, "no-etag", "");
+
+ return OK;
+}
+
+static apr_status_t includes_filter(ap_filter_t *f, apr_bucket_brigade *b)
+{
+ request_rec *r = f->r;
+ include_ctx_t *ctx = f->ctx;
+ request_rec *parent;
+ include_dir_config *conf = ap_get_module_config(r->per_dir_config,
+ &memcached_include_module);
+
+ include_server_config *sconf= ap_get_module_config(r->server->module_config,
+ &memcached_include_module);
+
+ if (!(ap_allow_options(r) & OPT_INCLUDES)) {
+ ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
+ "mod_include: Options +Includes (or IncludesNoExec) "
+ "wasn't set, INCLUDES filter removed");
+ ap_remove_output_filter(f);
+ return ap_pass_brigade(f->next, b);
+ }
+
+ if (!f->ctx) {
+ struct ssi_internal_ctx *intern;
+
+ /* create context for this filter */
+ f->ctx = ctx = apr_palloc(r->pool, sizeof(*ctx));
+ ctx->intern = intern = apr_palloc(r->pool, sizeof(*ctx->intern));
+ ctx->pool = r->pool;
+ apr_pool_create(&ctx->dpool, ctx->pool);
+
+ /* runtime data */
+ intern->tmp_bb = apr_brigade_create(ctx->pool, f->c->bucket_alloc);
+ intern->seen_eos = 0;
+ intern->state = PARSE_PRE_HEAD;
+ ctx->flags = (SSI_FLAG_PRINTING | SSI_FLAG_COND_TRUE);
+ if (ap_allow_options(r) & OPT_INCNOEXEC) {
+ ctx->flags |= SSI_FLAG_NO_EXEC;
+ }
+ intern->accessenable = conf->accessenable;
+
+ ctx->if_nesting_level = 0;
+ intern->re = NULL;
+
+ ctx->error_str = conf->default_error_msg;
+ ctx->time_str = conf->default_time_fmt;
+ intern->start_seq = sconf->default_start_tag;
+ intern->start_seq_pat = bndm_compile(ctx->pool, intern->start_seq,
+ strlen(intern->start_seq));
+ intern->end_seq = sconf->default_end_tag;
+ intern->end_seq_len = strlen(intern->end_seq);
+ intern->undefined_echo = conf->undefined_echo;
+ intern->undefined_echo_len = strlen(conf->undefined_echo);
+ }
+
+ if ((parent = ap_get_module_config(r->request_config, &memcached_include_module))) {
+ /* Kludge --- for nested includes, we want to keep the subprocess
+ * environment of the base document (for compatibility); that means
+ * torquing our own last_modified date as well so that the
+ * LAST_MODIFIED variable gets reset to the proper value if the
+ * nested document resets <!--#config timefmt -->.
+ */
+ r->subprocess_env = r->main->subprocess_env;
+ apr_pool_join(r->main->pool, r->pool);
+ r->finfo.mtime = r->main->finfo.mtime;
+ }
+ else {
+ /* we're not a nested include, so we create an initial
+ * environment */
+ ap_add_common_vars(r);
+ ap_add_cgi_vars(r);
+ add_include_vars(r, conf->default_time_fmt);
+ }
+ /* Always unset the content-length. There is no way to know if
+ * the content will be modified at some point by send_parsed_content.
+ * It is very possible for us to not find any content in the first
+ * 9k of the file, but still have to modify the content of the file.
+ * If we are going to pass the file through send_parsed_content, then
+ * the content-length should just be unset.
+ */
+ apr_table_unset(f->r->headers_out, "Content-Length");
+
+ /* Always unset the Last-Modified field - see RFC2616 - 13.3.4.
+ * We don't know if we are going to be including a file or executing
+ * a program which may change the Last-Modified header or make the
+ * content completely dynamic. Therefore, we can't support these
+ * headers.
+ * Exception: XBitHack full means we *should* set the Last-Modified field.
+ */
+
+ /* Assure the platform supports Group protections */
+ if ((conf->xbithack == XBITHACK_FULL)
+ && (r->finfo.valid & APR_FINFO_GPROT)
+ && (r->finfo.protection & APR_GEXECUTE)) {
+ ap_update_mtime(r, r->finfo.mtime);
+ ap_set_last_modified(r);
+ }
+ else {
+ apr_table_unset(f->r->headers_out, "Last-Modified");
+ }
+
+ /* add QUERY stuff to env cause it ain't yet */
+ if (r->args) {
+ char *arg_copy = apr_pstrdup(r->pool, r->args);
+
+ apr_table_setn(r->subprocess_env, "QUERY_STRING", r->args);
+ ap_unescape_url(arg_copy);
+ apr_table_setn(r->subprocess_env, "QUERY_STRING_UNESCAPED",
+ ap_escape_shell_cmd(r->pool, arg_copy));
+ }
+
+ return send_parsed_content(f, b);
+}
+
+static int include_fixup(request_rec *r)
+{
+ include_dir_config *conf;
+
+ conf = ap_get_module_config(r->per_dir_config, &memcached_include_module);
+
+ if (r->handler && (strcmp(r->handler, "server-parsed") == 0))
+ {
+ if (!r->content_type || !*r->content_type) {
+ ap_set_content_type(r, "text/html");
+ }
+ r->handler = "default-handler";
+ }
+ else
+#if defined(OS2) || defined(WIN32) || defined(NETWARE)
+ /* These OS's don't support xbithack. This is being worked on. */
+ {
+ return DECLINED;
+ }
+#else
+ {
+ if (conf->xbithack == XBITHACK_OFF) {
+ return DECLINED;
+ }
+
+ if (!(r->finfo.protection & APR_UEXECUTE)) {
+ return DECLINED;
+ }
+
+ if (!r->content_type || strcmp(r->content_type, "text/html")) {
+ return DECLINED;
+ }
+ }
+#endif
+
+ /* We always return declined, because the default handler actually
+ * serves the file. All we have to do is add the filter.
+ */
+ ap_add_output_filter("INCLUDES", NULL, r, r->connection);
+ return DECLINED;
+}
+
+
+/*
+ * +-------------------------------------------------------+
+ * | |
+ * | Configuration Handling
+ * | |
+ * +-------------------------------------------------------+
+ */
+
+static void *create_includes_dir_config(apr_pool_t *p, char *dummy)
+{
+ include_dir_config *result = apr_palloc(p, sizeof(include_dir_config));
+
+ result->default_error_msg = DEFAULT_ERROR_MSG;
+ result->default_time_fmt = DEFAULT_TIME_FORMAT;
+ result->undefined_echo = DEFAULT_UNDEFINED_ECHO;
+ result->xbithack = DEFAULT_XBITHACK;
+
+ return result;
+}
+
+static void *create_includes_server_config(apr_pool_t *p, server_rec *server)
+{
+ include_server_config *result;
+
+ result = apr_palloc(p, sizeof(include_server_config));
+ result->default_end_tag = DEFAULT_END_SEQUENCE;
+ result->default_start_tag = DEFAULT_START_SEQUENCE;
+
+ result->servers = apr_array_make(p, 1, sizeof(memcached_include_server_t));
+
+ result->max_servers = DEFAULT_MAX_SERVERS;
+ result->min_size = DEFAULT_MIN_SIZE;
+ result->max_size = DEFAULT_MAX_SIZE;
+ result->conn_min = DEFAULT_MIN;
+ result->conn_smax = DEFAULT_SMAX;
+ result->conn_max = DEFAULT_MAX;
+ result->conn_ttl = DEFAULT_TTL;
+
+ return result;
+}
+
+static const char *set_memcached_host(cmd_parms *cmd, void *mconfig, const char *arg)
+{
+ char *host, *port;
+ memcached_include_server_t *memcached_server = NULL;
+ include_server_config *conf = ap_get_module_config(cmd->server->module_config, &memcached_include_module);
+
+ /*
+ * I should consider using apr_parse_addr_port instead
+ * [http://apr.apache.org/docs/apr/1.3/group__apr__network__io.html#g90c31b2f012c6b1e2d842a96c4431de3]
+ */
+ host = apr_pstrdup(cmd->pool, arg);
+
+ port = strchr(host, ':');
+ if(port) {
+ *(port++) = '\0';
+ }
+
+ if(!*host || host == NULL || !*port || port == NULL) {
+ return "MemcachedCacheServer should be in the correct format : host:port";
+ }
+
+ memcached_server = apr_array_push(conf->servers);
+ memcached_server->host = host;
+ memcached_server->port = apr_atoi64(port);
+
+ /* ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, cmd->server, "Arg : %s Host : %s, Port : %d", arg, memcached_server->host, memcached_server->port); */
+
+ return NULL;
+}
+
+static const char *set_xbithack(cmd_parms *cmd, void *mconfig, const char *arg)
+{
+ include_dir_config *conf = mconfig;
+
+ if (!strcasecmp(arg, "off")) {
+ conf->xbithack = XBITHACK_OFF;
+ }
+ else if (!strcasecmp(arg, "on")) {
+ conf->xbithack = XBITHACK_ON;
+ }
+ else if (!strcasecmp(arg, "full")) {
+ conf->xbithack = XBITHACK_FULL;
+ }
+ else {
+ return "XBitHack must be set to Off, On, or Full";
+ }
+
+ return NULL;
+}
+
+static const char *set_default_start_tag(cmd_parms *cmd, void *mconfig,
+ const char *tag)
+{
+ include_server_config *conf;
+ const char *p = tag;
+
+ /* be consistent. (See below in set_default_end_tag) */
+ while (*p) {
+ if (apr_isspace(*p)) {
+ return "SSIStartTag may not contain any whitespaces";
+ }
+ ++p;
+ }
+
+ conf= ap_get_module_config(cmd->server->module_config , &memcached_include_module);
+ conf->default_start_tag = tag;
+
+ return NULL;
+}
+
+static const char *set_default_end_tag(cmd_parms *cmd, void *mconfig,
+ const char *tag)
+{
+ include_server_config *conf;
+ const char *p = tag;
+
+ /* sanity check. The parser may fail otherwise */
+ while (*p) {
+ if (apr_isspace(*p)) {
+ return "SSIEndTag may not contain any whitespaces";
+ }
+ ++p;
+ }
+
+ conf= ap_get_module_config(cmd->server->module_config , &memcached_include_module);
+ conf->default_end_tag = tag;
+
+ return NULL;
+}
+
+static const char *set_undefined_echo(cmd_parms *cmd, void *mconfig,
+ const char *msg)
+{
+ include_dir_config *conf = mconfig;
+ conf->undefined_echo = msg;
+
+ return NULL;
+}
+
+static const char *set_default_error_msg(cmd_parms *cmd, void *mconfig,
+ const char *msg)
+{
+ include_dir_config *conf = mconfig;
+ conf->default_error_msg = msg;
+
+ return NULL;
+}
+
+static const char *set_default_time_fmt(cmd_parms *cmd, void *mconfig,
+ const char *fmt)
+{
+ include_dir_config *conf = mconfig;
+ conf->default_time_fmt = fmt;
+
+ return NULL;
+}
+
+
+/*
+ * +-------------------------------------------------------+
+ * | |
+ * | Module Initialization and Configuration
+ * | |
+ * +-------------------------------------------------------+
+ */
+
+static int include_post_config(apr_pool_t *p, apr_pool_t *plog,
+ apr_pool_t *ptemp, server_rec *s)
+{
+ include_handlers = apr_hash_make(p);
+
+ ssi_pfn_register = APR_RETRIEVE_OPTIONAL_FN(ap_register_memcached_include_handler);
+
+ if(ssi_pfn_register) {
+ ssi_pfn_register("if", handle_if);
+ ssi_pfn_register("set", handle_set);
+ ssi_pfn_register("else", handle_else);
+ ssi_pfn_register("elif", handle_elif);
+ ssi_pfn_register("echo", handle_echo);
+ ssi_pfn_register("endif", handle_endif);
+ ssi_pfn_register("fsize", handle_fsize);
+ ssi_pfn_register("config", handle_config);
+ ssi_pfn_register("include", handle_include);
+ ssi_pfn_register("flastmod", handle_flastmod);
+ ssi_pfn_register("printenv", handle_printenv);
+ }
+
+ include_server_config *conf;
+ memcached_include_server_t *svr;
+ apr_status_t rv;
+ int i;
+
+ conf = (include_server_config *)ap_get_module_config(s->module_config, &memcached_include_module);
+
+ /* ap_log_error(APLOG_MARK, APLOG_INFO, 0, s, "Function: %pp, max_servers: %d", apr_memcache_create, conf->max_servers); */
+
+ rv = apr_memcache_create(p, conf->max_servers, 0, &(conf->memcached));
+
+ if(rv != APR_SUCCESS) {
+ ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, s, "Unable to create memcached structure");
+ } else {
+ ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, s, "Memcached struct successfully created");
+ }
+
+ svr = (memcached_include_server_t *)conf->servers->elts;
+
+ ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, "conf->servers->nelts : %d", conf->servers->nelts);
+
+ for(i = 0; i < conf->servers->nelts; i++) {
+
+ rv = apr_memcache_server_create(p, svr[i].host, svr[i].port,
+ conf->conn_min, conf->conn_smax,
+ conf->conn_max, conf->conn_ttl,
+ &(svr[i].server));
+ if(rv != APR_SUCCESS) {
+ ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, s, "Unable to create memcache server for %s:%d", svr[i].host, svr[i].port);
+ continue;
+ }
+
+ rv = apr_memcache_add_server(conf->memcached, svr[i].server);
+
+ if(rv != APR_SUCCESS) {
+ ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, s, "Unable to add memcache server for %s:%d", svr[i].host, svr[i].port);
+ }
+
+ ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, s, "Memcached server successfully created %s:%d", svr[i].host, svr[i].port);
+ }
+
+ return OK;
+}
+
+static const command_rec includes_cmds[] =
+{
+ AP_INIT_TAKE1("MemcachedHost", set_memcached_host, NULL, OR_OPTIONS,
+ "Memcached hostname or IP address with portnumber, like this, 127.0.0.1:11211"),
+ /*
+ AP_INIT_TAKE1("MemcachedTimeOut", set_memcached_timeout, NULL, OR_OPTIONS,
+ "Memcached timeout (in seconds)"),
+ */
+ AP_INIT_TAKE1("XBitHack", set_xbithack, NULL, OR_OPTIONS,
+ "Off, On, or Full"),
+ AP_INIT_TAKE1("SSIErrorMsg", set_default_error_msg, NULL, OR_ALL,
+ "a string"),
+ AP_INIT_TAKE1("SSITimeFormat", set_default_time_fmt, NULL, OR_ALL,
+ "a strftime(3) formatted string"),
+ AP_INIT_TAKE1("SSIStartTag", set_default_start_tag, NULL, RSRC_CONF,
+ "SSI Start String Tag"),
+ AP_INIT_TAKE1("SSIEndTag", set_default_end_tag, NULL, RSRC_CONF,
+ "SSI End String Tag"),
+ AP_INIT_TAKE1("SSIUndefinedEcho", set_undefined_echo, NULL, OR_ALL,
+ "String to be displayed if an echoed variable is undefined"),
+ AP_INIT_FLAG("SSIAccessEnable", ap_set_flag_slot,
+ (void *)APR_OFFSETOF(include_dir_config, accessenable),
+ OR_LIMIT, "Whether testing access is enabled. Limited to 'on' or 'off'"),
+ {NULL}
+};
+
+static void ap_register_memcached_include_handler(char *tag, include_handler_fn_t *func)
+{
+ apr_hash_set(include_handlers, tag, strlen(tag), (const void *)func);
+}
+
+static void register_hooks(apr_pool_t *p)
+{
+ APR_REGISTER_OPTIONAL_FN(ap_ssi_get_tag_and_value);
+ APR_REGISTER_OPTIONAL_FN(ap_ssi_parse_string);
+ APR_REGISTER_OPTIONAL_FN(ap_register_memcached_include_handler);
+ ap_hook_post_config(include_post_config, NULL, NULL, APR_HOOK_REALLY_FIRST);
+ ap_hook_fixups(include_fixup, NULL, NULL, APR_HOOK_LAST);
+ ap_register_output_filter("INCLUDES", includes_filter, includes_setup,
+ AP_FTYPE_RESOURCE);
+}
+
+module AP_MODULE_DECLARE_DATA memcached_include_module =
+{
+ STANDARD20_MODULE_STUFF,
+ create_includes_dir_config, /* dir config creater */
+ NULL, /* dir merger --- default is to override */
+ create_includes_server_config,/* server config */
+ NULL, /* merge server config */
+ includes_cmds, /* command apr_table_t */
+ register_hooks /* register hooks */
+};
diff --git a/mod_memcached_include.h b/mod_memcached_include.h
new file mode 100644
index 0000000..1d54097
--- /dev/null
+++ b/mod_memcached_include.h
@@ -0,0 +1,116 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @file mod_include.h
+ * @brief Server Side Include Filter Extension Module for Apache
+ *
+ * @defgroup MOD_INCLUDE mod_include
+ * @ingroup APACHE_MODS
+ * @{
+ */
+
+#ifndef _MOD_INCLUDE_H
+#define _MOD_INCLUDE_H 1
+
+#include "apr_pools.h"
+#include "apr_optional.h"
+
+/*
+ * Constants used for ap_ssi_get_tag_and_value's decode parameter
+ */
+#define SSI_VALUE_DECODED 1
+#define SSI_VALUE_RAW 0
+
+/*
+ * Constants used for ap_ssi_parse_string's leave_name parameter
+ */
+#define SSI_EXPAND_LEAVE_NAME 1
+#define SSI_EXPAND_DROP_NAME 0
+
+/*
+ * This macro creates a bucket which contains an error message and appends it
+ * to the current pass brigade
+ */
+#define SSI_CREATE_ERROR_BUCKET(ctx, f, bb) APR_BRIGADE_INSERT_TAIL((bb), \
+ apr_bucket_pool_create(apr_pstrdup((ctx)->pool, (ctx)->error_str), \
+ strlen((ctx)->error_str), (ctx)->pool, \
+ (f)->c->bucket_alloc))
+
+/*
+ * These constants are used to set or clear flag bits.
+ */
+#define SSI_FLAG_PRINTING (1<<0) /* Printing conditional lines. */
+#define SSI_FLAG_COND_TRUE (1<<1) /* Conditional eval'd to true. */
+#define SSI_FLAG_SIZE_IN_BYTES (1<<2) /* Sizes displayed in bytes. */
+#define SSI_FLAG_NO_EXEC (1<<3) /* No Exec in current context. */
+
+#define SSI_FLAG_SIZE_ABBREV (~(SSI_FLAG_SIZE_IN_BYTES))
+#define SSI_FLAG_CLEAR_PRINT_COND (~((SSI_FLAG_PRINTING) | \
+ (SSI_FLAG_COND_TRUE)))
+#define SSI_FLAG_CLEAR_PRINTING (~(SSI_FLAG_PRINTING))
+
+/*
+ * The public SSI context structure
+ */
+typedef struct {
+ /* permanent pool, use this for creating bucket data */
+ apr_pool_t *pool;
+
+ /* temp pool; will be cleared after the execution of every directive */
+ apr_pool_t *dpool;
+
+ /* See the SSI_FLAG_XXXXX definitions. */
+ int flags;
+
+ /* nesting of *invisible* ifs */
+ int if_nesting_level;
+
+ /* if true, the current buffer will be passed down the filter chain before
+ * continuing with next input bucket and the variable will be reset to
+ * false.
+ */
+ int flush_now;
+
+ /* argument counter (of the current directive) */
+ unsigned argc;
+
+ /* currently configured error string */
+ const char *error_str;
+
+ /* currently configured time format */
+ const char *time_str;
+
+ /* pointer to internal (non-public) data, don't touch */
+ struct ssi_internal_ctx *intern;
+} include_ctx_t;
+
+typedef apr_status_t (include_handler_fn_t)(include_ctx_t *, ap_filter_t *,
+ apr_bucket_brigade *);
+
+APR_DECLARE_OPTIONAL_FN(void, ap_ssi_get_tag_and_value,
+ (include_ctx_t *ctx, char **tag, char **tag_val,
+ int dodecode));
+
+APR_DECLARE_OPTIONAL_FN(char*, ap_ssi_parse_string,
+ (include_ctx_t *ctx, const char *in, char *out,
+ apr_size_t length, int leave_name));
+
+APR_DECLARE_OPTIONAL_FN(void, ap_register_memcached_include_handler,
+ (char *tag, include_handler_fn_t *func));
+
+#endif /* MOD_INCLUDE */
+/** @} */
diff --git a/modules.mk b/modules.mk
new file mode 100644
index 0000000..5259fbe
--- /dev/null
+++ b/modules.mk
@@ -0,0 +1,4 @@
+mod_memcached_include.la: mod_memcached_include.slo
+ $(SH_LINK) -rpath $(libexecdir) -module -avoid-version mod_memcached_include.lo
+DISTCLEAN_TARGETS = modules.mk
+shared = mod_memcached_include.la
diff --git a/tests/mod_memcached_include_tests b/tests/mod_memcached_include_tests
new file mode 100644
index 0000000..b13cc19
--- /dev/null
+++ b/tests/mod_memcached_include_tests
@@ -0,0 +1 @@
+<b>contenu de mod_memcached_include_test LOCAL</b>
diff --git a/tests/pull-filesystem.shtml b/tests/pull-filesystem.shtml
new file mode 100644
index 0000000..02d69c0
--- /dev/null
+++ b/tests/pull-filesystem.shtml
@@ -0,0 +1,7 @@
+<html>
+ <head></head>
+ <body>
+ <h1>Memcached tests</h1>
+ <!--#include file="mod_memcached_include_tests" -->
+ </body>
+</html>
diff --git a/tests/pull-memcached.shtml b/tests/pull-memcached.shtml
new file mode 100644
index 0000000..6ec5778
--- /dev/null
+++ b/tests/pull-memcached.shtml
@@ -0,0 +1,7 @@
+<html>
+ <head></head>
+ <body>
+ <h1>Memcached tests</h1>
+ <!--#include memcached="mod_memcached_include_tests" -->
+ </body>
+</html>
diff --git a/tests/push.php b/tests/push.php
new file mode 100755
index 0000000..d827183
--- /dev/null
+++ b/tests/push.php
@@ -0,0 +1,29 @@
+<?php
+define( MEMCACHED_HOST, '127.0.0.1' );
+define( MEMCACHED_PORT, '11211' );
+define( MEMCACHED_TIMEOUT, '10' );
+
+if( !extension_loaded( 'memcache' ) )
+{
+ die( 'Extension not loaded' );
+}
+if( $cr = memcache_connect( MEMCACHED_HOST, MEMCACHED_PORT, MEMCACHED_TIMEOUT ) )
+{
+ $key = 'mod_memcached_include_tests';
+ $fileContents = 'SSI block added at ' . date( 'Y/m/d H:i:s', time( ) );
+ $flag = false;
+
+ //the file does not exists
+ if( !memcache_replace( $cr, $key, $fileContents, $flag, 0 ) )
+ {
+ if( !memcache_add( $cr, $key, $fileContents, $flag, 0 ) )
+ {
+ print( 'Unable to add file' );
+ }
+ }
+}
+else
+{
+ print( 'unable to connect to memcached' );
+}
+?>
|
ztangent/checkergen
|
80656bfbd0c0ee7c74714f307fa776dd157cab68
|
Revert "Demonstration purposes only."
|
diff --git a/src/core.py b/src/core.py
index f467be0..6f08c43 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,545 +1,544 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgDisplayGroup -- A set of CheckerShapes to be displayed siet_stateaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import copy
import random
import itertools
from datetime import datetime
from xml.dom import minidom
import pyglet
import graphics
import priority
import trigger
import eyetracking
from utils import *
-# A change
# Use OrderedDict substitute if we don't have Python 2.7
if sys.version_info < (2, 7):
from odict import OrderedDict
else:
from collections import OrderedDict
CKG_FMT = 'ckg'
LOG_FMT = 'log'
MAX_EXPORT_FRAMES = 1000
EXPORT_DIR_SUFFIX = '-anim'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
INT_HALF_PERIODS = True
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = OrderedDict([('name', 'untitled'),
('fps', 60),
('res', (800, 600)),
('bg', (127, 127, 127)),
('pre', 0),
('post', 0),
('pre_cross', [(0, True)]),
('post_cross', [(0, True)]),
('cross_cols', ((0, 0, 0),
(255, 0, 0),
(0, 0, 255))),
('cross_times', ('Infinity', 1)),
('orders', []),
('disp_ops', None)])
DEFAULTS['disp_ops'] = OrderedDict([('repeats', 1),
('waitless', False),
('fullscreen', False),
('priority', None),
('logtime', False),
('logdur', False),
('trigser', False),
('trigpar', False),
('fpst', 0),
('freqcheck', False),
('phototest', False),
('photoburst', False),
('eyetrack', False),
('etuser', False),
('etvideo', None),
('tryagain', 0),
('trybreak', None),
('nolog', False),
('export', False),
('expo_dir', None),
('expo_dur', None),
('folder', True)])
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
pre_cross -- key-value pairs specifying at what times during the pre
period a cross should be shown (e.g. [(0, False), (2, True)]
means that a cross is not shown at the start, but is shown
from 2 seconds onwards)
post_cross -- key-value pairs specifying at what times during the post
period a cross should be shown
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'cross_cols':
if len(value) != 3:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name in ['pre_cross', 'post_cross']:
value = [(to_decimal(k), to_bool(v)) for (k, v) in value]
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def set_display_flags(self, **keywords):
"""Set default display flags for the project.
Same arguments as 'display', excluding 'name' and 'order'.
"""
for kw in keywords.keys():
if kw in self.disp_ops.keys() and keywords[kw] != None:
self.disp_ops[kw] = keywords[kw]
self._dirty = True
def set_group_orders(self, orders):
for order in orders:
for gid in order:
if gid < -1 or gid >= len(self.groups):
msg = 'invalid group id (out of range)'
raise ValueError(msg)
self.orders = orders
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
# Vars that are dicts
dicts_to_load = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_load = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
for d_name in dicts_to_load:
d = copy.deepcopy(self.__class__.DEFAULTS[d_name])
try:
d_el = [node for node in project.childNodes if
node.localName == d_name and
node.namespaceURI == XML_NAMESPACE][0]
for var in d.keys():
try:
d[var] = eval(xml_get(d_el, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}' in '{1}'".\
format(var, d_name)
print "using default value '{0}' instead...".\
format(d[var])
except IndexError:
print "warning: missing attribute set '{0}'".format(d_name)
print "using default values instead..."
setattr(self, d_name, d)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
# Vars that are dicts
dicts_to_save = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_save = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for d_name in dicts_to_save:
d_el = doc.createElement(d_name)
project.appendChild(d_el)
d = getattr(self, d_name)
for k, v in d.iteritems():
xml_set(doc, d_el, k, repr(v))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, **keywords):
"""Displays the stimulus on the screen.
name -- name that logfile will be saved with
repeats -- number of times specified order of display groups should
be repeated
waitless -- if true, no waitscreens will appear at the start of each
repeat
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
priority -- priority level to which process should be raised
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
trigser -- send triggers through serial port when each group is shown
trigpar -- send triggers through parallel port when each group is shown
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
freqcheck -- send fpst only at the start, the middle, and the end
for sanity checking of display and trigger fps
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- append a wait screen to the group queue every time
after this many groups have been appended to the queue
order -- order in which groups (specified by id) will be displayed
"""
# Create RunState
disp_ops = copy.deepcopy(self.disp_ops)
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'name' in keywords.keys() and keywords['name'] != None:
name = keywords['name']
else:
timestr = datetime.today().strftime('_%Y-%m-%d_%H-%M-%S')
name = self.name + timestr
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
waitscreen = CkgWaitScreen()
# Set runstate order id if necessary
if order in self.orders:
runstate.ord_id = self.orders.index(order)
# Count through pre
for count in range(self.pre * self.fps):
if runstate.terminate:
break
pre_time = to_decimal(count) / runstate.fps
if pre_time in dict(self.pre_cross):
runstate.show_cross = dict(self.pre_cross)[pre_time]
runstate.update()
# Loop through repeats
repeats = runstate.disp_ops['repeats']
ord_len = len(runstate.order)
for i in range(repeats):
# Restart eyetracking
if runstate.disp_ops['eyetrack']:
eyetracking.stop()
eyetracking.start()
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
# Loop through display groups
runstate.events['blk_on'] = True
for n, gid in enumerate(runstate.order):
# Set flag for freqcheck
if runstate.disp_ops['freqcheck']:
if ((i == 0 and n == 0) or
(i == repeats-1 and n == ord_len-1) or
(i == repeats//2 and n == ord_len//2)):
runstate.fc_send = True
else:
runstate.fc_send = False
if gid == -1:
waitscreen.reset()
waitscreen.display(runstate)
else:
self.groups[gid].display(runstate)
if not runstate.terminate:
# Append group id and fail state
runstate.gids.append(gid)
if runstate.disp_ops['eyetrack']:
runstate.fails.append(runstate.true_fail)
# Append groups to be added
if runstate.true_fail:
if (len(runstate.add_gids) <
runstate.disp_ops['tryagain']):
runstate.add_gids.append(gid)
runstate.events['blk_off'] = True
# Stop freqcheck before added groups
if runstate.disp_ops['freqcheck']:
runstate.fc_send = False
# Loop through added groups
if runstate.disp_ops['eyetrack']:
for blk in grouper(runstate.add_gids,
runstate.disp_ops['trybreak']):
# Restart eyetracking
if runstate.disp_ops['eyetrack']:
eyetracking.stop()
eyetracking.start()
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
runstate.events['blk_on'] = True
# Loop through display groups
for gid in blk:
if gid != None:
self.groups[gid].display(runstate)
if not runstate.terminate:
# Append group id and fail state
runstate.gids.append(gid)
if runstate.disp_ops['eyetrack']:
runstate.fails.append(runstate.true_fail)
runstate.events['blk_off'] = True
# Count through post
for count in range(self.post * self.fps):
if runstate.terminate:
break
post_time = to_decimal(count) / runstate.fps
if post_time in dict(self.post_cross):
runstate.show_cross = dict(self.post_cross)[post_time]
runstate.update()
# Stop and output log
runstate.stop()
if not runstate.disp_ops['nolog']:
runstate.log()
def export(self, **keywords):
"""Exports the stimulus as a series of images, one image per frame.
repeats -- number of times specified order of display groups should
be repeated
order -- order in which groups (specified by id) will be displayed
expo_dir -- directory to which images will be exported
expo_dur -- time in seconds to which export will be limited
folder -- if true, images will be contained in a separate folder
within export directory
force -- force export to go through even if a large number
of frames are to be exported
"""
|
ztangent/checkergen
|
d6f0d991fc8b8ebaa3d3bb23dcae3bd7c9c6050a
|
Demonstration purposes only.
|
diff --git a/src/core.py b/src/core.py
index 458b04e..253b9bf 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,544 +1,545 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import copy
import random
import itertools
from datetime import datetime
from xml.dom import minidom
import pyglet
import graphics
import priority
import trigger
import eyetracking
from utils import *
+# A change
# Use OrderedDict substitute if we don't have Python 2.7
if sys.version_info < (2, 7):
from odict import OrderedDict
else:
from collections import OrderedDict
CKG_FMT = 'ckg'
LOG_FMT = 'log'
MAX_EXPORT_FRAMES = 1000
EXPORT_DIR_SUFFIX = '-anim'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
INT_HALF_PERIODS = True
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = OrderedDict([('name', 'untitled'),
('fps', 60),
('res', (800, 600)),
('bg', (127, 127, 127)),
('pre', 0),
('post', 0),
('cross_cols', ((0, 0, 0), (255, 0, 0))),
('cross_times', ('Infinity', 1)),
('orders', []),
('disp_ops', None)])
DEFAULTS['disp_ops'] = OrderedDict([('repeats', 1),
('waitless', False),
('fullscreen', False),
('priority', None),
('logtime', False),
('logdur', False),
('trigser', False),
('trigpar', False),
('fpst', 0),
('freqcheck', False),
('phototest', False),
('photoburst', False),
('eyetrack', False),
('etuser', False),
('etvideo', None),
('tryagain', 0),
('trybreak', None),
('nolog', False),
('export', False),
('expo_dir', None),
('expo_dur', None),
('folder', True)])
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def set_display_flags(self, **keywords):
"""Set default display flags for the project.
Same arguments as 'display', excluding 'name' and 'order'.
"""
for kw in keywords.keys():
if kw in self.disp_ops.keys() and keywords[kw] != None:
self.disp_ops[kw] = keywords[kw]
self._dirty = True
def set_group_orders(self, orders):
for order in orders:
for gid in order:
if gid < -1 or gid >= len(self.groups):
msg = 'invalid group id (out of range)'
raise ValueError(msg)
self.orders = orders
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
# Vars that are dicts
dicts_to_load = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_load = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
for d_name in dicts_to_load:
d = copy.deepcopy(self.__class__.DEFAULTS[d_name])
try:
d_el = [node for node in project.childNodes if
node.localName == d_name and
node.namespaceURI == XML_NAMESPACE][0]
for var in d.keys():
try:
d[var] = eval(xml_get(d_el, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}' in '{1}'".\
format(var, d_name)
print "using default value '{0}' instead...".\
format(d[var])
except IndexError:
print "warning: missing attribute set '{0}'".format(d_name)
print "using default values instead..."
setattr(self, d_name, d)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
# Vars that are dicts
dicts_to_save = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_save = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for d_name in dicts_to_save:
d_el = doc.createElement(d_name)
project.appendChild(d_el)
d = getattr(self, d_name)
for k, v in d.iteritems():
xml_set(doc, d_el, k, repr(v))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, **keywords):
"""Displays the stimulus on the screen.
name -- name that logfile will be saved with
repeats -- number of times specified order of display groups should
be repeated
waitless -- if true, no waitscreens will appear at the start of each
repeat
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
priority -- priority level to which process should be raised
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
trigser -- send triggers through serial port when each group is shown
trigpar -- send triggers through parallel port when each group is shown
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
freqcheck -- send fpst only at the start, the middle, and the end
for sanity checking of display and trigger fps
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- append a wait screen to the group queue every time
after this many groups have been appended to the queue
order -- order in which groups (specified by id) will be displayed
"""
# Create RunState
disp_ops = copy.deepcopy(self.disp_ops)
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'name' in keywords.keys() and keywords['name'] != None:
name = keywords['name']
else:
timestr = datetime.today().strftime('_%Y-%m-%d_%H-%M-%S')
name = self.name + timestr
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
waitscreen = CkgWaitScreen()
# Set order id to be sent if necessary
if order in self.orders:
runstate.events['ord_id'] = self.orders.index(order)
# Count through pre
for count in range(self.pre * self.fps):
if runstate.terminate:
break
runstate.update()
# Loop through repeats
repeats = runstate.disp_ops['repeats']
ord_len = len(runstate.order)
for i in range(repeats):
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
# Loop through display groups
runstate.events['blk_on'] = True
for n, gid in enumerate(runstate.order):
# Set flag for freqcheck
if runstate.disp_ops['freqcheck']:
if ((i == 0 and n == 0) or
(i == repeats-1 and n == ord_len-1) or
(i == repeats//2 and n == ord_len//2)):
runstate.fc_send = True
else:
runstate.fc_send = False
if gid == -1:
waitscreen.reset()
waitscreen.display(runstate)
else:
self.groups[gid].display(runstate)
# Append failed groups
if runstate.disp_ops['eyetrack'] and runstate.true_fail:
if len(runstate.add_gids) < runstate.disp_ops['tryagain']:
runstate.add_gids.append(gid)
else:
runstate.fail_gids.append(gid)
runstate.events['blk_off'] = True
# Stop freqcheck before added groups
if runstate.disp_ops['freqcheck']:
runstate.fc_send = False
# Loop through added groups
if runstate.disp_ops['eyetrack']:
for blk in grouper(runstate.add_gids,
runstate.disp_ops['trybreak']):
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
runstate.events['blk_on'] = True
# Loop through display groups
for gid in blk:
if gid != None:
self.groups[gid].display(runstate)
runstate.events['blk_off'] = True
# Count through post
for count in range(self.post * self.fps):
if runstate.terminate:
break
runstate.update()
# Stop and output log
runstate.stop()
if not runstate.disp_ops['nolog']:
runstate.log()
def export(self, **keywords):
"""Exports the stimulus as a series of images, one image per frame.
repeats -- number of times specified order of display groups should
be repeated
order -- order in which groups (specified by id) will be displayed
expo_dir -- directory to which images will be exported
expo_dur -- time in seconds to which export will be limited
folder -- if true, images will be contained in a separate folder
within export directory
force -- force export to go through even if a large number
of frames are to be exported
"""
# Create RunState
disp_ops = copy.deepcopy(self.__class__.DEFAULTS['disp_ops'])
disp_ops['export'] = True
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=self.name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
# Warn user if a lot of frames will be exported
if 'force' not in keywords.keys():
keywords['force'] = False
groups_dur = sum([self.groups[i].duration()
for i in order]) * disp_ops['repeats']
total_frames = (self.pre + groups_dur + self.post) * self.fps
frames = min(total_frames, disp_ops['expo_dur'] * self.fps)
if frames > MAX_EXPORT_FRAMES and not keywords['force']:
msg = 'large number ({0}) of frames to be exported'.\
format(int(frames))
raise FrameOverflowError(msg)
runstate.frames = frames
# Count through pre
for count in range(self.pre * self.fps):
if runstate.terminate:
break
|
ztangent/checkergen
|
3a64ed7dd63145ef2db2a95ca81151b086430956
|
Fixed logic for when to send 102.
|
diff --git a/src/core.py b/src/core.py
index 0a3b961..6f08c43 100755
--- a/src/core.py
+++ b/src/core.py
@@ -282,1025 +282,1025 @@ class CkgProj:
vars_to_load = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
for d_name in dicts_to_load:
d = copy.deepcopy(self.__class__.DEFAULTS[d_name])
try:
d_el = [node for node in project.childNodes if
node.localName == d_name and
node.namespaceURI == XML_NAMESPACE][0]
for var in d.keys():
try:
d[var] = eval(xml_get(d_el, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}' in '{1}'".\
format(var, d_name)
print "using default value '{0}' instead...".\
format(d[var])
except IndexError:
print "warning: missing attribute set '{0}'".format(d_name)
print "using default values instead..."
setattr(self, d_name, d)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
# Vars that are dicts
dicts_to_save = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_save = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for d_name in dicts_to_save:
d_el = doc.createElement(d_name)
project.appendChild(d_el)
d = getattr(self, d_name)
for k, v in d.iteritems():
xml_set(doc, d_el, k, repr(v))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, **keywords):
"""Displays the stimulus on the screen.
name -- name that logfile will be saved with
repeats -- number of times specified order of display groups should
be repeated
waitless -- if true, no waitscreens will appear at the start of each
repeat
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
priority -- priority level to which process should be raised
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
trigser -- send triggers through serial port when each group is shown
trigpar -- send triggers through parallel port when each group is shown
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
freqcheck -- send fpst only at the start, the middle, and the end
for sanity checking of display and trigger fps
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- append a wait screen to the group queue every time
after this many groups have been appended to the queue
order -- order in which groups (specified by id) will be displayed
"""
# Create RunState
disp_ops = copy.deepcopy(self.disp_ops)
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'name' in keywords.keys() and keywords['name'] != None:
name = keywords['name']
else:
timestr = datetime.today().strftime('_%Y-%m-%d_%H-%M-%S')
name = self.name + timestr
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
waitscreen = CkgWaitScreen()
# Set runstate order id if necessary
if order in self.orders:
runstate.ord_id = self.orders.index(order)
# Count through pre
for count in range(self.pre * self.fps):
if runstate.terminate:
break
pre_time = to_decimal(count) / runstate.fps
if pre_time in dict(self.pre_cross):
runstate.show_cross = dict(self.pre_cross)[pre_time]
runstate.update()
# Loop through repeats
repeats = runstate.disp_ops['repeats']
ord_len = len(runstate.order)
for i in range(repeats):
# Restart eyetracking
if runstate.disp_ops['eyetrack']:
eyetracking.stop()
eyetracking.start()
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
# Loop through display groups
runstate.events['blk_on'] = True
for n, gid in enumerate(runstate.order):
# Set flag for freqcheck
if runstate.disp_ops['freqcheck']:
if ((i == 0 and n == 0) or
(i == repeats-1 and n == ord_len-1) or
(i == repeats//2 and n == ord_len//2)):
runstate.fc_send = True
else:
runstate.fc_send = False
if gid == -1:
waitscreen.reset()
waitscreen.display(runstate)
else:
self.groups[gid].display(runstate)
if not runstate.terminate:
# Append group id and fail state
runstate.gids.append(gid)
if runstate.disp_ops['eyetrack']:
runstate.fails.append(runstate.true_fail)
# Append groups to be added
if runstate.true_fail:
if (len(runstate.add_gids) <
runstate.disp_ops['tryagain']):
runstate.add_gids.append(gid)
runstate.events['blk_off'] = True
# Stop freqcheck before added groups
if runstate.disp_ops['freqcheck']:
runstate.fc_send = False
# Loop through added groups
if runstate.disp_ops['eyetrack']:
for blk in grouper(runstate.add_gids,
runstate.disp_ops['trybreak']):
# Restart eyetracking
if runstate.disp_ops['eyetrack']:
eyetracking.stop()
eyetracking.start()
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
runstate.events['blk_on'] = True
# Loop through display groups
for gid in blk:
if gid != None:
self.groups[gid].display(runstate)
if not runstate.terminate:
# Append group id and fail state
runstate.gids.append(gid)
if runstate.disp_ops['eyetrack']:
runstate.fails.append(runstate.true_fail)
runstate.events['blk_off'] = True
# Count through post
for count in range(self.post * self.fps):
if runstate.terminate:
break
post_time = to_decimal(count) / runstate.fps
if post_time in dict(self.post_cross):
runstate.show_cross = dict(self.post_cross)[post_time]
runstate.update()
# Stop and output log
runstate.stop()
if not runstate.disp_ops['nolog']:
runstate.log()
def export(self, **keywords):
"""Exports the stimulus as a series of images, one image per frame.
repeats -- number of times specified order of display groups should
be repeated
order -- order in which groups (specified by id) will be displayed
expo_dir -- directory to which images will be exported
expo_dur -- time in seconds to which export will be limited
folder -- if true, images will be contained in a separate folder
within export directory
force -- force export to go through even if a large number
of frames are to be exported
"""
# Create RunState
disp_ops = copy.deepcopy(self.__class__.DEFAULTS['disp_ops'])
disp_ops['export'] = True
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=self.name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
# Warn user if a lot of frames will be exported
if 'force' not in keywords.keys():
keywords['force'] = False
groups_dur = sum([self.groups[i].duration()
for i in order]) * disp_ops['repeats']
total_frames = (self.pre + groups_dur + self.post) * self.fps
frames = min(total_frames, disp_ops['expo_dur'] * self.fps)
if frames > MAX_EXPORT_FRAMES and not keywords['force']:
msg = 'large number ({0}) of frames to be exported'.\
format(int(frames))
raise FrameOverflowError(msg)
runstate.frames = frames
# Count through pre
for count in range(self.pre * self.fps):
if runstate.terminate:
break
runstate.update()
# Loop through repeats
repeats = runstate.disp_ops['repeats']
for i in range(repeats):
# Loop through display groups
for n, gid in enumerate(runstate.order):
if gid != -1:
self.groups[gid].display(runstate)
# Count through post
for count in range(self.post * self.fps):
if runstate.terminate:
break
runstate.update()
# Stop runstate
runstate.stop()
class CkgRunState:
"""Contains information about the state of a checkergen project
when it is being displayed or exported."""
DEFAULTS = dict([('name', 'untitled'),
('res', None),
('fps', None),
('bg', None),
('cross_cols', None),
('cross_times', None),
('order', []),
('disp_ops', None),
('events', None),
('gids', []),
('fails', []),
('add_gids', []),
('timestamps', []),
('durstamps', []),
('trigstamps', []),
('eye_x', []),
('eye_y', [])])
DEFAULTS['events'] = dict([('ord_id', None),
('blk_on', False),
('blk_off', False),
('track_on', False),
('track_off', False),
('fix_on', False),
('fix_off', False),
('grp_on', False),
('grp_off', False),
('sids', set())])
def __init__(self, **keywords):
"""Creates the RunState."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
def start(self):
"""Initialize all subsystems and start the run."""
if self.disp_ops == None:
msg = "RunState lacks display options"
raise ValueError(msg)
if min(self.res, self.fps, self.bg,
self.cross_cols, self.cross_times) == None:
msg = "RunState intialized with insufficent project information"
raise ValueError(msg)
self._count = 0
self._old_code = 0
self.ord_id = None
self.terminate = False
# Flag used by freqcheck
self.fc_send = False
# Create fixation crosses
self.show_cross = True
self.fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if self.disp_ops['phototest']:
self.test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Initialize export
if self.disp_ops['export']:
if not os.path.isdir(self.disp_ops['expo_dir']):
msg = 'export path is not a directory'
raise IOError(msg)
if self.disp_ops['folder']:
self.save_dir = os.path.join(self.disp_ops['expo_dir'],
self.name + EXPORT_DIR_SUFFIX)
else:
self.save_dir = self.disp_ops['expo_dir']
if not os.path.isdir(self.save_dir):
os.mkdir(self.save_dir)
# Initialize ports
if self.disp_ops['trigser']:
if not trigger.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trigpar']:
if not trigger.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
trigger.init(self.disp_ops['trigser'], self.disp_ops['trigpar'])
# Initialize eyetracking
if self.disp_ops['eyetrack']:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trybreak'] == None:
self.disp_ops['trybreak'] = len(self.order)
self.fixated = False
self.old_fixated = False
self.tracked = False
self.old_tracked = False
self.fix_fail = False
self.true_fail = False
eyetracking.select_source(self.disp_ops['etuser'],
self.disp_ops['etvideo'])
eyetracking.start()
# Create window if not exporting
self.scaling = False
if not self.disp_ops['export']:
# Stretch to fit screen only if project res does not
# equal screen res
if self.disp_ops['fullscreen']:
self.window = pyglet.window.Window(fullscreen=True,
visible=False)
if (self.window.width, self.window.height) != self.res:
self.scaling = True
else:
self.window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
self.keystates = pyglet.window.key.KeyStateHandler()
self.window.push_handlers(self.keystates)
# Clear window and make visible
self.window.switch_to()
graphics.set_clear_color(self.bg)
self.window.clear()
self.window.set_visible()
# Create framebuffer object for drawing unscaled or exported scene
if self.scaling or self.disp_ops['export']:
self.canvas = pyglet.image.Texture.create(*self.res)
self.fbo = graphics.Framebuffer(self.canvas)
self.fbo.start_render()
graphics.set_clear_color(self.bg)
self.fbo.clear()
# Set process priority
if self.disp_ops['priority'] != None:
try:
priority.set(self.disp_ops['priority'])
except ValueError:
priority.set(int(self.disp_ops['priority']))
except:
pass
# Start timers
if self.disp_ops['logtime']:
self.timer = Timer()
self.timer.start()
if self.disp_ops['logdur']:
self.dur = Timer()
self.dur.start()
def update(self):
"""Update the RunState."""
# Check for tracking and fixation
if self.disp_ops['eyetrack']:
eyetracking.poll_tracker()
self.old_tracked = self.tracked
self.tracked = (eyetracking.get_status(self.fps) != -1)
self.old_fixated = self.fixated
self.fixated = (eyetracking.get_status(self.fps) == 1)
if self.show_cross:
if self.fixated:
# Draw normal cross color if fixating
self.fix_crosses[0].draw()
elif self.tracked:
# Draw 2nd cross color if tracked, not fixating
self.fix_crosses[1].draw()
else:
# Draw 3rd cross color if untracked
self.fix_crosses[2].draw()
# Update eyetracking events
if self.tracked != self.old_tracked:
if self.tracked:
self.events['track_on'] = True
else:
self.events['track_off'] = True
if self.fixated != self.old_fixated:
if self.fixated:
self.events['fix_on'] = True
else:
self.events['fix_off'] = True
if self.events['grp_on']:
- if not self.fixated:
+ if self.tracked and not self.fixated:
self.events['fix_off'] = True
# Check for failure of trial
if self.tracked and not self.fixated:
self.fix_fail = True
else:
# Change cross color based on time
if self.show_cross:
if (self._count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
self.fix_crosses[0].draw()
else:
self.fix_crosses[1].draw()
if self.disp_ops['export']:
# Save current frame to file
savepath = os.path.join(
self.save_dir, '{0}{2}.{1}'.\
format(self.name, 'png',
repr(self._count).zfill(numdigits(self.frames-1))))
self.canvas.save(savepath)
else:
# Blit canvas to screen if necessary
if self.scaling:
self.fbo.end_render()
self.canvas.blit(0, 0)
self.window.switch_to()
self.window.dispatch_events()
self.window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to lists
if self.disp_ops['logtime']:
self.timestamps.append(self.timer.elapsed())
elif self.disp_ops['logdur']:
self.timestamps.append('')
if self.disp_ops['logdur']:
self.durstamps.append(self.dur.restart())
elif self.disp_ops['logtime']:
self.durstamps.append('')
# Send trigger ASAP after flip
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
if self.encode_events() != self._old_code:
trigger.send(self.disp_ops['trigser'],
self.disp_ops['trigpar'],
self.encode_events())
self._old_code = self.encode_events
# Log eye positions and when triggers are sent
if self.disp_ops['logtime']:
if self.disp_ops['eyetrack']:
self.eye_x.append(eyetracking.x_pos())
self.eye_y.append(eyetracking.y_pos())
else:
self.eye_x.append('')
self.eye_y.append('')
if self.encode_events() > 0:
self.trigstamps.append(self.encode_events())
else:
self.trigstamps.append('')
# Clear canvas, events, prepare for next frame
if self.disp_ops['export']:
self.fbo.clear()
else:
if self.scaling:
self.fbo.start_render()
self.fbo.clear()
else:
self.window.clear()
if self.window.has_exit:
self.terminate = True
# Send ord_id immediately after blk_on
send_ord_id_next = self.events['blk_on']
self.events = copy.deepcopy(self.__class__.DEFAULTS['events'])
if send_ord_id_next:
self.events['ord_id'] = self.ord_id
self._count += 1
# Terminate export if the time has come
if self.disp_ops['export']:
if self._count >= self.frames:
self.terminate = True
def stop(self):
"""Clean up RunState."""
if self.disp_ops['eyetrack']:
eyetracking.stop()
if self.scaling or self.disp_ops['export']:
self.fbo.delete()
del self.canvas
if not self.disp_ops['export']:
self.window.close()
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
trigger.quit(self.disp_ops['trigser'], self.disp_ops['trigpar'])
try:
priority.set('normal')
except:
pass
def encode_events(self):
"""Hard code specific trigger values for events."""
code = 0
if self.events['ord_id'] != None:
code = self.events['ord_id'] + 1
elif self.events['blk_on']:
code = 128
elif self.events['blk_off']:
code = 127
else:
et_state = 0
if self.events['fix_on']:
et_state = 4
elif self.events['track_on']:
et_state = 2
if self.events['track_off']:
et_state = 1
elif self.events['fix_off']:
et_state = 2
if self.events['grp_on']:
code = 100 + et_state
elif self.events['grp_off']:
code = 90 + et_state
elif et_state > 0:
code = 110 + et_state
elif len(self.events['sids']) > 0:
code = ((0 in self.events['sids'])*2**0 +
(1 in self.events['sids'])*2**1 +
(2 in self.events['sids'])*2**2 +
(3 in self.events['sids'])*2**3 +
16)
return code
def log(self, path=None):
"""Write a log file for the experimental run in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, LOG_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(LOG_FMT):
path = '{0}.{1}'.format(path, LOG_FMT)
with open(path, 'wb') as logfile:
writer = csv.writer(logfile, dialect='excel-tab')
writer.writerow(['checkergen log file'])
writer.writerow(['display options:'])
writer.writerow(self.disp_ops.keys())
writer.writerow(self.disp_ops.values())
writer.writerow(['order:'] + self.order)
writer.writerow(['groups', 'failure'])
if not self.disp_ops['eyetrack']:
self.fails = ['NA'] * len(self.gids)
for i in zip(self.gids, self.fails):
writer.writerow(list(i))
if self.disp_ops['eyetrack']:
writer.writerow(['groups added'])
for blk in grouper(self.add_gids,
self.disp_ops['trybreak'], ''):
writer.writerow(blk)
if self.disp_ops['logtime'] or self.disp_ops['logdur']:
stamps = [self.timestamps, self.durstamps, self.trigstamps,
self.eye_x, self.eye_y]
writer.writerow(['timestamps', 'durations', 'triggers',
'eye x (mm)', 'eye y (mm)'])
for stamp in zip(*stamps):
writer.writerow(list(stamp))
class CkgDisplayGroup:
DEFAULTS = OrderedDict([('pre', 0),
('disp', 'Infinity'),
('post', 0),
('pre_cross', [(0, True)]),
('post_cross', [(0, True)])])
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
pre_cross -- key-value pairs specifying at what times during the pre
period a cross should be shown (e.g. [(0, False), (2, True)]
means that a cross is not shown at the start, but is shown
from 2 seconds onwards)
post_cross -- key-value pairs specifying at what times during the post
period a cross should be shown
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in ['pre', 'disp', 'post']:
value = to_decimal(value)
elif name in ['pre_cross', 'post_cross']:
value = [(to_decimal(k), to_bool(v)) for (k, v) in value]
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets counts and all contained shapes."""
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, runstate):
"""Draws all contained shapes during the appropriate interval."""
for shape in self.shapes:
shape.draw(photoburst=runstate.disp_ops['photoburst'])
def update(self, runstate):
"""Updates contained shapes, sets event triggers."""
# Set events to be sent
if runstate.disp_ops['fpst'] > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= runstate.disp_ops['fpst']:
if not runstate.disp_ops['freqcheck'] or runstate.fc_send:
runstate.events['sids'].add(n)
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(runstate.fps)
def display(self, runstate):
"""Display the group in the context described by supplied runstate."""
self.reset()
for count in range(self.pre * runstate.fps):
if runstate.terminate:
break
pre_time = to_decimal(count) / runstate.fps
if pre_time in dict(self.pre_cross):
runstate.show_cross = dict(self.pre_cross)[pre_time]
runstate.update()
runstate.events['grp_on'] = True
runstate.show_cross = True
if runstate.disp_ops['eyetrack']:
runstate.fix_fail = False
runstate.true_fail = False
for count in range(self.disp * runstate.fps):
if runstate.terminate:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
runstate.events['grp_off'] = True
if runstate.disp_ops['eyetrack']:
if runstate.fix_fail:
runstate.true_fail = True
for count in range(self.post * runstate.fps):
if runstate.terminate:
break
post_time = to_decimal(count) / runstate.fps
if post_time in dict(self.post_cross):
runstate.show_cross = dict(self.post_cross)[post_time]
runstate.update()
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.steps_done = 0
def draw(self, runstate):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, runstate):
"""Checks for keypress, sends trigger upon end."""
if max([runstate.keystates[key] for
key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
def display(self, runstate):
"""Displays waitscreen in context described by supplied runstate."""
runstate.show_cross = True
while self.steps_done < self.num_steps:
if runstate.terminate:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = OrderedDict([('dims', (5, 5)),
('init_unit', (30, 30)),
('end_unit', (50, 50)),
('position', (0, 0)),
('anchor', 'bottomleft'),
('cols', ((0, 0, 0), (255, 255, 255))),
('freq', 1),
('phase', 0)])
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
if INT_HALF_PERIODS:
frames_per_half_period = round(fps / (self.freq * 2))
degs_per_frame = 180 / to_decimal(frames_per_half_period)
else:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
|
ztangent/checkergen
|
3dd8fc7a5112738123d05fed606c8e0464378cee
|
Fix eyetracking logic once and for all..
|
diff --git a/src/eyetracking.py b/src/eyetracking.py
index 4407e79..ae402c5 100644
--- a/src/eyetracking.py
+++ b/src/eyetracking.py
@@ -1,201 +1,200 @@
"""Provides support for CRS VideoEyetracker Toolbox."""
import os.path
from utils import *
FIX_POS = (0, 0)
FIX_RANGE = (20, 20)
PERIOD = 300
try:
import win32com.client
available = True
except ImportError:
available = False
# COM ProgID of the Toolbox
ProgID = "crsVET.VideoEyeTracker"
RecordName = "etResultSet"
# VET application object
VET = None
class EyetrackingError(Exception):
"""Raised when something goes wrong with VET."""
pass
if available:
# Try dispatching object, else unavailable
try:
from win32com.client import gencache
# Ensure makepy module is generated
gencache.EnsureModule('{248DBF0C-A874-4032-82CE-DC5B307BB6E7}',
0, 3, 11)
VET = win32com.client.Dispatch(ProgID)
DummyResultSet = win32com.client.Record(RecordName, VET)
except:
available = False
if available:
# For easier access to constants and standardization with MATLAB interface
CRS = win32com.client.constants
data = None
last_status = -1
new_status = -1
count = 0
def select_source(user_select = False, path = None):
if user_select:
if not VET.SelectVideoSource(CRS.vsUserSelect, ''):
msg = 'could not select video source'
raise EyetrackingError(msg)
elif path != None:
# Open from file
if not VET.SelectVideoSource(CRS.vsFile, path):
msg = 'could not use path as video source'
raise EyetrackingError(msg)
else:
# Default to 250 Hz High Speed Camera
if not VET.SelectVideoSource(CRS.vsHighSpeedCamera250, ''):
msg = 'could not select video source'
raise EyetrackingError(msg)
def is_source_ready():
"""Returns true if a video source has been selected."""
if VET.VideoSourceType == 0:
return False
else:
return True
def show_camera():
VET.CreateCameraScreen(0)
def quit_camera():
VET.DestroyCameraScreen()
def setup(viewing_distance=None, screen_dims=None,
fixation_period=None, fixation_range=None):
"""Calibrates the display and sets fixation properties."""
if viewing_distance != None and screen_dims != None:
if len(screen_dims) != 2:
msg = 'screen_dims must be a 2-tuple'
raise ValueError(msg)
VET.SetDeviceParameters(CRS.deUser, viewing_distance,
screen_dims[0], screen_dims[1])
if fixation_period != None:
VET.FixationPeriod = fixation_period
if fixation_range != None:
VET.FixationRange = fixation_range
def calibrate(path = None):
"""Calibrate the subject.
Optionally supply a path with no spaces to a
calibration file to load."""
if not is_source_ready():
select_source()
if not VET.Tracking:
VET.ClearDataBuffer()
VET.StartTracking()
if path == None:
if not VET.Calibrate():
msg = 'calibration failed'
raise EyetrackingError(msg)
else:
if not os.path.isfile(path):
msg = 'specified file does not exist'
raise EyetrackingError(msg)
if not VET.LoadCalibrationFile(path):
msg = 'file could not be loaded'
raise EyetrackingError(msg)
if not is_calibrated():
msg = 'calibration failed'
raise EyetrackingError(msg)
def is_calibrated():
if VET.CalibrationStatus()[0] != 0:
return True
else:
return False
def start():
"""Start tracking the eye."""
global data
global last_status
global new_status
global count
if not is_source_ready():
select_source()
if not is_calibrated():
msg = 'subject not yet calibrated'
raise EyetrackingError(msg)
data = None
last_status = -1
new_status = -1
count = 0
VET.ClearDataBuffer()
VET.StartTracking()
def stop():
"""Stop tracking the eye."""
VET.StopTracking()
def poll_tracker():
"""Poll tracker for tracking information."""
global data
data = VET.GetLatestEyePosition(DummyResultSet)[1]
def get_status(fps, period=PERIOD,
fix_pos=FIX_POS,
fix_range=FIX_RANGE):
"""Returns fixation/tracking status.
-1 for untracked, 0 for unfixated, 1 for fixated.
fps -- frames per second at which stimulus is running
period -- duration in milliseconds during which eye has to
maintain the same status in order for value returned
by this function to change
fix_pos -- (x, y) position of desired fixation location in mm
from center of screen
fix_range -- (width, height) of box surrounding fix_pos within
which fixation is allowed (in mm)
"""
global last_status
global new_status
global count
pos = (data.ScreenPositionXmm, data.ScreenPositionYmm)
diff = [abs(p - fp) for p, fp in zip(pos, fix_pos)]
if data.Tracked == True:
if diff[0] < fix_range[0] and diff[1] < fix_range[1]:
cur_status = 1
else:
cur_status = 0
else:
cur_status = -1
- if cur_status == new_status:
+ if cur_status == new_status and cur_status != last_status:
count += 1
else:
count = 0
- if cur_status != last_status:
- new_status = cur_status
if count >= period / to_decimal(1000) * fps:
count = 0
- last_status = new_status
+ last_status = cur_status
+ new_status = cur_status
return last_status
def x_pos():
if data.Tracked:
return float(data.ScreenPositionXmm)
else:
return ''
def y_pos():
if data.Tracked:
return float(data.ScreenPositionYmm)
else:
return ''
|
ztangent/checkergen
|
479af8c76134102af9589120338194d6253f334c
|
Fixed eyetracking bug, tracking and fixation checking synchronized.
|
diff --git a/src/core.py b/src/core.py
index 536bd22..0a3b961 100755
--- a/src/core.py
+++ b/src/core.py
@@ -255,1027 +255,1027 @@ class CkgProj:
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
# Vars that are dicts
dicts_to_load = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_load = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
for d_name in dicts_to_load:
d = copy.deepcopy(self.__class__.DEFAULTS[d_name])
try:
d_el = [node for node in project.childNodes if
node.localName == d_name and
node.namespaceURI == XML_NAMESPACE][0]
for var in d.keys():
try:
d[var] = eval(xml_get(d_el, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}' in '{1}'".\
format(var, d_name)
print "using default value '{0}' instead...".\
format(d[var])
except IndexError:
print "warning: missing attribute set '{0}'".format(d_name)
print "using default values instead..."
setattr(self, d_name, d)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
# Vars that are dicts
dicts_to_save = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_save = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for d_name in dicts_to_save:
d_el = doc.createElement(d_name)
project.appendChild(d_el)
d = getattr(self, d_name)
for k, v in d.iteritems():
xml_set(doc, d_el, k, repr(v))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, **keywords):
"""Displays the stimulus on the screen.
name -- name that logfile will be saved with
repeats -- number of times specified order of display groups should
be repeated
waitless -- if true, no waitscreens will appear at the start of each
repeat
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
priority -- priority level to which process should be raised
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
trigser -- send triggers through serial port when each group is shown
trigpar -- send triggers through parallel port when each group is shown
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
freqcheck -- send fpst only at the start, the middle, and the end
for sanity checking of display and trigger fps
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- append a wait screen to the group queue every time
after this many groups have been appended to the queue
order -- order in which groups (specified by id) will be displayed
"""
# Create RunState
disp_ops = copy.deepcopy(self.disp_ops)
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'name' in keywords.keys() and keywords['name'] != None:
name = keywords['name']
else:
timestr = datetime.today().strftime('_%Y-%m-%d_%H-%M-%S')
name = self.name + timestr
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
waitscreen = CkgWaitScreen()
# Set runstate order id if necessary
if order in self.orders:
runstate.ord_id = self.orders.index(order)
# Count through pre
for count in range(self.pre * self.fps):
if runstate.terminate:
break
pre_time = to_decimal(count) / runstate.fps
if pre_time in dict(self.pre_cross):
runstate.show_cross = dict(self.pre_cross)[pre_time]
runstate.update()
# Loop through repeats
repeats = runstate.disp_ops['repeats']
ord_len = len(runstate.order)
for i in range(repeats):
# Restart eyetracking
if runstate.disp_ops['eyetrack']:
eyetracking.stop()
eyetracking.start()
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
# Loop through display groups
runstate.events['blk_on'] = True
for n, gid in enumerate(runstate.order):
# Set flag for freqcheck
if runstate.disp_ops['freqcheck']:
if ((i == 0 and n == 0) or
(i == repeats-1 and n == ord_len-1) or
(i == repeats//2 and n == ord_len//2)):
runstate.fc_send = True
else:
runstate.fc_send = False
if gid == -1:
waitscreen.reset()
waitscreen.display(runstate)
else:
self.groups[gid].display(runstate)
if not runstate.terminate:
# Append group id and fail state
runstate.gids.append(gid)
if runstate.disp_ops['eyetrack']:
runstate.fails.append(runstate.true_fail)
# Append groups to be added
if runstate.true_fail:
if (len(runstate.add_gids) <
runstate.disp_ops['tryagain']):
runstate.add_gids.append(gid)
runstate.events['blk_off'] = True
# Stop freqcheck before added groups
if runstate.disp_ops['freqcheck']:
runstate.fc_send = False
# Loop through added groups
if runstate.disp_ops['eyetrack']:
for blk in grouper(runstate.add_gids,
runstate.disp_ops['trybreak']):
# Restart eyetracking
if runstate.disp_ops['eyetrack']:
eyetracking.stop()
eyetracking.start()
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
runstate.events['blk_on'] = True
# Loop through display groups
for gid in blk:
if gid != None:
self.groups[gid].display(runstate)
if not runstate.terminate:
# Append group id and fail state
runstate.gids.append(gid)
if runstate.disp_ops['eyetrack']:
runstate.fails.append(runstate.true_fail)
runstate.events['blk_off'] = True
# Count through post
for count in range(self.post * self.fps):
if runstate.terminate:
break
post_time = to_decimal(count) / runstate.fps
if post_time in dict(self.post_cross):
runstate.show_cross = dict(self.post_cross)[post_time]
runstate.update()
# Stop and output log
runstate.stop()
if not runstate.disp_ops['nolog']:
runstate.log()
def export(self, **keywords):
"""Exports the stimulus as a series of images, one image per frame.
repeats -- number of times specified order of display groups should
be repeated
order -- order in which groups (specified by id) will be displayed
expo_dir -- directory to which images will be exported
expo_dur -- time in seconds to which export will be limited
folder -- if true, images will be contained in a separate folder
within export directory
force -- force export to go through even if a large number
of frames are to be exported
"""
# Create RunState
disp_ops = copy.deepcopy(self.__class__.DEFAULTS['disp_ops'])
disp_ops['export'] = True
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=self.name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
# Warn user if a lot of frames will be exported
if 'force' not in keywords.keys():
keywords['force'] = False
groups_dur = sum([self.groups[i].duration()
for i in order]) * disp_ops['repeats']
total_frames = (self.pre + groups_dur + self.post) * self.fps
frames = min(total_frames, disp_ops['expo_dur'] * self.fps)
if frames > MAX_EXPORT_FRAMES and not keywords['force']:
msg = 'large number ({0}) of frames to be exported'.\
format(int(frames))
raise FrameOverflowError(msg)
runstate.frames = frames
# Count through pre
for count in range(self.pre * self.fps):
if runstate.terminate:
break
runstate.update()
# Loop through repeats
repeats = runstate.disp_ops['repeats']
for i in range(repeats):
# Loop through display groups
for n, gid in enumerate(runstate.order):
if gid != -1:
self.groups[gid].display(runstate)
# Count through post
for count in range(self.post * self.fps):
if runstate.terminate:
break
runstate.update()
# Stop runstate
runstate.stop()
class CkgRunState:
"""Contains information about the state of a checkergen project
when it is being displayed or exported."""
DEFAULTS = dict([('name', 'untitled'),
('res', None),
('fps', None),
('bg', None),
('cross_cols', None),
('cross_times', None),
('order', []),
('disp_ops', None),
('events', None),
('gids', []),
('fails', []),
('add_gids', []),
('timestamps', []),
('durstamps', []),
('trigstamps', []),
('eye_x', []),
('eye_y', [])])
DEFAULTS['events'] = dict([('ord_id', None),
('blk_on', False),
('blk_off', False),
('track_on', False),
('track_off', False),
('fix_on', False),
('fix_off', False),
('grp_on', False),
('grp_off', False),
('sids', set())])
def __init__(self, **keywords):
"""Creates the RunState."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
def start(self):
"""Initialize all subsystems and start the run."""
if self.disp_ops == None:
msg = "RunState lacks display options"
raise ValueError(msg)
if min(self.res, self.fps, self.bg,
self.cross_cols, self.cross_times) == None:
msg = "RunState intialized with insufficent project information"
raise ValueError(msg)
self._count = 0
self._old_code = 0
self.ord_id = None
self.terminate = False
# Flag used by freqcheck
self.fc_send = False
# Create fixation crosses
self.show_cross = True
self.fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if self.disp_ops['phototest']:
self.test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Initialize export
if self.disp_ops['export']:
if not os.path.isdir(self.disp_ops['expo_dir']):
msg = 'export path is not a directory'
raise IOError(msg)
if self.disp_ops['folder']:
self.save_dir = os.path.join(self.disp_ops['expo_dir'],
self.name + EXPORT_DIR_SUFFIX)
else:
self.save_dir = self.disp_ops['expo_dir']
if not os.path.isdir(self.save_dir):
os.mkdir(self.save_dir)
# Initialize ports
if self.disp_ops['trigser']:
if not trigger.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trigpar']:
if not trigger.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
trigger.init(self.disp_ops['trigser'], self.disp_ops['trigpar'])
# Initialize eyetracking
if self.disp_ops['eyetrack']:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trybreak'] == None:
self.disp_ops['trybreak'] = len(self.order)
self.fixated = False
self.old_fixated = False
self.tracked = False
self.old_tracked = False
self.fix_fail = False
self.true_fail = False
eyetracking.select_source(self.disp_ops['etuser'],
self.disp_ops['etvideo'])
eyetracking.start()
# Create window if not exporting
self.scaling = False
if not self.disp_ops['export']:
# Stretch to fit screen only if project res does not
# equal screen res
if self.disp_ops['fullscreen']:
self.window = pyglet.window.Window(fullscreen=True,
visible=False)
if (self.window.width, self.window.height) != self.res:
self.scaling = True
else:
self.window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
self.keystates = pyglet.window.key.KeyStateHandler()
self.window.push_handlers(self.keystates)
# Clear window and make visible
self.window.switch_to()
graphics.set_clear_color(self.bg)
self.window.clear()
self.window.set_visible()
# Create framebuffer object for drawing unscaled or exported scene
if self.scaling or self.disp_ops['export']:
self.canvas = pyglet.image.Texture.create(*self.res)
self.fbo = graphics.Framebuffer(self.canvas)
self.fbo.start_render()
graphics.set_clear_color(self.bg)
self.fbo.clear()
# Set process priority
if self.disp_ops['priority'] != None:
try:
priority.set(self.disp_ops['priority'])
except ValueError:
priority.set(int(self.disp_ops['priority']))
except:
pass
# Start timers
if self.disp_ops['logtime']:
self.timer = Timer()
self.timer.start()
if self.disp_ops['logdur']:
self.dur = Timer()
self.dur.start()
def update(self):
"""Update the RunState."""
# Check for tracking and fixation
if self.disp_ops['eyetrack']:
eyetracking.poll_tracker()
self.old_tracked = self.tracked
- self.tracked = eyetracking.is_tracked(self.fps)
+ self.tracked = (eyetracking.get_status(self.fps) != -1)
self.old_fixated = self.fixated
- self.fixated = eyetracking.is_fixated(self.fps)
+ self.fixated = (eyetracking.get_status(self.fps) == 1)
if self.show_cross:
if self.fixated:
# Draw normal cross color if fixating
self.fix_crosses[0].draw()
elif self.tracked:
# Draw 2nd cross color if tracked, not fixating
self.fix_crosses[1].draw()
else:
# Draw 3rd cross color if untracked
self.fix_crosses[2].draw()
# Update eyetracking events
if self.tracked != self.old_tracked:
if self.tracked:
self.events['track_on'] = True
else:
self.events['track_off'] = True
if self.fixated != self.old_fixated:
if self.fixated:
self.events['fix_on'] = True
else:
self.events['fix_off'] = True
if self.events['grp_on']:
if not self.fixated:
self.events['fix_off'] = True
# Check for failure of trial
if self.tracked and not self.fixated:
self.fix_fail = True
else:
# Change cross color based on time
if self.show_cross:
if (self._count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
self.fix_crosses[0].draw()
else:
self.fix_crosses[1].draw()
if self.disp_ops['export']:
# Save current frame to file
savepath = os.path.join(
self.save_dir, '{0}{2}.{1}'.\
format(self.name, 'png',
repr(self._count).zfill(numdigits(self.frames-1))))
self.canvas.save(savepath)
else:
# Blit canvas to screen if necessary
if self.scaling:
self.fbo.end_render()
self.canvas.blit(0, 0)
self.window.switch_to()
self.window.dispatch_events()
self.window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to lists
if self.disp_ops['logtime']:
self.timestamps.append(self.timer.elapsed())
elif self.disp_ops['logdur']:
self.timestamps.append('')
if self.disp_ops['logdur']:
self.durstamps.append(self.dur.restart())
elif self.disp_ops['logtime']:
self.durstamps.append('')
# Send trigger ASAP after flip
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
if self.encode_events() != self._old_code:
trigger.send(self.disp_ops['trigser'],
self.disp_ops['trigpar'],
self.encode_events())
self._old_code = self.encode_events
# Log eye positions and when triggers are sent
if self.disp_ops['logtime']:
if self.disp_ops['eyetrack']:
self.eye_x.append(eyetracking.x_pos())
self.eye_y.append(eyetracking.y_pos())
else:
self.eye_x.append('')
self.eye_y.append('')
if self.encode_events() > 0:
self.trigstamps.append(self.encode_events())
else:
self.trigstamps.append('')
# Clear canvas, events, prepare for next frame
if self.disp_ops['export']:
self.fbo.clear()
else:
if self.scaling:
self.fbo.start_render()
self.fbo.clear()
else:
self.window.clear()
if self.window.has_exit:
self.terminate = True
# Send ord_id immediately after blk_on
send_ord_id_next = self.events['blk_on']
self.events = copy.deepcopy(self.__class__.DEFAULTS['events'])
if send_ord_id_next:
self.events['ord_id'] = self.ord_id
self._count += 1
# Terminate export if the time has come
if self.disp_ops['export']:
if self._count >= self.frames:
self.terminate = True
def stop(self):
"""Clean up RunState."""
if self.disp_ops['eyetrack']:
eyetracking.stop()
if self.scaling or self.disp_ops['export']:
self.fbo.delete()
del self.canvas
if not self.disp_ops['export']:
self.window.close()
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
trigger.quit(self.disp_ops['trigser'], self.disp_ops['trigpar'])
try:
priority.set('normal')
except:
pass
def encode_events(self):
"""Hard code specific trigger values for events."""
code = 0
if self.events['ord_id'] != None:
code = self.events['ord_id'] + 1
elif self.events['blk_on']:
code = 128
elif self.events['blk_off']:
code = 127
else:
et_state = 0
if self.events['fix_on']:
et_state = 4
elif self.events['track_on']:
et_state = 2
if self.events['track_off']:
et_state = 1
elif self.events['fix_off']:
et_state = 2
if self.events['grp_on']:
code = 100 + et_state
elif self.events['grp_off']:
code = 90 + et_state
elif et_state > 0:
code = 110 + et_state
elif len(self.events['sids']) > 0:
code = ((0 in self.events['sids'])*2**0 +
(1 in self.events['sids'])*2**1 +
(2 in self.events['sids'])*2**2 +
(3 in self.events['sids'])*2**3 +
16)
return code
def log(self, path=None):
"""Write a log file for the experimental run in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, LOG_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(LOG_FMT):
path = '{0}.{1}'.format(path, LOG_FMT)
with open(path, 'wb') as logfile:
writer = csv.writer(logfile, dialect='excel-tab')
writer.writerow(['checkergen log file'])
writer.writerow(['display options:'])
writer.writerow(self.disp_ops.keys())
writer.writerow(self.disp_ops.values())
writer.writerow(['order:'] + self.order)
writer.writerow(['groups', 'failure'])
if not self.disp_ops['eyetrack']:
self.fails = ['NA'] * len(self.gids)
for i in zip(self.gids, self.fails):
writer.writerow(list(i))
if self.disp_ops['eyetrack']:
writer.writerow(['groups added'])
for blk in grouper(self.add_gids,
self.disp_ops['trybreak'], ''):
writer.writerow(blk)
if self.disp_ops['logtime'] or self.disp_ops['logdur']:
stamps = [self.timestamps, self.durstamps, self.trigstamps,
self.eye_x, self.eye_y]
writer.writerow(['timestamps', 'durations', 'triggers',
'eye x (mm)', 'eye y (mm)'])
for stamp in zip(*stamps):
writer.writerow(list(stamp))
class CkgDisplayGroup:
DEFAULTS = OrderedDict([('pre', 0),
('disp', 'Infinity'),
('post', 0),
('pre_cross', [(0, True)]),
('post_cross', [(0, True)])])
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
pre_cross -- key-value pairs specifying at what times during the pre
period a cross should be shown (e.g. [(0, False), (2, True)]
means that a cross is not shown at the start, but is shown
from 2 seconds onwards)
post_cross -- key-value pairs specifying at what times during the post
period a cross should be shown
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in ['pre', 'disp', 'post']:
value = to_decimal(value)
elif name in ['pre_cross', 'post_cross']:
value = [(to_decimal(k), to_bool(v)) for (k, v) in value]
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets counts and all contained shapes."""
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, runstate):
"""Draws all contained shapes during the appropriate interval."""
for shape in self.shapes:
shape.draw(photoburst=runstate.disp_ops['photoburst'])
def update(self, runstate):
"""Updates contained shapes, sets event triggers."""
# Set events to be sent
if runstate.disp_ops['fpst'] > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= runstate.disp_ops['fpst']:
if not runstate.disp_ops['freqcheck'] or runstate.fc_send:
runstate.events['sids'].add(n)
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(runstate.fps)
def display(self, runstate):
"""Display the group in the context described by supplied runstate."""
self.reset()
for count in range(self.pre * runstate.fps):
if runstate.terminate:
break
pre_time = to_decimal(count) / runstate.fps
if pre_time in dict(self.pre_cross):
runstate.show_cross = dict(self.pre_cross)[pre_time]
runstate.update()
runstate.events['grp_on'] = True
runstate.show_cross = True
if runstate.disp_ops['eyetrack']:
runstate.fix_fail = False
runstate.true_fail = False
for count in range(self.disp * runstate.fps):
if runstate.terminate:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
runstate.events['grp_off'] = True
if runstate.disp_ops['eyetrack']:
if runstate.fix_fail:
runstate.true_fail = True
for count in range(self.post * runstate.fps):
if runstate.terminate:
break
post_time = to_decimal(count) / runstate.fps
if post_time in dict(self.post_cross):
runstate.show_cross = dict(self.post_cross)[post_time]
runstate.update()
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.steps_done = 0
def draw(self, runstate):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, runstate):
"""Checks for keypress, sends trigger upon end."""
if max([runstate.keystates[key] for
key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
def display(self, runstate):
"""Displays waitscreen in context described by supplied runstate."""
runstate.show_cross = True
while self.steps_done < self.num_steps:
if runstate.terminate:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = OrderedDict([('dims', (5, 5)),
('init_unit', (30, 30)),
('end_unit', (50, 50)),
('position', (0, 0)),
('anchor', 'bottomleft'),
('cols', ((0, 0, 0), (255, 255, 255))),
('freq', 1),
('phase', 0)])
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
if INT_HALF_PERIODS:
frames_per_half_period = round(fps / (self.freq * 2))
degs_per_frame = 180 / to_decimal(frames_per_half_period)
else:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
diff --git a/src/eyetracking.py b/src/eyetracking.py
index 7f59a31..4407e79 100644
--- a/src/eyetracking.py
+++ b/src/eyetracking.py
@@ -1,215 +1,201 @@
"""Provides support for CRS VideoEyetracker Toolbox."""
import os.path
from utils import *
FIX_POS = (0, 0)
FIX_RANGE = (20, 20)
-FIX_PER = 300
-TRACK_PER = 300
+PERIOD = 300
try:
import win32com.client
available = True
except ImportError:
available = False
# COM ProgID of the Toolbox
ProgID = "crsVET.VideoEyeTracker"
RecordName = "etResultSet"
# VET application object
VET = None
class EyetrackingError(Exception):
"""Raised when something goes wrong with VET."""
pass
if available:
# Try dispatching object, else unavailable
try:
from win32com.client import gencache
# Ensure makepy module is generated
gencache.EnsureModule('{248DBF0C-A874-4032-82CE-DC5B307BB6E7}',
0, 3, 11)
VET = win32com.client.Dispatch(ProgID)
DummyResultSet = win32com.client.Record(RecordName, VET)
except:
available = False
if available:
# For easier access to constants and standardization with MATLAB interface
CRS = win32com.client.constants
data = None
- lastfixstatus = 0
- newfixstatus = 0
- fixcount = 0
- lasttrackstatus = False
- trackcount = 0
+ last_status = -1
+ new_status = -1
+ count = 0
def select_source(user_select = False, path = None):
if user_select:
if not VET.SelectVideoSource(CRS.vsUserSelect, ''):
msg = 'could not select video source'
raise EyetrackingError(msg)
elif path != None:
# Open from file
if not VET.SelectVideoSource(CRS.vsFile, path):
msg = 'could not use path as video source'
raise EyetrackingError(msg)
else:
# Default to 250 Hz High Speed Camera
if not VET.SelectVideoSource(CRS.vsHighSpeedCamera250, ''):
msg = 'could not select video source'
raise EyetrackingError(msg)
def is_source_ready():
"""Returns true if a video source has been selected."""
if VET.VideoSourceType == 0:
return False
else:
return True
def show_camera():
VET.CreateCameraScreen(0)
def quit_camera():
VET.DestroyCameraScreen()
def setup(viewing_distance=None, screen_dims=None,
fixation_period=None, fixation_range=None):
"""Calibrates the display and sets fixation properties."""
if viewing_distance != None and screen_dims != None:
if len(screen_dims) != 2:
msg = 'screen_dims must be a 2-tuple'
raise ValueError(msg)
VET.SetDeviceParameters(CRS.deUser, viewing_distance,
screen_dims[0], screen_dims[1])
if fixation_period != None:
VET.FixationPeriod = fixation_period
if fixation_range != None:
VET.FixationRange = fixation_range
def calibrate(path = None):
"""Calibrate the subject.
Optionally supply a path with no spaces to a
calibration file to load."""
if not is_source_ready():
select_source()
if not VET.Tracking:
VET.ClearDataBuffer()
VET.StartTracking()
if path == None:
if not VET.Calibrate():
msg = 'calibration failed'
raise EyetrackingError(msg)
else:
if not os.path.isfile(path):
msg = 'specified file does not exist'
raise EyetrackingError(msg)
if not VET.LoadCalibrationFile(path):
msg = 'file could not be loaded'
raise EyetrackingError(msg)
if not is_calibrated():
msg = 'calibration failed'
raise EyetrackingError(msg)
def is_calibrated():
if VET.CalibrationStatus()[0] != 0:
return True
else:
return False
def start():
"""Start tracking the eye."""
+ global data
+ global last_status
+ global new_status
+ global count
if not is_source_ready():
select_source()
if not is_calibrated():
msg = 'subject not yet calibrated'
raise EyetrackingError(msg)
+ data = None
+ last_status = -1
+ new_status = -1
+ count = 0
VET.ClearDataBuffer()
VET.StartTracking()
def stop():
"""Stop tracking the eye."""
VET.StopTracking()
def poll_tracker():
"""Poll tracker for tracking information."""
global data
data = VET.GetLatestEyePosition(DummyResultSet)[1]
- def is_tracked(fps, track_period=TRACK_PER):
- """Returns true if the eye is being tracked.
+ def get_status(fps, period=PERIOD,
+ fix_pos=FIX_POS,
+ fix_range=FIX_RANGE):
+ """Returns fixation/tracking status.
+ -1 for untracked, 0 for unfixated, 1 for fixated.
fps -- frames per second at which stimulus is running
- track_period -- duration in milliseconds during which eye has to
- be consistently tracked or untracked in order for value returned
+ period -- duration in milliseconds during which eye has to
+ maintain the same status in order for value returned
by this function to change
- """
- global lasttrackstatus
- global trackcount
- if data.Tracked != lasttrackstatus:
- trackcount += 1
- else:
- trackcount = 0
- if trackcount >= track_period / to_decimal(1000) * fps:
- trackcount = 0
- lasttrackstatus = data.Tracked
- return lasttrackstatus
-
- def is_fixated(fps, fix_pos=FIX_POS,
- fix_range=FIX_RANGE,
- fix_period=FIX_PER):
- """Checks whether subject is fixating on specified location.
-
- fps -- frames per second at which stimulus is running
-
fix_pos -- (x, y) position of desired fixation location in mm
from center of screen
fix_range -- (width, height) of box surrounding fix_pos within
which fixation is allowed (in mm)
- fix_period -- duration in milliseconds during which eye has to
- be consistently fixated or not fixated in order for value returned
- by this function to change
-
"""
- global lastfixstatus
- global newfixstatus
- global fixcount
+ global last_status
+ global new_status
+ global count
pos = (data.ScreenPositionXmm, data.ScreenPositionYmm)
diff = [abs(p - fp) for p, fp in zip(pos, fix_pos)]
- curfixstatus = -1
if data.Tracked == True:
if diff[0] < fix_range[0] and diff[1] < fix_range[1]:
- curfixstatus = 1
+ cur_status = 1
else:
- curfixstatus = 0
- if curfixstatus == newfixstatus:
- fixcount += 1
+ cur_status = 0
+ else:
+ cur_status = -1
+ if cur_status == new_status:
+ count += 1
else:
- fixcount = 0
- if curfixstatus != lastfixstatus:
- newfixstatus = curfixstatus
- if fixcount >= fix_period / to_decimal(1000) * fps:
- fixcount = 0
- lastfixstatus = newfixstatus
- return (lastfixstatus == 1)
+ count = 0
+ if cur_status != last_status:
+ new_status = cur_status
+ if count >= period / to_decimal(1000) * fps:
+ count = 0
+ last_status = new_status
+ return last_status
def x_pos():
if data.Tracked:
return float(data.ScreenPositionXmm)
else:
return ''
def y_pos():
if data.Tracked:
return float(data.ScreenPositionYmm)
else:
return ''
|
ztangent/checkergen
|
23345e5d825e3940aca56f9a34c21d4002c8c551
|
Improved fixation detection, poll eyetracker once per frame only.
|
diff --git a/src/core.py b/src/core.py
index f070248..536bd22 100755
--- a/src/core.py
+++ b/src/core.py
@@ -253,1051 +253,1055 @@ class CkgProj:
self.orders = orders
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
# Vars that are dicts
dicts_to_load = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_load = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
for d_name in dicts_to_load:
d = copy.deepcopy(self.__class__.DEFAULTS[d_name])
try:
d_el = [node for node in project.childNodes if
node.localName == d_name and
node.namespaceURI == XML_NAMESPACE][0]
for var in d.keys():
try:
d[var] = eval(xml_get(d_el, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}' in '{1}'".\
format(var, d_name)
print "using default value '{0}' instead...".\
format(d[var])
except IndexError:
print "warning: missing attribute set '{0}'".format(d_name)
print "using default values instead..."
setattr(self, d_name, d)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
# Vars that are dicts
dicts_to_save = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_save = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for d_name in dicts_to_save:
d_el = doc.createElement(d_name)
project.appendChild(d_el)
d = getattr(self, d_name)
for k, v in d.iteritems():
xml_set(doc, d_el, k, repr(v))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, **keywords):
"""Displays the stimulus on the screen.
name -- name that logfile will be saved with
repeats -- number of times specified order of display groups should
be repeated
waitless -- if true, no waitscreens will appear at the start of each
repeat
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
priority -- priority level to which process should be raised
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
trigser -- send triggers through serial port when each group is shown
trigpar -- send triggers through parallel port when each group is shown
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
freqcheck -- send fpst only at the start, the middle, and the end
for sanity checking of display and trigger fps
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- append a wait screen to the group queue every time
after this many groups have been appended to the queue
order -- order in which groups (specified by id) will be displayed
"""
# Create RunState
disp_ops = copy.deepcopy(self.disp_ops)
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'name' in keywords.keys() and keywords['name'] != None:
name = keywords['name']
else:
timestr = datetime.today().strftime('_%Y-%m-%d_%H-%M-%S')
name = self.name + timestr
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
waitscreen = CkgWaitScreen()
# Set runstate order id if necessary
if order in self.orders:
runstate.ord_id = self.orders.index(order)
# Count through pre
for count in range(self.pre * self.fps):
if runstate.terminate:
break
pre_time = to_decimal(count) / runstate.fps
if pre_time in dict(self.pre_cross):
runstate.show_cross = dict(self.pre_cross)[pre_time]
runstate.update()
# Loop through repeats
repeats = runstate.disp_ops['repeats']
ord_len = len(runstate.order)
for i in range(repeats):
# Restart eyetracking
if runstate.disp_ops['eyetrack']:
eyetracking.stop()
eyetracking.start()
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
# Loop through display groups
runstate.events['blk_on'] = True
for n, gid in enumerate(runstate.order):
# Set flag for freqcheck
if runstate.disp_ops['freqcheck']:
if ((i == 0 and n == 0) or
(i == repeats-1 and n == ord_len-1) or
(i == repeats//2 and n == ord_len//2)):
runstate.fc_send = True
else:
runstate.fc_send = False
if gid == -1:
waitscreen.reset()
waitscreen.display(runstate)
else:
self.groups[gid].display(runstate)
if not runstate.terminate:
# Append group id and fail state
runstate.gids.append(gid)
if runstate.disp_ops['eyetrack']:
runstate.fails.append(runstate.true_fail)
# Append groups to be added
if runstate.true_fail:
if (len(runstate.add_gids) <
runstate.disp_ops['tryagain']):
runstate.add_gids.append(gid)
runstate.events['blk_off'] = True
# Stop freqcheck before added groups
if runstate.disp_ops['freqcheck']:
runstate.fc_send = False
# Loop through added groups
if runstate.disp_ops['eyetrack']:
for blk in grouper(runstate.add_gids,
runstate.disp_ops['trybreak']):
# Restart eyetracking
if runstate.disp_ops['eyetrack']:
eyetracking.stop()
eyetracking.start()
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
runstate.events['blk_on'] = True
# Loop through display groups
for gid in blk:
if gid != None:
self.groups[gid].display(runstate)
if not runstate.terminate:
# Append group id and fail state
runstate.gids.append(gid)
if runstate.disp_ops['eyetrack']:
runstate.fails.append(runstate.true_fail)
runstate.events['blk_off'] = True
# Count through post
for count in range(self.post * self.fps):
if runstate.terminate:
break
post_time = to_decimal(count) / runstate.fps
if post_time in dict(self.post_cross):
runstate.show_cross = dict(self.post_cross)[post_time]
runstate.update()
# Stop and output log
runstate.stop()
if not runstate.disp_ops['nolog']:
runstate.log()
def export(self, **keywords):
"""Exports the stimulus as a series of images, one image per frame.
repeats -- number of times specified order of display groups should
be repeated
order -- order in which groups (specified by id) will be displayed
expo_dir -- directory to which images will be exported
expo_dur -- time in seconds to which export will be limited
folder -- if true, images will be contained in a separate folder
within export directory
force -- force export to go through even if a large number
of frames are to be exported
"""
# Create RunState
disp_ops = copy.deepcopy(self.__class__.DEFAULTS['disp_ops'])
disp_ops['export'] = True
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=self.name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
# Warn user if a lot of frames will be exported
if 'force' not in keywords.keys():
keywords['force'] = False
groups_dur = sum([self.groups[i].duration()
for i in order]) * disp_ops['repeats']
total_frames = (self.pre + groups_dur + self.post) * self.fps
frames = min(total_frames, disp_ops['expo_dur'] * self.fps)
if frames > MAX_EXPORT_FRAMES and not keywords['force']:
msg = 'large number ({0}) of frames to be exported'.\
format(int(frames))
raise FrameOverflowError(msg)
runstate.frames = frames
# Count through pre
for count in range(self.pre * self.fps):
if runstate.terminate:
break
runstate.update()
# Loop through repeats
repeats = runstate.disp_ops['repeats']
for i in range(repeats):
# Loop through display groups
for n, gid in enumerate(runstate.order):
if gid != -1:
self.groups[gid].display(runstate)
# Count through post
for count in range(self.post * self.fps):
if runstate.terminate:
break
runstate.update()
# Stop runstate
runstate.stop()
class CkgRunState:
"""Contains information about the state of a checkergen project
when it is being displayed or exported."""
DEFAULTS = dict([('name', 'untitled'),
('res', None),
('fps', None),
('bg', None),
('cross_cols', None),
('cross_times', None),
('order', []),
('disp_ops', None),
('events', None),
('gids', []),
('fails', []),
('add_gids', []),
('timestamps', []),
('durstamps', []),
('trigstamps', []),
('eye_x', []),
('eye_y', [])])
DEFAULTS['events'] = dict([('ord_id', None),
('blk_on', False),
('blk_off', False),
('track_on', False),
('track_off', False),
('fix_on', False),
('fix_off', False),
('grp_on', False),
('grp_off', False),
('sids', set())])
def __init__(self, **keywords):
"""Creates the RunState."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
def start(self):
"""Initialize all subsystems and start the run."""
if self.disp_ops == None:
msg = "RunState lacks display options"
raise ValueError(msg)
if min(self.res, self.fps, self.bg,
self.cross_cols, self.cross_times) == None:
msg = "RunState intialized with insufficent project information"
raise ValueError(msg)
self._count = 0
self._old_code = 0
self.ord_id = None
self.terminate = False
# Flag used by freqcheck
self.fc_send = False
# Create fixation crosses
self.show_cross = True
self.fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if self.disp_ops['phototest']:
self.test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Initialize export
if self.disp_ops['export']:
if not os.path.isdir(self.disp_ops['expo_dir']):
msg = 'export path is not a directory'
raise IOError(msg)
if self.disp_ops['folder']:
self.save_dir = os.path.join(self.disp_ops['expo_dir'],
self.name + EXPORT_DIR_SUFFIX)
else:
self.save_dir = self.disp_ops['expo_dir']
if not os.path.isdir(self.save_dir):
os.mkdir(self.save_dir)
# Initialize ports
if self.disp_ops['trigser']:
if not trigger.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trigpar']:
if not trigger.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
trigger.init(self.disp_ops['trigser'], self.disp_ops['trigpar'])
# Initialize eyetracking
if self.disp_ops['eyetrack']:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trybreak'] == None:
self.disp_ops['trybreak'] = len(self.order)
self.fixated = False
self.old_fixated = False
self.tracked = False
self.old_tracked = False
self.fix_fail = False
self.true_fail = False
eyetracking.select_source(self.disp_ops['etuser'],
self.disp_ops['etvideo'])
eyetracking.start()
# Create window if not exporting
self.scaling = False
if not self.disp_ops['export']:
# Stretch to fit screen only if project res does not
# equal screen res
if self.disp_ops['fullscreen']:
self.window = pyglet.window.Window(fullscreen=True,
visible=False)
if (self.window.width, self.window.height) != self.res:
self.scaling = True
else:
self.window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
self.keystates = pyglet.window.key.KeyStateHandler()
self.window.push_handlers(self.keystates)
# Clear window and make visible
self.window.switch_to()
graphics.set_clear_color(self.bg)
self.window.clear()
self.window.set_visible()
# Create framebuffer object for drawing unscaled or exported scene
if self.scaling or self.disp_ops['export']:
self.canvas = pyglet.image.Texture.create(*self.res)
self.fbo = graphics.Framebuffer(self.canvas)
self.fbo.start_render()
graphics.set_clear_color(self.bg)
self.fbo.clear()
# Set process priority
if self.disp_ops['priority'] != None:
try:
priority.set(self.disp_ops['priority'])
except ValueError:
priority.set(int(self.disp_ops['priority']))
except:
pass
# Start timers
if self.disp_ops['logtime']:
self.timer = Timer()
self.timer.start()
if self.disp_ops['logdur']:
self.dur = Timer()
self.dur.start()
def update(self):
"""Update the RunState."""
# Check for tracking and fixation
if self.disp_ops['eyetrack']:
+ eyetracking.poll_tracker()
self.old_tracked = self.tracked
self.tracked = eyetracking.is_tracked(self.fps)
self.old_fixated = self.fixated
self.fixated = eyetracking.is_fixated(self.fps)
if self.show_cross:
if self.fixated:
# Draw normal cross color if fixating
self.fix_crosses[0].draw()
elif self.tracked:
# Draw 2nd cross color if tracked, not fixating
self.fix_crosses[1].draw()
else:
# Draw 3rd cross color if untracked
self.fix_crosses[2].draw()
# Update eyetracking events
if self.tracked != self.old_tracked:
if self.tracked:
self.events['track_on'] = True
else:
self.events['track_off'] = True
if self.fixated != self.old_fixated:
if self.fixated:
self.events['fix_on'] = True
else:
self.events['fix_off'] = True
+ if self.events['grp_on']:
+ if not self.fixated:
+ self.events['fix_off'] = True
# Check for failure of trial
if self.tracked and not self.fixated:
self.fix_fail = True
else:
# Change cross color based on time
if self.show_cross:
if (self._count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
self.fix_crosses[0].draw()
else:
self.fix_crosses[1].draw()
if self.disp_ops['export']:
# Save current frame to file
savepath = os.path.join(
self.save_dir, '{0}{2}.{1}'.\
format(self.name, 'png',
repr(self._count).zfill(numdigits(self.frames-1))))
self.canvas.save(savepath)
else:
# Blit canvas to screen if necessary
if self.scaling:
self.fbo.end_render()
self.canvas.blit(0, 0)
self.window.switch_to()
self.window.dispatch_events()
self.window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to lists
if self.disp_ops['logtime']:
self.timestamps.append(self.timer.elapsed())
elif self.disp_ops['logdur']:
self.timestamps.append('')
if self.disp_ops['logdur']:
self.durstamps.append(self.dur.restart())
elif self.disp_ops['logtime']:
self.durstamps.append('')
# Send trigger ASAP after flip
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
if self.encode_events() != self._old_code:
trigger.send(self.disp_ops['trigser'],
self.disp_ops['trigpar'],
self.encode_events())
self._old_code = self.encode_events
# Log eye positions and when triggers are sent
if self.disp_ops['logtime']:
if self.disp_ops['eyetrack']:
self.eye_x.append(eyetracking.x_pos())
self.eye_y.append(eyetracking.y_pos())
else:
self.eye_x.append('')
self.eye_y.append('')
if self.encode_events() > 0:
self.trigstamps.append(self.encode_events())
else:
self.trigstamps.append('')
# Clear canvas, events, prepare for next frame
if self.disp_ops['export']:
self.fbo.clear()
else:
if self.scaling:
self.fbo.start_render()
self.fbo.clear()
else:
self.window.clear()
if self.window.has_exit:
self.terminate = True
# Send ord_id immediately after blk_on
send_ord_id_next = self.events['blk_on']
self.events = copy.deepcopy(self.__class__.DEFAULTS['events'])
if send_ord_id_next:
self.events['ord_id'] = self.ord_id
self._count += 1
# Terminate export if the time has come
if self.disp_ops['export']:
if self._count >= self.frames:
self.terminate = True
def stop(self):
"""Clean up RunState."""
if self.disp_ops['eyetrack']:
eyetracking.stop()
if self.scaling or self.disp_ops['export']:
self.fbo.delete()
del self.canvas
if not self.disp_ops['export']:
self.window.close()
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
trigger.quit(self.disp_ops['trigser'], self.disp_ops['trigpar'])
try:
priority.set('normal')
except:
pass
def encode_events(self):
"""Hard code specific trigger values for events."""
code = 0
if self.events['ord_id'] != None:
code = self.events['ord_id'] + 1
elif self.events['blk_on']:
code = 128
elif self.events['blk_off']:
code = 127
else:
et_state = 0
if self.events['fix_on']:
et_state = 4
elif self.events['track_on']:
et_state = 2
if self.events['track_off']:
et_state = 1
elif self.events['fix_off']:
et_state = 2
if self.events['grp_on']:
code = 100 + et_state
elif self.events['grp_off']:
code = 90 + et_state
elif et_state > 0:
code = 110 + et_state
elif len(self.events['sids']) > 0:
code = ((0 in self.events['sids'])*2**0 +
(1 in self.events['sids'])*2**1 +
(2 in self.events['sids'])*2**2 +
(3 in self.events['sids'])*2**3 +
16)
return code
def log(self, path=None):
"""Write a log file for the experimental run in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, LOG_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(LOG_FMT):
path = '{0}.{1}'.format(path, LOG_FMT)
with open(path, 'wb') as logfile:
writer = csv.writer(logfile, dialect='excel-tab')
writer.writerow(['checkergen log file'])
writer.writerow(['display options:'])
writer.writerow(self.disp_ops.keys())
writer.writerow(self.disp_ops.values())
writer.writerow(['order:'] + self.order)
writer.writerow(['groups', 'failure'])
if not self.disp_ops['eyetrack']:
self.fails = ['NA'] * len(self.gids)
for i in zip(self.gids, self.fails):
writer.writerow(list(i))
if self.disp_ops['eyetrack']:
writer.writerow(['groups added'])
for blk in grouper(self.add_gids,
self.disp_ops['trybreak'], ''):
writer.writerow(blk)
if self.disp_ops['logtime'] or self.disp_ops['logdur']:
stamps = [self.timestamps, self.durstamps, self.trigstamps,
self.eye_x, self.eye_y]
writer.writerow(['timestamps', 'durations', 'triggers',
'eye x (mm)', 'eye y (mm)'])
for stamp in zip(*stamps):
writer.writerow(list(stamp))
class CkgDisplayGroup:
DEFAULTS = OrderedDict([('pre', 0),
('disp', 'Infinity'),
('post', 0),
('pre_cross', [(0, True)]),
('post_cross', [(0, True)])])
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
pre_cross -- key-value pairs specifying at what times during the pre
period a cross should be shown (e.g. [(0, False), (2, True)]
means that a cross is not shown at the start, but is shown
from 2 seconds onwards)
post_cross -- key-value pairs specifying at what times during the post
period a cross should be shown
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in ['pre', 'disp', 'post']:
value = to_decimal(value)
elif name in ['pre_cross', 'post_cross']:
value = [(to_decimal(k), to_bool(v)) for (k, v) in value]
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets counts and all contained shapes."""
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, runstate):
"""Draws all contained shapes during the appropriate interval."""
for shape in self.shapes:
shape.draw(photoburst=runstate.disp_ops['photoburst'])
def update(self, runstate):
"""Updates contained shapes, sets event triggers."""
# Set events to be sent
if runstate.disp_ops['fpst'] > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= runstate.disp_ops['fpst']:
if not runstate.disp_ops['freqcheck'] or runstate.fc_send:
runstate.events['sids'].add(n)
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(runstate.fps)
def display(self, runstate):
"""Display the group in the context described by supplied runstate."""
self.reset()
for count in range(self.pre * runstate.fps):
if runstate.terminate:
break
pre_time = to_decimal(count) / runstate.fps
if pre_time in dict(self.pre_cross):
runstate.show_cross = dict(self.pre_cross)[pre_time]
runstate.update()
runstate.events['grp_on'] = True
runstate.show_cross = True
if runstate.disp_ops['eyetrack']:
runstate.fix_fail = False
runstate.true_fail = False
for count in range(self.disp * runstate.fps):
if runstate.terminate:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
runstate.events['grp_off'] = True
if runstate.disp_ops['eyetrack']:
if runstate.fix_fail:
runstate.true_fail = True
for count in range(self.post * runstate.fps):
if runstate.terminate:
break
post_time = to_decimal(count) / runstate.fps
if post_time in dict(self.post_cross):
runstate.show_cross = dict(self.post_cross)[post_time]
runstate.update()
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.steps_done = 0
def draw(self, runstate):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, runstate):
"""Checks for keypress, sends trigger upon end."""
if max([runstate.keystates[key] for
key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
def display(self, runstate):
"""Displays waitscreen in context described by supplied runstate."""
runstate.show_cross = True
while self.steps_done < self.num_steps:
if runstate.terminate:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = OrderedDict([('dims', (5, 5)),
('init_unit', (30, 30)),
('end_unit', (50, 50)),
('position', (0, 0)),
('anchor', 'bottomleft'),
('cols', ((0, 0, 0), (255, 255, 255))),
('freq', 1),
('phase', 0)])
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
if INT_HALF_PERIODS:
frames_per_half_period = round(fps / (self.freq * 2))
degs_per_frame = 180 / to_decimal(frames_per_half_period)
else:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
diff --git a/src/eyetracking.py b/src/eyetracking.py
index fce8582..7f59a31 100644
--- a/src/eyetracking.py
+++ b/src/eyetracking.py
@@ -1,207 +1,215 @@
"""Provides support for CRS VideoEyetracker Toolbox."""
import os.path
from utils import *
FIX_POS = (0, 0)
FIX_RANGE = (20, 20)
FIX_PER = 300
TRACK_PER = 300
try:
import win32com.client
available = True
except ImportError:
available = False
# COM ProgID of the Toolbox
ProgID = "crsVET.VideoEyeTracker"
RecordName = "etResultSet"
# VET application object
VET = None
class EyetrackingError(Exception):
"""Raised when something goes wrong with VET."""
pass
if available:
# Try dispatching object, else unavailable
try:
from win32com.client import gencache
# Ensure makepy module is generated
gencache.EnsureModule('{248DBF0C-A874-4032-82CE-DC5B307BB6E7}',
0, 3, 11)
VET = win32com.client.Dispatch(ProgID)
DummyResultSet = win32com.client.Record(RecordName, VET)
except:
available = False
if available:
# For easier access to constants and standardization with MATLAB interface
CRS = win32com.client.constants
- lastfixstatus = False
+ data = None
+ lastfixstatus = 0
+ newfixstatus = 0
fixcount = 0
lasttrackstatus = False
trackcount = 0
def select_source(user_select = False, path = None):
if user_select:
if not VET.SelectVideoSource(CRS.vsUserSelect, ''):
msg = 'could not select video source'
raise EyetrackingError(msg)
elif path != None:
# Open from file
if not VET.SelectVideoSource(CRS.vsFile, path):
msg = 'could not use path as video source'
raise EyetrackingError(msg)
else:
# Default to 250 Hz High Speed Camera
if not VET.SelectVideoSource(CRS.vsHighSpeedCamera250, ''):
msg = 'could not select video source'
raise EyetrackingError(msg)
def is_source_ready():
"""Returns true if a video source has been selected."""
if VET.VideoSourceType == 0:
return False
else:
return True
def show_camera():
VET.CreateCameraScreen(0)
def quit_camera():
VET.DestroyCameraScreen()
def setup(viewing_distance=None, screen_dims=None,
fixation_period=None, fixation_range=None):
"""Calibrates the display and sets fixation properties."""
if viewing_distance != None and screen_dims != None:
if len(screen_dims) != 2:
msg = 'screen_dims must be a 2-tuple'
raise ValueError(msg)
VET.SetDeviceParameters(CRS.deUser, viewing_distance,
screen_dims[0], screen_dims[1])
if fixation_period != None:
VET.FixationPeriod = fixation_period
if fixation_range != None:
VET.FixationRange = fixation_range
def calibrate(path = None):
"""Calibrate the subject.
Optionally supply a path with no spaces to a
calibration file to load."""
if not is_source_ready():
select_source()
if not VET.Tracking:
VET.ClearDataBuffer()
VET.StartTracking()
if path == None:
if not VET.Calibrate():
msg = 'calibration failed'
raise EyetrackingError(msg)
else:
if not os.path.isfile(path):
msg = 'specified file does not exist'
raise EyetrackingError(msg)
if not VET.LoadCalibrationFile(path):
msg = 'file could not be loaded'
raise EyetrackingError(msg)
if not is_calibrated():
msg = 'calibration failed'
raise EyetrackingError(msg)
def is_calibrated():
if VET.CalibrationStatus()[0] != 0:
return True
else:
return False
def start():
"""Start tracking the eye."""
if not is_source_ready():
select_source()
if not is_calibrated():
msg = 'subject not yet calibrated'
raise EyetrackingError(msg)
VET.ClearDataBuffer()
VET.StartTracking()
def stop():
"""Stop tracking the eye."""
VET.StopTracking()
+ def poll_tracker():
+ """Poll tracker for tracking information."""
+ global data
+ data = VET.GetLatestEyePosition(DummyResultSet)[1]
+
def is_tracked(fps, track_period=TRACK_PER):
"""Returns true if the eye is being tracked.
fps -- frames per second at which stimulus is running
track_period -- duration in milliseconds during which eye has to
be consistently tracked or untracked in order for value returned
by this function to change
"""
global lasttrackstatus
global trackcount
- data = VET.GetLatestEyePosition(DummyResultSet)[1]
if data.Tracked != lasttrackstatus:
trackcount += 1
else:
trackcount = 0
if trackcount >= track_period / to_decimal(1000) * fps:
trackcount = 0
lasttrackstatus = data.Tracked
return lasttrackstatus
def is_fixated(fps, fix_pos=FIX_POS,
fix_range=FIX_RANGE,
fix_period=FIX_PER):
"""Checks whether subject is fixating on specified location.
fps -- frames per second at which stimulus is running
fix_pos -- (x, y) position of desired fixation location in mm
from center of screen
fix_range -- (width, height) of box surrounding fix_pos within
which fixation is allowed (in mm)
fix_period -- duration in milliseconds during which eye has to
be consistently fixated or not fixated in order for value returned
by this function to change
"""
global lastfixstatus
+ global newfixstatus
global fixcount
- data = VET.GetLatestEyePosition(DummyResultSet)[1]
pos = (data.ScreenPositionXmm, data.ScreenPositionYmm)
diff = [abs(p - fp) for p, fp in zip(pos, fix_pos)]
- curfixstatus = False
+ curfixstatus = -1
if data.Tracked == True:
if diff[0] < fix_range[0] and diff[1] < fix_range[1]:
- curfixstatus = True
- if curfixstatus != lastfixstatus:
+ curfixstatus = 1
+ else:
+ curfixstatus = 0
+ if curfixstatus == newfixstatus:
fixcount += 1
else:
fixcount = 0
+ if curfixstatus != lastfixstatus:
+ newfixstatus = curfixstatus
if fixcount >= fix_period / to_decimal(1000) * fps:
fixcount = 0
- lastfixstatus = curfixstatus
- return lastfixstatus
+ lastfixstatus = newfixstatus
+ return (lastfixstatus == 1)
def x_pos():
- data = VET.GetLatestEyePosition(DummyResultSet)[1]
if data.Tracked:
return float(data.ScreenPositionXmm)
else:
- return "untracked"
+ return ''
def y_pos():
- data = VET.GetLatestEyePosition(DummyResultSet)[1]
if data.Tracked:
return float(data.ScreenPositionYmm)
else:
- return "untracked"
+ return ''
|
ztangent/checkergen
|
b0283700ead9103db81c6d5aaa9a61c55e9c199b
|
Cross always shown during stimuli, eye positions logged.
|
diff --git a/src/core.py b/src/core.py
index 8e0dced..f070248 100755
--- a/src/core.py
+++ b/src/core.py
@@ -104,1233 +104,1247 @@ class CkgProj:
('logdur', False),
('trigser', False),
('trigpar', False),
('fpst', 0),
('freqcheck', False),
('phototest', False),
('photoburst', False),
('eyetrack', False),
('etuser', False),
('etvideo', None),
('tryagain', 0),
('trybreak', None),
('nolog', False),
('export', False),
('expo_dir', None),
('expo_dur', None),
('folder', True)])
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
pre_cross -- key-value pairs specifying at what times during the pre
period a cross should be shown (e.g. [(0, False), (2, True)]
means that a cross is not shown at the start, but is shown
from 2 seconds onwards)
post_cross -- key-value pairs specifying at what times during the post
period a cross should be shown
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'cross_cols':
if len(value) != 3:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name in ['pre_cross', 'post_cross']:
value = [(to_decimal(k), to_bool(v)) for (k, v) in value]
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def set_display_flags(self, **keywords):
"""Set default display flags for the project.
Same arguments as 'display', excluding 'name' and 'order'.
"""
for kw in keywords.keys():
if kw in self.disp_ops.keys() and keywords[kw] != None:
self.disp_ops[kw] = keywords[kw]
self._dirty = True
def set_group_orders(self, orders):
for order in orders:
for gid in order:
if gid < -1 or gid >= len(self.groups):
msg = 'invalid group id (out of range)'
raise ValueError(msg)
self.orders = orders
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
# Vars that are dicts
dicts_to_load = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_load = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
for d_name in dicts_to_load:
d = copy.deepcopy(self.__class__.DEFAULTS[d_name])
try:
d_el = [node for node in project.childNodes if
node.localName == d_name and
node.namespaceURI == XML_NAMESPACE][0]
for var in d.keys():
try:
d[var] = eval(xml_get(d_el, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}' in '{1}'".\
format(var, d_name)
print "using default value '{0}' instead...".\
format(d[var])
except IndexError:
print "warning: missing attribute set '{0}'".format(d_name)
print "using default values instead..."
setattr(self, d_name, d)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
# Vars that are dicts
dicts_to_save = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_save = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for d_name in dicts_to_save:
d_el = doc.createElement(d_name)
project.appendChild(d_el)
d = getattr(self, d_name)
for k, v in d.iteritems():
xml_set(doc, d_el, k, repr(v))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, **keywords):
"""Displays the stimulus on the screen.
name -- name that logfile will be saved with
repeats -- number of times specified order of display groups should
be repeated
waitless -- if true, no waitscreens will appear at the start of each
repeat
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
priority -- priority level to which process should be raised
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
trigser -- send triggers through serial port when each group is shown
trigpar -- send triggers through parallel port when each group is shown
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
freqcheck -- send fpst only at the start, the middle, and the end
for sanity checking of display and trigger fps
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- append a wait screen to the group queue every time
after this many groups have been appended to the queue
order -- order in which groups (specified by id) will be displayed
"""
# Create RunState
disp_ops = copy.deepcopy(self.disp_ops)
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'name' in keywords.keys() and keywords['name'] != None:
name = keywords['name']
else:
timestr = datetime.today().strftime('_%Y-%m-%d_%H-%M-%S')
name = self.name + timestr
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
waitscreen = CkgWaitScreen()
# Set runstate order id if necessary
if order in self.orders:
runstate.ord_id = self.orders.index(order)
# Count through pre
for count in range(self.pre * self.fps):
if runstate.terminate:
break
pre_time = to_decimal(count) / runstate.fps
if pre_time in dict(self.pre_cross):
runstate.show_cross = dict(self.pre_cross)[pre_time]
runstate.update()
# Loop through repeats
repeats = runstate.disp_ops['repeats']
ord_len = len(runstate.order)
for i in range(repeats):
# Restart eyetracking
if runstate.disp_ops['eyetrack']:
eyetracking.stop()
eyetracking.start()
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
# Loop through display groups
runstate.events['blk_on'] = True
for n, gid in enumerate(runstate.order):
# Set flag for freqcheck
if runstate.disp_ops['freqcheck']:
if ((i == 0 and n == 0) or
(i == repeats-1 and n == ord_len-1) or
(i == repeats//2 and n == ord_len//2)):
runstate.fc_send = True
else:
runstate.fc_send = False
if gid == -1:
waitscreen.reset()
waitscreen.display(runstate)
else:
self.groups[gid].display(runstate)
if not runstate.terminate:
# Append group id and fail state
runstate.gids.append(gid)
if runstate.disp_ops['eyetrack']:
runstate.fails.append(runstate.true_fail)
# Append groups to be added
if runstate.true_fail:
if (len(runstate.add_gids) <
runstate.disp_ops['tryagain']):
runstate.add_gids.append(gid)
runstate.events['blk_off'] = True
# Stop freqcheck before added groups
if runstate.disp_ops['freqcheck']:
runstate.fc_send = False
# Loop through added groups
if runstate.disp_ops['eyetrack']:
for blk in grouper(runstate.add_gids,
runstate.disp_ops['trybreak']):
# Restart eyetracking
if runstate.disp_ops['eyetrack']:
eyetracking.stop()
eyetracking.start()
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
runstate.events['blk_on'] = True
# Loop through display groups
for gid in blk:
if gid != None:
self.groups[gid].display(runstate)
if not runstate.terminate:
# Append group id and fail state
runstate.gids.append(gid)
if runstate.disp_ops['eyetrack']:
runstate.fails.append(runstate.true_fail)
runstate.events['blk_off'] = True
# Count through post
for count in range(self.post * self.fps):
if runstate.terminate:
break
post_time = to_decimal(count) / runstate.fps
if post_time in dict(self.post_cross):
runstate.show_cross = dict(self.post_cross)[post_time]
runstate.update()
# Stop and output log
runstate.stop()
if not runstate.disp_ops['nolog']:
runstate.log()
def export(self, **keywords):
"""Exports the stimulus as a series of images, one image per frame.
repeats -- number of times specified order of display groups should
be repeated
order -- order in which groups (specified by id) will be displayed
expo_dir -- directory to which images will be exported
expo_dur -- time in seconds to which export will be limited
folder -- if true, images will be contained in a separate folder
within export directory
force -- force export to go through even if a large number
of frames are to be exported
"""
# Create RunState
disp_ops = copy.deepcopy(self.__class__.DEFAULTS['disp_ops'])
disp_ops['export'] = True
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=self.name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
# Warn user if a lot of frames will be exported
if 'force' not in keywords.keys():
keywords['force'] = False
groups_dur = sum([self.groups[i].duration()
for i in order]) * disp_ops['repeats']
total_frames = (self.pre + groups_dur + self.post) * self.fps
frames = min(total_frames, disp_ops['expo_dur'] * self.fps)
if frames > MAX_EXPORT_FRAMES and not keywords['force']:
msg = 'large number ({0}) of frames to be exported'.\
format(int(frames))
raise FrameOverflowError(msg)
runstate.frames = frames
# Count through pre
for count in range(self.pre * self.fps):
if runstate.terminate:
break
runstate.update()
# Loop through repeats
repeats = runstate.disp_ops['repeats']
for i in range(repeats):
# Loop through display groups
for n, gid in enumerate(runstate.order):
if gid != -1:
self.groups[gid].display(runstate)
# Count through post
for count in range(self.post * self.fps):
if runstate.terminate:
break
runstate.update()
# Stop runstate
runstate.stop()
class CkgRunState:
"""Contains information about the state of a checkergen project
when it is being displayed or exported."""
DEFAULTS = dict([('name', 'untitled'),
('res', None),
('fps', None),
('bg', None),
('cross_cols', None),
('cross_times', None),
('order', []),
('disp_ops', None),
('events', None),
('gids', []),
('fails', []),
('add_gids', []),
('timestamps', []),
('durstamps', []),
- ('trigstamps', [])])
+ ('trigstamps', []),
+ ('eye_x', []),
+ ('eye_y', [])])
DEFAULTS['events'] = dict([('ord_id', None),
('blk_on', False),
('blk_off', False),
('track_on', False),
('track_off', False),
('fix_on', False),
('fix_off', False),
('grp_on', False),
('grp_off', False),
('sids', set())])
def __init__(self, **keywords):
"""Creates the RunState."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
def start(self):
"""Initialize all subsystems and start the run."""
if self.disp_ops == None:
msg = "RunState lacks display options"
raise ValueError(msg)
if min(self.res, self.fps, self.bg,
self.cross_cols, self.cross_times) == None:
msg = "RunState intialized with insufficent project information"
raise ValueError(msg)
self._count = 0
self._old_code = 0
self.ord_id = None
self.terminate = False
# Flag used by freqcheck
self.fc_send = False
# Create fixation crosses
self.show_cross = True
self.fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if self.disp_ops['phototest']:
self.test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Initialize export
if self.disp_ops['export']:
if not os.path.isdir(self.disp_ops['expo_dir']):
msg = 'export path is not a directory'
raise IOError(msg)
if self.disp_ops['folder']:
self.save_dir = os.path.join(self.disp_ops['expo_dir'],
self.name + EXPORT_DIR_SUFFIX)
else:
self.save_dir = self.disp_ops['expo_dir']
if not os.path.isdir(self.save_dir):
os.mkdir(self.save_dir)
# Initialize ports
if self.disp_ops['trigser']:
if not trigger.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trigpar']:
if not trigger.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
trigger.init(self.disp_ops['trigser'], self.disp_ops['trigpar'])
# Initialize eyetracking
if self.disp_ops['eyetrack']:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trybreak'] == None:
self.disp_ops['trybreak'] = len(self.order)
self.fixated = False
self.old_fixated = False
self.tracked = False
self.old_tracked = False
self.fix_fail = False
self.true_fail = False
eyetracking.select_source(self.disp_ops['etuser'],
self.disp_ops['etvideo'])
eyetracking.start()
# Create window if not exporting
self.scaling = False
if not self.disp_ops['export']:
# Stretch to fit screen only if project res does not
# equal screen res
if self.disp_ops['fullscreen']:
self.window = pyglet.window.Window(fullscreen=True,
visible=False)
if (self.window.width, self.window.height) != self.res:
self.scaling = True
else:
self.window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
self.keystates = pyglet.window.key.KeyStateHandler()
self.window.push_handlers(self.keystates)
# Clear window and make visible
self.window.switch_to()
graphics.set_clear_color(self.bg)
self.window.clear()
self.window.set_visible()
# Create framebuffer object for drawing unscaled or exported scene
if self.scaling or self.disp_ops['export']:
self.canvas = pyglet.image.Texture.create(*self.res)
self.fbo = graphics.Framebuffer(self.canvas)
self.fbo.start_render()
graphics.set_clear_color(self.bg)
self.fbo.clear()
# Set process priority
if self.disp_ops['priority'] != None:
try:
priority.set(self.disp_ops['priority'])
except ValueError:
priority.set(int(self.disp_ops['priority']))
except:
pass
# Start timers
if self.disp_ops['logtime']:
self.timer = Timer()
self.timer.start()
if self.disp_ops['logdur']:
self.dur = Timer()
self.dur.start()
def update(self):
"""Update the RunState."""
# Check for tracking and fixation
if self.disp_ops['eyetrack']:
self.old_tracked = self.tracked
self.tracked = eyetracking.is_tracked(self.fps)
self.old_fixated = self.fixated
self.fixated = eyetracking.is_fixated(self.fps)
if self.show_cross:
if self.fixated:
# Draw normal cross color if fixating
self.fix_crosses[0].draw()
elif self.tracked:
# Draw 2nd cross color if tracked, not fixating
self.fix_crosses[1].draw()
else:
# Draw 3rd cross color if untracked
self.fix_crosses[2].draw()
# Update eyetracking events
if self.tracked != self.old_tracked:
if self.tracked:
self.events['track_on'] = True
else:
self.events['track_off'] = True
if self.fixated != self.old_fixated:
if self.fixated:
self.events['fix_on'] = True
else:
self.events['fix_off'] = True
# Check for failure of trial
if self.tracked and not self.fixated:
self.fix_fail = True
+
else:
# Change cross color based on time
if self.show_cross:
if (self._count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
self.fix_crosses[0].draw()
else:
self.fix_crosses[1].draw()
if self.disp_ops['export']:
# Save current frame to file
savepath = os.path.join(
self.save_dir, '{0}{2}.{1}'.\
format(self.name, 'png',
repr(self._count).zfill(numdigits(self.frames-1))))
self.canvas.save(savepath)
else:
# Blit canvas to screen if necessary
if self.scaling:
self.fbo.end_render()
self.canvas.blit(0, 0)
self.window.switch_to()
self.window.dispatch_events()
self.window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to lists
if self.disp_ops['logtime']:
self.timestamps.append(self.timer.elapsed())
elif self.disp_ops['logdur']:
self.timestamps.append('')
if self.disp_ops['logdur']:
self.durstamps.append(self.dur.restart())
elif self.disp_ops['logtime']:
self.durstamps.append('')
# Send trigger ASAP after flip
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
if self.encode_events() != self._old_code:
trigger.send(self.disp_ops['trigser'],
self.disp_ops['trigpar'],
self.encode_events())
self._old_code = self.encode_events
- # Log when triggers are sent
- if self.disp_ops['logtime'] and self.encode_events() > 0:
- self.trigstamps.append(self.encode_events())
- else:
- self.trigstamps.append('')
+ # Log eye positions and when triggers are sent
+ if self.disp_ops['logtime']:
+ if self.disp_ops['eyetrack']:
+ self.eye_x.append(eyetracking.x_pos())
+ self.eye_y.append(eyetracking.y_pos())
+ else:
+ self.eye_x.append('')
+ self.eye_y.append('')
+ if self.encode_events() > 0:
+ self.trigstamps.append(self.encode_events())
+ else:
+ self.trigstamps.append('')
# Clear canvas, events, prepare for next frame
if self.disp_ops['export']:
self.fbo.clear()
else:
if self.scaling:
self.fbo.start_render()
self.fbo.clear()
else:
self.window.clear()
if self.window.has_exit:
self.terminate = True
# Send ord_id immediately after blk_on
send_ord_id_next = self.events['blk_on']
self.events = copy.deepcopy(self.__class__.DEFAULTS['events'])
if send_ord_id_next:
self.events['ord_id'] = self.ord_id
self._count += 1
# Terminate export if the time has come
if self.disp_ops['export']:
if self._count >= self.frames:
self.terminate = True
def stop(self):
"""Clean up RunState."""
if self.disp_ops['eyetrack']:
eyetracking.stop()
if self.scaling or self.disp_ops['export']:
self.fbo.delete()
del self.canvas
if not self.disp_ops['export']:
self.window.close()
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
trigger.quit(self.disp_ops['trigser'], self.disp_ops['trigpar'])
try:
priority.set('normal')
except:
pass
def encode_events(self):
"""Hard code specific trigger values for events."""
code = 0
if self.events['ord_id'] != None:
code = self.events['ord_id'] + 1
elif self.events['blk_on']:
code = 128
elif self.events['blk_off']:
code = 127
else:
et_state = 0
if self.events['fix_on']:
et_state = 4
elif self.events['track_on']:
et_state = 2
if self.events['track_off']:
et_state = 1
elif self.events['fix_off']:
et_state = 2
if self.events['grp_on']:
code = 100 + et_state
elif self.events['grp_off']:
code = 90 + et_state
elif et_state > 0:
code = 110 + et_state
elif len(self.events['sids']) > 0:
code = ((0 in self.events['sids'])*2**0 +
(1 in self.events['sids'])*2**1 +
(2 in self.events['sids'])*2**2 +
(3 in self.events['sids'])*2**3 +
16)
return code
def log(self, path=None):
"""Write a log file for the experimental run in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, LOG_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(LOG_FMT):
path = '{0}.{1}'.format(path, LOG_FMT)
with open(path, 'wb') as logfile:
writer = csv.writer(logfile, dialect='excel-tab')
writer.writerow(['checkergen log file'])
writer.writerow(['display options:'])
writer.writerow(self.disp_ops.keys())
writer.writerow(self.disp_ops.values())
writer.writerow(['order:'] + self.order)
writer.writerow(['groups', 'failure'])
if not self.disp_ops['eyetrack']:
self.fails = ['NA'] * len(self.gids)
for i in zip(self.gids, self.fails):
writer.writerow(list(i))
if self.disp_ops['eyetrack']:
writer.writerow(['groups added'])
for blk in grouper(self.add_gids,
self.disp_ops['trybreak'], ''):
writer.writerow(blk)
if self.disp_ops['logtime'] or self.disp_ops['logdur']:
- stamps = [self.timestamps, self.durstamps, self.trigstamps]
- writer.writerow(['timestamps', 'durations', 'triggers'])
+ stamps = [self.timestamps, self.durstamps, self.trigstamps,
+ self.eye_x, self.eye_y]
+ writer.writerow(['timestamps', 'durations', 'triggers',
+ 'eye x (mm)', 'eye y (mm)'])
for stamp in zip(*stamps):
writer.writerow(list(stamp))
class CkgDisplayGroup:
DEFAULTS = OrderedDict([('pre', 0),
('disp', 'Infinity'),
('post', 0),
('pre_cross', [(0, True)]),
('post_cross', [(0, True)])])
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
pre_cross -- key-value pairs specifying at what times during the pre
period a cross should be shown (e.g. [(0, False), (2, True)]
means that a cross is not shown at the start, but is shown
from 2 seconds onwards)
post_cross -- key-value pairs specifying at what times during the post
period a cross should be shown
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in ['pre', 'disp', 'post']:
value = to_decimal(value)
elif name in ['pre_cross', 'post_cross']:
value = [(to_decimal(k), to_bool(v)) for (k, v) in value]
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets counts and all contained shapes."""
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, runstate):
"""Draws all contained shapes during the appropriate interval."""
for shape in self.shapes:
shape.draw(photoburst=runstate.disp_ops['photoburst'])
def update(self, runstate):
"""Updates contained shapes, sets event triggers."""
# Set events to be sent
if runstate.disp_ops['fpst'] > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= runstate.disp_ops['fpst']:
if not runstate.disp_ops['freqcheck'] or runstate.fc_send:
runstate.events['sids'].add(n)
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(runstate.fps)
def display(self, runstate):
"""Display the group in the context described by supplied runstate."""
self.reset()
for count in range(self.pre * runstate.fps):
if runstate.terminate:
break
pre_time = to_decimal(count) / runstate.fps
if pre_time in dict(self.pre_cross):
runstate.show_cross = dict(self.pre_cross)[pre_time]
runstate.update()
runstate.events['grp_on'] = True
+ runstate.show_cross = True
if runstate.disp_ops['eyetrack']:
runstate.fix_fail = False
runstate.true_fail = False
for count in range(self.disp * runstate.fps):
if runstate.terminate:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
runstate.events['grp_off'] = True
if runstate.disp_ops['eyetrack']:
if runstate.fix_fail:
runstate.true_fail = True
for count in range(self.post * runstate.fps):
if runstate.terminate:
break
post_time = to_decimal(count) / runstate.fps
if post_time in dict(self.post_cross):
runstate.show_cross = dict(self.post_cross)[post_time]
runstate.update()
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.steps_done = 0
def draw(self, runstate):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, runstate):
"""Checks for keypress, sends trigger upon end."""
if max([runstate.keystates[key] for
key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
def display(self, runstate):
"""Displays waitscreen in context described by supplied runstate."""
+ runstate.show_cross = True
while self.steps_done < self.num_steps:
if runstate.terminate:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = OrderedDict([('dims', (5, 5)),
('init_unit', (30, 30)),
('end_unit', (50, 50)),
('position', (0, 0)),
('anchor', 'bottomleft'),
('cols', ((0, 0, 0), (255, 255, 255))),
('freq', 1),
('phase', 0)])
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
if INT_HALF_PERIODS:
frames_per_half_period = round(fps / (self.freq * 2))
degs_per_frame = 180 / to_decimal(frames_per_half_period)
else:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
anchor=self.anchor)
cur_unit_rect.col = self.cols[(i + j) % 2]
cur_unit_rect.add_to_batch(self._batches[0])
cur_unit_rect.col = self.cols[(i + j + 1) % 2]
cur_unit_rect.add_to_batch(self._batches[1])
# Increase x values
cur_unit_pos[0] += \
graphics.locations[self.anchor][0] * cur_unit[0]
cur_unit[0] += unit_grad[0]
# Reset x values
cur_unit_pos[0] = init_pos[0]
cur_unit[0] = init_unit[0]
# Increase y values
cur_unit_pos[1] += \
graphics.locations[self.anchor][1] * cur_unit[1]
cur_unit[1] += unit_grad[1]
self._computed = True
def draw(self, photoburst=False, always_compute=False):
"""Draws appropriate batch depending on current phase.
photoburst -- draw first color for only one frame for testing purposes
always_compute -- recompute what the checkerboard should look like
every frame
"""
if not self._computed or always_compute:
self.compute()
self._cur_phase %= 360
n = int(self._cur_phase // 180)
if photoburst and n == 0 and not self.flipped:
n = 1
self._batches[n].draw()
def lazydraw(self):
"""Only draws on color reversal."""
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if (cur_n != prev_n) or self._first_draw:
self.draw()
if self._first_draw:
self._first_draw = False
diff --git a/src/eyetracking.py b/src/eyetracking.py
index 793b339..fce8582 100644
--- a/src/eyetracking.py
+++ b/src/eyetracking.py
@@ -1,193 +1,207 @@
"""Provides support for CRS VideoEyetracker Toolbox."""
import os.path
from utils import *
FIX_POS = (0, 0)
FIX_RANGE = (20, 20)
FIX_PER = 300
TRACK_PER = 300
try:
import win32com.client
available = True
except ImportError:
available = False
# COM ProgID of the Toolbox
ProgID = "crsVET.VideoEyeTracker"
RecordName = "etResultSet"
# VET application object
VET = None
class EyetrackingError(Exception):
"""Raised when something goes wrong with VET."""
pass
if available:
# Try dispatching object, else unavailable
try:
from win32com.client import gencache
# Ensure makepy module is generated
gencache.EnsureModule('{248DBF0C-A874-4032-82CE-DC5B307BB6E7}',
0, 3, 11)
VET = win32com.client.Dispatch(ProgID)
DummyResultSet = win32com.client.Record(RecordName, VET)
except:
available = False
if available:
# For easier access to constants and standardization with MATLAB interface
CRS = win32com.client.constants
lastfixstatus = False
fixcount = 0
lasttrackstatus = False
trackcount = 0
def select_source(user_select = False, path = None):
if user_select:
if not VET.SelectVideoSource(CRS.vsUserSelect, ''):
msg = 'could not select video source'
raise EyetrackingError(msg)
elif path != None:
# Open from file
if not VET.SelectVideoSource(CRS.vsFile, path):
msg = 'could not use path as video source'
raise EyetrackingError(msg)
else:
# Default to 250 Hz High Speed Camera
if not VET.SelectVideoSource(CRS.vsHighSpeedCamera250, ''):
msg = 'could not select video source'
raise EyetrackingError(msg)
def is_source_ready():
"""Returns true if a video source has been selected."""
if VET.VideoSourceType == 0:
return False
else:
return True
def show_camera():
VET.CreateCameraScreen(0)
def quit_camera():
VET.DestroyCameraScreen()
def setup(viewing_distance=None, screen_dims=None,
fixation_period=None, fixation_range=None):
"""Calibrates the display and sets fixation properties."""
if viewing_distance != None and screen_dims != None:
if len(screen_dims) != 2:
msg = 'screen_dims must be a 2-tuple'
raise ValueError(msg)
VET.SetDeviceParameters(CRS.deUser, viewing_distance,
screen_dims[0], screen_dims[1])
if fixation_period != None:
VET.FixationPeriod = fixation_period
if fixation_range != None:
VET.FixationRange = fixation_range
def calibrate(path = None):
"""Calibrate the subject.
Optionally supply a path with no spaces to a
calibration file to load."""
if not is_source_ready():
select_source()
if not VET.Tracking:
VET.ClearDataBuffer()
VET.StartTracking()
if path == None:
if not VET.Calibrate():
msg = 'calibration failed'
raise EyetrackingError(msg)
else:
if not os.path.isfile(path):
msg = 'specified file does not exist'
raise EyetrackingError(msg)
if not VET.LoadCalibrationFile(path):
msg = 'file could not be loaded'
raise EyetrackingError(msg)
if not is_calibrated():
msg = 'calibration failed'
raise EyetrackingError(msg)
def is_calibrated():
if VET.CalibrationStatus()[0] != 0:
return True
else:
return False
def start():
"""Start tracking the eye."""
if not is_source_ready():
select_source()
if not is_calibrated():
msg = 'subject not yet calibrated'
raise EyetrackingError(msg)
VET.ClearDataBuffer()
VET.StartTracking()
def stop():
"""Stop tracking the eye."""
VET.StopTracking()
def is_tracked(fps, track_period=TRACK_PER):
"""Returns true if the eye is being tracked.
fps -- frames per second at which stimulus is running
track_period -- duration in milliseconds during which eye has to
be consistently tracked or untracked in order for value returned
by this function to change
"""
global lasttrackstatus
global trackcount
data = VET.GetLatestEyePosition(DummyResultSet)[1]
if data.Tracked != lasttrackstatus:
trackcount += 1
else:
trackcount = 0
if trackcount >= track_period / to_decimal(1000) * fps:
trackcount = 0
lasttrackstatus = data.Tracked
return lasttrackstatus
def is_fixated(fps, fix_pos=FIX_POS,
fix_range=FIX_RANGE,
fix_period=FIX_PER):
"""Checks whether subject is fixating on specified location.
fps -- frames per second at which stimulus is running
fix_pos -- (x, y) position of desired fixation location in mm
from center of screen
fix_range -- (width, height) of box surrounding fix_pos within
which fixation is allowed (in mm)
fix_period -- duration in milliseconds during which eye has to
be consistently fixated or not fixated in order for value returned
by this function to change
"""
global lastfixstatus
global fixcount
data = VET.GetLatestEyePosition(DummyResultSet)[1]
pos = (data.ScreenPositionXmm, data.ScreenPositionYmm)
diff = [abs(p - fp) for p, fp in zip(pos, fix_pos)]
curfixstatus = False
if data.Tracked == True:
if diff[0] < fix_range[0] and diff[1] < fix_range[1]:
curfixstatus = True
if curfixstatus != lastfixstatus:
fixcount += 1
else:
fixcount = 0
if fixcount >= fix_period / to_decimal(1000) * fps:
fixcount = 0
lastfixstatus = curfixstatus
return lastfixstatus
+
+ def x_pos():
+ data = VET.GetLatestEyePosition(DummyResultSet)[1]
+ if data.Tracked:
+ return float(data.ScreenPositionXmm)
+ else:
+ return "untracked"
+
+ def y_pos():
+ data = VET.GetLatestEyePosition(DummyResultSet)[1]
+ if data.Tracked:
+ return float(data.ScreenPositionYmm)
+ else:
+ return "untracked"
|
ztangent/checkergen
|
7b60fc243f4cfb28c69756aca1ccde6095b07961
|
CLI can edit pre_cross, post_cross values.
|
diff --git a/example.ckg b/example.ckg
index b4ffb99..9d2162a 100644
--- a/example.ckg
+++ b/example.ckg
@@ -1,80 +1,84 @@
<?xml version="1.0" ?>
<project xmlns="http://github.com/ZOMGxuan/checkergen">
<fps>Decimal('60')</fps>
<res>(800, 600)</res>
<bg>(127, 127, 127)</bg>
<pre>Decimal('0')</pre>
<post>Decimal('0')</post>
+ <pre_cross>[(Decimal('0'), True)]</pre_cross>
+ <post_cross>[(Decimal('0'), True)]</post_cross>
<cross_cols>((0, 0, 0), (255, 0, 0), (0, 0, 255))</cross_cols>
<cross_times>(Decimal('Infinity'), Decimal('1'))</cross_times>
<orders>[]</orders>
<disp_ops>
<repeats>1</repeats>
<waitless>False</waitless>
<fullscreen>False</fullscreen>
<priority>None</priority>
<logtime>False</logtime>
<logdur>False</logdur>
<trigser>False</trigser>
<trigpar>False</trigpar>
<fpst>0</fpst>
<freqcheck>False</freqcheck>
<phototest>False</phototest>
<photoburst>False</photoburst>
<eyetrack>False</eyetrack>
<etuser>False</etuser>
<etvideo>None</etvideo>
<tryagain>0</tryagain>
<trybreak>None</trybreak>
<nolog>False</nolog>
<export>False</export>
<expo_dir>None</expo_dir>
<expo_dur>None</expo_dur>
<folder>True</folder>
</disp_ops>
<group>
<pre>Decimal('2')</pre>
<disp>Decimal('10')</disp>
<post>Decimal('2')</post>
+ <pre_cross>[(Decimal('0'), True)]</pre_cross>
+ <post_cross>[(Decimal('0'), True)]</post_cross>
<shape type="board">
<dims>(5, 5)</dims>
<init_unit>(Decimal('40'), Decimal('40'))</init_unit>
<end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<position>(Decimal('420'), Decimal('320'))</position>
<anchor>'bottomleft'</anchor>
<cols>((0, 0, 0), (255, 255, 255))</cols>
<freq>Decimal('1')</freq>
<phase>Decimal('0')</phase>
</shape>
<shape type="board">
<dims>(5, 5)</dims>
<init_unit>(Decimal('40'), Decimal('40'))</init_unit>
<end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<position>(Decimal('380'), Decimal('320'))</position>
<anchor>'bottomright'</anchor>
<cols>((0, 0, 0), (255, 255, 255))</cols>
<freq>Decimal('2')</freq>
<phase>Decimal('90')</phase>
</shape>
<shape type="board">
<dims>(5, 5)</dims>
<init_unit>(Decimal('40'), Decimal('40'))</init_unit>
<end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<position>(Decimal('420'), Decimal('280'))</position>
<anchor>'topleft'</anchor>
<cols>((0, 0, 0), (255, 255, 255))</cols>
<freq>Decimal('3')</freq>
<phase>Decimal('180')</phase>
</shape>
<shape type="board">
<dims>(5, 5)</dims>
<init_unit>(Decimal('40'), Decimal('40'))</init_unit>
<end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<position>(Decimal('380'), Decimal('280'))</position>
<anchor>'topright'</anchor>
<cols>((0, 0, 0), (255, 255, 255))</cols>
<freq>Decimal('4')</freq>
<phase>Decimal('270')</phase>
</shape>
</group>
</project>
diff --git a/src/cli.py b/src/cli.py
index beea467..ae18285 100644
--- a/src/cli.py
+++ b/src/cli.py
@@ -1,1168 +1,1208 @@
"""Defines command-line-interface for checkergen."""
import os
import sys
if os.name == 'posix':
import readline
import argparse
import cmd
import shlex
import core
import priority
import eyetracking
from graphics import locations
from utils import *
CMD_PROMPT = '(ckg) '
CMD_EOF_STRING = 'Ctrl-D'
if sys.platform == 'win32':
CMD_EOF_STRING = 'Ctrl-Z + Enter'
CMD_INTRO = '\n'.join(["Enter 'help' for a list of commands.",
"Enter 'quit' or {0} to exit.".format(CMD_EOF_STRING)])
def store_list(nargs=None, sep=',', typecast=None, castargs=[]):
"""Returns argparse action that stores a list or tuple."""
class ListAction(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
vallist = values.split(sep)
if nargs != None and len(vallist) != nargs:
msg = ("argument '{f}' should be a list of " +
"{nargs} values separated by '{sep}'").\
format(f=self.dest,nargs=nargs,sep=sep)
raise argparse.ArgumentError(self, msg)
if typecast != None:
for n, val in enumerate(vallist):
try:
val = typecast(*([val] + castargs))
vallist[n] = val
except (ValueError, TypeError):
msg = ("element '{val}' of argument '{f}' " +
"is of the wrong type").\
format(val=vallist[n],f=self.dest)
raise argparse.ArgumentError(self, msg)
if nargs == None:
setattr(args, self.dest, vallist)
else:
setattr(args, self.dest, tuple(vallist))
return ListAction
def store_truth(y_words=['t','y','1','True','true','yes','Yes'],
n_words=['f','n','0','False','false','no','No']):
"""Returns argparse action that stores the truth based on keywords."""
class TruthAction(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
if values in y_words:
setattr(args, self.dest, True)
elif values in n_words:
setattr(args, self.dest, False)
else:
msg = 'true/false keyword unrecognized'
raise argparse.ArgumentError(self, msg)
return TruthAction
# The main parser invoked at the command-line
PARSER = argparse.ArgumentParser(
description='''Generate flashing checkerboard patterns for display
or export as a series of images, intended for use in
psychophysics experiments. Enters interactive command
line mode if no options are specified.''')
PARSER.add_argument('-c', '--cmd', dest='cmd_mode', action='store_true',
help='enter command line mode regardless of other options')
PARSER.add_argument('-d', '--display',
dest='display_flag', action='store_true',
help='displays the stimulus on the screen')
PARSER.add_argument('-e', '--export', dest='export_dur', metavar='DUR',
help='export DUR seconds of the stimulus')
PARSER.add_argument('-f', '--fullscreen', action='store_true',
help='stimulus displayed in fullscreen mode')
PARSER.add_argument('--dir', dest='export_dir',
default=os.getcwd(), metavar='PATH',
help='''destination directory for export
(default: current working directory)''')
PARSER.add_argument('path', metavar='project', nargs='?', type=file,
help='checkergen project file to open')
def process_args(args):
"""Further processes the arguments returned by the main parser."""
if args.export_dur != None:
args.export_flag = True
else:
args.export_flag = False
if not args.display_flag and not args.export_flag:
args.cmd_mode = True
if args.path != None:
if not os.path.isfile(args.path):
msg = 'error: path specified is not a file'
return msg
args.proj = core.CkgProj(path=args.path)
os.chdir(os.path.dirname(os.path.abspath(args.path)))
try:
args.group = args.proj.groups[0]
except IndexError:
args.group = None
else:
args.proj = None
args.group = None
if args.display_flag or args.export_flag:
msg = 'error: no project file specified for display or export'
return msg
class CmdParserError(Exception):
"""To be raised when CmdParser encounters an error."""
pass
class CmdParser(argparse.ArgumentParser):
"""Override ArgumentParser so that it doesn't exit the program."""
def error(self, msg):
raise CmdParserError(msg)
class CkgCmd(cmd.Cmd):
@staticmethod
def yn_parse(s):
if s in ['y', 'Y', 'yes', 'YES', 'Yes']:
return True
elif s in ['n', 'N', 'no', 'NO', 'No']:
return False
else:
msg = "only 'y','n' or variants accepted"
raise ValueError(msg)
def save_check(self, msg=None):
"""Checks and prompts the user to save if necessary."""
if self.cur_proj == None:
return
if not self.cur_proj.is_dirty():
return
if msg == None:
msg = 'Would you like to save the current project first? (y/n)'
print msg
while True:
try:
if self.__class__.yn_parse(raw_input()):
self.do_save('')
break
except TypeError:
print str(sys.exc_value)
except EOFError:
return True
def do_new(self, line):
"""Creates new project with given name (can contain whitespace)."""
name = line.strip().strip('"\'')
if len(name) == 0:
name = 'untitled'
if self.save_check():
return
self.cur_proj = core.CkgProj(name=name)
print 'project \'{0}\' created'.format(self.cur_proj.name)
def do_open(self, line):
"""Open specified project file."""
path = line.strip().strip('"\'')
if len(path) == 0:
print 'error: no path specified'
return
if self.save_check():
return
try:
self.cur_proj = core.CkgProj(path=path)
except (core.FileFormatError, IOError):
print "error:", str(sys.exc_value)
return
os.chdir(os.path.dirname(os.path.abspath(path)))
try:
self.cur_group = self.cur_proj.groups[0]
except IndexError:
self.cur_group = None
print 'project \'{0}\' loaded'.format(self.cur_proj.name)
def do_close(self, line):
"""Prompts the user to save, then closes current project."""
if self.cur_proj == None:
print 'no project to close'
return
if self.save_check():
return
self.cur_proj = None
print 'project closed'
def do_save(self, line):
"""Saves the current project to the specified path."""
if self.cur_proj == None:
print 'no project to save'
return
path = line.strip().strip('"\'')
if len(path) == 0:
path = os.getcwd()
path = os.path.abspath(path)
if os.path.isdir(path):
path = os.path.join(path,
'.'.join([self.cur_proj.name, core.CKG_FMT]))
elif os.path.isdir(os.path.dirname(path)):
pass
else:
print 'error: specified directory does not exist'
return
# project save will add file extension if necessary
try:
path = self.cur_proj.save(path)
except IOError:
print "error:", str(sys.exc_value)
return
print 'project saved to "{0}"'.format(path)
set_parser = CmdParser(add_help=False, prog='set',
description='''Sets various project settings.''')
set_parser.add_argument('-n', '--name',
help='''project name, always the same as the
filename without the extension''')
set_parser.add_argument('-f', '--fps', type=to_decimal,
help='''number of stimulus frames
rendered per second''')
set_parser.add_argument('-r', '--res', action=store_list(2, ',', int),
help='stimulus canvas size/resolution in pixels',
metavar='WIDTH,HEIGHT')
set_parser.add_argument('-bg', '--bg', metavar='COLOR', type=to_color,
help='''background color of the canvas
(color format: R,G,B,
component range from 0-255)''')
set_parser.add_argument('-pr', '--pre',
type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown before any display groups''')
set_parser.add_argument('-po', '--post',
type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown after all display groups''')
+ set_parser.add_argument('-prx', '--pre_cross', metavar='T1,B1;T2,B2;...',
+ action=store_list(None, ';', to_list, [',']),
+ help='''list of time-boolean pairs separated
+ by semicolons where the boolean value
+ represents the visibility of the cross
+ at that time during the pre period''')
+ set_parser.add_argument('-pox', '--post_cross', metavar='T1,B1;T2,B2;...',
+ action=store_list(None, ';', to_list, [',']),
+ help='''list of time-boolean pairs separated
+ by semicolons where the boolean value
+ represents the visibility of the cross
+ at that time during the post period''')
set_parser.add_argument('-cc', '--cross_cols',
metavar='COLOR1,COLOR2,COLOR3',
action=store_list(3, ',', to_color, [';']),
help='''fixation cross coloration
(color format: R;G;B,
component range from 0-255)''')
set_parser.add_argument('-ct', '--cross_times', metavar='TIME1,TIME2',
action=store_list(2, ',', to_decimal),
help='''time in seconds each cross color
will be displayed''')
set_group = set_parser.add_mutually_exclusive_group()
set_group.add_argument('-o', '--orders', metavar='ORDER1;ORDER2;...',
action=store_list(None, ';', to_list, [',', int]),
help='''list of orders separated by semicolons
where each order is a list of group ids
separated by commas''')
set_group.add_argument('-go', '--genorders', action='store_true',
help='''automatically generate a reduced latin
square for use as group orders''')
def help_set(self):
self.__class__.set_parser.print_help()
def do_set(self, line):
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
try:
args = self.__class__.set_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.set_parser.print_usage()
return
names = public_dir(args)
names.remove('orders')
names.remove('genorders')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
setattr(self.cur_proj, name, val)
noflags = False
if args.genorders:
orders = cyclic_permute(range(len(self.cur_proj.groups)))
try:
self.cur_proj.set_group_orders(orders)
except ValueError:
print "error:", str(sys.exc_value)
noflags = False
elif args.orders != None:
try:
self.cur_proj.set_group_orders(args.orders)
except ValueError:
print "error:", str(sys.exc_value)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.set_parser.print_usage()
mkgrp_parser = CmdParser(add_help=False, prog='mkgrp',
formatter_class=
argparse.ArgumentDefaultsHelpFormatter,
description='''Makes a new display group
with the given parameters.''')
mkgrp_parser.add_argument('pre', type=to_decimal, default=0, nargs='?',
help='''time in seconds a blank screen will
be shown before shapes are displayed''')
mkgrp_parser.add_argument('disp', type=to_decimal,
nargs='?', default='Infinity',
help='''time in seconds shapes will be
displayed''')
mkgrp_parser.add_argument('post', type=to_decimal, default=0, nargs='?',
help='''time in seconds a blank screen will
be shown after shapes are displayed''')
def help_mkgrp(self):
self.__class__.mkgrp_parser.print_help()
def do_mkgrp(self, line):
"""Makes a display group with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
try:
args = self.__class__.mkgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mkgrp_parser.print_usage()
return
group_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_group = core.CkgDisplayGroup(**group_dict)
new_id = self.cur_proj.add_group(new_group)
print "display group", new_id, "added"
self.cur_group = new_group
print "group", new_id, "is now the current display group"
edgrp_parser = CmdParser(add_help=False, prog='edgrp',
description='''Edits attributes of display groups
specified by ids.''')
edgrp_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='ids of display groups to be edited')
edgrp_parser.add_argument('--pre', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown before shapes are displayed''')
edgrp_parser.add_argument('--disp', type=to_decimal, metavar='SECONDS',
help='''time in seconds shapes will be
displayed''')
edgrp_parser.add_argument('--post', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown after shapes are displayed''')
+ edgrp_parser.add_argument('-prx', '--pre_cross',
+ metavar='T1,B1;T2,B2;...',
+ action=store_list(None, ';', to_list, [',']),
+ help='''list of time-boolean pairs separated
+ by semicolons where the boolean value
+ represents the visibility of the cross
+ at that time during the pre period''')
+ edgrp_parser.add_argument('-pox', '--post_cross',
+ metavar='T1,B1;T2,B2;...',
+ action=store_list(None, ';', to_list, [',']),
+ help='''list of time-boolean pairs separated
+ by semicolons where the boolean value
+ represents the visibility of the cross
+ at that time during the post period''')
+
def help_edgrp(self):
self.__class__.edgrp_parser.print_help()
def do_edgrp(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.edgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.edgrp_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_proj.groups) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_group_attr(x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.edgrp_parser.print_usage()
rmgrp_parser = CmdParser(add_help=False, prog='rmgrp',
description='''Removes display groups specified
by ids.''')
rmgrp_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='ids of display groups to be removed')
rmgrp_parser.add_argument('-a', '--all', action='store_true',
help='remove all groups from the project')
def help_rmgrp(self):
self.__class__.rmgrp_parser.print_help()
def do_rmgrp(self, line):
"""Removes display groups specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups to remove'
return
try:
args = self.__class__.rmgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rmgrp_parser.print_usage()
return
rmlist = []
if args.all:
for group in self.cur_proj.groups[:]:
self.cur_proj.del_group(group)
print "all display groups removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_proj.groups) or x < 0:
print "display group", x, "does not exist"
continue
rmlist.append(self.cur_proj.groups[x])
print "display group", x, "removed"
for group in rmlist:
self.cur_proj.del_group(group)
# Remember to point self.cur_group somewhere sane
if self.cur_group not in self.cur_proj.groups:
if len(self.cur_proj.groups) == 0:
self.cur_group = None
else:
self.cur_group = self.cur_proj.groups[0]
print "group 0 is now the current display group"
chgrp_parser = CmdParser(add_help=False, prog='chgrp',
description='''Changes display group that is
currently active for editing.
Prints current group id if
no group id is specified''')
chgrp_parser.add_argument('gid', metavar='id', type=int, nargs='?',
help='id of display group to be made active')
def help_chgrp(self):
self.__class__.chgrp_parser.print_help()
def do_chgrp(self, line):
"""Changes group that is currently active for editing."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups that can be made active'
return
try:
args = self.__class__.chgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.chgrp_parser.print_usage()
return
if args.gid == None:
print "group",\
self.cur_proj.groups.index(self.cur_group),\
"is the current display group"
elif args.gid >= len(self.cur_proj.groups) or args.gid < 0:
print "group", args.gid, "does not exist"
else:
self.cur_group = self.cur_proj.groups[args.gid]
print "group", args.gid, "is now the current display group"
mk_parser = CmdParser(add_help=False, prog='mk',
description='''Makes a new checkerboard in the
current group with the given
parameters.''')
mk_parser.add_argument('dims', action=store_list(2, ',', to_decimal),
help='''width,height of checkerboard in no. of
unit cells''')
mk_parser.add_argument('init_unit', action=store_list(2, ',', to_decimal),
help='width,height of initial unit cell in pixels')
mk_parser.add_argument('end_unit', action=store_list(2, ',', to_decimal),
help='width,height of final unit cell in pixels')
mk_parser.add_argument('position', action=store_list(2, ',', to_decimal),
help='x,y position of checkerboard in pixels')
mk_parser.add_argument('anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='anchor')
mk_parser.add_argument('cols', action=store_list(2, ',', to_color, [';']),
help='''color1,color2 of the checkerboard
(color format: R;G;B,
component range from 0-255)''')
mk_parser.add_argument('freq', type=to_decimal,
help='frequency of color reversal in Hz')
mk_parser.add_argument('phase', type=to_decimal, nargs='?', default='0',
help='initial phase in degrees')
def help_mk(self):
self.__class__.mk_parser.print_help()
def do_mk(self, line):
"""Makes a checkerboard with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
if self.cur_group == None:
print 'automatically adding display group...'
self.do_mkgrp('')
try:
args = self.__class__.mk_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mk_parser.print_usage()
return
shape_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_shape = core.CheckerBoard(**shape_dict)
new_id = self.cur_proj.add_shape_to_group(self.cur_group, new_shape)
print "checkerboard", new_id, "added"
ed_parser = CmdParser(add_help=False, prog='ed',
description='''Edits attributes of checkerboards
specified by ids.''')
ed_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='''ids of checkerboards in the current
group to be edited''')
ed_parser.add_argument('--dims', action=store_list(2, ',', to_decimal),
help='checkerboard dimensions in unit cells',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--init_unit',
action=store_list(2, ',', to_decimal),
help='initial unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--end_unit',
action=store_list(2, ',', to_decimal),
help='final unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--position',
action=store_list(2, ',', to_decimal),
help='position of checkerboard in pixels',
metavar='X,Y')
ed_parser.add_argument('--anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='LOCATION')
ed_parser.add_argument('--cols', metavar='COLOR1,COLOR2',
action=store_list(2, ',', to_color, [';']),
help='''checkerboard colors (color format:
R;G;B, component range
from 0-255)''')
ed_parser.add_argument('--freq', type=to_decimal,
help='frequency of color reversal in Hz')
ed_parser.add_argument('--phase', type=to_decimal,
help='initial phase in degrees')
def help_ed(self):
self.__class__.ed_parser.print_help()
def do_ed(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, please create one first'
return
try:
args = self.__class__.ed_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ed_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_group.shapes) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_shape_attr(self.cur_group, x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.ed_parser.print_usage()
rm_parser = CmdParser(add_help=False, prog='rm',
description='''Removes checkerboards specified
by ids.''')
rm_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''ids of checkerboards in the current group
to be removed''')
rm_parser.add_argument('-a', '--all', action='store_true',
help='''remove all checkerboards in the
current group''')
def help_rm(self):
self.__class__.rm_parser.print_help()
def do_rm(self, line):
"""Removes checkerboards specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, no boards to remove'
return
try:
args = self.__class__.rm_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rm_parser.print_usage()
return
rmlist = []
if args.all:
for shape in self.cur_group.shapes:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
print "all checkerboards removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_group.shapes) or x < 0:
print "checkerboard", x, "does not exist"
continue
rmlist.append(self.cur_group.shapes[x])
print "checkerboard", x, "removed"
for shape in rmlist:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
ls_parser = CmdParser(add_help=False, prog='ls',
description='''Lists project, display group and
checkerboard settings. If no group ids
are specified, all display groups
are listed.''')
ls_parser.add_argument('gids', nargs='*', metavar='gid', type=int,
help='''ids of the display groups to be listed''')
ls_group = ls_parser.add_mutually_exclusive_group()
ls_group.add_argument('-s', '--settings', action='store_true',
help='list only project settings')
ls_group.add_argument('-g', '--groups', action='store_true',
help='list only display groups')
ls_group.add_argument('-d', '--disp_ops', action='store_true',
help='list display options')
ls_group.add_argument('-o', '--orders', action='store_true',
help='list group orderings')
def help_ls(self):
self.__class__.ls_parser.print_help()
def do_ls(self, line):
"""Lists project, display group and checkerboard settings."""
def ls_str(s, seps=[',',';']):
"""Special space-saving output formatter."""
if type(s) in [tuple, list]:
if len(seps) > 1:
newseps = seps[1:]
else:
newseps = seps
return seps[0].join([ls_str(i, newseps) for i in s])
else:
return str(s)
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.ls_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ls_parser.print_usage()
return
# Remove duplicates and ascending sort
args.gids = sorted(set(args.gids))
if len(self.cur_proj.groups) == 0:
if len(args.gids) > 0:
print 'this project has no display groups that can be listed'
return
else:
for gid in args.gids[:]:
if gid >= len(self.cur_proj.groups) or gid < 0:
args.gids.remove(gid)
print 'display group', gid, 'does not exist'
if args.gids == []:
args.gids = range(len(self.cur_proj.groups))
else:
# If any (valid) groups are specified
# don't show project settings
args.groups = True
args.show_all = not max(args.settings, args.groups,
args.disp_ops, args.orders)
if args.show_all or args.settings:
print 'PROJECT SETTINGS'.center(70,'*')
print \
'name'.rjust(16),\
'fps'.rjust(7),\
'resolution'.rjust(14),\
'bg color'.rjust(18)
print \
ls_str(self.cur_proj.name).rjust(16),\
ls_str(self.cur_proj.fps).rjust(7),\
ls_str(self.cur_proj.res).rjust(14),\
ls_str(self.cur_proj.bg).rjust(18)
print \
'pre-display'.rjust(26),\
'post-display'.rjust(26)
print \
ls_str(self.cur_proj.pre).rjust(26),\
ls_str(self.cur_proj.post).rjust(26)
+ print \
+ 'pre-cross'.rjust(26),\
+ 'post-cross'.rjust(26)
+ print \
+ ls_str(self.cur_proj.pre_cross).rjust(26),\
+ ls_str(self.cur_proj.post_cross).rjust(26)
print \
'cross colors'.rjust(26),\
'cross times'.rjust(26)
print \
ls_str(self.cur_proj.cross_cols).rjust(26),\
ls_str(self.cur_proj.cross_times).rjust(26)
if args.show_all:
# Insert empty line between different info sets
print ''
if args.show_all or args.disp_ops:
print 'DISPLAY OPTIONS'.center(70,'*')
for k, v in self.cur_proj.disp_ops.items():
print ''.ljust(20), ls_str(k).ljust(20), ls_str(v).ljust(20)
if args.show_all:
# Insert empty line between different info sets
print ''
if args.show_all or args.orders:
print 'GROUP ORDERINGS'.center(70,'*')
if self.cur_proj.orders == []:
order = range(len(self.cur_proj.groups))
print \
''.ljust(20),\
'default order'.ljust(20),\
ls_str(order).ljust(20)
else:
for n, order in enumerate(self.cur_proj.orders):
print \
''.ljust(20),\
'order {n}'.format(n=n).ljust(20),\
ls_str(order).ljust(20)
if args.show_all:
# Insert empty line between different info sets
print ''
if args.show_all or args.groups:
for i, n in enumerate(args.gids):
if i != 0:
# Print newline seperator between each group
print ''
group = self.cur_proj.groups[n]
print 'GROUP {n}'.format(n=n).center(70,'*')
print \
'pre-display'.rjust(20),\
'display'.rjust(20),\
'post-display'.rjust(20)
print \
ls_str(group.pre).rjust(20),\
ls_str(group.disp).rjust(20),\
ls_str(group.post).rjust(20)
+ print \
+ 'pre-cross'.rjust(26),\
+ 'post-cross'.rjust(26)
+ print \
+ ls_str(group.pre_cross).rjust(26),\
+ ls_str(group.post_cross).rjust(26)
+
if len(group.shapes) > 0:
print \
''.rjust(2),\
'shape id'.rjust(8),\
'dims'.rjust(10),\
'init_unit'.rjust(14),\
'end_unit'.rjust(14),\
'position'.rjust(14)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.dims).rjust(10),\
ls_str(shape.init_unit).rjust(14),\
ls_str(shape.end_unit).rjust(14),\
ls_str(shape.position).rjust(14)
print '\n',\
''.rjust(2),\
'shape id'.rjust(8),\
'colors'.rjust(27),\
'anchor'.rjust(12),\
'freq'.rjust(6),\
'phase'.rjust(7)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.cols).rjust(27),\
ls_str(shape.anchor).rjust(12),\
ls_str(shape.freq).rjust(6),\
ls_str(shape.phase).rjust(7)
display_parser = CmdParser(add_help=False, prog='display',
description='''Displays the stimulus in a
window or in fullscreen.''')
display_parser.add_argument('-s', '--save', action='store_true',
help='''save specified display flags
as default flags for project
instead of presenting stimulus''')
display_parser.add_argument('-n', '--name', metavar='FOOBAR',
help='''name of log file to be written''')
display_parser.add_argument('-r', '--repeats', metavar='N', type=int,
help='''repeatedly display specified display
groups N number of times''')
display_parser.add_argument('-wl', '--waitless', action=store_truth(),
metavar='t/f',
help='''do not add waitscreens before the
start of each repeat''')
display_parser.add_argument('-f', '--fullscreen', action=store_truth(),
metavar='t/f',
help='sets fullscreen mode, ESC to quit')
display_parser.add_argument('-p', '--priority', metavar='LEVEL',
help='''set priority while displaying,
higher priority results in
less dropped frames (choices:
0-3, low, normal, high,
realtime)''')
display_parser.add_argument('-pt', '--phototest', action=store_truth(),
metavar='t/f',
help='''draw white test rectangle in topleft
corner of screen when groups become
visible for a photodiode to detect''')
display_parser.add_argument('-pb', '--photoburst', action=store_truth(),
metavar='t/f',
help='''make checkerboards only draw first
color for one frame to facilitate
testing with a photodiode''')
display_parser.add_argument('-lt', '--logtime', action=store_truth(),
metavar='t/f',
help='output frame timestamps to a log file')
display_parser.add_argument('-ld', '--logdur', action=store_truth(),
metavar='t/f',
help='output frame durations to a log file')
display_parser.add_argument('-ss', '--trigser', action=store_truth(),
metavar='t/f',
help='''send triggers through the serial port
when shapes are being displayed''')
display_parser.add_argument('-sp', '--trigpar', action=store_truth(),
metavar='t/f',
help='''send triggers through the parallel port
when shapes are being displayed''')
display_parser.add_argument('-fpst', metavar='M', type=int,
help='''unique trigger corresponding to a
checkerboard is sent after the shape
undergoes M color flips (default:
disabled, M=0)''')
display_parser.add_argument('-fc', '--freqcheck', action=store_truth(),
metavar='t/f',
help='''only send triggers for board color
flips at the start, middle and end
of the run''')
display_parser.add_argument('-et', '--eyetrack', action=store_truth(),
metavar='t/f',
help='''use eyetracking to ensure that subject
fixates on the cross in the center''')
display_parser.add_argument('-eu', '--etuser', action=store_truth(),
metavar='t/f',
help='''allow user to select eyetracking video
source from a dialog''')
display_parser.add_argument('-ev', '--etvideo', metavar='path',
help='''path (with no spaces) to eyetracking
video file to be used as the source''')
display_parser.add_argument('-ta', '--tryagain', metavar='I', type=int,
help='''append groups during which subject
failed to fixate up to I times to the
list of groups to be displayed
(default: disabled, I=0)''')
display_parser.add_argument('-tb', '--trybreak', metavar='J', type=int,
help='''used with --tryagain, append a wait
screen to the list of groups to be
displayed after every J groups have
been appended to the list (default:
J=total number of groups)''')
display_parser.add_argument('-nl', '--nolog', action=store_truth(),
metavar='t/f',
help='''do not write a log file''')
display_parser.add_argument('order', nargs='*', metavar='id', type=int,
help='''order in which groups should be
displayed (default: random order
from list of orders if specified
in project, ascending otherwise)''')
def help_display(self):
self.__class__.display_parser.print_help()
def do_display(self, line):
"""Displays the stimulus in a window or in fullscreen"""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.display_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
if len(args.order) > 0:
for i in set(args.order):
if i >= len(self.cur_proj.groups) or i < -1:
print 'error: group', i, 'does not exist'
return
if args.eyetrack and eyetracking.available:
if not eyetracking.is_calibrated():
try:
self.do_calibrate('',query=True)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
return
if args.save:
self.cur_proj.set_display_flags(repeats=args.repeats,
waitless=args.waitless,
fullscreen=args.fullscreen,
priority=args.priority,
logtime=args.logtime,
logdur=args.logdur,
trigser=args.trigser,
trigpar=args.trigpar,
fpst=args.fpst,
freqcheck=args.freqcheck,
phototest=args.phototest,
photoburst=args.photoburst,
eyetrack=args.eyetrack,
etuser=args.etuser,
etvideo=args.etvideo,
tryagain=args.tryagain,
trybreak=args.trybreak,
nolog=args.nolog)
print "display flags saved to project"
else:
print "displaying...",
try:
self.cur_proj.display(name=args.name,
repeats=args.repeats,
waitless=args.waitless,
fullscreen=args.fullscreen,
priority=args.priority,
logtime=args.logtime,
logdur=args.logdur,
trigser=args.trigser,
trigpar=args.trigpar,
fpst=args.fpst,
freqcheck=args.freqcheck,
phototest=args.phototest,
photoburst=args.photoburst,
eyetrack=args.eyetrack,
etuser=args.etuser,
etvideo=args.etvideo,
tryagain=args.tryagain,
trybreak=args.trybreak,
nolog=args.nolog,
order=args.order)
except (IOError, NotImplementedError,
eyetracking.EyetrackingError):
print ''
print "error:", str(sys.exc_value)
try:
priority.set('normal')
except:
pass
return
print "done"
export_parser = CmdParser(add_help=False, prog='export',
description='''Exports stimulus as an image
sequence (in a folder) to the
specified directory.''')
export_parser.add_argument('-n','--nofolder',
dest='folder', action='store_false',
help='''force images not to exported in
a containing folder''')
export_parser.add_argument('-r', '--repeats', metavar='N', type=int,
help='''repeatedly export specified display
groups N number of times''')
export_parser.add_argument('duration', nargs='?',
type=to_decimal, default='Infinity',
help='''number of seconds of the stimulus
that should be exported (default:
as long as the entire stimulus)''')
export_parser.add_argument('dir', nargs='?', default=os.getcwd(),
help='''destination directory for export
(default: current working directory)''')
export_parser.add_argument('order', nargs='*', metavar='id', type=int,
help='''order in which groups should be
displayed (default: random order
from list of orders if specified
in project, ascending otherwise)''')
def help_export(self):
self.__class__.export_parser.print_help()
def do_export(self, line):
"""Exports stimulus as an image sequence to the specified directory."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.export_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.export_parser.print_usage()
return
if len(args.order) > 0:
for i in set(args.order):
if i >= len(self.cur_proj.groups) or i < -1:
print 'error: group', i, 'does not exist'
return
try:
self.cur_proj.export(repeats=args.repeats,
order=args.order,
expo_dir=args.dir,
expo_dur=args.duration,
folder=args.folder)
except IOError:
print "error:", str(sys.exc_value)
return
except core.FrameOverflowError:
print "warning:", str(sys.exc_value)
print "Are you sure you want to continue?"
while True:
try:
if self.__class__.yn_parse(raw_input()):
self.cur_proj.export(repeats=args.repeats,
order=args.order,
expo_dir=args.dir,
expo_dur=args.duration,
folder=args.folder,
force=True)
break
else:
return
except TypeError:
print str(sys.exc_value)
except EOFError:
return
print "Export done."
def do_calibrate(self, line, query=False):
"""Calibrate subject for eyetracking, or load a calibration file."""
if not eyetracking.available:
print "error: eyetracking functionality not available"
return
if query:
print "path to calibration file (leave empty for GUI tool):"
try:
path = raw_input().strip().strip('"\'')
except EOFError:
msg = "calibration cancelled"
raise eyetracking.EyetrackingError(msg)
else:
path = line.strip().strip('"\'')
if len(path) == 0:
path = None
if not eyetracking.is_source_ready():
# Select default source if none has been selected
eyetracking.select_source()
try:
eyetracking.calibrate(path)
except eyetracking.EyetrackingError:
if query:
raise
else:
print "error:", str(sys.exc_value)
return
if path!= None and len(path) > 0:
print "calibration file successfully loaded"
etsetup_parser = CmdParser(add_help=False, prog='etsetup',
description='''Set various eyetracking
parameters.''')
etsetup_parser.add_argument('-fp', '--fixperiod', type=int, metavar='MS',
help='''time in milliseconds subject
has to stare at the same spot
for fixation to be detected''')
etsetup_parser.add_argument('-fr', '--fixrange', type=float, metavar='MM',
help='''distance in mm beyond which the
eye position cannot change for
a fixation to be detected''')
etsetup_parser.add_argument('-s', '--size', metavar='WIDTH,HEIGHT',
action=store_list(2, ',', float),
help='physical screen dimensions in mm')
etsetup_parser.add_argument('-vd', '--viewdist', type=int, metavar='MM',
help='''viewing distance between subject's
eyes and the screen''')
def help_etsetup(self):
self.__class__.etsetup_parser.print_help()
def do_etsetup(self, line):
try:
args = self.__class__.etsetup_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.etsetup_parser.print_usage()
return
try:
eyetracking.setup(viewing_distance=args.viewdist,
screen_dims=args.size,
fixation_period=args.fixperiod,
fixation_range=args.fixrange)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
def do_pwd(self, line):
"""Prints the current working directory."""
print os.getcwd()
def do_cd(self, line):
"""Change working directory to specified path."""
path = line.strip().strip('"\'')
if not os.path.isdir(path):
print "error: specified path is not a directory"
return
os.chdir(path)
def do_quit(self, line):
"""Quits the program."""
if self.save_check():
return
return True
def help_EOF(self):
print "Typing {0} issues this command, which quits the program."\
.format(CMD_EOF_STRING)
def do_EOF(self, line):
"""Typing Ctrl-D issues this command, which quits the program."""
print '\r'
if self.save_check():
return
return True
def help_help(self):
print 'Prints a list of commands.'
print "Type 'help <topic>' for more details on each command."
def default(self, line):
command = line.split()[0]
print \
"'{0}' is not a checkergen command.".format(command),\
"Type 'help' for a list of commands"
diff --git a/src/core.py b/src/core.py
index 15a721a..8e0dced 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,1336 +1,1336 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgDisplayGroup -- A set of CheckerShapes to be displayed siet_stateaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import copy
import random
import itertools
from datetime import datetime
from xml.dom import minidom
import pyglet
import graphics
import priority
import trigger
import eyetracking
from utils import *
# Use OrderedDict substitute if we don't have Python 2.7
if sys.version_info < (2, 7):
from odict import OrderedDict
else:
from collections import OrderedDict
CKG_FMT = 'ckg'
LOG_FMT = 'log'
MAX_EXPORT_FRAMES = 1000
EXPORT_DIR_SUFFIX = '-anim'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
INT_HALF_PERIODS = True
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = OrderedDict([('name', 'untitled'),
('fps', 60),
('res', (800, 600)),
('bg', (127, 127, 127)),
('pre', 0),
('post', 0),
('pre_cross', [(0, True)]),
('post_cross', [(0, True)]),
('cross_cols', ((0, 0, 0),
(255, 0, 0),
(0, 0, 255))),
('cross_times', ('Infinity', 1)),
('orders', []),
('disp_ops', None)])
DEFAULTS['disp_ops'] = OrderedDict([('repeats', 1),
('waitless', False),
('fullscreen', False),
('priority', None),
('logtime', False),
('logdur', False),
('trigser', False),
('trigpar', False),
('fpst', 0),
('freqcheck', False),
('phototest', False),
('photoburst', False),
('eyetrack', False),
('etuser', False),
('etvideo', None),
('tryagain', 0),
('trybreak', None),
('nolog', False),
('export', False),
('expo_dir', None),
('expo_dur', None),
('folder', True)])
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
- pre_cross -- dictionary specifying at what times during the pre
- period a cross should be shown (e.g. {to_decimal(0): False,
- to_decimal(2): True} means that a cross is not shown at the start,
- but is shown from 2 seconds onwards)
+ pre_cross -- key-value pairs specifying at what times during the pre
+ period a cross should be shown (e.g. [(0, False), (2, True)]
+ means that a cross is not shown at the start, but is shown
+ from 2 seconds onwards)
- post_cross -- dictionary specifying at what times during the post
+ post_cross -- key-value pairs specifying at what times during the post
period a cross should be shown
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'cross_cols':
if len(value) != 3:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name in ['pre_cross', 'post_cross']:
- value = [(to_decimal(k), v) for (k, v) in value]
+ value = [(to_decimal(k), to_bool(v)) for (k, v) in value]
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def set_display_flags(self, **keywords):
"""Set default display flags for the project.
Same arguments as 'display', excluding 'name' and 'order'.
"""
for kw in keywords.keys():
if kw in self.disp_ops.keys() and keywords[kw] != None:
self.disp_ops[kw] = keywords[kw]
self._dirty = True
def set_group_orders(self, orders):
for order in orders:
for gid in order:
if gid < -1 or gid >= len(self.groups):
msg = 'invalid group id (out of range)'
raise ValueError(msg)
self.orders = orders
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
# Vars that are dicts
dicts_to_load = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_load = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
for d_name in dicts_to_load:
d = copy.deepcopy(self.__class__.DEFAULTS[d_name])
try:
d_el = [node for node in project.childNodes if
node.localName == d_name and
node.namespaceURI == XML_NAMESPACE][0]
for var in d.keys():
try:
d[var] = eval(xml_get(d_el, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}' in '{1}'".\
format(var, d_name)
print "using default value '{0}' instead...".\
format(d[var])
except IndexError:
print "warning: missing attribute set '{0}'".format(d_name)
print "using default values instead..."
setattr(self, d_name, d)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
# Vars that are dicts
dicts_to_save = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_save = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for d_name in dicts_to_save:
d_el = doc.createElement(d_name)
project.appendChild(d_el)
d = getattr(self, d_name)
for k, v in d.iteritems():
xml_set(doc, d_el, k, repr(v))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, **keywords):
"""Displays the stimulus on the screen.
name -- name that logfile will be saved with
repeats -- number of times specified order of display groups should
be repeated
waitless -- if true, no waitscreens will appear at the start of each
repeat
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
priority -- priority level to which process should be raised
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
trigser -- send triggers through serial port when each group is shown
trigpar -- send triggers through parallel port when each group is shown
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
freqcheck -- send fpst only at the start, the middle, and the end
for sanity checking of display and trigger fps
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- append a wait screen to the group queue every time
after this many groups have been appended to the queue
order -- order in which groups (specified by id) will be displayed
"""
# Create RunState
disp_ops = copy.deepcopy(self.disp_ops)
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'name' in keywords.keys() and keywords['name'] != None:
name = keywords['name']
else:
timestr = datetime.today().strftime('_%Y-%m-%d_%H-%M-%S')
name = self.name + timestr
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
waitscreen = CkgWaitScreen()
# Set runstate order id if necessary
if order in self.orders:
runstate.ord_id = self.orders.index(order)
# Count through pre
for count in range(self.pre * self.fps):
if runstate.terminate:
break
pre_time = to_decimal(count) / runstate.fps
if pre_time in dict(self.pre_cross):
runstate.show_cross = dict(self.pre_cross)[pre_time]
runstate.update()
# Loop through repeats
repeats = runstate.disp_ops['repeats']
ord_len = len(runstate.order)
for i in range(repeats):
# Restart eyetracking
if runstate.disp_ops['eyetrack']:
eyetracking.stop()
eyetracking.start()
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
# Loop through display groups
runstate.events['blk_on'] = True
for n, gid in enumerate(runstate.order):
# Set flag for freqcheck
if runstate.disp_ops['freqcheck']:
if ((i == 0 and n == 0) or
(i == repeats-1 and n == ord_len-1) or
(i == repeats//2 and n == ord_len//2)):
runstate.fc_send = True
else:
runstate.fc_send = False
if gid == -1:
waitscreen.reset()
waitscreen.display(runstate)
else:
self.groups[gid].display(runstate)
if not runstate.terminate:
# Append group id and fail state
runstate.gids.append(gid)
if runstate.disp_ops['eyetrack']:
runstate.fails.append(runstate.true_fail)
# Append groups to be added
if runstate.true_fail:
if (len(runstate.add_gids) <
runstate.disp_ops['tryagain']):
runstate.add_gids.append(gid)
runstate.events['blk_off'] = True
# Stop freqcheck before added groups
if runstate.disp_ops['freqcheck']:
runstate.fc_send = False
# Loop through added groups
if runstate.disp_ops['eyetrack']:
for blk in grouper(runstate.add_gids,
runstate.disp_ops['trybreak']):
# Restart eyetracking
if runstate.disp_ops['eyetrack']:
eyetracking.stop()
eyetracking.start()
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
runstate.events['blk_on'] = True
# Loop through display groups
for gid in blk:
if gid != None:
self.groups[gid].display(runstate)
if not runstate.terminate:
# Append group id and fail state
runstate.gids.append(gid)
if runstate.disp_ops['eyetrack']:
runstate.fails.append(runstate.true_fail)
runstate.events['blk_off'] = True
# Count through post
for count in range(self.post * self.fps):
if runstate.terminate:
break
post_time = to_decimal(count) / runstate.fps
if post_time in dict(self.post_cross):
runstate.show_cross = dict(self.post_cross)[post_time]
runstate.update()
# Stop and output log
runstate.stop()
if not runstate.disp_ops['nolog']:
runstate.log()
def export(self, **keywords):
"""Exports the stimulus as a series of images, one image per frame.
repeats -- number of times specified order of display groups should
be repeated
order -- order in which groups (specified by id) will be displayed
expo_dir -- directory to which images will be exported
expo_dur -- time in seconds to which export will be limited
folder -- if true, images will be contained in a separate folder
within export directory
force -- force export to go through even if a large number
of frames are to be exported
"""
# Create RunState
disp_ops = copy.deepcopy(self.__class__.DEFAULTS['disp_ops'])
disp_ops['export'] = True
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=self.name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
# Warn user if a lot of frames will be exported
if 'force' not in keywords.keys():
keywords['force'] = False
groups_dur = sum([self.groups[i].duration()
for i in order]) * disp_ops['repeats']
total_frames = (self.pre + groups_dur + self.post) * self.fps
frames = min(total_frames, disp_ops['expo_dur'] * self.fps)
if frames > MAX_EXPORT_FRAMES and not keywords['force']:
msg = 'large number ({0}) of frames to be exported'.\
format(int(frames))
raise FrameOverflowError(msg)
runstate.frames = frames
# Count through pre
for count in range(self.pre * self.fps):
if runstate.terminate:
break
runstate.update()
# Loop through repeats
repeats = runstate.disp_ops['repeats']
for i in range(repeats):
# Loop through display groups
for n, gid in enumerate(runstate.order):
if gid != -1:
self.groups[gid].display(runstate)
# Count through post
for count in range(self.post * self.fps):
if runstate.terminate:
break
runstate.update()
# Stop runstate
runstate.stop()
class CkgRunState:
"""Contains information about the state of a checkergen project
when it is being displayed or exported."""
DEFAULTS = dict([('name', 'untitled'),
('res', None),
('fps', None),
('bg', None),
('cross_cols', None),
('cross_times', None),
('order', []),
('disp_ops', None),
('events', None),
('gids', []),
('fails', []),
('add_gids', []),
('timestamps', []),
('durstamps', []),
('trigstamps', [])])
DEFAULTS['events'] = dict([('ord_id', None),
('blk_on', False),
('blk_off', False),
('track_on', False),
('track_off', False),
('fix_on', False),
('fix_off', False),
('grp_on', False),
('grp_off', False),
('sids', set())])
def __init__(self, **keywords):
"""Creates the RunState."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
def start(self):
"""Initialize all subsystems and start the run."""
if self.disp_ops == None:
msg = "RunState lacks display options"
raise ValueError(msg)
if min(self.res, self.fps, self.bg,
self.cross_cols, self.cross_times) == None:
msg = "RunState intialized with insufficent project information"
raise ValueError(msg)
self._count = 0
self._old_code = 0
self.ord_id = None
self.terminate = False
# Flag used by freqcheck
self.fc_send = False
# Create fixation crosses
self.show_cross = True
self.fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if self.disp_ops['phototest']:
self.test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Initialize export
if self.disp_ops['export']:
if not os.path.isdir(self.disp_ops['expo_dir']):
msg = 'export path is not a directory'
raise IOError(msg)
if self.disp_ops['folder']:
self.save_dir = os.path.join(self.disp_ops['expo_dir'],
self.name + EXPORT_DIR_SUFFIX)
else:
self.save_dir = self.disp_ops['expo_dir']
if not os.path.isdir(self.save_dir):
os.mkdir(self.save_dir)
# Initialize ports
if self.disp_ops['trigser']:
if not trigger.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trigpar']:
if not trigger.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
trigger.init(self.disp_ops['trigser'], self.disp_ops['trigpar'])
# Initialize eyetracking
if self.disp_ops['eyetrack']:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trybreak'] == None:
self.disp_ops['trybreak'] = len(self.order)
self.fixated = False
self.old_fixated = False
self.tracked = False
self.old_tracked = False
self.fix_fail = False
self.true_fail = False
eyetracking.select_source(self.disp_ops['etuser'],
self.disp_ops['etvideo'])
eyetracking.start()
# Create window if not exporting
self.scaling = False
if not self.disp_ops['export']:
# Stretch to fit screen only if project res does not
# equal screen res
if self.disp_ops['fullscreen']:
self.window = pyglet.window.Window(fullscreen=True,
visible=False)
if (self.window.width, self.window.height) != self.res:
self.scaling = True
else:
self.window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
self.keystates = pyglet.window.key.KeyStateHandler()
self.window.push_handlers(self.keystates)
# Clear window and make visible
self.window.switch_to()
graphics.set_clear_color(self.bg)
self.window.clear()
self.window.set_visible()
# Create framebuffer object for drawing unscaled or exported scene
if self.scaling or self.disp_ops['export']:
self.canvas = pyglet.image.Texture.create(*self.res)
self.fbo = graphics.Framebuffer(self.canvas)
self.fbo.start_render()
graphics.set_clear_color(self.bg)
self.fbo.clear()
# Set process priority
if self.disp_ops['priority'] != None:
try:
priority.set(self.disp_ops['priority'])
except ValueError:
priority.set(int(self.disp_ops['priority']))
except:
pass
# Start timers
if self.disp_ops['logtime']:
self.timer = Timer()
self.timer.start()
if self.disp_ops['logdur']:
self.dur = Timer()
self.dur.start()
def update(self):
"""Update the RunState."""
# Check for tracking and fixation
if self.disp_ops['eyetrack']:
self.old_tracked = self.tracked
self.tracked = eyetracking.is_tracked(self.fps)
self.old_fixated = self.fixated
self.fixated = eyetracking.is_fixated(self.fps)
if self.show_cross:
if self.fixated:
# Draw normal cross color if fixating
self.fix_crosses[0].draw()
elif self.tracked:
# Draw 2nd cross color if tracked, not fixating
self.fix_crosses[1].draw()
else:
# Draw 3rd cross color if untracked
self.fix_crosses[2].draw()
# Update eyetracking events
if self.tracked != self.old_tracked:
if self.tracked:
self.events['track_on'] = True
else:
self.events['track_off'] = True
if self.fixated != self.old_fixated:
if self.fixated:
self.events['fix_on'] = True
else:
self.events['fix_off'] = True
# Check for failure of trial
if self.tracked and not self.fixated:
self.fix_fail = True
else:
# Change cross color based on time
if self.show_cross:
if (self._count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
self.fix_crosses[0].draw()
else:
self.fix_crosses[1].draw()
if self.disp_ops['export']:
# Save current frame to file
savepath = os.path.join(
self.save_dir, '{0}{2}.{1}'.\
format(self.name, 'png',
repr(self._count).zfill(numdigits(self.frames-1))))
self.canvas.save(savepath)
else:
# Blit canvas to screen if necessary
if self.scaling:
self.fbo.end_render()
self.canvas.blit(0, 0)
self.window.switch_to()
self.window.dispatch_events()
self.window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to lists
if self.disp_ops['logtime']:
self.timestamps.append(self.timer.elapsed())
elif self.disp_ops['logdur']:
self.timestamps.append('')
if self.disp_ops['logdur']:
self.durstamps.append(self.dur.restart())
elif self.disp_ops['logtime']:
self.durstamps.append('')
# Send trigger ASAP after flip
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
if self.encode_events() != self._old_code:
trigger.send(self.disp_ops['trigser'],
self.disp_ops['trigpar'],
self.encode_events())
self._old_code = self.encode_events
# Log when triggers are sent
if self.disp_ops['logtime'] and self.encode_events() > 0:
self.trigstamps.append(self.encode_events())
else:
self.trigstamps.append('')
# Clear canvas, events, prepare for next frame
if self.disp_ops['export']:
self.fbo.clear()
else:
if self.scaling:
self.fbo.start_render()
self.fbo.clear()
else:
self.window.clear()
if self.window.has_exit:
self.terminate = True
# Send ord_id immediately after blk_on
send_ord_id_next = self.events['blk_on']
self.events = copy.deepcopy(self.__class__.DEFAULTS['events'])
if send_ord_id_next:
self.events['ord_id'] = self.ord_id
self._count += 1
# Terminate export if the time has come
if self.disp_ops['export']:
if self._count >= self.frames:
self.terminate = True
def stop(self):
"""Clean up RunState."""
if self.disp_ops['eyetrack']:
eyetracking.stop()
if self.scaling or self.disp_ops['export']:
self.fbo.delete()
del self.canvas
if not self.disp_ops['export']:
self.window.close()
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
trigger.quit(self.disp_ops['trigser'], self.disp_ops['trigpar'])
try:
priority.set('normal')
except:
pass
def encode_events(self):
"""Hard code specific trigger values for events."""
code = 0
if self.events['ord_id'] != None:
code = self.events['ord_id'] + 1
elif self.events['blk_on']:
code = 128
elif self.events['blk_off']:
code = 127
else:
et_state = 0
if self.events['fix_on']:
et_state = 4
elif self.events['track_on']:
et_state = 2
if self.events['track_off']:
et_state = 1
elif self.events['fix_off']:
et_state = 2
if self.events['grp_on']:
code = 100 + et_state
elif self.events['grp_off']:
code = 90 + et_state
elif et_state > 0:
code = 110 + et_state
elif len(self.events['sids']) > 0:
code = ((0 in self.events['sids'])*2**0 +
(1 in self.events['sids'])*2**1 +
(2 in self.events['sids'])*2**2 +
(3 in self.events['sids'])*2**3 +
16)
return code
def log(self, path=None):
"""Write a log file for the experimental run in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, LOG_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(LOG_FMT):
path = '{0}.{1}'.format(path, LOG_FMT)
with open(path, 'wb') as logfile:
writer = csv.writer(logfile, dialect='excel-tab')
writer.writerow(['checkergen log file'])
writer.writerow(['display options:'])
writer.writerow(self.disp_ops.keys())
writer.writerow(self.disp_ops.values())
writer.writerow(['order:'] + self.order)
writer.writerow(['groups', 'failure'])
if not self.disp_ops['eyetrack']:
self.fails = ['NA'] * len(self.gids)
for i in zip(self.gids, self.fails):
writer.writerow(list(i))
if self.disp_ops['eyetrack']:
writer.writerow(['groups added'])
for blk in grouper(self.add_gids,
self.disp_ops['trybreak'], ''):
writer.writerow(blk)
if self.disp_ops['logtime'] or self.disp_ops['logdur']:
stamps = [self.timestamps, self.durstamps, self.trigstamps]
writer.writerow(['timestamps', 'durations', 'triggers'])
for stamp in zip(*stamps):
writer.writerow(list(stamp))
class CkgDisplayGroup:
DEFAULTS = OrderedDict([('pre', 0),
('disp', 'Infinity'),
('post', 0),
('pre_cross', [(0, True)]),
('post_cross', [(0, True)])])
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
pre_cross -- key-value pairs specifying at what times during the pre
- period a cross should be shown (e.g. {to_decimal(0): False,
- to_decimal(2): True} means that a cross is not shown at the start,
- but is shown from 2 seconds onwards)
+ period a cross should be shown (e.g. [(0, False), (2, True)]
+ means that a cross is not shown at the start, but is shown
+ from 2 seconds onwards)
post_cross -- key-value pairs specifying at what times during the post
period a cross should be shown
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in ['pre', 'disp', 'post']:
value = to_decimal(value)
elif name in ['pre_cross', 'post_cross']:
- value = [(to_decimal(k), v) for (k, v) in value]
+ value = [(to_decimal(k), to_bool(v)) for (k, v) in value]
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets counts and all contained shapes."""
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, runstate):
"""Draws all contained shapes during the appropriate interval."""
for shape in self.shapes:
shape.draw(photoburst=runstate.disp_ops['photoburst'])
def update(self, runstate):
"""Updates contained shapes, sets event triggers."""
# Set events to be sent
if runstate.disp_ops['fpst'] > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= runstate.disp_ops['fpst']:
if not runstate.disp_ops['freqcheck'] or runstate.fc_send:
runstate.events['sids'].add(n)
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(runstate.fps)
def display(self, runstate):
"""Display the group in the context described by supplied runstate."""
self.reset()
for count in range(self.pre * runstate.fps):
if runstate.terminate:
break
pre_time = to_decimal(count) / runstate.fps
if pre_time in dict(self.pre_cross):
runstate.show_cross = dict(self.pre_cross)[pre_time]
runstate.update()
runstate.events['grp_on'] = True
if runstate.disp_ops['eyetrack']:
runstate.fix_fail = False
runstate.true_fail = False
for count in range(self.disp * runstate.fps):
if runstate.terminate:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
runstate.events['grp_off'] = True
if runstate.disp_ops['eyetrack']:
if runstate.fix_fail:
runstate.true_fail = True
for count in range(self.post * runstate.fps):
if runstate.terminate:
break
post_time = to_decimal(count) / runstate.fps
if post_time in dict(self.post_cross):
runstate.show_cross = dict(self.post_cross)[post_time]
runstate.update()
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.steps_done = 0
def draw(self, runstate):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, runstate):
"""Checks for keypress, sends trigger upon end."""
if max([runstate.keystates[key] for
key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
def display(self, runstate):
"""Displays waitscreen in context described by supplied runstate."""
while self.steps_done < self.num_steps:
if runstate.terminate:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = OrderedDict([('dims', (5, 5)),
('init_unit', (30, 30)),
('end_unit', (50, 50)),
('position', (0, 0)),
('anchor', 'bottomleft'),
('cols', ((0, 0, 0), (255, 255, 255))),
('freq', 1),
('phase', 0)])
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
if INT_HALF_PERIODS:
frames_per_half_period = round(fps / (self.freq * 2))
degs_per_frame = 180 / to_decimal(frames_per_half_period)
else:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
anchor=self.anchor)
cur_unit_rect.col = self.cols[(i + j) % 2]
cur_unit_rect.add_to_batch(self._batches[0])
cur_unit_rect.col = self.cols[(i + j + 1) % 2]
cur_unit_rect.add_to_batch(self._batches[1])
# Increase x values
cur_unit_pos[0] += \
graphics.locations[self.anchor][0] * cur_unit[0]
cur_unit[0] += unit_grad[0]
# Reset x values
cur_unit_pos[0] = init_pos[0]
cur_unit[0] = init_unit[0]
# Increase y values
cur_unit_pos[1] += \
graphics.locations[self.anchor][1] * cur_unit[1]
cur_unit[1] += unit_grad[1]
self._computed = True
def draw(self, photoburst=False, always_compute=False):
"""Draws appropriate batch depending on current phase.
photoburst -- draw first color for only one frame for testing purposes
always_compute -- recompute what the checkerboard should look like
every frame
"""
if not self._computed or always_compute:
self.compute()
self._cur_phase %= 360
n = int(self._cur_phase // 180)
if photoburst and n == 0 and not self.flipped:
n = 1
self._batches[n].draw()
def lazydraw(self):
"""Only draws on color reversal."""
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if (cur_n != prev_n) or self._first_draw:
self.draw()
if self._first_draw:
self._first_draw = False
diff --git a/src/utils.py b/src/utils.py
index 623d62e..a3f82f5 100644
--- a/src/utils.py
+++ b/src/utils.py
@@ -1,103 +1,115 @@
"""Utility functions and classes."""
import os
import time
import math
from decimal import *
from itertools import *
def numdigits(x):
"""Returns number of digits in a decimal integer."""
if x == 0:
return 1
elif x < 0:
x = -x
return int(math.log(x, 10)) + 1
def public_dir(obj):
"""Returns all 'public' attributes of an object"""
names = dir(obj)
for name in names[:]:
if name[0] == '_' or name[-1] == '_':
names.remove(name)
return names
+def to_bool(s,
+ y_words=['t','y','1','True','true','yes','Yes'],
+ n_words=['f','n','0','False','false','no','No']):
+ """Converts certain strings to True or False."""
+ if str(s) in y_words:
+ return True
+ elif str(s) in n_words:
+ return False
+ else:
+ msg = 'Invalid true/false keyword'
+ raise ValueError(msg)
+
def to_decimal(s):
"""ValueError raising Decimal converter."""
try:
return Decimal(s)
except (InvalidOperation, TypeError):
try:
return Decimal(str(s))
except (InvalidOperation, TypeError):
raise ValueError
def to_color(s, sep=','):
"""Tries to cast a string to a color (3-tuple)."""
c = tuple([int(x) for x in s.split(sep)])
if len(c) != 3:
raise ValueError
return c
def to_list(s, sep=',', typecast=None):
"""Cast comma separated values to a list."""
l = s.split(sep)
if typecast != None:
l = [typecast(i) for i in l]
return l
def cyclic_permute(sequence):
"""Return a list of all cyclic permutations of supplied sequence."""
n = len(sequence)
return [[sequence[i - j] for i in range(n)] for j in range(n, 0, -1)]
# From itertools documentation
def grouper(iterable, n, fillvalue=None):
"""grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"""
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
class Timer:
"""High-res timer that should be cross-platform."""
def __init__(self):
# Assigns appropriate clock function based on OS
if os.name == 'nt':
self.clock = time.clock
self.clock()
elif os.name == 'posix':
self.clock = time.time
self.running = False
def start(self):
self.start_time = self.clock()
self.running = True
def stop(self):
if not self.running:
return None
self.stop_time = self.clock()
self.running = False
return self.stop_time - self.start_time
def elapsed(self):
if not self.running:
return None
cur_time = self.clock()
return cur_time - self.start_time
def restart(self):
old_start_time = self.start_time
self.start_time = self.clock()
self.running = True
return self.start_time - old_start_time
def tick(self, fps):
"""Limits loop to specified fps. To be placed at start of loop."""
fps = float(fps)
ret = self.elapsed()
if self.elapsed() != -1:
while self.elapsed() < (1.0 / fps):
pass
self.start()
if ret != -1:
return ret * 1000
|
ztangent/checkergen
|
f0af3f24a64e31715610d5a190aeee0180817eee
|
Cross visibility can be set during pre and post periods.
|
diff --git a/example.ckg b/example.ckg
index 6faf27e..b4ffb99 100644
--- a/example.ckg
+++ b/example.ckg
@@ -1,80 +1,80 @@
<?xml version="1.0" ?>
<project xmlns="http://github.com/ZOMGxuan/checkergen">
<fps>Decimal('60')</fps>
<res>(800, 600)</res>
<bg>(127, 127, 127)</bg>
<pre>Decimal('0')</pre>
<post>Decimal('0')</post>
- <cross_cols>((0, 0, 0), (255, 0, 0))</cross_cols>
+ <cross_cols>((0, 0, 0), (255, 0, 0), (0, 0, 255))</cross_cols>
<cross_times>(Decimal('Infinity'), Decimal('1'))</cross_times>
<orders>[]</orders>
<disp_ops>
<repeats>1</repeats>
<waitless>False</waitless>
<fullscreen>False</fullscreen>
<priority>None</priority>
<logtime>False</logtime>
<logdur>False</logdur>
<trigser>False</trigser>
<trigpar>False</trigpar>
<fpst>0</fpst>
<freqcheck>False</freqcheck>
<phototest>False</phototest>
<photoburst>False</photoburst>
<eyetrack>False</eyetrack>
<etuser>False</etuser>
<etvideo>None</etvideo>
<tryagain>0</tryagain>
<trybreak>None</trybreak>
<nolog>False</nolog>
<export>False</export>
<expo_dir>None</expo_dir>
<expo_dur>None</expo_dur>
<folder>True</folder>
</disp_ops>
<group>
<pre>Decimal('2')</pre>
<disp>Decimal('10')</disp>
<post>Decimal('2')</post>
<shape type="board">
<dims>(5, 5)</dims>
<init_unit>(Decimal('40'), Decimal('40'))</init_unit>
<end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<position>(Decimal('420'), Decimal('320'))</position>
<anchor>'bottomleft'</anchor>
<cols>((0, 0, 0), (255, 255, 255))</cols>
<freq>Decimal('1')</freq>
<phase>Decimal('0')</phase>
</shape>
<shape type="board">
<dims>(5, 5)</dims>
<init_unit>(Decimal('40'), Decimal('40'))</init_unit>
<end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<position>(Decimal('380'), Decimal('320'))</position>
<anchor>'bottomright'</anchor>
<cols>((0, 0, 0), (255, 255, 255))</cols>
<freq>Decimal('2')</freq>
<phase>Decimal('90')</phase>
</shape>
<shape type="board">
<dims>(5, 5)</dims>
<init_unit>(Decimal('40'), Decimal('40'))</init_unit>
<end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<position>(Decimal('420'), Decimal('280'))</position>
<anchor>'topleft'</anchor>
<cols>((0, 0, 0), (255, 255, 255))</cols>
<freq>Decimal('3')</freq>
<phase>Decimal('180')</phase>
</shape>
<shape type="board">
<dims>(5, 5)</dims>
<init_unit>(Decimal('40'), Decimal('40'))</init_unit>
<end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<position>(Decimal('380'), Decimal('280'))</position>
<anchor>'topright'</anchor>
<cols>((0, 0, 0), (255, 255, 255))</cols>
<freq>Decimal('4')</freq>
<phase>Decimal('270')</phase>
</shape>
</group>
</project>
diff --git a/src/core.py b/src/core.py
index 58a36c1..15a721a 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,1294 +1,1336 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgDisplayGroup -- A set of CheckerShapes to be displayed siet_stateaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import copy
import random
import itertools
from datetime import datetime
from xml.dom import minidom
import pyglet
import graphics
import priority
import trigger
import eyetracking
from utils import *
# Use OrderedDict substitute if we don't have Python 2.7
if sys.version_info < (2, 7):
from odict import OrderedDict
else:
from collections import OrderedDict
CKG_FMT = 'ckg'
LOG_FMT = 'log'
MAX_EXPORT_FRAMES = 1000
EXPORT_DIR_SUFFIX = '-anim'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
INT_HALF_PERIODS = True
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = OrderedDict([('name', 'untitled'),
('fps', 60),
('res', (800, 600)),
('bg', (127, 127, 127)),
('pre', 0),
('post', 0),
+ ('pre_cross', [(0, True)]),
+ ('post_cross', [(0, True)]),
('cross_cols', ((0, 0, 0),
(255, 0, 0),
(0, 0, 255))),
('cross_times', ('Infinity', 1)),
('orders', []),
('disp_ops', None)])
DEFAULTS['disp_ops'] = OrderedDict([('repeats', 1),
('waitless', False),
('fullscreen', False),
('priority', None),
('logtime', False),
('logdur', False),
('trigser', False),
('trigpar', False),
('fpst', 0),
('freqcheck', False),
('phototest', False),
('photoburst', False),
('eyetrack', False),
('etuser', False),
('etvideo', None),
('tryagain', 0),
('trybreak', None),
('nolog', False),
('export', False),
('expo_dir', None),
('expo_dur', None),
('folder', True)])
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
+ pre_cross -- dictionary specifying at what times during the pre
+ period a cross should be shown (e.g. {to_decimal(0): False,
+ to_decimal(2): True} means that a cross is not shown at the start,
+ but is shown from 2 seconds onwards)
+
+ post_cross -- dictionary specifying at what times during the post
+ period a cross should be shown
+
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'cross_cols':
if len(value) != 3:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
+ elif name in ['pre_cross', 'post_cross']:
+ value = [(to_decimal(k), v) for (k, v) in value]
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def set_display_flags(self, **keywords):
"""Set default display flags for the project.
Same arguments as 'display', excluding 'name' and 'order'.
"""
for kw in keywords.keys():
if kw in self.disp_ops.keys() and keywords[kw] != None:
self.disp_ops[kw] = keywords[kw]
self._dirty = True
def set_group_orders(self, orders):
for order in orders:
for gid in order:
if gid < -1 or gid >= len(self.groups):
msg = 'invalid group id (out of range)'
raise ValueError(msg)
self.orders = orders
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
# Vars that are dicts
dicts_to_load = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_load = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
for d_name in dicts_to_load:
d = copy.deepcopy(self.__class__.DEFAULTS[d_name])
try:
d_el = [node for node in project.childNodes if
node.localName == d_name and
node.namespaceURI == XML_NAMESPACE][0]
for var in d.keys():
try:
d[var] = eval(xml_get(d_el, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}' in '{1}'".\
format(var, d_name)
print "using default value '{0}' instead...".\
format(d[var])
except IndexError:
print "warning: missing attribute set '{0}'".format(d_name)
print "using default values instead..."
setattr(self, d_name, d)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
# Vars that are dicts
dicts_to_save = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_save = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for d_name in dicts_to_save:
d_el = doc.createElement(d_name)
project.appendChild(d_el)
d = getattr(self, d_name)
for k, v in d.iteritems():
xml_set(doc, d_el, k, repr(v))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, **keywords):
"""Displays the stimulus on the screen.
name -- name that logfile will be saved with
repeats -- number of times specified order of display groups should
be repeated
waitless -- if true, no waitscreens will appear at the start of each
repeat
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
priority -- priority level to which process should be raised
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
trigser -- send triggers through serial port when each group is shown
trigpar -- send triggers through parallel port when each group is shown
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
freqcheck -- send fpst only at the start, the middle, and the end
for sanity checking of display and trigger fps
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- append a wait screen to the group queue every time
after this many groups have been appended to the queue
order -- order in which groups (specified by id) will be displayed
"""
# Create RunState
disp_ops = copy.deepcopy(self.disp_ops)
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'name' in keywords.keys() and keywords['name'] != None:
name = keywords['name']
else:
timestr = datetime.today().strftime('_%Y-%m-%d_%H-%M-%S')
name = self.name + timestr
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
waitscreen = CkgWaitScreen()
# Set runstate order id if necessary
if order in self.orders:
runstate.ord_id = self.orders.index(order)
# Count through pre
for count in range(self.pre * self.fps):
if runstate.terminate:
break
+ pre_time = to_decimal(count) / runstate.fps
+ if pre_time in dict(self.pre_cross):
+ runstate.show_cross = dict(self.pre_cross)[pre_time]
runstate.update()
# Loop through repeats
repeats = runstate.disp_ops['repeats']
ord_len = len(runstate.order)
for i in range(repeats):
# Restart eyetracking
if runstate.disp_ops['eyetrack']:
eyetracking.stop()
eyetracking.start()
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
# Loop through display groups
runstate.events['blk_on'] = True
for n, gid in enumerate(runstate.order):
# Set flag for freqcheck
if runstate.disp_ops['freqcheck']:
if ((i == 0 and n == 0) or
(i == repeats-1 and n == ord_len-1) or
(i == repeats//2 and n == ord_len//2)):
runstate.fc_send = True
else:
runstate.fc_send = False
if gid == -1:
waitscreen.reset()
waitscreen.display(runstate)
else:
self.groups[gid].display(runstate)
if not runstate.terminate:
# Append group id and fail state
runstate.gids.append(gid)
if runstate.disp_ops['eyetrack']:
runstate.fails.append(runstate.true_fail)
# Append groups to be added
if runstate.true_fail:
if (len(runstate.add_gids) <
runstate.disp_ops['tryagain']):
runstate.add_gids.append(gid)
runstate.events['blk_off'] = True
# Stop freqcheck before added groups
if runstate.disp_ops['freqcheck']:
runstate.fc_send = False
# Loop through added groups
if runstate.disp_ops['eyetrack']:
for blk in grouper(runstate.add_gids,
runstate.disp_ops['trybreak']):
# Restart eyetracking
if runstate.disp_ops['eyetrack']:
eyetracking.stop()
eyetracking.start()
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
runstate.events['blk_on'] = True
# Loop through display groups
for gid in blk:
if gid != None:
self.groups[gid].display(runstate)
if not runstate.terminate:
# Append group id and fail state
runstate.gids.append(gid)
if runstate.disp_ops['eyetrack']:
runstate.fails.append(runstate.true_fail)
runstate.events['blk_off'] = True
# Count through post
for count in range(self.post * self.fps):
if runstate.terminate:
break
+ post_time = to_decimal(count) / runstate.fps
+ if post_time in dict(self.post_cross):
+ runstate.show_cross = dict(self.post_cross)[post_time]
runstate.update()
# Stop and output log
runstate.stop()
if not runstate.disp_ops['nolog']:
runstate.log()
def export(self, **keywords):
"""Exports the stimulus as a series of images, one image per frame.
repeats -- number of times specified order of display groups should
be repeated
order -- order in which groups (specified by id) will be displayed
expo_dir -- directory to which images will be exported
expo_dur -- time in seconds to which export will be limited
folder -- if true, images will be contained in a separate folder
within export directory
force -- force export to go through even if a large number
of frames are to be exported
"""
# Create RunState
disp_ops = copy.deepcopy(self.__class__.DEFAULTS['disp_ops'])
disp_ops['export'] = True
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=self.name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
# Warn user if a lot of frames will be exported
if 'force' not in keywords.keys():
keywords['force'] = False
groups_dur = sum([self.groups[i].duration()
for i in order]) * disp_ops['repeats']
total_frames = (self.pre + groups_dur + self.post) * self.fps
frames = min(total_frames, disp_ops['expo_dur'] * self.fps)
if frames > MAX_EXPORT_FRAMES and not keywords['force']:
msg = 'large number ({0}) of frames to be exported'.\
format(int(frames))
raise FrameOverflowError(msg)
runstate.frames = frames
# Count through pre
for count in range(self.pre * self.fps):
if runstate.terminate:
break
runstate.update()
# Loop through repeats
repeats = runstate.disp_ops['repeats']
for i in range(repeats):
# Loop through display groups
for n, gid in enumerate(runstate.order):
if gid != -1:
self.groups[gid].display(runstate)
# Count through post
for count in range(self.post * self.fps):
if runstate.terminate:
break
runstate.update()
# Stop runstate
runstate.stop()
class CkgRunState:
"""Contains information about the state of a checkergen project
when it is being displayed or exported."""
DEFAULTS = dict([('name', 'untitled'),
('res', None),
('fps', None),
('bg', None),
('cross_cols', None),
('cross_times', None),
('order', []),
('disp_ops', None),
('events', None),
('gids', []),
('fails', []),
('add_gids', []),
('timestamps', []),
('durstamps', []),
('trigstamps', [])])
DEFAULTS['events'] = dict([('ord_id', None),
('blk_on', False),
('blk_off', False),
('track_on', False),
('track_off', False),
('fix_on', False),
('fix_off', False),
('grp_on', False),
('grp_off', False),
('sids', set())])
def __init__(self, **keywords):
"""Creates the RunState."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
def start(self):
"""Initialize all subsystems and start the run."""
if self.disp_ops == None:
msg = "RunState lacks display options"
raise ValueError(msg)
if min(self.res, self.fps, self.bg,
self.cross_cols, self.cross_times) == None:
msg = "RunState intialized with insufficent project information"
raise ValueError(msg)
self._count = 0
self._old_code = 0
self.ord_id = None
self.terminate = False
# Flag used by freqcheck
self.fc_send = False
# Create fixation crosses
+ self.show_cross = True
self.fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if self.disp_ops['phototest']:
self.test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Initialize export
if self.disp_ops['export']:
if not os.path.isdir(self.disp_ops['expo_dir']):
msg = 'export path is not a directory'
raise IOError(msg)
if self.disp_ops['folder']:
self.save_dir = os.path.join(self.disp_ops['expo_dir'],
self.name + EXPORT_DIR_SUFFIX)
else:
self.save_dir = self.disp_ops['expo_dir']
if not os.path.isdir(self.save_dir):
os.mkdir(self.save_dir)
# Initialize ports
if self.disp_ops['trigser']:
if not trigger.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trigpar']:
if not trigger.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
trigger.init(self.disp_ops['trigser'], self.disp_ops['trigpar'])
# Initialize eyetracking
if self.disp_ops['eyetrack']:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trybreak'] == None:
self.disp_ops['trybreak'] = len(self.order)
self.fixated = False
self.old_fixated = False
self.tracked = False
self.old_tracked = False
self.fix_fail = False
self.true_fail = False
eyetracking.select_source(self.disp_ops['etuser'],
self.disp_ops['etvideo'])
eyetracking.start()
# Create window if not exporting
self.scaling = False
if not self.disp_ops['export']:
# Stretch to fit screen only if project res does not
# equal screen res
if self.disp_ops['fullscreen']:
self.window = pyglet.window.Window(fullscreen=True,
visible=False)
if (self.window.width, self.window.height) != self.res:
self.scaling = True
else:
self.window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
self.keystates = pyglet.window.key.KeyStateHandler()
self.window.push_handlers(self.keystates)
# Clear window and make visible
self.window.switch_to()
graphics.set_clear_color(self.bg)
self.window.clear()
self.window.set_visible()
# Create framebuffer object for drawing unscaled or exported scene
if self.scaling or self.disp_ops['export']:
self.canvas = pyglet.image.Texture.create(*self.res)
self.fbo = graphics.Framebuffer(self.canvas)
self.fbo.start_render()
graphics.set_clear_color(self.bg)
self.fbo.clear()
# Set process priority
if self.disp_ops['priority'] != None:
try:
priority.set(self.disp_ops['priority'])
except ValueError:
priority.set(int(self.disp_ops['priority']))
except:
pass
# Start timers
if self.disp_ops['logtime']:
self.timer = Timer()
self.timer.start()
if self.disp_ops['logdur']:
self.dur = Timer()
self.dur.start()
def update(self):
"""Update the RunState."""
# Check for tracking and fixation
if self.disp_ops['eyetrack']:
self.old_tracked = self.tracked
self.tracked = eyetracking.is_tracked(self.fps)
self.old_fixated = self.fixated
self.fixated = eyetracking.is_fixated(self.fps)
- if self.fixated:
- # Draw normal cross color if fixating
- self.fix_crosses[0].draw()
- elif self.tracked:
- # Draw 2nd cross color if tracked, not fixating
- self.fix_crosses[1].draw()
- else:
- # Draw 3rd cross color if untracked
- self.fix_crosses[2].draw()
+ if self.show_cross:
+ if self.fixated:
+ # Draw normal cross color if fixating
+ self.fix_crosses[0].draw()
+ elif self.tracked:
+ # Draw 2nd cross color if tracked, not fixating
+ self.fix_crosses[1].draw()
+ else:
+ # Draw 3rd cross color if untracked
+ self.fix_crosses[2].draw()
# Update eyetracking events
if self.tracked != self.old_tracked:
if self.tracked:
self.events['track_on'] = True
else:
self.events['track_off'] = True
if self.fixated != self.old_fixated:
if self.fixated:
self.events['fix_on'] = True
else:
self.events['fix_off'] = True
# Check for failure of trial
if self.tracked and not self.fixated:
self.fix_fail = True
else:
# Change cross color based on time
- if (self._count % (sum(self.cross_times) * self.fps)
- < self.cross_times[0] * self.fps):
- self.fix_crosses[0].draw()
- else:
- self.fix_crosses[1].draw()
+ if self.show_cross:
+ if (self._count % (sum(self.cross_times) * self.fps)
+ < self.cross_times[0] * self.fps):
+ self.fix_crosses[0].draw()
+ else:
+ self.fix_crosses[1].draw()
if self.disp_ops['export']:
# Save current frame to file
savepath = os.path.join(
self.save_dir, '{0}{2}.{1}'.\
format(self.name, 'png',
repr(self._count).zfill(numdigits(self.frames-1))))
self.canvas.save(savepath)
else:
# Blit canvas to screen if necessary
if self.scaling:
self.fbo.end_render()
self.canvas.blit(0, 0)
self.window.switch_to()
self.window.dispatch_events()
self.window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to lists
if self.disp_ops['logtime']:
self.timestamps.append(self.timer.elapsed())
elif self.disp_ops['logdur']:
self.timestamps.append('')
if self.disp_ops['logdur']:
self.durstamps.append(self.dur.restart())
elif self.disp_ops['logtime']:
self.durstamps.append('')
# Send trigger ASAP after flip
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
if self.encode_events() != self._old_code:
trigger.send(self.disp_ops['trigser'],
self.disp_ops['trigpar'],
self.encode_events())
self._old_code = self.encode_events
# Log when triggers are sent
if self.disp_ops['logtime'] and self.encode_events() > 0:
self.trigstamps.append(self.encode_events())
else:
self.trigstamps.append('')
# Clear canvas, events, prepare for next frame
if self.disp_ops['export']:
self.fbo.clear()
else:
if self.scaling:
self.fbo.start_render()
self.fbo.clear()
else:
self.window.clear()
if self.window.has_exit:
self.terminate = True
# Send ord_id immediately after blk_on
send_ord_id_next = self.events['blk_on']
self.events = copy.deepcopy(self.__class__.DEFAULTS['events'])
if send_ord_id_next:
self.events['ord_id'] = self.ord_id
self._count += 1
# Terminate export if the time has come
if self.disp_ops['export']:
if self._count >= self.frames:
self.terminate = True
def stop(self):
"""Clean up RunState."""
if self.disp_ops['eyetrack']:
eyetracking.stop()
if self.scaling or self.disp_ops['export']:
self.fbo.delete()
del self.canvas
if not self.disp_ops['export']:
self.window.close()
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
trigger.quit(self.disp_ops['trigser'], self.disp_ops['trigpar'])
try:
priority.set('normal')
except:
pass
def encode_events(self):
"""Hard code specific trigger values for events."""
code = 0
if self.events['ord_id'] != None:
code = self.events['ord_id'] + 1
elif self.events['blk_on']:
code = 128
elif self.events['blk_off']:
code = 127
else:
et_state = 0
if self.events['fix_on']:
et_state = 4
elif self.events['track_on']:
et_state = 2
if self.events['track_off']:
et_state = 1
elif self.events['fix_off']:
et_state = 2
if self.events['grp_on']:
code = 100 + et_state
elif self.events['grp_off']:
code = 90 + et_state
elif et_state > 0:
code = 110 + et_state
elif len(self.events['sids']) > 0:
code = ((0 in self.events['sids'])*2**0 +
(1 in self.events['sids'])*2**1 +
(2 in self.events['sids'])*2**2 +
(3 in self.events['sids'])*2**3 +
16)
return code
def log(self, path=None):
"""Write a log file for the experimental run in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, LOG_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(LOG_FMT):
path = '{0}.{1}'.format(path, LOG_FMT)
with open(path, 'wb') as logfile:
writer = csv.writer(logfile, dialect='excel-tab')
writer.writerow(['checkergen log file'])
writer.writerow(['display options:'])
writer.writerow(self.disp_ops.keys())
writer.writerow(self.disp_ops.values())
writer.writerow(['order:'] + self.order)
writer.writerow(['groups', 'failure'])
if not self.disp_ops['eyetrack']:
self.fails = ['NA'] * len(self.gids)
for i in zip(self.gids, self.fails):
writer.writerow(list(i))
if self.disp_ops['eyetrack']:
writer.writerow(['groups added'])
for blk in grouper(self.add_gids,
self.disp_ops['trybreak'], ''):
writer.writerow(blk)
if self.disp_ops['logtime'] or self.disp_ops['logdur']:
stamps = [self.timestamps, self.durstamps, self.trigstamps]
writer.writerow(['timestamps', 'durations', 'triggers'])
for stamp in zip(*stamps):
writer.writerow(list(stamp))
class CkgDisplayGroup:
- DEFAULTS = OrderedDict([('pre', 0), ('disp', 'Infinity'), ('post', 0)])
+ DEFAULTS = OrderedDict([('pre', 0),
+ ('disp', 'Infinity'),
+ ('post', 0),
+ ('pre_cross', [(0, True)]),
+ ('post_cross', [(0, True)])])
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
+ pre_cross -- key-value pairs specifying at what times during the pre
+ period a cross should be shown (e.g. {to_decimal(0): False,
+ to_decimal(2): True} means that a cross is not shown at the start,
+ but is shown from 2 seconds onwards)
+
+ post_cross -- key-value pairs specifying at what times during the post
+ period a cross should be shown
+
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.shapes = []
self.reset()
def __setattr__(self, name, value):
- if name in self.__class__.DEFAULTS:
+ if name in ['pre', 'disp', 'post']:
value = to_decimal(value)
+ elif name in ['pre_cross', 'post_cross']:
+ value = [(to_decimal(k), v) for (k, v) in value]
+
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets counts and all contained shapes."""
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, runstate):
"""Draws all contained shapes during the appropriate interval."""
for shape in self.shapes:
shape.draw(photoburst=runstate.disp_ops['photoburst'])
def update(self, runstate):
"""Updates contained shapes, sets event triggers."""
# Set events to be sent
if runstate.disp_ops['fpst'] > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= runstate.disp_ops['fpst']:
if not runstate.disp_ops['freqcheck'] or runstate.fc_send:
runstate.events['sids'].add(n)
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(runstate.fps)
def display(self, runstate):
"""Display the group in the context described by supplied runstate."""
self.reset()
for count in range(self.pre * runstate.fps):
if runstate.terminate:
break
+ pre_time = to_decimal(count) / runstate.fps
+ if pre_time in dict(self.pre_cross):
+ runstate.show_cross = dict(self.pre_cross)[pre_time]
runstate.update()
runstate.events['grp_on'] = True
if runstate.disp_ops['eyetrack']:
runstate.fix_fail = False
runstate.true_fail = False
for count in range(self.disp * runstate.fps):
if runstate.terminate:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
runstate.events['grp_off'] = True
if runstate.disp_ops['eyetrack']:
if runstate.fix_fail:
runstate.true_fail = True
for count in range(self.post * runstate.fps):
if runstate.terminate:
break
+ post_time = to_decimal(count) / runstate.fps
+ if post_time in dict(self.post_cross):
+ runstate.show_cross = dict(self.post_cross)[post_time]
runstate.update()
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.steps_done = 0
def draw(self, runstate):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, runstate):
"""Checks for keypress, sends trigger upon end."""
if max([runstate.keystates[key] for
key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
def display(self, runstate):
"""Displays waitscreen in context described by supplied runstate."""
while self.steps_done < self.num_steps:
if runstate.terminate:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = OrderedDict([('dims', (5, 5)),
('init_unit', (30, 30)),
('end_unit', (50, 50)),
('position', (0, 0)),
('anchor', 'bottomleft'),
('cols', ((0, 0, 0), (255, 255, 255))),
('freq', 1),
('phase', 0)])
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
if INT_HALF_PERIODS:
frames_per_half_period = round(fps / (self.freq * 2))
degs_per_frame = 180 / to_decimal(frames_per_half_period)
else:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
anchor=self.anchor)
cur_unit_rect.col = self.cols[(i + j) % 2]
cur_unit_rect.add_to_batch(self._batches[0])
cur_unit_rect.col = self.cols[(i + j + 1) % 2]
cur_unit_rect.add_to_batch(self._batches[1])
# Increase x values
cur_unit_pos[0] += \
graphics.locations[self.anchor][0] * cur_unit[0]
cur_unit[0] += unit_grad[0]
# Reset x values
cur_unit_pos[0] = init_pos[0]
cur_unit[0] = init_unit[0]
# Increase y values
cur_unit_pos[1] += \
graphics.locations[self.anchor][1] * cur_unit[1]
cur_unit[1] += unit_grad[1]
self._computed = True
def draw(self, photoburst=False, always_compute=False):
"""Draws appropriate batch depending on current phase.
photoburst -- draw first color for only one frame for testing purposes
always_compute -- recompute what the checkerboard should look like
every frame
"""
if not self._computed or always_compute:
self.compute()
self._cur_phase %= 360
n = int(self._cur_phase // 180)
if photoburst and n == 0 and not self.flipped:
n = 1
self._batches[n].draw()
def lazydraw(self):
"""Only draws on color reversal."""
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if (cur_n != prev_n) or self._first_draw:
self.draw()
if self._first_draw:
self._first_draw = False
|
ztangent/checkergen
|
a08d4a05f924f927bfcb9260a60b1d240cb1c04a
|
CLI reflects changes in fix cross coloration (3 colors instead of 2)
|
diff --git a/src/cli.py b/src/cli.py
index 8e3de68..beea467 100644
--- a/src/cli.py
+++ b/src/cli.py
@@ -1,756 +1,757 @@
"""Defines command-line-interface for checkergen."""
import os
import sys
if os.name == 'posix':
import readline
import argparse
import cmd
import shlex
import core
import priority
import eyetracking
from graphics import locations
from utils import *
CMD_PROMPT = '(ckg) '
CMD_EOF_STRING = 'Ctrl-D'
if sys.platform == 'win32':
CMD_EOF_STRING = 'Ctrl-Z + Enter'
CMD_INTRO = '\n'.join(["Enter 'help' for a list of commands.",
"Enter 'quit' or {0} to exit.".format(CMD_EOF_STRING)])
def store_list(nargs=None, sep=',', typecast=None, castargs=[]):
"""Returns argparse action that stores a list or tuple."""
class ListAction(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
vallist = values.split(sep)
if nargs != None and len(vallist) != nargs:
msg = ("argument '{f}' should be a list of " +
"{nargs} values separated by '{sep}'").\
format(f=self.dest,nargs=nargs,sep=sep)
raise argparse.ArgumentError(self, msg)
if typecast != None:
for n, val in enumerate(vallist):
try:
val = typecast(*([val] + castargs))
vallist[n] = val
except (ValueError, TypeError):
msg = ("element '{val}' of argument '{f}' " +
"is of the wrong type").\
format(val=vallist[n],f=self.dest)
raise argparse.ArgumentError(self, msg)
if nargs == None:
setattr(args, self.dest, vallist)
else:
setattr(args, self.dest, tuple(vallist))
return ListAction
def store_truth(y_words=['t','y','1','True','true','yes','Yes'],
n_words=['f','n','0','False','false','no','No']):
"""Returns argparse action that stores the truth based on keywords."""
class TruthAction(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
if values in y_words:
setattr(args, self.dest, True)
elif values in n_words:
setattr(args, self.dest, False)
else:
msg = 'true/false keyword unrecognized'
raise argparse.ArgumentError(self, msg)
return TruthAction
# The main parser invoked at the command-line
PARSER = argparse.ArgumentParser(
description='''Generate flashing checkerboard patterns for display
or export as a series of images, intended for use in
psychophysics experiments. Enters interactive command
line mode if no options are specified.''')
PARSER.add_argument('-c', '--cmd', dest='cmd_mode', action='store_true',
help='enter command line mode regardless of other options')
PARSER.add_argument('-d', '--display',
dest='display_flag', action='store_true',
help='displays the stimulus on the screen')
PARSER.add_argument('-e', '--export', dest='export_dur', metavar='DUR',
help='export DUR seconds of the stimulus')
PARSER.add_argument('-f', '--fullscreen', action='store_true',
help='stimulus displayed in fullscreen mode')
PARSER.add_argument('--dir', dest='export_dir',
default=os.getcwd(), metavar='PATH',
help='''destination directory for export
(default: current working directory)''')
PARSER.add_argument('path', metavar='project', nargs='?', type=file,
help='checkergen project file to open')
def process_args(args):
"""Further processes the arguments returned by the main parser."""
if args.export_dur != None:
args.export_flag = True
else:
args.export_flag = False
if not args.display_flag and not args.export_flag:
args.cmd_mode = True
if args.path != None:
if not os.path.isfile(args.path):
msg = 'error: path specified is not a file'
return msg
args.proj = core.CkgProj(path=args.path)
os.chdir(os.path.dirname(os.path.abspath(args.path)))
try:
args.group = args.proj.groups[0]
except IndexError:
args.group = None
else:
args.proj = None
args.group = None
if args.display_flag or args.export_flag:
msg = 'error: no project file specified for display or export'
return msg
class CmdParserError(Exception):
"""To be raised when CmdParser encounters an error."""
pass
class CmdParser(argparse.ArgumentParser):
"""Override ArgumentParser so that it doesn't exit the program."""
def error(self, msg):
raise CmdParserError(msg)
class CkgCmd(cmd.Cmd):
@staticmethod
def yn_parse(s):
if s in ['y', 'Y', 'yes', 'YES', 'Yes']:
return True
elif s in ['n', 'N', 'no', 'NO', 'No']:
return False
else:
msg = "only 'y','n' or variants accepted"
raise ValueError(msg)
def save_check(self, msg=None):
"""Checks and prompts the user to save if necessary."""
if self.cur_proj == None:
return
if not self.cur_proj.is_dirty():
return
if msg == None:
msg = 'Would you like to save the current project first? (y/n)'
print msg
while True:
try:
if self.__class__.yn_parse(raw_input()):
self.do_save('')
break
except TypeError:
print str(sys.exc_value)
except EOFError:
return True
def do_new(self, line):
"""Creates new project with given name (can contain whitespace)."""
name = line.strip().strip('"\'')
if len(name) == 0:
name = 'untitled'
if self.save_check():
return
self.cur_proj = core.CkgProj(name=name)
print 'project \'{0}\' created'.format(self.cur_proj.name)
def do_open(self, line):
"""Open specified project file."""
path = line.strip().strip('"\'')
if len(path) == 0:
print 'error: no path specified'
return
if self.save_check():
return
try:
self.cur_proj = core.CkgProj(path=path)
except (core.FileFormatError, IOError):
print "error:", str(sys.exc_value)
return
os.chdir(os.path.dirname(os.path.abspath(path)))
try:
self.cur_group = self.cur_proj.groups[0]
except IndexError:
self.cur_group = None
print 'project \'{0}\' loaded'.format(self.cur_proj.name)
def do_close(self, line):
"""Prompts the user to save, then closes current project."""
if self.cur_proj == None:
print 'no project to close'
return
if self.save_check():
return
self.cur_proj = None
print 'project closed'
def do_save(self, line):
"""Saves the current project to the specified path."""
if self.cur_proj == None:
print 'no project to save'
return
path = line.strip().strip('"\'')
if len(path) == 0:
path = os.getcwd()
path = os.path.abspath(path)
if os.path.isdir(path):
path = os.path.join(path,
'.'.join([self.cur_proj.name, core.CKG_FMT]))
elif os.path.isdir(os.path.dirname(path)):
pass
else:
print 'error: specified directory does not exist'
return
# project save will add file extension if necessary
try:
path = self.cur_proj.save(path)
except IOError:
print "error:", str(sys.exc_value)
return
print 'project saved to "{0}"'.format(path)
set_parser = CmdParser(add_help=False, prog='set',
description='''Sets various project settings.''')
set_parser.add_argument('-n', '--name',
help='''project name, always the same as the
filename without the extension''')
set_parser.add_argument('-f', '--fps', type=to_decimal,
help='''number of stimulus frames
rendered per second''')
set_parser.add_argument('-r', '--res', action=store_list(2, ',', int),
help='stimulus canvas size/resolution in pixels',
metavar='WIDTH,HEIGHT')
set_parser.add_argument('-bg', '--bg', metavar='COLOR', type=to_color,
help='''background color of the canvas
(color format: R,G,B,
component range from 0-255)''')
set_parser.add_argument('-pr', '--pre',
type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown before any display groups''')
set_parser.add_argument('-po', '--post',
type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown after all display groups''')
- set_parser.add_argument('-cc', '--cross_cols', metavar='COLOR1,COLOR2',
- action=store_list(2, ',', to_color, [';']),
+ set_parser.add_argument('-cc', '--cross_cols',
+ metavar='COLOR1,COLOR2,COLOR3',
+ action=store_list(3, ',', to_color, [';']),
help='''fixation cross coloration
(color format: R;G;B,
component range from 0-255)''')
set_parser.add_argument('-ct', '--cross_times', metavar='TIME1,TIME2',
action=store_list(2, ',', to_decimal),
help='''time in seconds each cross color
will be displayed''')
set_group = set_parser.add_mutually_exclusive_group()
set_group.add_argument('-o', '--orders', metavar='ORDER1;ORDER2;...',
action=store_list(None, ';', to_list, [',', int]),
help='''list of orders separated by semicolons
where each order is a list of group ids
separated by commas''')
set_group.add_argument('-go', '--genorders', action='store_true',
help='''automatically generate a reduced latin
square for use as group orders''')
def help_set(self):
self.__class__.set_parser.print_help()
def do_set(self, line):
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
try:
args = self.__class__.set_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.set_parser.print_usage()
return
names = public_dir(args)
names.remove('orders')
names.remove('genorders')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
setattr(self.cur_proj, name, val)
noflags = False
if args.genorders:
orders = cyclic_permute(range(len(self.cur_proj.groups)))
try:
self.cur_proj.set_group_orders(orders)
except ValueError:
print "error:", str(sys.exc_value)
noflags = False
elif args.orders != None:
try:
self.cur_proj.set_group_orders(args.orders)
except ValueError:
print "error:", str(sys.exc_value)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.set_parser.print_usage()
mkgrp_parser = CmdParser(add_help=False, prog='mkgrp',
formatter_class=
argparse.ArgumentDefaultsHelpFormatter,
description='''Makes a new display group
with the given parameters.''')
mkgrp_parser.add_argument('pre', type=to_decimal, default=0, nargs='?',
help='''time in seconds a blank screen will
be shown before shapes are displayed''')
mkgrp_parser.add_argument('disp', type=to_decimal,
nargs='?', default='Infinity',
help='''time in seconds shapes will be
displayed''')
mkgrp_parser.add_argument('post', type=to_decimal, default=0, nargs='?',
help='''time in seconds a blank screen will
be shown after shapes are displayed''')
def help_mkgrp(self):
self.__class__.mkgrp_parser.print_help()
def do_mkgrp(self, line):
"""Makes a display group with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
try:
args = self.__class__.mkgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mkgrp_parser.print_usage()
return
group_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_group = core.CkgDisplayGroup(**group_dict)
new_id = self.cur_proj.add_group(new_group)
print "display group", new_id, "added"
self.cur_group = new_group
print "group", new_id, "is now the current display group"
edgrp_parser = CmdParser(add_help=False, prog='edgrp',
description='''Edits attributes of display groups
specified by ids.''')
edgrp_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='ids of display groups to be edited')
edgrp_parser.add_argument('--pre', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown before shapes are displayed''')
edgrp_parser.add_argument('--disp', type=to_decimal, metavar='SECONDS',
help='''time in seconds shapes will be
displayed''')
edgrp_parser.add_argument('--post', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown after shapes are displayed''')
def help_edgrp(self):
self.__class__.edgrp_parser.print_help()
def do_edgrp(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.edgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.edgrp_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_proj.groups) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_group_attr(x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.edgrp_parser.print_usage()
rmgrp_parser = CmdParser(add_help=False, prog='rmgrp',
description='''Removes display groups specified
by ids.''')
rmgrp_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='ids of display groups to be removed')
rmgrp_parser.add_argument('-a', '--all', action='store_true',
help='remove all groups from the project')
def help_rmgrp(self):
self.__class__.rmgrp_parser.print_help()
def do_rmgrp(self, line):
"""Removes display groups specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups to remove'
return
try:
args = self.__class__.rmgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rmgrp_parser.print_usage()
return
rmlist = []
if args.all:
for group in self.cur_proj.groups[:]:
self.cur_proj.del_group(group)
print "all display groups removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_proj.groups) or x < 0:
print "display group", x, "does not exist"
continue
rmlist.append(self.cur_proj.groups[x])
print "display group", x, "removed"
for group in rmlist:
self.cur_proj.del_group(group)
# Remember to point self.cur_group somewhere sane
if self.cur_group not in self.cur_proj.groups:
if len(self.cur_proj.groups) == 0:
self.cur_group = None
else:
self.cur_group = self.cur_proj.groups[0]
print "group 0 is now the current display group"
chgrp_parser = CmdParser(add_help=False, prog='chgrp',
description='''Changes display group that is
currently active for editing.
Prints current group id if
no group id is specified''')
chgrp_parser.add_argument('gid', metavar='id', type=int, nargs='?',
help='id of display group to be made active')
def help_chgrp(self):
self.__class__.chgrp_parser.print_help()
def do_chgrp(self, line):
"""Changes group that is currently active for editing."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups that can be made active'
return
try:
args = self.__class__.chgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.chgrp_parser.print_usage()
return
if args.gid == None:
print "group",\
self.cur_proj.groups.index(self.cur_group),\
"is the current display group"
elif args.gid >= len(self.cur_proj.groups) or args.gid < 0:
print "group", args.gid, "does not exist"
else:
self.cur_group = self.cur_proj.groups[args.gid]
print "group", args.gid, "is now the current display group"
mk_parser = CmdParser(add_help=False, prog='mk',
description='''Makes a new checkerboard in the
current group with the given
parameters.''')
mk_parser.add_argument('dims', action=store_list(2, ',', to_decimal),
help='''width,height of checkerboard in no. of
unit cells''')
mk_parser.add_argument('init_unit', action=store_list(2, ',', to_decimal),
help='width,height of initial unit cell in pixels')
mk_parser.add_argument('end_unit', action=store_list(2, ',', to_decimal),
help='width,height of final unit cell in pixels')
mk_parser.add_argument('position', action=store_list(2, ',', to_decimal),
help='x,y position of checkerboard in pixels')
mk_parser.add_argument('anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='anchor')
mk_parser.add_argument('cols', action=store_list(2, ',', to_color, [';']),
help='''color1,color2 of the checkerboard
(color format: R;G;B,
component range from 0-255)''')
mk_parser.add_argument('freq', type=to_decimal,
help='frequency of color reversal in Hz')
mk_parser.add_argument('phase', type=to_decimal, nargs='?', default='0',
help='initial phase in degrees')
def help_mk(self):
self.__class__.mk_parser.print_help()
def do_mk(self, line):
"""Makes a checkerboard with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
if self.cur_group == None:
print 'automatically adding display group...'
self.do_mkgrp('')
try:
args = self.__class__.mk_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mk_parser.print_usage()
return
shape_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_shape = core.CheckerBoard(**shape_dict)
new_id = self.cur_proj.add_shape_to_group(self.cur_group, new_shape)
print "checkerboard", new_id, "added"
ed_parser = CmdParser(add_help=False, prog='ed',
description='''Edits attributes of checkerboards
specified by ids.''')
ed_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='''ids of checkerboards in the current
group to be edited''')
ed_parser.add_argument('--dims', action=store_list(2, ',', to_decimal),
help='checkerboard dimensions in unit cells',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--init_unit',
action=store_list(2, ',', to_decimal),
help='initial unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--end_unit',
action=store_list(2, ',', to_decimal),
help='final unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--position',
action=store_list(2, ',', to_decimal),
help='position of checkerboard in pixels',
metavar='X,Y')
ed_parser.add_argument('--anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='LOCATION')
ed_parser.add_argument('--cols', metavar='COLOR1,COLOR2',
action=store_list(2, ',', to_color, [';']),
help='''checkerboard colors (color format:
R;G;B, component range
from 0-255)''')
ed_parser.add_argument('--freq', type=to_decimal,
help='frequency of color reversal in Hz')
ed_parser.add_argument('--phase', type=to_decimal,
help='initial phase in degrees')
def help_ed(self):
self.__class__.ed_parser.print_help()
def do_ed(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, please create one first'
return
try:
args = self.__class__.ed_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ed_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_group.shapes) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_shape_attr(self.cur_group, x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.ed_parser.print_usage()
rm_parser = CmdParser(add_help=False, prog='rm',
description='''Removes checkerboards specified
by ids.''')
rm_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''ids of checkerboards in the current group
to be removed''')
rm_parser.add_argument('-a', '--all', action='store_true',
help='''remove all checkerboards in the
current group''')
def help_rm(self):
self.__class__.rm_parser.print_help()
def do_rm(self, line):
"""Removes checkerboards specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, no boards to remove'
return
try:
args = self.__class__.rm_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rm_parser.print_usage()
return
rmlist = []
if args.all:
for shape in self.cur_group.shapes:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
print "all checkerboards removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_group.shapes) or x < 0:
print "checkerboard", x, "does not exist"
continue
rmlist.append(self.cur_group.shapes[x])
print "checkerboard", x, "removed"
for shape in rmlist:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
ls_parser = CmdParser(add_help=False, prog='ls',
description='''Lists project, display group and
checkerboard settings. If no group ids
are specified, all display groups
are listed.''')
ls_parser.add_argument('gids', nargs='*', metavar='gid', type=int,
help='''ids of the display groups to be listed''')
ls_group = ls_parser.add_mutually_exclusive_group()
ls_group.add_argument('-s', '--settings', action='store_true',
help='list only project settings')
ls_group.add_argument('-g', '--groups', action='store_true',
help='list only display groups')
ls_group.add_argument('-d', '--disp_ops', action='store_true',
help='list display options')
ls_group.add_argument('-o', '--orders', action='store_true',
help='list group orderings')
def help_ls(self):
self.__class__.ls_parser.print_help()
def do_ls(self, line):
"""Lists project, display group and checkerboard settings."""
def ls_str(s, seps=[',',';']):
"""Special space-saving output formatter."""
if type(s) in [tuple, list]:
if len(seps) > 1:
newseps = seps[1:]
else:
newseps = seps
return seps[0].join([ls_str(i, newseps) for i in s])
else:
return str(s)
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.ls_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ls_parser.print_usage()
return
# Remove duplicates and ascending sort
args.gids = sorted(set(args.gids))
if len(self.cur_proj.groups) == 0:
if len(args.gids) > 0:
print 'this project has no display groups that can be listed'
return
else:
for gid in args.gids[:]:
if gid >= len(self.cur_proj.groups) or gid < 0:
args.gids.remove(gid)
print 'display group', gid, 'does not exist'
if args.gids == []:
args.gids = range(len(self.cur_proj.groups))
else:
# If any (valid) groups are specified
# don't show project settings
args.groups = True
args.show_all = not max(args.settings, args.groups,
args.disp_ops, args.orders)
if args.show_all or args.settings:
print 'PROJECT SETTINGS'.center(70,'*')
print \
'name'.rjust(16),\
'fps'.rjust(7),\
'resolution'.rjust(14),\
'bg color'.rjust(18)
print \
ls_str(self.cur_proj.name).rjust(16),\
ls_str(self.cur_proj.fps).rjust(7),\
ls_str(self.cur_proj.res).rjust(14),\
ls_str(self.cur_proj.bg).rjust(18)
print \
'pre-display'.rjust(26),\
'post-display'.rjust(26)
print \
ls_str(self.cur_proj.pre).rjust(26),\
ls_str(self.cur_proj.post).rjust(26)
print \
'cross colors'.rjust(26),\
'cross times'.rjust(26)
print \
ls_str(self.cur_proj.cross_cols).rjust(26),\
ls_str(self.cur_proj.cross_times).rjust(26)
if args.show_all:
# Insert empty line between different info sets
print ''
if args.show_all or args.disp_ops:
print 'DISPLAY OPTIONS'.center(70,'*')
for k, v in self.cur_proj.disp_ops.items():
print ''.ljust(20), ls_str(k).ljust(20), ls_str(v).ljust(20)
if args.show_all:
# Insert empty line between different info sets
print ''
if args.show_all or args.orders:
print 'GROUP ORDERINGS'.center(70,'*')
if self.cur_proj.orders == []:
order = range(len(self.cur_proj.groups))
print \
''.ljust(20),\
'default order'.ljust(20),\
ls_str(order).ljust(20)
else:
for n, order in enumerate(self.cur_proj.orders):
print \
|
ztangent/checkergen
|
10432f61f97e60ea0f3c33d3642ebaa576c87941
|
Fixation cross turns blue when untracked, red when not fixating.
|
diff --git a/src/core.py b/src/core.py
index b407c1f..58a36c1 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,1264 +1,1269 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgDisplayGroup -- A set of CheckerShapes to be displayed siet_stateaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import copy
import random
import itertools
from datetime import datetime
from xml.dom import minidom
import pyglet
import graphics
import priority
import trigger
import eyetracking
from utils import *
# Use OrderedDict substitute if we don't have Python 2.7
if sys.version_info < (2, 7):
from odict import OrderedDict
else:
from collections import OrderedDict
CKG_FMT = 'ckg'
LOG_FMT = 'log'
MAX_EXPORT_FRAMES = 1000
EXPORT_DIR_SUFFIX = '-anim'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
INT_HALF_PERIODS = True
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = OrderedDict([('name', 'untitled'),
('fps', 60),
('res', (800, 600)),
('bg', (127, 127, 127)),
('pre', 0),
('post', 0),
- ('cross_cols', ((0, 0, 0), (255, 0, 0))),
+ ('cross_cols', ((0, 0, 0),
+ (255, 0, 0),
+ (0, 0, 255))),
('cross_times', ('Infinity', 1)),
('orders', []),
('disp_ops', None)])
DEFAULTS['disp_ops'] = OrderedDict([('repeats', 1),
('waitless', False),
('fullscreen', False),
('priority', None),
('logtime', False),
('logdur', False),
('trigser', False),
('trigpar', False),
('fpst', 0),
('freqcheck', False),
('phototest', False),
('photoburst', False),
('eyetrack', False),
('etuser', False),
('etvideo', None),
('tryagain', 0),
('trybreak', None),
('nolog', False),
('export', False),
('expo_dir', None),
('expo_dur', None),
('folder', True)])
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'cross_cols':
- if len(value) != 2:
+ if len(value) != 3:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def set_display_flags(self, **keywords):
"""Set default display flags for the project.
Same arguments as 'display', excluding 'name' and 'order'.
"""
for kw in keywords.keys():
if kw in self.disp_ops.keys() and keywords[kw] != None:
self.disp_ops[kw] = keywords[kw]
self._dirty = True
def set_group_orders(self, orders):
for order in orders:
for gid in order:
if gid < -1 or gid >= len(self.groups):
msg = 'invalid group id (out of range)'
raise ValueError(msg)
self.orders = orders
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
# Vars that are dicts
dicts_to_load = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_load = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
for d_name in dicts_to_load:
d = copy.deepcopy(self.__class__.DEFAULTS[d_name])
try:
d_el = [node for node in project.childNodes if
node.localName == d_name and
node.namespaceURI == XML_NAMESPACE][0]
for var in d.keys():
try:
d[var] = eval(xml_get(d_el, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}' in '{1}'".\
format(var, d_name)
print "using default value '{0}' instead...".\
format(d[var])
except IndexError:
print "warning: missing attribute set '{0}'".format(d_name)
print "using default values instead..."
setattr(self, d_name, d)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
# Vars that are dicts
dicts_to_save = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_save = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for d_name in dicts_to_save:
d_el = doc.createElement(d_name)
project.appendChild(d_el)
d = getattr(self, d_name)
for k, v in d.iteritems():
xml_set(doc, d_el, k, repr(v))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, **keywords):
"""Displays the stimulus on the screen.
name -- name that logfile will be saved with
repeats -- number of times specified order of display groups should
be repeated
waitless -- if true, no waitscreens will appear at the start of each
repeat
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
priority -- priority level to which process should be raised
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
trigser -- send triggers through serial port when each group is shown
trigpar -- send triggers through parallel port when each group is shown
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
freqcheck -- send fpst only at the start, the middle, and the end
for sanity checking of display and trigger fps
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- append a wait screen to the group queue every time
after this many groups have been appended to the queue
order -- order in which groups (specified by id) will be displayed
"""
# Create RunState
disp_ops = copy.deepcopy(self.disp_ops)
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'name' in keywords.keys() and keywords['name'] != None:
name = keywords['name']
else:
timestr = datetime.today().strftime('_%Y-%m-%d_%H-%M-%S')
name = self.name + timestr
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
waitscreen = CkgWaitScreen()
# Set runstate order id if necessary
if order in self.orders:
runstate.ord_id = self.orders.index(order)
# Count through pre
for count in range(self.pre * self.fps):
if runstate.terminate:
break
runstate.update()
# Loop through repeats
repeats = runstate.disp_ops['repeats']
ord_len = len(runstate.order)
for i in range(repeats):
# Restart eyetracking
if runstate.disp_ops['eyetrack']:
eyetracking.stop()
eyetracking.start()
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
# Loop through display groups
runstate.events['blk_on'] = True
for n, gid in enumerate(runstate.order):
# Set flag for freqcheck
if runstate.disp_ops['freqcheck']:
if ((i == 0 and n == 0) or
(i == repeats-1 and n == ord_len-1) or
(i == repeats//2 and n == ord_len//2)):
runstate.fc_send = True
else:
runstate.fc_send = False
if gid == -1:
waitscreen.reset()
waitscreen.display(runstate)
else:
self.groups[gid].display(runstate)
if not runstate.terminate:
# Append group id and fail state
runstate.gids.append(gid)
if runstate.disp_ops['eyetrack']:
runstate.fails.append(runstate.true_fail)
# Append groups to be added
if runstate.true_fail:
if (len(runstate.add_gids) <
runstate.disp_ops['tryagain']):
runstate.add_gids.append(gid)
runstate.events['blk_off'] = True
# Stop freqcheck before added groups
if runstate.disp_ops['freqcheck']:
runstate.fc_send = False
# Loop through added groups
if runstate.disp_ops['eyetrack']:
for blk in grouper(runstate.add_gids,
runstate.disp_ops['trybreak']):
# Restart eyetracking
if runstate.disp_ops['eyetrack']:
eyetracking.stop()
eyetracking.start()
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
runstate.events['blk_on'] = True
# Loop through display groups
for gid in blk:
if gid != None:
self.groups[gid].display(runstate)
if not runstate.terminate:
# Append group id and fail state
runstate.gids.append(gid)
if runstate.disp_ops['eyetrack']:
runstate.fails.append(runstate.true_fail)
runstate.events['blk_off'] = True
# Count through post
for count in range(self.post * self.fps):
if runstate.terminate:
break
runstate.update()
# Stop and output log
runstate.stop()
if not runstate.disp_ops['nolog']:
runstate.log()
def export(self, **keywords):
"""Exports the stimulus as a series of images, one image per frame.
repeats -- number of times specified order of display groups should
be repeated
order -- order in which groups (specified by id) will be displayed
expo_dir -- directory to which images will be exported
expo_dur -- time in seconds to which export will be limited
folder -- if true, images will be contained in a separate folder
within export directory
force -- force export to go through even if a large number
of frames are to be exported
"""
# Create RunState
disp_ops = copy.deepcopy(self.__class__.DEFAULTS['disp_ops'])
disp_ops['export'] = True
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=self.name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
# Warn user if a lot of frames will be exported
if 'force' not in keywords.keys():
keywords['force'] = False
groups_dur = sum([self.groups[i].duration()
for i in order]) * disp_ops['repeats']
total_frames = (self.pre + groups_dur + self.post) * self.fps
frames = min(total_frames, disp_ops['expo_dur'] * self.fps)
if frames > MAX_EXPORT_FRAMES and not keywords['force']:
msg = 'large number ({0}) of frames to be exported'.\
format(int(frames))
raise FrameOverflowError(msg)
runstate.frames = frames
# Count through pre
for count in range(self.pre * self.fps):
if runstate.terminate:
break
runstate.update()
# Loop through repeats
repeats = runstate.disp_ops['repeats']
for i in range(repeats):
# Loop through display groups
for n, gid in enumerate(runstate.order):
if gid != -1:
self.groups[gid].display(runstate)
# Count through post
for count in range(self.post * self.fps):
if runstate.terminate:
break
runstate.update()
# Stop runstate
runstate.stop()
class CkgRunState:
"""Contains information about the state of a checkergen project
when it is being displayed or exported."""
DEFAULTS = dict([('name', 'untitled'),
('res', None),
('fps', None),
('bg', None),
('cross_cols', None),
('cross_times', None),
('order', []),
('disp_ops', None),
('events', None),
('gids', []),
('fails', []),
('add_gids', []),
('timestamps', []),
('durstamps', []),
('trigstamps', [])])
DEFAULTS['events'] = dict([('ord_id', None),
('blk_on', False),
('blk_off', False),
('track_on', False),
('track_off', False),
('fix_on', False),
('fix_off', False),
('grp_on', False),
('grp_off', False),
('sids', set())])
def __init__(self, **keywords):
"""Creates the RunState."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
def start(self):
"""Initialize all subsystems and start the run."""
if self.disp_ops == None:
msg = "RunState lacks display options"
raise ValueError(msg)
if min(self.res, self.fps, self.bg,
self.cross_cols, self.cross_times) == None:
msg = "RunState intialized with insufficent project information"
raise ValueError(msg)
self._count = 0
self._old_code = 0
self.ord_id = None
self.terminate = False
# Flag used by freqcheck
self.fc_send = False
# Create fixation crosses
self.fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if self.disp_ops['phototest']:
self.test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Initialize export
if self.disp_ops['export']:
if not os.path.isdir(self.disp_ops['expo_dir']):
msg = 'export path is not a directory'
raise IOError(msg)
if self.disp_ops['folder']:
self.save_dir = os.path.join(self.disp_ops['expo_dir'],
self.name + EXPORT_DIR_SUFFIX)
else:
self.save_dir = self.disp_ops['expo_dir']
if not os.path.isdir(self.save_dir):
os.mkdir(self.save_dir)
# Initialize ports
if self.disp_ops['trigser']:
if not trigger.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trigpar']:
if not trigger.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
trigger.init(self.disp_ops['trigser'], self.disp_ops['trigpar'])
# Initialize eyetracking
if self.disp_ops['eyetrack']:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trybreak'] == None:
self.disp_ops['trybreak'] = len(self.order)
self.fixated = False
self.old_fixated = False
self.tracked = False
self.old_tracked = False
self.fix_fail = False
self.true_fail = False
eyetracking.select_source(self.disp_ops['etuser'],
self.disp_ops['etvideo'])
eyetracking.start()
# Create window if not exporting
self.scaling = False
if not self.disp_ops['export']:
# Stretch to fit screen only if project res does not
# equal screen res
if self.disp_ops['fullscreen']:
self.window = pyglet.window.Window(fullscreen=True,
visible=False)
if (self.window.width, self.window.height) != self.res:
self.scaling = True
else:
self.window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
self.keystates = pyglet.window.key.KeyStateHandler()
self.window.push_handlers(self.keystates)
# Clear window and make visible
self.window.switch_to()
graphics.set_clear_color(self.bg)
self.window.clear()
self.window.set_visible()
# Create framebuffer object for drawing unscaled or exported scene
if self.scaling or self.disp_ops['export']:
self.canvas = pyglet.image.Texture.create(*self.res)
self.fbo = graphics.Framebuffer(self.canvas)
self.fbo.start_render()
graphics.set_clear_color(self.bg)
self.fbo.clear()
# Set process priority
if self.disp_ops['priority'] != None:
try:
priority.set(self.disp_ops['priority'])
except ValueError:
priority.set(int(self.disp_ops['priority']))
except:
pass
# Start timers
if self.disp_ops['logtime']:
self.timer = Timer()
self.timer.start()
if self.disp_ops['logdur']:
self.dur = Timer()
self.dur.start()
def update(self):
"""Update the RunState."""
# Check for tracking and fixation
if self.disp_ops['eyetrack']:
self.old_tracked = self.tracked
self.tracked = eyetracking.is_tracked(self.fps)
self.old_fixated = self.fixated
self.fixated = eyetracking.is_fixated(self.fps)
if self.fixated:
# Draw normal cross color if fixating
self.fix_crosses[0].draw()
- else:
- # Draw alternative cross color if not fixating
+ elif self.tracked:
+ # Draw 2nd cross color if tracked, not fixating
self.fix_crosses[1].draw()
+ else:
+ # Draw 3rd cross color if untracked
+ self.fix_crosses[2].draw()
# Update eyetracking events
if self.tracked != self.old_tracked:
if self.tracked:
self.events['track_on'] = True
else:
self.events['track_off'] = True
if self.fixated != self.old_fixated:
if self.fixated:
self.events['fix_on'] = True
else:
self.events['fix_off'] = True
# Check for failure of trial
if self.tracked and not self.fixated:
self.fix_fail = True
else:
# Change cross color based on time
if (self._count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
self.fix_crosses[0].draw()
else:
self.fix_crosses[1].draw()
if self.disp_ops['export']:
# Save current frame to file
savepath = os.path.join(
self.save_dir, '{0}{2}.{1}'.\
format(self.name, 'png',
repr(self._count).zfill(numdigits(self.frames-1))))
self.canvas.save(savepath)
else:
# Blit canvas to screen if necessary
if self.scaling:
self.fbo.end_render()
self.canvas.blit(0, 0)
self.window.switch_to()
self.window.dispatch_events()
self.window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to lists
if self.disp_ops['logtime']:
self.timestamps.append(self.timer.elapsed())
elif self.disp_ops['logdur']:
self.timestamps.append('')
if self.disp_ops['logdur']:
self.durstamps.append(self.dur.restart())
elif self.disp_ops['logtime']:
self.durstamps.append('')
# Send trigger ASAP after flip
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
if self.encode_events() != self._old_code:
trigger.send(self.disp_ops['trigser'],
self.disp_ops['trigpar'],
self.encode_events())
self._old_code = self.encode_events
# Log when triggers are sent
if self.disp_ops['logtime'] and self.encode_events() > 0:
self.trigstamps.append(self.encode_events())
else:
self.trigstamps.append('')
# Clear canvas, events, prepare for next frame
if self.disp_ops['export']:
self.fbo.clear()
else:
if self.scaling:
self.fbo.start_render()
self.fbo.clear()
else:
self.window.clear()
if self.window.has_exit:
self.terminate = True
# Send ord_id immediately after blk_on
send_ord_id_next = self.events['blk_on']
self.events = copy.deepcopy(self.__class__.DEFAULTS['events'])
if send_ord_id_next:
self.events['ord_id'] = self.ord_id
self._count += 1
# Terminate export if the time has come
if self.disp_ops['export']:
if self._count >= self.frames:
self.terminate = True
def stop(self):
"""Clean up RunState."""
if self.disp_ops['eyetrack']:
eyetracking.stop()
if self.scaling or self.disp_ops['export']:
self.fbo.delete()
del self.canvas
if not self.disp_ops['export']:
self.window.close()
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
trigger.quit(self.disp_ops['trigser'], self.disp_ops['trigpar'])
try:
priority.set('normal')
except:
pass
def encode_events(self):
"""Hard code specific trigger values for events."""
code = 0
if self.events['ord_id'] != None:
code = self.events['ord_id'] + 1
elif self.events['blk_on']:
code = 128
elif self.events['blk_off']:
code = 127
else:
et_state = 0
if self.events['fix_on']:
et_state = 4
elif self.events['track_on']:
et_state = 2
if self.events['track_off']:
et_state = 1
elif self.events['fix_off']:
et_state = 2
if self.events['grp_on']:
code = 100 + et_state
elif self.events['grp_off']:
code = 90 + et_state
elif et_state > 0:
code = 110 + et_state
elif len(self.events['sids']) > 0:
code = ((0 in self.events['sids'])*2**0 +
(1 in self.events['sids'])*2**1 +
(2 in self.events['sids'])*2**2 +
(3 in self.events['sids'])*2**3 +
16)
return code
def log(self, path=None):
"""Write a log file for the experimental run in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, LOG_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(LOG_FMT):
path = '{0}.{1}'.format(path, LOG_FMT)
with open(path, 'wb') as logfile:
writer = csv.writer(logfile, dialect='excel-tab')
writer.writerow(['checkergen log file'])
writer.writerow(['display options:'])
writer.writerow(self.disp_ops.keys())
writer.writerow(self.disp_ops.values())
writer.writerow(['order:'] + self.order)
writer.writerow(['groups', 'failure'])
if not self.disp_ops['eyetrack']:
self.fails = ['NA'] * len(self.gids)
for i in zip(self.gids, self.fails):
writer.writerow(list(i))
if self.disp_ops['eyetrack']:
writer.writerow(['groups added'])
for blk in grouper(self.add_gids,
self.disp_ops['trybreak'], ''):
writer.writerow(blk)
if self.disp_ops['logtime'] or self.disp_ops['logdur']:
stamps = [self.timestamps, self.durstamps, self.trigstamps]
writer.writerow(['timestamps', 'durations', 'triggers'])
for stamp in zip(*stamps):
writer.writerow(list(stamp))
class CkgDisplayGroup:
DEFAULTS = OrderedDict([('pre', 0), ('disp', 'Infinity'), ('post', 0)])
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets counts and all contained shapes."""
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, runstate):
"""Draws all contained shapes during the appropriate interval."""
for shape in self.shapes:
shape.draw(photoburst=runstate.disp_ops['photoburst'])
def update(self, runstate):
"""Updates contained shapes, sets event triggers."""
# Set events to be sent
if runstate.disp_ops['fpst'] > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= runstate.disp_ops['fpst']:
if not runstate.disp_ops['freqcheck'] or runstate.fc_send:
runstate.events['sids'].add(n)
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(runstate.fps)
def display(self, runstate):
"""Display the group in the context described by supplied runstate."""
self.reset()
for count in range(self.pre * runstate.fps):
if runstate.terminate:
break
runstate.update()
runstate.events['grp_on'] = True
if runstate.disp_ops['eyetrack']:
runstate.fix_fail = False
runstate.true_fail = False
for count in range(self.disp * runstate.fps):
if runstate.terminate:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
runstate.events['grp_off'] = True
if runstate.disp_ops['eyetrack']:
if runstate.fix_fail:
runstate.true_fail = True
for count in range(self.post * runstate.fps):
if runstate.terminate:
break
runstate.update()
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.steps_done = 0
def draw(self, runstate):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, runstate):
"""Checks for keypress, sends trigger upon end."""
if max([runstate.keystates[key] for
key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
def display(self, runstate):
"""Displays waitscreen in context described by supplied runstate."""
while self.steps_done < self.num_steps:
if runstate.terminate:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = OrderedDict([('dims', (5, 5)),
('init_unit', (30, 30)),
('end_unit', (50, 50)),
('position', (0, 0)),
('anchor', 'bottomleft'),
('cols', ((0, 0, 0), (255, 255, 255))),
('freq', 1),
('phase', 0)])
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
if INT_HALF_PERIODS:
frames_per_half_period = round(fps / (self.freq * 2))
degs_per_frame = 180 / to_decimal(frames_per_half_period)
else:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
anchor=self.anchor)
cur_unit_rect.col = self.cols[(i + j) % 2]
cur_unit_rect.add_to_batch(self._batches[0])
cur_unit_rect.col = self.cols[(i + j + 1) % 2]
cur_unit_rect.add_to_batch(self._batches[1])
# Increase x values
cur_unit_pos[0] += \
graphics.locations[self.anchor][0] * cur_unit[0]
cur_unit[0] += unit_grad[0]
# Reset x values
cur_unit_pos[0] = init_pos[0]
cur_unit[0] = init_unit[0]
# Increase y values
cur_unit_pos[1] += \
graphics.locations[self.anchor][1] * cur_unit[1]
cur_unit[1] += unit_grad[1]
self._computed = True
|
ztangent/checkergen
|
a139a86b7e9d15c12d7b514d5671051e2023376b
|
Restart tracking between blocks, et triggers override fpst triggers, some trigger value changes.
|
diff --git a/src/core.py b/src/core.py
index 67f470b..b407c1f 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,1281 +1,1289 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
-CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
+CkgDisplayGroup -- A set of CheckerShapes to be displayed siet_stateaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import copy
import random
import itertools
from datetime import datetime
from xml.dom import minidom
import pyglet
import graphics
import priority
import trigger
import eyetracking
from utils import *
# Use OrderedDict substitute if we don't have Python 2.7
if sys.version_info < (2, 7):
from odict import OrderedDict
else:
from collections import OrderedDict
CKG_FMT = 'ckg'
LOG_FMT = 'log'
MAX_EXPORT_FRAMES = 1000
EXPORT_DIR_SUFFIX = '-anim'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
INT_HALF_PERIODS = True
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = OrderedDict([('name', 'untitled'),
('fps', 60),
('res', (800, 600)),
('bg', (127, 127, 127)),
('pre', 0),
('post', 0),
('cross_cols', ((0, 0, 0), (255, 0, 0))),
('cross_times', ('Infinity', 1)),
('orders', []),
('disp_ops', None)])
DEFAULTS['disp_ops'] = OrderedDict([('repeats', 1),
('waitless', False),
('fullscreen', False),
('priority', None),
('logtime', False),
('logdur', False),
('trigser', False),
('trigpar', False),
('fpst', 0),
('freqcheck', False),
('phototest', False),
('photoburst', False),
('eyetrack', False),
('etuser', False),
('etvideo', None),
('tryagain', 0),
('trybreak', None),
('nolog', False),
('export', False),
('expo_dir', None),
('expo_dur', None),
('folder', True)])
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def set_display_flags(self, **keywords):
"""Set default display flags for the project.
Same arguments as 'display', excluding 'name' and 'order'.
"""
for kw in keywords.keys():
if kw in self.disp_ops.keys() and keywords[kw] != None:
self.disp_ops[kw] = keywords[kw]
self._dirty = True
def set_group_orders(self, orders):
for order in orders:
for gid in order:
if gid < -1 or gid >= len(self.groups):
msg = 'invalid group id (out of range)'
raise ValueError(msg)
self.orders = orders
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
# Vars that are dicts
dicts_to_load = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_load = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
for d_name in dicts_to_load:
d = copy.deepcopy(self.__class__.DEFAULTS[d_name])
try:
d_el = [node for node in project.childNodes if
node.localName == d_name and
node.namespaceURI == XML_NAMESPACE][0]
for var in d.keys():
try:
d[var] = eval(xml_get(d_el, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}' in '{1}'".\
format(var, d_name)
print "using default value '{0}' instead...".\
format(d[var])
except IndexError:
print "warning: missing attribute set '{0}'".format(d_name)
print "using default values instead..."
setattr(self, d_name, d)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
# Vars that are dicts
dicts_to_save = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_save = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for d_name in dicts_to_save:
d_el = doc.createElement(d_name)
project.appendChild(d_el)
d = getattr(self, d_name)
for k, v in d.iteritems():
xml_set(doc, d_el, k, repr(v))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, **keywords):
"""Displays the stimulus on the screen.
name -- name that logfile will be saved with
repeats -- number of times specified order of display groups should
be repeated
waitless -- if true, no waitscreens will appear at the start of each
repeat
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
priority -- priority level to which process should be raised
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
trigser -- send triggers through serial port when each group is shown
trigpar -- send triggers through parallel port when each group is shown
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
freqcheck -- send fpst only at the start, the middle, and the end
for sanity checking of display and trigger fps
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- append a wait screen to the group queue every time
after this many groups have been appended to the queue
order -- order in which groups (specified by id) will be displayed
"""
# Create RunState
disp_ops = copy.deepcopy(self.disp_ops)
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'name' in keywords.keys() and keywords['name'] != None:
name = keywords['name']
else:
timestr = datetime.today().strftime('_%Y-%m-%d_%H-%M-%S')
name = self.name + timestr
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
waitscreen = CkgWaitScreen()
# Set runstate order id if necessary
if order in self.orders:
runstate.ord_id = self.orders.index(order)
# Count through pre
for count in range(self.pre * self.fps):
if runstate.terminate:
break
runstate.update()
# Loop through repeats
repeats = runstate.disp_ops['repeats']
ord_len = len(runstate.order)
for i in range(repeats):
+ # Restart eyetracking
+ if runstate.disp_ops['eyetrack']:
+ eyetracking.stop()
+ eyetracking.start()
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
# Loop through display groups
runstate.events['blk_on'] = True
for n, gid in enumerate(runstate.order):
# Set flag for freqcheck
if runstate.disp_ops['freqcheck']:
if ((i == 0 and n == 0) or
(i == repeats-1 and n == ord_len-1) or
(i == repeats//2 and n == ord_len//2)):
runstate.fc_send = True
else:
runstate.fc_send = False
if gid == -1:
waitscreen.reset()
waitscreen.display(runstate)
else:
self.groups[gid].display(runstate)
if not runstate.terminate:
# Append group id and fail state
runstate.gids.append(gid)
if runstate.disp_ops['eyetrack']:
runstate.fails.append(runstate.true_fail)
- # Append groups to be added
- if runstate.disp_ops['eyetrack'] and runstate.true_fail:
- if (len(runstate.add_gids) <
- runstate.disp_ops['tryagain']):
- runstate.add_gids.append(gid)
+ # Append groups to be added
+ if runstate.true_fail:
+ if (len(runstate.add_gids) <
+ runstate.disp_ops['tryagain']):
+ runstate.add_gids.append(gid)
runstate.events['blk_off'] = True
# Stop freqcheck before added groups
if runstate.disp_ops['freqcheck']:
runstate.fc_send = False
# Loop through added groups
if runstate.disp_ops['eyetrack']:
for blk in grouper(runstate.add_gids,
runstate.disp_ops['trybreak']):
+ # Restart eyetracking
+ if runstate.disp_ops['eyetrack']:
+ eyetracking.stop()
+ eyetracking.start()
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
runstate.events['blk_on'] = True
# Loop through display groups
for gid in blk:
if gid != None:
self.groups[gid].display(runstate)
if not runstate.terminate:
# Append group id and fail state
runstate.gids.append(gid)
if runstate.disp_ops['eyetrack']:
runstate.fails.append(runstate.true_fail)
runstate.events['blk_off'] = True
# Count through post
for count in range(self.post * self.fps):
if runstate.terminate:
break
runstate.update()
# Stop and output log
runstate.stop()
if not runstate.disp_ops['nolog']:
runstate.log()
def export(self, **keywords):
"""Exports the stimulus as a series of images, one image per frame.
repeats -- number of times specified order of display groups should
be repeated
order -- order in which groups (specified by id) will be displayed
expo_dir -- directory to which images will be exported
expo_dur -- time in seconds to which export will be limited
folder -- if true, images will be contained in a separate folder
within export directory
force -- force export to go through even if a large number
of frames are to be exported
"""
# Create RunState
disp_ops = copy.deepcopy(self.__class__.DEFAULTS['disp_ops'])
disp_ops['export'] = True
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=self.name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
# Warn user if a lot of frames will be exported
if 'force' not in keywords.keys():
keywords['force'] = False
groups_dur = sum([self.groups[i].duration()
for i in order]) * disp_ops['repeats']
total_frames = (self.pre + groups_dur + self.post) * self.fps
frames = min(total_frames, disp_ops['expo_dur'] * self.fps)
if frames > MAX_EXPORT_FRAMES and not keywords['force']:
msg = 'large number ({0}) of frames to be exported'.\
format(int(frames))
raise FrameOverflowError(msg)
runstate.frames = frames
# Count through pre
for count in range(self.pre * self.fps):
if runstate.terminate:
break
runstate.update()
# Loop through repeats
repeats = runstate.disp_ops['repeats']
for i in range(repeats):
# Loop through display groups
for n, gid in enumerate(runstate.order):
if gid != -1:
self.groups[gid].display(runstate)
# Count through post
for count in range(self.post * self.fps):
if runstate.terminate:
break
runstate.update()
# Stop runstate
runstate.stop()
class CkgRunState:
"""Contains information about the state of a checkergen project
when it is being displayed or exported."""
DEFAULTS = dict([('name', 'untitled'),
('res', None),
('fps', None),
('bg', None),
('cross_cols', None),
('cross_times', None),
('order', []),
('disp_ops', None),
('events', None),
('gids', []),
('fails', []),
('add_gids', []),
('timestamps', []),
('durstamps', []),
('trigstamps', [])])
DEFAULTS['events'] = dict([('ord_id', None),
('blk_on', False),
('blk_off', False),
('track_on', False),
('track_off', False),
('fix_on', False),
('fix_off', False),
('grp_on', False),
('grp_off', False),
('sids', set())])
def __init__(self, **keywords):
"""Creates the RunState."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
def start(self):
"""Initialize all subsystems and start the run."""
if self.disp_ops == None:
msg = "RunState lacks display options"
raise ValueError(msg)
if min(self.res, self.fps, self.bg,
self.cross_cols, self.cross_times) == None:
msg = "RunState intialized with insufficent project information"
raise ValueError(msg)
self._count = 0
self._old_code = 0
self.ord_id = None
self.terminate = False
# Flag used by freqcheck
self.fc_send = False
# Create fixation crosses
self.fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if self.disp_ops['phototest']:
self.test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Initialize export
if self.disp_ops['export']:
if not os.path.isdir(self.disp_ops['expo_dir']):
msg = 'export path is not a directory'
raise IOError(msg)
if self.disp_ops['folder']:
self.save_dir = os.path.join(self.disp_ops['expo_dir'],
self.name + EXPORT_DIR_SUFFIX)
else:
self.save_dir = self.disp_ops['expo_dir']
if not os.path.isdir(self.save_dir):
os.mkdir(self.save_dir)
# Initialize ports
if self.disp_ops['trigser']:
if not trigger.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trigpar']:
if not trigger.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
trigger.init(self.disp_ops['trigser'], self.disp_ops['trigpar'])
# Initialize eyetracking
if self.disp_ops['eyetrack']:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trybreak'] == None:
self.disp_ops['trybreak'] = len(self.order)
self.fixated = False
self.old_fixated = False
self.tracked = False
self.old_tracked = False
self.fix_fail = False
self.true_fail = False
eyetracking.select_source(self.disp_ops['etuser'],
self.disp_ops['etvideo'])
eyetracking.start()
# Create window if not exporting
self.scaling = False
if not self.disp_ops['export']:
# Stretch to fit screen only if project res does not
# equal screen res
if self.disp_ops['fullscreen']:
self.window = pyglet.window.Window(fullscreen=True,
visible=False)
if (self.window.width, self.window.height) != self.res:
self.scaling = True
else:
self.window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
self.keystates = pyglet.window.key.KeyStateHandler()
self.window.push_handlers(self.keystates)
# Clear window and make visible
self.window.switch_to()
graphics.set_clear_color(self.bg)
self.window.clear()
self.window.set_visible()
# Create framebuffer object for drawing unscaled or exported scene
if self.scaling or self.disp_ops['export']:
self.canvas = pyglet.image.Texture.create(*self.res)
self.fbo = graphics.Framebuffer(self.canvas)
self.fbo.start_render()
graphics.set_clear_color(self.bg)
self.fbo.clear()
# Set process priority
if self.disp_ops['priority'] != None:
try:
priority.set(self.disp_ops['priority'])
except ValueError:
priority.set(int(self.disp_ops['priority']))
except:
pass
# Start timers
if self.disp_ops['logtime']:
self.timer = Timer()
self.timer.start()
if self.disp_ops['logdur']:
self.dur = Timer()
self.dur.start()
def update(self):
"""Update the RunState."""
# Check for tracking and fixation
if self.disp_ops['eyetrack']:
self.old_tracked = self.tracked
self.tracked = eyetracking.is_tracked(self.fps)
self.old_fixated = self.fixated
self.fixated = eyetracking.is_fixated(self.fps)
if self.fixated:
# Draw normal cross color if fixating
self.fix_crosses[0].draw()
else:
# Draw alternative cross color if not fixating
self.fix_crosses[1].draw()
# Update eyetracking events
if self.tracked != self.old_tracked:
if self.tracked:
self.events['track_on'] = True
else:
self.events['track_off'] = True
if self.fixated != self.old_fixated:
if self.fixated:
self.events['fix_on'] = True
else:
self.events['fix_off'] = True
# Check for failure of trial
if self.tracked and not self.fixated:
self.fix_fail = True
else:
# Change cross color based on time
if (self._count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
self.fix_crosses[0].draw()
else:
self.fix_crosses[1].draw()
if self.disp_ops['export']:
# Save current frame to file
savepath = os.path.join(
self.save_dir, '{0}{2}.{1}'.\
format(self.name, 'png',
repr(self._count).zfill(numdigits(self.frames-1))))
self.canvas.save(savepath)
else:
# Blit canvas to screen if necessary
if self.scaling:
self.fbo.end_render()
self.canvas.blit(0, 0)
self.window.switch_to()
self.window.dispatch_events()
self.window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to lists
if self.disp_ops['logtime']:
self.timestamps.append(self.timer.elapsed())
elif self.disp_ops['logdur']:
self.timestamps.append('')
if self.disp_ops['logdur']:
self.durstamps.append(self.dur.restart())
elif self.disp_ops['logtime']:
self.durstamps.append('')
# Send trigger ASAP after flip
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
if self.encode_events() != self._old_code:
trigger.send(self.disp_ops['trigser'],
self.disp_ops['trigpar'],
self.encode_events())
self._old_code = self.encode_events
# Log when triggers are sent
if self.disp_ops['logtime'] and self.encode_events() > 0:
self.trigstamps.append(self.encode_events())
else:
self.trigstamps.append('')
# Clear canvas, events, prepare for next frame
if self.disp_ops['export']:
self.fbo.clear()
else:
if self.scaling:
self.fbo.start_render()
self.fbo.clear()
else:
self.window.clear()
if self.window.has_exit:
self.terminate = True
# Send ord_id immediately after blk_on
send_ord_id_next = self.events['blk_on']
self.events = copy.deepcopy(self.__class__.DEFAULTS['events'])
if send_ord_id_next:
self.events['ord_id'] = self.ord_id
self._count += 1
# Terminate export if the time has come
if self.disp_ops['export']:
if self._count >= self.frames:
self.terminate = True
def stop(self):
"""Clean up RunState."""
if self.disp_ops['eyetrack']:
eyetracking.stop()
if self.scaling or self.disp_ops['export']:
self.fbo.delete()
del self.canvas
if not self.disp_ops['export']:
self.window.close()
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
trigger.quit(self.disp_ops['trigser'], self.disp_ops['trigpar'])
try:
priority.set('normal')
except:
pass
def encode_events(self):
"""Hard code specific trigger values for events."""
code = 0
if self.events['ord_id'] != None:
code = self.events['ord_id'] + 1
elif self.events['blk_on']:
code = 128
elif self.events['blk_off']:
code = 127
else:
- mult = 0
+ et_state = 0
if self.events['fix_on']:
- mult = 4
+ et_state = 4
elif self.events['track_on']:
- mult = 3
+ et_state = 2
if self.events['track_off']:
- mult = 1
+ et_state = 1
elif self.events['fix_off']:
- mult = 2
+ et_state = 2
if self.events['grp_on']:
- code = 100 + mult
+ code = 100 + et_state
elif self.events['grp_off']:
- code = 90 + mult
+ code = 90 + et_state
+ elif et_state > 0:
+ code = 110 + et_state
elif len(self.events['sids']) > 0:
code = ((0 in self.events['sids'])*2**0 +
(1 in self.events['sids'])*2**1 +
(2 in self.events['sids'])*2**2 +
- (3 in self.events['sids'])*2**3)
- code = mult*16 + code
- elif mult > 0:
- code = 110 + mult
+ (3 in self.events['sids'])*2**3 +
+ 16)
return code
def log(self, path=None):
"""Write a log file for the experimental run in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, LOG_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(LOG_FMT):
path = '{0}.{1}'.format(path, LOG_FMT)
with open(path, 'wb') as logfile:
writer = csv.writer(logfile, dialect='excel-tab')
writer.writerow(['checkergen log file'])
writer.writerow(['display options:'])
writer.writerow(self.disp_ops.keys())
writer.writerow(self.disp_ops.values())
writer.writerow(['order:'] + self.order)
writer.writerow(['groups', 'failure'])
if not self.disp_ops['eyetrack']:
self.fails = ['NA'] * len(self.gids)
for i in zip(self.gids, self.fails):
writer.writerow(list(i))
if self.disp_ops['eyetrack']:
writer.writerow(['groups added'])
for blk in grouper(self.add_gids,
self.disp_ops['trybreak'], ''):
writer.writerow(blk)
if self.disp_ops['logtime'] or self.disp_ops['logdur']:
stamps = [self.timestamps, self.durstamps, self.trigstamps]
writer.writerow(['timestamps', 'durations', 'triggers'])
for stamp in zip(*stamps):
writer.writerow(list(stamp))
class CkgDisplayGroup:
DEFAULTS = OrderedDict([('pre', 0), ('disp', 'Infinity'), ('post', 0)])
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets counts and all contained shapes."""
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, runstate):
"""Draws all contained shapes during the appropriate interval."""
for shape in self.shapes:
shape.draw(photoburst=runstate.disp_ops['photoburst'])
def update(self, runstate):
"""Updates contained shapes, sets event triggers."""
# Set events to be sent
if runstate.disp_ops['fpst'] > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= runstate.disp_ops['fpst']:
if not runstate.disp_ops['freqcheck'] or runstate.fc_send:
runstate.events['sids'].add(n)
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(runstate.fps)
def display(self, runstate):
"""Display the group in the context described by supplied runstate."""
self.reset()
for count in range(self.pre * runstate.fps):
if runstate.terminate:
break
runstate.update()
runstate.events['grp_on'] = True
if runstate.disp_ops['eyetrack']:
runstate.fix_fail = False
runstate.true_fail = False
for count in range(self.disp * runstate.fps):
if runstate.terminate:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
runstate.events['grp_off'] = True
if runstate.disp_ops['eyetrack']:
if runstate.fix_fail:
runstate.true_fail = True
for count in range(self.post * runstate.fps):
if runstate.terminate:
break
runstate.update()
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.steps_done = 0
def draw(self, runstate):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, runstate):
"""Checks for keypress, sends trigger upon end."""
if max([runstate.keystates[key] for
key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
def display(self, runstate):
"""Displays waitscreen in context described by supplied runstate."""
while self.steps_done < self.num_steps:
if runstate.terminate:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = OrderedDict([('dims', (5, 5)),
('init_unit', (30, 30)),
('end_unit', (50, 50)),
('position', (0, 0)),
('anchor', 'bottomleft'),
('cols', ((0, 0, 0), (255, 255, 255))),
('freq', 1),
('phase', 0)])
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
if INT_HALF_PERIODS:
frames_per_half_period = round(fps / (self.freq * 2))
degs_per_frame = 180 / to_decimal(frames_per_half_period)
else:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
anchor=self.anchor)
cur_unit_rect.col = self.cols[(i + j) % 2]
cur_unit_rect.add_to_batch(self._batches[0])
cur_unit_rect.col = self.cols[(i + j + 1) % 2]
cur_unit_rect.add_to_batch(self._batches[1])
# Increase x values
cur_unit_pos[0] += \
graphics.locations[self.anchor][0] * cur_unit[0]
cur_unit[0] += unit_grad[0]
# Reset x values
cur_unit_pos[0] = init_pos[0]
cur_unit[0] = init_unit[0]
# Increase y values
cur_unit_pos[1] += \
graphics.locations[self.anchor][1] * cur_unit[1]
cur_unit[1] += unit_grad[1]
self._computed = True
def draw(self, photoburst=False, always_compute=False):
"""Draws appropriate batch depending on current phase.
photoburst -- draw first color for only one frame for testing purposes
always_compute -- recompute what the checkerboard should look like
every frame
"""
if not self._computed or always_compute:
self.compute()
self._cur_phase %= 360
n = int(self._cur_phase // 180)
if photoburst and n == 0 and not self.flipped:
n = 1
self._batches[n].draw()
def lazydraw(self):
"""Only draws on color reversal."""
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if (cur_n != prev_n) or self._first_draw:
self.draw()
if self._first_draw:
self._first_draw = False
diff --git a/src/eyetracking.py b/src/eyetracking.py
index 60ebc0c..793b339 100644
--- a/src/eyetracking.py
+++ b/src/eyetracking.py
@@ -1,195 +1,193 @@
"""Provides support for CRS VideoEyetracker Toolbox."""
import os.path
from utils import *
FIX_POS = (0, 0)
FIX_RANGE = (20, 20)
FIX_PER = 300
TRACK_PER = 300
try:
import win32com.client
available = True
except ImportError:
available = False
# COM ProgID of the Toolbox
ProgID = "crsVET.VideoEyeTracker"
RecordName = "etResultSet"
# VET application object
VET = None
class EyetrackingError(Exception):
"""Raised when something goes wrong with VET."""
pass
if available:
# Try dispatching object, else unavailable
try:
from win32com.client import gencache
# Ensure makepy module is generated
gencache.EnsureModule('{248DBF0C-A874-4032-82CE-DC5B307BB6E7}',
0, 3, 11)
VET = win32com.client.Dispatch(ProgID)
DummyResultSet = win32com.client.Record(RecordName, VET)
except:
available = False
if available:
# For easier access to constants and standardization with MATLAB interface
CRS = win32com.client.constants
lastfixstatus = False
fixcount = 0
lasttrackstatus = False
trackcount = 0
def select_source(user_select = False, path = None):
if user_select:
if not VET.SelectVideoSource(CRS.vsUserSelect, ''):
msg = 'could not select video source'
raise EyetrackingError(msg)
elif path != None:
# Open from file
if not VET.SelectVideoSource(CRS.vsFile, path):
msg = 'could not use path as video source'
raise EyetrackingError(msg)
else:
# Default to 250 Hz High Speed Camera
if not VET.SelectVideoSource(CRS.vsHighSpeedCamera250, ''):
msg = 'could not select video source'
raise EyetrackingError(msg)
def is_source_ready():
"""Returns true if a video source has been selected."""
if VET.VideoSourceType == 0:
return False
else:
return True
def show_camera():
VET.CreateCameraScreen(0)
def quit_camera():
VET.DestroyCameraScreen()
def setup(viewing_distance=None, screen_dims=None,
fixation_period=None, fixation_range=None):
"""Calibrates the display and sets fixation properties."""
if viewing_distance != None and screen_dims != None:
if len(screen_dims) != 2:
msg = 'screen_dims must be a 2-tuple'
raise ValueError(msg)
VET.SetDeviceParameters(CRS.deUser, viewing_distance,
screen_dims[0], screen_dims[1])
if fixation_period != None:
VET.FixationPeriod = fixation_period
if fixation_range != None:
VET.FixationRange = fixation_range
def calibrate(path = None):
"""Calibrate the subject.
Optionally supply a path with no spaces to a
calibration file to load."""
if not is_source_ready():
select_source()
if not VET.Tracking:
VET.ClearDataBuffer()
VET.StartTracking()
if path == None:
if not VET.Calibrate():
msg = 'calibration failed'
raise EyetrackingError(msg)
else:
if not os.path.isfile(path):
msg = 'specified file does not exist'
raise EyetrackingError(msg)
if not VET.LoadCalibrationFile(path):
msg = 'file could not be loaded'
raise EyetrackingError(msg)
if not is_calibrated():
msg = 'calibration failed'
raise EyetrackingError(msg)
def is_calibrated():
if VET.CalibrationStatus()[0] != 0:
return True
else:
return False
def start():
"""Start tracking the eye."""
- global lastgoodstamp
if not is_source_ready():
select_source()
if not is_calibrated():
msg = 'subject not yet calibrated'
raise EyetrackingError(msg)
- lastgoodstamp = 0
VET.ClearDataBuffer()
VET.StartTracking()
def stop():
"""Stop tracking the eye."""
VET.StopTracking()
def is_tracked(fps, track_period=TRACK_PER):
"""Returns true if the eye is being tracked.
fps -- frames per second at which stimulus is running
track_period -- duration in milliseconds during which eye has to
be consistently tracked or untracked in order for value returned
by this function to change
"""
global lasttrackstatus
global trackcount
data = VET.GetLatestEyePosition(DummyResultSet)[1]
if data.Tracked != lasttrackstatus:
trackcount += 1
else:
trackcount = 0
if trackcount >= track_period / to_decimal(1000) * fps:
trackcount = 0
lasttrackstatus = data.Tracked
return lasttrackstatus
def is_fixated(fps, fix_pos=FIX_POS,
fix_range=FIX_RANGE,
fix_period=FIX_PER):
"""Checks whether subject is fixating on specified location.
fps -- frames per second at which stimulus is running
fix_pos -- (x, y) position of desired fixation location in mm
from center of screen
fix_range -- (width, height) of box surrounding fix_pos within
which fixation is allowed (in mm)
fix_period -- duration in milliseconds during which eye has to
be consistently fixated or not fixated in order for value returned
by this function to change
"""
global lastfixstatus
global fixcount
data = VET.GetLatestEyePosition(DummyResultSet)[1]
pos = (data.ScreenPositionXmm, data.ScreenPositionYmm)
diff = [abs(p - fp) for p, fp in zip(pos, fix_pos)]
curfixstatus = False
if data.Tracked == True:
if diff[0] < fix_range[0] and diff[1] < fix_range[1]:
curfixstatus = True
if curfixstatus != lastfixstatus:
fixcount += 1
else:
fixcount = 0
if fixcount >= fix_period / to_decimal(1000) * fps:
fixcount = 0
lastfixstatus = curfixstatus
return lastfixstatus
|
ztangent/checkergen
|
b4bc17822617766a766a698c20c3d5257dd4677b
|
Ord_id now sent immediately after blk_on.
|
diff --git a/src/core.py b/src/core.py
index 1082053..67f470b 100755
--- a/src/core.py
+++ b/src/core.py
@@ -310,970 +310,972 @@ class CkgProj:
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
# Vars that are dicts
dicts_to_save = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_save = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for d_name in dicts_to_save:
d_el = doc.createElement(d_name)
project.appendChild(d_el)
d = getattr(self, d_name)
for k, v in d.iteritems():
xml_set(doc, d_el, k, repr(v))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, **keywords):
"""Displays the stimulus on the screen.
name -- name that logfile will be saved with
repeats -- number of times specified order of display groups should
be repeated
waitless -- if true, no waitscreens will appear at the start of each
repeat
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
priority -- priority level to which process should be raised
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
trigser -- send triggers through serial port when each group is shown
trigpar -- send triggers through parallel port when each group is shown
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
freqcheck -- send fpst only at the start, the middle, and the end
for sanity checking of display and trigger fps
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- append a wait screen to the group queue every time
after this many groups have been appended to the queue
order -- order in which groups (specified by id) will be displayed
"""
# Create RunState
disp_ops = copy.deepcopy(self.disp_ops)
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'name' in keywords.keys() and keywords['name'] != None:
name = keywords['name']
else:
timestr = datetime.today().strftime('_%Y-%m-%d_%H-%M-%S')
name = self.name + timestr
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
waitscreen = CkgWaitScreen()
# Set runstate order id if necessary
if order in self.orders:
runstate.ord_id = self.orders.index(order)
# Count through pre
for count in range(self.pre * self.fps):
if runstate.terminate:
break
runstate.update()
# Loop through repeats
repeats = runstate.disp_ops['repeats']
ord_len = len(runstate.order)
for i in range(repeats):
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
# Loop through display groups
runstate.events['blk_on'] = True
for n, gid in enumerate(runstate.order):
# Set flag for freqcheck
if runstate.disp_ops['freqcheck']:
if ((i == 0 and n == 0) or
(i == repeats-1 and n == ord_len-1) or
(i == repeats//2 and n == ord_len//2)):
runstate.fc_send = True
else:
runstate.fc_send = False
if gid == -1:
waitscreen.reset()
waitscreen.display(runstate)
else:
self.groups[gid].display(runstate)
if not runstate.terminate:
# Append group id and fail state
runstate.gids.append(gid)
if runstate.disp_ops['eyetrack']:
runstate.fails.append(runstate.true_fail)
# Append groups to be added
if runstate.disp_ops['eyetrack'] and runstate.true_fail:
if (len(runstate.add_gids) <
runstate.disp_ops['tryagain']):
runstate.add_gids.append(gid)
runstate.events['blk_off'] = True
# Stop freqcheck before added groups
if runstate.disp_ops['freqcheck']:
runstate.fc_send = False
# Loop through added groups
if runstate.disp_ops['eyetrack']:
for blk in grouper(runstate.add_gids,
runstate.disp_ops['trybreak']):
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
runstate.events['blk_on'] = True
# Loop through display groups
for gid in blk:
if gid != None:
self.groups[gid].display(runstate)
if not runstate.terminate:
# Append group id and fail state
runstate.gids.append(gid)
if runstate.disp_ops['eyetrack']:
runstate.fails.append(runstate.true_fail)
runstate.events['blk_off'] = True
# Count through post
for count in range(self.post * self.fps):
if runstate.terminate:
break
runstate.update()
# Stop and output log
runstate.stop()
if not runstate.disp_ops['nolog']:
runstate.log()
def export(self, **keywords):
"""Exports the stimulus as a series of images, one image per frame.
repeats -- number of times specified order of display groups should
be repeated
order -- order in which groups (specified by id) will be displayed
expo_dir -- directory to which images will be exported
expo_dur -- time in seconds to which export will be limited
folder -- if true, images will be contained in a separate folder
within export directory
force -- force export to go through even if a large number
of frames are to be exported
"""
# Create RunState
disp_ops = copy.deepcopy(self.__class__.DEFAULTS['disp_ops'])
disp_ops['export'] = True
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=self.name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
# Warn user if a lot of frames will be exported
if 'force' not in keywords.keys():
keywords['force'] = False
groups_dur = sum([self.groups[i].duration()
for i in order]) * disp_ops['repeats']
total_frames = (self.pre + groups_dur + self.post) * self.fps
frames = min(total_frames, disp_ops['expo_dur'] * self.fps)
if frames > MAX_EXPORT_FRAMES and not keywords['force']:
msg = 'large number ({0}) of frames to be exported'.\
format(int(frames))
raise FrameOverflowError(msg)
runstate.frames = frames
# Count through pre
for count in range(self.pre * self.fps):
if runstate.terminate:
break
runstate.update()
# Loop through repeats
repeats = runstate.disp_ops['repeats']
for i in range(repeats):
# Loop through display groups
for n, gid in enumerate(runstate.order):
if gid != -1:
self.groups[gid].display(runstate)
# Count through post
for count in range(self.post * self.fps):
if runstate.terminate:
break
runstate.update()
# Stop runstate
runstate.stop()
class CkgRunState:
"""Contains information about the state of a checkergen project
when it is being displayed or exported."""
DEFAULTS = dict([('name', 'untitled'),
('res', None),
('fps', None),
('bg', None),
('cross_cols', None),
('cross_times', None),
('order', []),
('disp_ops', None),
('events', None),
('gids', []),
('fails', []),
('add_gids', []),
('timestamps', []),
('durstamps', []),
('trigstamps', [])])
DEFAULTS['events'] = dict([('ord_id', None),
('blk_on', False),
('blk_off', False),
('track_on', False),
('track_off', False),
('fix_on', False),
('fix_off', False),
('grp_on', False),
('grp_off', False),
('sids', set())])
def __init__(self, **keywords):
"""Creates the RunState."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
def start(self):
"""Initialize all subsystems and start the run."""
if self.disp_ops == None:
msg = "RunState lacks display options"
raise ValueError(msg)
if min(self.res, self.fps, self.bg,
self.cross_cols, self.cross_times) == None:
msg = "RunState intialized with insufficent project information"
raise ValueError(msg)
self._count = 0
self._old_code = 0
self.ord_id = None
self.terminate = False
# Flag used by freqcheck
self.fc_send = False
# Create fixation crosses
self.fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if self.disp_ops['phototest']:
self.test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Initialize export
if self.disp_ops['export']:
if not os.path.isdir(self.disp_ops['expo_dir']):
msg = 'export path is not a directory'
raise IOError(msg)
if self.disp_ops['folder']:
self.save_dir = os.path.join(self.disp_ops['expo_dir'],
self.name + EXPORT_DIR_SUFFIX)
else:
self.save_dir = self.disp_ops['expo_dir']
if not os.path.isdir(self.save_dir):
os.mkdir(self.save_dir)
# Initialize ports
if self.disp_ops['trigser']:
if not trigger.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trigpar']:
if not trigger.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
trigger.init(self.disp_ops['trigser'], self.disp_ops['trigpar'])
# Initialize eyetracking
if self.disp_ops['eyetrack']:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trybreak'] == None:
self.disp_ops['trybreak'] = len(self.order)
self.fixated = False
self.old_fixated = False
self.tracked = False
self.old_tracked = False
self.fix_fail = False
self.true_fail = False
eyetracking.select_source(self.disp_ops['etuser'],
self.disp_ops['etvideo'])
eyetracking.start()
# Create window if not exporting
self.scaling = False
if not self.disp_ops['export']:
# Stretch to fit screen only if project res does not
# equal screen res
if self.disp_ops['fullscreen']:
self.window = pyglet.window.Window(fullscreen=True,
visible=False)
if (self.window.width, self.window.height) != self.res:
self.scaling = True
else:
self.window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
self.keystates = pyglet.window.key.KeyStateHandler()
self.window.push_handlers(self.keystates)
# Clear window and make visible
self.window.switch_to()
graphics.set_clear_color(self.bg)
self.window.clear()
self.window.set_visible()
# Create framebuffer object for drawing unscaled or exported scene
if self.scaling or self.disp_ops['export']:
self.canvas = pyglet.image.Texture.create(*self.res)
self.fbo = graphics.Framebuffer(self.canvas)
self.fbo.start_render()
graphics.set_clear_color(self.bg)
self.fbo.clear()
# Set process priority
if self.disp_ops['priority'] != None:
try:
priority.set(self.disp_ops['priority'])
except ValueError:
priority.set(int(self.disp_ops['priority']))
except:
pass
# Start timers
if self.disp_ops['logtime']:
self.timer = Timer()
self.timer.start()
if self.disp_ops['logdur']:
self.dur = Timer()
self.dur.start()
def update(self):
"""Update the RunState."""
# Check for tracking and fixation
if self.disp_ops['eyetrack']:
self.old_tracked = self.tracked
self.tracked = eyetracking.is_tracked(self.fps)
self.old_fixated = self.fixated
self.fixated = eyetracking.is_fixated(self.fps)
if self.fixated:
# Draw normal cross color if fixating
self.fix_crosses[0].draw()
else:
# Draw alternative cross color if not fixating
self.fix_crosses[1].draw()
# Update eyetracking events
if self.tracked != self.old_tracked:
if self.tracked:
self.events['track_on'] = True
else:
self.events['track_off'] = True
if self.fixated != self.old_fixated:
if self.fixated:
self.events['fix_on'] = True
else:
self.events['fix_off'] = True
# Check for failure of trial
if self.tracked and not self.fixated:
self.fix_fail = True
else:
# Change cross color based on time
if (self._count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
self.fix_crosses[0].draw()
else:
self.fix_crosses[1].draw()
if self.disp_ops['export']:
# Save current frame to file
savepath = os.path.join(
self.save_dir, '{0}{2}.{1}'.\
format(self.name, 'png',
repr(self._count).zfill(numdigits(self.frames-1))))
self.canvas.save(savepath)
else:
# Blit canvas to screen if necessary
if self.scaling:
self.fbo.end_render()
self.canvas.blit(0, 0)
self.window.switch_to()
self.window.dispatch_events()
self.window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to lists
if self.disp_ops['logtime']:
self.timestamps.append(self.timer.elapsed())
elif self.disp_ops['logdur']:
self.timestamps.append('')
if self.disp_ops['logdur']:
self.durstamps.append(self.dur.restart())
elif self.disp_ops['logtime']:
self.durstamps.append('')
# Send trigger ASAP after flip
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
if self.encode_events() != self._old_code:
trigger.send(self.disp_ops['trigser'],
self.disp_ops['trigpar'],
self.encode_events())
self._old_code = self.encode_events
# Log when triggers are sent
if self.disp_ops['logtime'] and self.encode_events() > 0:
self.trigstamps.append(self.encode_events())
else:
self.trigstamps.append('')
# Clear canvas, events, prepare for next frame
if self.disp_ops['export']:
self.fbo.clear()
else:
if self.scaling:
self.fbo.start_render()
self.fbo.clear()
else:
self.window.clear()
if self.window.has_exit:
self.terminate = True
+ # Send ord_id immediately after blk_on
+ send_ord_id_next = self.events['blk_on']
self.events = copy.deepcopy(self.__class__.DEFAULTS['events'])
+ if send_ord_id_next:
+ self.events['ord_id'] = self.ord_id
self._count += 1
# Terminate export if the time has come
if self.disp_ops['export']:
if self._count >= self.frames:
self.terminate = True
def stop(self):
"""Clean up RunState."""
if self.disp_ops['eyetrack']:
eyetracking.stop()
if self.scaling or self.disp_ops['export']:
self.fbo.delete()
del self.canvas
if not self.disp_ops['export']:
self.window.close()
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
trigger.quit(self.disp_ops['trigser'], self.disp_ops['trigpar'])
try:
priority.set('normal')
except:
pass
def encode_events(self):
"""Hard code specific trigger values for events."""
code = 0
if self.events['ord_id'] != None:
code = self.events['ord_id'] + 1
elif self.events['blk_on']:
code = 128
elif self.events['blk_off']:
code = 127
else:
mult = 0
if self.events['fix_on']:
mult = 4
elif self.events['track_on']:
mult = 3
if self.events['track_off']:
mult = 1
elif self.events['fix_off']:
mult = 2
if self.events['grp_on']:
code = 100 + mult
elif self.events['grp_off']:
code = 90 + mult
elif len(self.events['sids']) > 0:
code = ((0 in self.events['sids'])*2**0 +
(1 in self.events['sids'])*2**1 +
(2 in self.events['sids'])*2**2 +
(3 in self.events['sids'])*2**3)
code = mult*16 + code
elif mult > 0:
code = 110 + mult
return code
def log(self, path=None):
"""Write a log file for the experimental run in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, LOG_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(LOG_FMT):
path = '{0}.{1}'.format(path, LOG_FMT)
with open(path, 'wb') as logfile:
writer = csv.writer(logfile, dialect='excel-tab')
writer.writerow(['checkergen log file'])
writer.writerow(['display options:'])
writer.writerow(self.disp_ops.keys())
writer.writerow(self.disp_ops.values())
writer.writerow(['order:'] + self.order)
writer.writerow(['groups', 'failure'])
if not self.disp_ops['eyetrack']:
self.fails = ['NA'] * len(self.gids)
for i in zip(self.gids, self.fails):
writer.writerow(list(i))
if self.disp_ops['eyetrack']:
writer.writerow(['groups added'])
for blk in grouper(self.add_gids,
self.disp_ops['trybreak'], ''):
writer.writerow(blk)
if self.disp_ops['logtime'] or self.disp_ops['logdur']:
stamps = [self.timestamps, self.durstamps, self.trigstamps]
writer.writerow(['timestamps', 'durations', 'triggers'])
for stamp in zip(*stamps):
writer.writerow(list(stamp))
class CkgDisplayGroup:
DEFAULTS = OrderedDict([('pre', 0), ('disp', 'Infinity'), ('post', 0)])
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets counts and all contained shapes."""
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, runstate):
"""Draws all contained shapes during the appropriate interval."""
for shape in self.shapes:
shape.draw(photoburst=runstate.disp_ops['photoburst'])
def update(self, runstate):
"""Updates contained shapes, sets event triggers."""
# Set events to be sent
if runstate.disp_ops['fpst'] > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= runstate.disp_ops['fpst']:
if not runstate.disp_ops['freqcheck'] or runstate.fc_send:
runstate.events['sids'].add(n)
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(runstate.fps)
def display(self, runstate):
"""Display the group in the context described by supplied runstate."""
self.reset()
for count in range(self.pre * runstate.fps):
if runstate.terminate:
break
runstate.update()
runstate.events['grp_on'] = True
if runstate.disp_ops['eyetrack']:
runstate.fix_fail = False
runstate.true_fail = False
for count in range(self.disp * runstate.fps):
if runstate.terminate:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
runstate.events['grp_off'] = True
if runstate.disp_ops['eyetrack']:
if runstate.fix_fail:
runstate.true_fail = True
for count in range(self.post * runstate.fps):
if runstate.terminate:
break
runstate.update()
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.steps_done = 0
def draw(self, runstate):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, runstate):
"""Checks for keypress, sends trigger upon end."""
if max([runstate.keystates[key] for
key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
- if self.steps_done == 1:
- runstate.events['ord_id'] = runstate.ord_id
def display(self, runstate):
"""Displays waitscreen in context described by supplied runstate."""
while self.steps_done < self.num_steps:
if runstate.terminate:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = OrderedDict([('dims', (5, 5)),
('init_unit', (30, 30)),
('end_unit', (50, 50)),
('position', (0, 0)),
('anchor', 'bottomleft'),
('cols', ((0, 0, 0), (255, 255, 255))),
('freq', 1),
('phase', 0)])
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
if INT_HALF_PERIODS:
frames_per_half_period = round(fps / (self.freq * 2))
degs_per_frame = 180 / to_decimal(frames_per_half_period)
else:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
anchor=self.anchor)
cur_unit_rect.col = self.cols[(i + j) % 2]
cur_unit_rect.add_to_batch(self._batches[0])
cur_unit_rect.col = self.cols[(i + j + 1) % 2]
cur_unit_rect.add_to_batch(self._batches[1])
# Increase x values
cur_unit_pos[0] += \
graphics.locations[self.anchor][0] * cur_unit[0]
cur_unit[0] += unit_grad[0]
# Reset x values
cur_unit_pos[0] = init_pos[0]
cur_unit[0] = init_unit[0]
# Increase y values
cur_unit_pos[1] += \
graphics.locations[self.anchor][1] * cur_unit[1]
cur_unit[1] += unit_grad[1]
self._computed = True
def draw(self, photoburst=False, always_compute=False):
"""Draws appropriate batch depending on current phase.
photoburst -- draw first color for only one frame for testing purposes
always_compute -- recompute what the checkerboard should look like
every frame
"""
if not self._computed or always_compute:
self.compute()
self._cur_phase %= 360
n = int(self._cur_phase // 180)
if photoburst and n == 0 and not self.flipped:
n = 1
self._batches[n].draw()
def lazydraw(self):
"""Only draws on color reversal."""
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if (cur_n != prev_n) or self._first_draw:
self.draw()
if self._first_draw:
self._first_draw = False
|
ztangent/checkergen
|
6819b49f7a7ca003c24668fcb5930797aa8b170b
|
Changed when order id is sent (after pressing Enter at waitscreen).
|
diff --git a/src/core.py b/src/core.py
index 177e3cb..1082053 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,1274 +1,1279 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import copy
import random
import itertools
from datetime import datetime
from xml.dom import minidom
import pyglet
import graphics
import priority
import trigger
import eyetracking
from utils import *
# Use OrderedDict substitute if we don't have Python 2.7
if sys.version_info < (2, 7):
from odict import OrderedDict
else:
from collections import OrderedDict
CKG_FMT = 'ckg'
LOG_FMT = 'log'
MAX_EXPORT_FRAMES = 1000
EXPORT_DIR_SUFFIX = '-anim'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
INT_HALF_PERIODS = True
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = OrderedDict([('name', 'untitled'),
('fps', 60),
('res', (800, 600)),
('bg', (127, 127, 127)),
('pre', 0),
('post', 0),
('cross_cols', ((0, 0, 0), (255, 0, 0))),
('cross_times', ('Infinity', 1)),
('orders', []),
('disp_ops', None)])
DEFAULTS['disp_ops'] = OrderedDict([('repeats', 1),
('waitless', False),
('fullscreen', False),
('priority', None),
('logtime', False),
('logdur', False),
('trigser', False),
('trigpar', False),
('fpst', 0),
('freqcheck', False),
('phototest', False),
('photoburst', False),
('eyetrack', False),
('etuser', False),
('etvideo', None),
('tryagain', 0),
('trybreak', None),
('nolog', False),
('export', False),
('expo_dir', None),
('expo_dur', None),
('folder', True)])
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def set_display_flags(self, **keywords):
"""Set default display flags for the project.
Same arguments as 'display', excluding 'name' and 'order'.
"""
for kw in keywords.keys():
if kw in self.disp_ops.keys() and keywords[kw] != None:
self.disp_ops[kw] = keywords[kw]
self._dirty = True
def set_group_orders(self, orders):
for order in orders:
for gid in order:
if gid < -1 or gid >= len(self.groups):
msg = 'invalid group id (out of range)'
raise ValueError(msg)
self.orders = orders
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
# Vars that are dicts
dicts_to_load = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_load = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
for d_name in dicts_to_load:
d = copy.deepcopy(self.__class__.DEFAULTS[d_name])
try:
d_el = [node for node in project.childNodes if
node.localName == d_name and
node.namespaceURI == XML_NAMESPACE][0]
for var in d.keys():
try:
d[var] = eval(xml_get(d_el, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}' in '{1}'".\
format(var, d_name)
print "using default value '{0}' instead...".\
format(d[var])
except IndexError:
print "warning: missing attribute set '{0}'".format(d_name)
print "using default values instead..."
setattr(self, d_name, d)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
# Vars that are dicts
dicts_to_save = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_save = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for d_name in dicts_to_save:
d_el = doc.createElement(d_name)
project.appendChild(d_el)
d = getattr(self, d_name)
for k, v in d.iteritems():
xml_set(doc, d_el, k, repr(v))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, **keywords):
"""Displays the stimulus on the screen.
name -- name that logfile will be saved with
repeats -- number of times specified order of display groups should
be repeated
waitless -- if true, no waitscreens will appear at the start of each
repeat
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
priority -- priority level to which process should be raised
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
trigser -- send triggers through serial port when each group is shown
trigpar -- send triggers through parallel port when each group is shown
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
freqcheck -- send fpst only at the start, the middle, and the end
for sanity checking of display and trigger fps
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- append a wait screen to the group queue every time
after this many groups have been appended to the queue
order -- order in which groups (specified by id) will be displayed
"""
# Create RunState
disp_ops = copy.deepcopy(self.disp_ops)
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'name' in keywords.keys() and keywords['name'] != None:
name = keywords['name']
else:
timestr = datetime.today().strftime('_%Y-%m-%d_%H-%M-%S')
name = self.name + timestr
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
waitscreen = CkgWaitScreen()
- # Set order id to be sent if necessary
+ # Set runstate order id if necessary
if order in self.orders:
- runstate.events['ord_id'] = self.orders.index(order)
-
+ runstate.ord_id = self.orders.index(order)
# Count through pre
for count in range(self.pre * self.fps):
if runstate.terminate:
break
runstate.update()
# Loop through repeats
repeats = runstate.disp_ops['repeats']
ord_len = len(runstate.order)
for i in range(repeats):
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
# Loop through display groups
runstate.events['blk_on'] = True
for n, gid in enumerate(runstate.order):
# Set flag for freqcheck
if runstate.disp_ops['freqcheck']:
if ((i == 0 and n == 0) or
(i == repeats-1 and n == ord_len-1) or
(i == repeats//2 and n == ord_len//2)):
runstate.fc_send = True
else:
runstate.fc_send = False
if gid == -1:
waitscreen.reset()
waitscreen.display(runstate)
else:
self.groups[gid].display(runstate)
- # Append group id and fail state
- runstate.gids.append(gid)
- if runstate.disp_ops['eyetrack']:
- runstate.fails.append(runstate.true_fail)
- # Append groups to be added
- if runstate.disp_ops['eyetrack'] and runstate.true_fail:
- if len(runstate.add_gids) < runstate.disp_ops['tryagain']:
- runstate.add_gids.append(gid)
+ if not runstate.terminate:
+ # Append group id and fail state
+ runstate.gids.append(gid)
+ if runstate.disp_ops['eyetrack']:
+ runstate.fails.append(runstate.true_fail)
+ # Append groups to be added
+ if runstate.disp_ops['eyetrack'] and runstate.true_fail:
+ if (len(runstate.add_gids) <
+ runstate.disp_ops['tryagain']):
+ runstate.add_gids.append(gid)
runstate.events['blk_off'] = True
# Stop freqcheck before added groups
if runstate.disp_ops['freqcheck']:
runstate.fc_send = False
# Loop through added groups
if runstate.disp_ops['eyetrack']:
for blk in grouper(runstate.add_gids,
runstate.disp_ops['trybreak']):
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
runstate.events['blk_on'] = True
# Loop through display groups
for gid in blk:
if gid != None:
self.groups[gid].display(runstate)
- # Append group id and fail state
- runstate.gids.append(gid)
- if runstate.disp_ops['eyetrack']:
- runstate.fails.append(runstate.true_fail)
+ if not runstate.terminate:
+ # Append group id and fail state
+ runstate.gids.append(gid)
+ if runstate.disp_ops['eyetrack']:
+ runstate.fails.append(runstate.true_fail)
runstate.events['blk_off'] = True
# Count through post
for count in range(self.post * self.fps):
if runstate.terminate:
break
runstate.update()
# Stop and output log
runstate.stop()
if not runstate.disp_ops['nolog']:
runstate.log()
def export(self, **keywords):
"""Exports the stimulus as a series of images, one image per frame.
repeats -- number of times specified order of display groups should
be repeated
order -- order in which groups (specified by id) will be displayed
expo_dir -- directory to which images will be exported
expo_dur -- time in seconds to which export will be limited
folder -- if true, images will be contained in a separate folder
within export directory
force -- force export to go through even if a large number
of frames are to be exported
"""
# Create RunState
disp_ops = copy.deepcopy(self.__class__.DEFAULTS['disp_ops'])
disp_ops['export'] = True
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=self.name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
# Warn user if a lot of frames will be exported
if 'force' not in keywords.keys():
keywords['force'] = False
groups_dur = sum([self.groups[i].duration()
for i in order]) * disp_ops['repeats']
total_frames = (self.pre + groups_dur + self.post) * self.fps
frames = min(total_frames, disp_ops['expo_dur'] * self.fps)
if frames > MAX_EXPORT_FRAMES and not keywords['force']:
msg = 'large number ({0}) of frames to be exported'.\
format(int(frames))
raise FrameOverflowError(msg)
runstate.frames = frames
# Count through pre
for count in range(self.pre * self.fps):
if runstate.terminate:
break
runstate.update()
# Loop through repeats
repeats = runstate.disp_ops['repeats']
for i in range(repeats):
# Loop through display groups
for n, gid in enumerate(runstate.order):
if gid != -1:
self.groups[gid].display(runstate)
# Count through post
for count in range(self.post * self.fps):
if runstate.terminate:
break
runstate.update()
# Stop runstate
runstate.stop()
class CkgRunState:
"""Contains information about the state of a checkergen project
when it is being displayed or exported."""
DEFAULTS = dict([('name', 'untitled'),
('res', None),
('fps', None),
('bg', None),
('cross_cols', None),
('cross_times', None),
('order', []),
('disp_ops', None),
('events', None),
('gids', []),
('fails', []),
('add_gids', []),
('timestamps', []),
('durstamps', []),
('trigstamps', [])])
DEFAULTS['events'] = dict([('ord_id', None),
('blk_on', False),
('blk_off', False),
('track_on', False),
('track_off', False),
('fix_on', False),
('fix_off', False),
('grp_on', False),
('grp_off', False),
('sids', set())])
def __init__(self, **keywords):
"""Creates the RunState."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
def start(self):
"""Initialize all subsystems and start the run."""
if self.disp_ops == None:
msg = "RunState lacks display options"
raise ValueError(msg)
if min(self.res, self.fps, self.bg,
self.cross_cols, self.cross_times) == None:
msg = "RunState intialized with insufficent project information"
raise ValueError(msg)
self._count = 0
self._old_code = 0
+ self.ord_id = None
self.terminate = False
# Flag used by freqcheck
self.fc_send = False
# Create fixation crosses
self.fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if self.disp_ops['phototest']:
self.test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Initialize export
if self.disp_ops['export']:
if not os.path.isdir(self.disp_ops['expo_dir']):
msg = 'export path is not a directory'
raise IOError(msg)
if self.disp_ops['folder']:
self.save_dir = os.path.join(self.disp_ops['expo_dir'],
self.name + EXPORT_DIR_SUFFIX)
else:
self.save_dir = self.disp_ops['expo_dir']
if not os.path.isdir(self.save_dir):
os.mkdir(self.save_dir)
# Initialize ports
if self.disp_ops['trigser']:
if not trigger.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trigpar']:
if not trigger.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
trigger.init(self.disp_ops['trigser'], self.disp_ops['trigpar'])
# Initialize eyetracking
if self.disp_ops['eyetrack']:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trybreak'] == None:
self.disp_ops['trybreak'] = len(self.order)
self.fixated = False
self.old_fixated = False
self.tracked = False
self.old_tracked = False
self.fix_fail = False
self.true_fail = False
eyetracking.select_source(self.disp_ops['etuser'],
self.disp_ops['etvideo'])
eyetracking.start()
# Create window if not exporting
self.scaling = False
if not self.disp_ops['export']:
# Stretch to fit screen only if project res does not
# equal screen res
if self.disp_ops['fullscreen']:
self.window = pyglet.window.Window(fullscreen=True,
visible=False)
if (self.window.width, self.window.height) != self.res:
self.scaling = True
else:
self.window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
self.keystates = pyglet.window.key.KeyStateHandler()
self.window.push_handlers(self.keystates)
# Clear window and make visible
self.window.switch_to()
graphics.set_clear_color(self.bg)
self.window.clear()
self.window.set_visible()
# Create framebuffer object for drawing unscaled or exported scene
if self.scaling or self.disp_ops['export']:
self.canvas = pyglet.image.Texture.create(*self.res)
self.fbo = graphics.Framebuffer(self.canvas)
self.fbo.start_render()
graphics.set_clear_color(self.bg)
self.fbo.clear()
# Set process priority
if self.disp_ops['priority'] != None:
try:
priority.set(self.disp_ops['priority'])
except ValueError:
priority.set(int(self.disp_ops['priority']))
except:
pass
# Start timers
if self.disp_ops['logtime']:
self.timer = Timer()
self.timer.start()
if self.disp_ops['logdur']:
self.dur = Timer()
self.dur.start()
def update(self):
"""Update the RunState."""
# Check for tracking and fixation
if self.disp_ops['eyetrack']:
self.old_tracked = self.tracked
self.tracked = eyetracking.is_tracked(self.fps)
self.old_fixated = self.fixated
self.fixated = eyetracking.is_fixated(self.fps)
if self.fixated:
# Draw normal cross color if fixating
self.fix_crosses[0].draw()
else:
# Draw alternative cross color if not fixating
self.fix_crosses[1].draw()
# Update eyetracking events
if self.tracked != self.old_tracked:
if self.tracked:
self.events['track_on'] = True
else:
self.events['track_off'] = True
if self.fixated != self.old_fixated:
if self.fixated:
self.events['fix_on'] = True
else:
self.events['fix_off'] = True
# Check for failure of trial
if self.tracked and not self.fixated:
self.fix_fail = True
else:
# Change cross color based on time
if (self._count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
self.fix_crosses[0].draw()
else:
self.fix_crosses[1].draw()
if self.disp_ops['export']:
# Save current frame to file
savepath = os.path.join(
self.save_dir, '{0}{2}.{1}'.\
format(self.name, 'png',
repr(self._count).zfill(numdigits(self.frames-1))))
self.canvas.save(savepath)
else:
# Blit canvas to screen if necessary
if self.scaling:
self.fbo.end_render()
self.canvas.blit(0, 0)
self.window.switch_to()
self.window.dispatch_events()
self.window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to lists
if self.disp_ops['logtime']:
self.timestamps.append(self.timer.elapsed())
elif self.disp_ops['logdur']:
self.timestamps.append('')
if self.disp_ops['logdur']:
self.durstamps.append(self.dur.restart())
elif self.disp_ops['logtime']:
self.durstamps.append('')
# Send trigger ASAP after flip
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
if self.encode_events() != self._old_code:
trigger.send(self.disp_ops['trigser'],
self.disp_ops['trigpar'],
self.encode_events())
self._old_code = self.encode_events
# Log when triggers are sent
if self.disp_ops['logtime'] and self.encode_events() > 0:
self.trigstamps.append(self.encode_events())
else:
self.trigstamps.append('')
# Clear canvas, events, prepare for next frame
if self.disp_ops['export']:
self.fbo.clear()
else:
if self.scaling:
self.fbo.start_render()
self.fbo.clear()
else:
self.window.clear()
if self.window.has_exit:
self.terminate = True
self.events = copy.deepcopy(self.__class__.DEFAULTS['events'])
self._count += 1
# Terminate export if the time has come
if self.disp_ops['export']:
if self._count >= self.frames:
self.terminate = True
def stop(self):
"""Clean up RunState."""
if self.disp_ops['eyetrack']:
eyetracking.stop()
if self.scaling or self.disp_ops['export']:
self.fbo.delete()
del self.canvas
if not self.disp_ops['export']:
self.window.close()
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
trigger.quit(self.disp_ops['trigser'], self.disp_ops['trigpar'])
try:
priority.set('normal')
except:
pass
def encode_events(self):
"""Hard code specific trigger values for events."""
code = 0
if self.events['ord_id'] != None:
code = self.events['ord_id'] + 1
elif self.events['blk_on']:
code = 128
elif self.events['blk_off']:
code = 127
else:
mult = 0
if self.events['fix_on']:
mult = 4
elif self.events['track_on']:
mult = 3
if self.events['track_off']:
mult = 1
elif self.events['fix_off']:
mult = 2
if self.events['grp_on']:
code = 100 + mult
elif self.events['grp_off']:
code = 90 + mult
elif len(self.events['sids']) > 0:
code = ((0 in self.events['sids'])*2**0 +
(1 in self.events['sids'])*2**1 +
(2 in self.events['sids'])*2**2 +
(3 in self.events['sids'])*2**3)
code = mult*16 + code
elif mult > 0:
code = 110 + mult
return code
def log(self, path=None):
"""Write a log file for the experimental run in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, LOG_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(LOG_FMT):
path = '{0}.{1}'.format(path, LOG_FMT)
with open(path, 'wb') as logfile:
writer = csv.writer(logfile, dialect='excel-tab')
writer.writerow(['checkergen log file'])
writer.writerow(['display options:'])
writer.writerow(self.disp_ops.keys())
writer.writerow(self.disp_ops.values())
writer.writerow(['order:'] + self.order)
writer.writerow(['groups', 'failure'])
if not self.disp_ops['eyetrack']:
self.fails = ['NA'] * len(self.gids)
for i in zip(self.gids, self.fails):
writer.writerow(list(i))
if self.disp_ops['eyetrack']:
writer.writerow(['groups added'])
for blk in grouper(self.add_gids,
self.disp_ops['trybreak'], ''):
writer.writerow(blk)
if self.disp_ops['logtime'] or self.disp_ops['logdur']:
stamps = [self.timestamps, self.durstamps, self.trigstamps]
writer.writerow(['timestamps', 'durations', 'triggers'])
for stamp in zip(*stamps):
writer.writerow(list(stamp))
class CkgDisplayGroup:
DEFAULTS = OrderedDict([('pre', 0), ('disp', 'Infinity'), ('post', 0)])
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets counts and all contained shapes."""
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, runstate):
"""Draws all contained shapes during the appropriate interval."""
for shape in self.shapes:
shape.draw(photoburst=runstate.disp_ops['photoburst'])
def update(self, runstate):
"""Updates contained shapes, sets event triggers."""
# Set events to be sent
if runstate.disp_ops['fpst'] > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= runstate.disp_ops['fpst']:
if not runstate.disp_ops['freqcheck'] or runstate.fc_send:
runstate.events['sids'].add(n)
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(runstate.fps)
def display(self, runstate):
"""Display the group in the context described by supplied runstate."""
self.reset()
for count in range(self.pre * runstate.fps):
if runstate.terminate:
break
runstate.update()
runstate.events['grp_on'] = True
if runstate.disp_ops['eyetrack']:
runstate.fix_fail = False
runstate.true_fail = False
for count in range(self.disp * runstate.fps):
if runstate.terminate:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
runstate.events['grp_off'] = True
if runstate.disp_ops['eyetrack']:
if runstate.fix_fail:
runstate.true_fail = True
for count in range(self.post * runstate.fps):
if runstate.terminate:
break
runstate.update()
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.steps_done = 0
def draw(self, runstate):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, runstate):
"""Checks for keypress, sends trigger upon end."""
if max([runstate.keystates[key] for
key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
+ if self.steps_done == 1:
+ runstate.events['ord_id'] = runstate.ord_id
def display(self, runstate):
"""Displays waitscreen in context described by supplied runstate."""
while self.steps_done < self.num_steps:
if runstate.terminate:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = OrderedDict([('dims', (5, 5)),
('init_unit', (30, 30)),
('end_unit', (50, 50)),
('position', (0, 0)),
('anchor', 'bottomleft'),
('cols', ((0, 0, 0), (255, 255, 255))),
('freq', 1),
('phase', 0)])
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
if INT_HALF_PERIODS:
frames_per_half_period = round(fps / (self.freq * 2))
degs_per_frame = 180 / to_decimal(frames_per_half_period)
else:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
anchor=self.anchor)
cur_unit_rect.col = self.cols[(i + j) % 2]
cur_unit_rect.add_to_batch(self._batches[0])
cur_unit_rect.col = self.cols[(i + j + 1) % 2]
cur_unit_rect.add_to_batch(self._batches[1])
# Increase x values
cur_unit_pos[0] += \
graphics.locations[self.anchor][0] * cur_unit[0]
cur_unit[0] += unit_grad[0]
# Reset x values
cur_unit_pos[0] = init_pos[0]
cur_unit[0] = init_unit[0]
# Increase y values
cur_unit_pos[1] += \
graphics.locations[self.anchor][1] * cur_unit[1]
cur_unit[1] += unit_grad[1]
self._computed = True
def draw(self, photoburst=False, always_compute=False):
"""Draws appropriate batch depending on current phase.
photoburst -- draw first color for only one frame for testing purposes
always_compute -- recompute what the checkerboard should look like
every frame
"""
if not self._computed or always_compute:
self.compute()
self._cur_phase %= 360
n = int(self._cur_phase // 180)
if photoburst and n == 0 and not self.flipped:
n = 1
self._batches[n].draw()
def lazydraw(self):
"""Only draws on color reversal."""
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if (cur_n != prev_n) or self._first_draw:
self.draw()
if self._first_draw:
self._first_draw = False
|
ztangent/checkergen
|
986f7335fbd5c0793edca7bce1ab5d18b8bb8473
|
Changed how fixation failure is logged, fixed some priority setting bugs.
|
diff --git a/src/cli.py b/src/cli.py
index 0650859..8e3de68 100644
--- a/src/cli.py
+++ b/src/cli.py
@@ -467,702 +467,701 @@ class CkgCmd(cmd.Cmd):
"is the current display group"
elif args.gid >= len(self.cur_proj.groups) or args.gid < 0:
print "group", args.gid, "does not exist"
else:
self.cur_group = self.cur_proj.groups[args.gid]
print "group", args.gid, "is now the current display group"
mk_parser = CmdParser(add_help=False, prog='mk',
description='''Makes a new checkerboard in the
current group with the given
parameters.''')
mk_parser.add_argument('dims', action=store_list(2, ',', to_decimal),
help='''width,height of checkerboard in no. of
unit cells''')
mk_parser.add_argument('init_unit', action=store_list(2, ',', to_decimal),
help='width,height of initial unit cell in pixels')
mk_parser.add_argument('end_unit', action=store_list(2, ',', to_decimal),
help='width,height of final unit cell in pixels')
mk_parser.add_argument('position', action=store_list(2, ',', to_decimal),
help='x,y position of checkerboard in pixels')
mk_parser.add_argument('anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='anchor')
mk_parser.add_argument('cols', action=store_list(2, ',', to_color, [';']),
help='''color1,color2 of the checkerboard
(color format: R;G;B,
component range from 0-255)''')
mk_parser.add_argument('freq', type=to_decimal,
help='frequency of color reversal in Hz')
mk_parser.add_argument('phase', type=to_decimal, nargs='?', default='0',
help='initial phase in degrees')
def help_mk(self):
self.__class__.mk_parser.print_help()
def do_mk(self, line):
"""Makes a checkerboard with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
if self.cur_group == None:
print 'automatically adding display group...'
self.do_mkgrp('')
try:
args = self.__class__.mk_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mk_parser.print_usage()
return
shape_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_shape = core.CheckerBoard(**shape_dict)
new_id = self.cur_proj.add_shape_to_group(self.cur_group, new_shape)
print "checkerboard", new_id, "added"
ed_parser = CmdParser(add_help=False, prog='ed',
description='''Edits attributes of checkerboards
specified by ids.''')
ed_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='''ids of checkerboards in the current
group to be edited''')
ed_parser.add_argument('--dims', action=store_list(2, ',', to_decimal),
help='checkerboard dimensions in unit cells',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--init_unit',
action=store_list(2, ',', to_decimal),
help='initial unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--end_unit',
action=store_list(2, ',', to_decimal),
help='final unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--position',
action=store_list(2, ',', to_decimal),
help='position of checkerboard in pixels',
metavar='X,Y')
ed_parser.add_argument('--anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='LOCATION')
ed_parser.add_argument('--cols', metavar='COLOR1,COLOR2',
action=store_list(2, ',', to_color, [';']),
help='''checkerboard colors (color format:
R;G;B, component range
from 0-255)''')
ed_parser.add_argument('--freq', type=to_decimal,
help='frequency of color reversal in Hz')
ed_parser.add_argument('--phase', type=to_decimal,
help='initial phase in degrees')
def help_ed(self):
self.__class__.ed_parser.print_help()
def do_ed(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, please create one first'
return
try:
args = self.__class__.ed_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ed_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_group.shapes) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_shape_attr(self.cur_group, x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.ed_parser.print_usage()
rm_parser = CmdParser(add_help=False, prog='rm',
description='''Removes checkerboards specified
by ids.''')
rm_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''ids of checkerboards in the current group
to be removed''')
rm_parser.add_argument('-a', '--all', action='store_true',
help='''remove all checkerboards in the
current group''')
def help_rm(self):
self.__class__.rm_parser.print_help()
def do_rm(self, line):
"""Removes checkerboards specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, no boards to remove'
return
try:
args = self.__class__.rm_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rm_parser.print_usage()
return
rmlist = []
if args.all:
for shape in self.cur_group.shapes:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
print "all checkerboards removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_group.shapes) or x < 0:
print "checkerboard", x, "does not exist"
continue
rmlist.append(self.cur_group.shapes[x])
print "checkerboard", x, "removed"
for shape in rmlist:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
ls_parser = CmdParser(add_help=False, prog='ls',
description='''Lists project, display group and
checkerboard settings. If no group ids
are specified, all display groups
are listed.''')
ls_parser.add_argument('gids', nargs='*', metavar='gid', type=int,
help='''ids of the display groups to be listed''')
ls_group = ls_parser.add_mutually_exclusive_group()
ls_group.add_argument('-s', '--settings', action='store_true',
help='list only project settings')
ls_group.add_argument('-g', '--groups', action='store_true',
help='list only display groups')
ls_group.add_argument('-d', '--disp_ops', action='store_true',
help='list display options')
ls_group.add_argument('-o', '--orders', action='store_true',
help='list group orderings')
def help_ls(self):
self.__class__.ls_parser.print_help()
def do_ls(self, line):
"""Lists project, display group and checkerboard settings."""
def ls_str(s, seps=[',',';']):
"""Special space-saving output formatter."""
if type(s) in [tuple, list]:
if len(seps) > 1:
newseps = seps[1:]
else:
newseps = seps
return seps[0].join([ls_str(i, newseps) for i in s])
else:
return str(s)
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.ls_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ls_parser.print_usage()
return
# Remove duplicates and ascending sort
args.gids = sorted(set(args.gids))
if len(self.cur_proj.groups) == 0:
if len(args.gids) > 0:
print 'this project has no display groups that can be listed'
return
else:
for gid in args.gids[:]:
if gid >= len(self.cur_proj.groups) or gid < 0:
args.gids.remove(gid)
print 'display group', gid, 'does not exist'
if args.gids == []:
args.gids = range(len(self.cur_proj.groups))
else:
# If any (valid) groups are specified
# don't show project settings
args.groups = True
args.show_all = not max(args.settings, args.groups,
args.disp_ops, args.orders)
if args.show_all or args.settings:
print 'PROJECT SETTINGS'.center(70,'*')
print \
'name'.rjust(16),\
'fps'.rjust(7),\
'resolution'.rjust(14),\
'bg color'.rjust(18)
print \
ls_str(self.cur_proj.name).rjust(16),\
ls_str(self.cur_proj.fps).rjust(7),\
ls_str(self.cur_proj.res).rjust(14),\
ls_str(self.cur_proj.bg).rjust(18)
print \
'pre-display'.rjust(26),\
'post-display'.rjust(26)
print \
ls_str(self.cur_proj.pre).rjust(26),\
ls_str(self.cur_proj.post).rjust(26)
print \
'cross colors'.rjust(26),\
'cross times'.rjust(26)
print \
ls_str(self.cur_proj.cross_cols).rjust(26),\
ls_str(self.cur_proj.cross_times).rjust(26)
if args.show_all:
# Insert empty line between different info sets
print ''
if args.show_all or args.disp_ops:
print 'DISPLAY OPTIONS'.center(70,'*')
for k, v in self.cur_proj.disp_ops.items():
print ''.ljust(20), ls_str(k).ljust(20), ls_str(v).ljust(20)
if args.show_all:
# Insert empty line between different info sets
print ''
if args.show_all or args.orders:
print 'GROUP ORDERINGS'.center(70,'*')
if self.cur_proj.orders == []:
order = range(len(self.cur_proj.groups))
print \
''.ljust(20),\
'default order'.ljust(20),\
ls_str(order).ljust(20)
else:
for n, order in enumerate(self.cur_proj.orders):
print \
''.ljust(20),\
'order {n}'.format(n=n).ljust(20),\
ls_str(order).ljust(20)
if args.show_all:
# Insert empty line between different info sets
print ''
if args.show_all or args.groups:
for i, n in enumerate(args.gids):
if i != 0:
# Print newline seperator between each group
print ''
group = self.cur_proj.groups[n]
print 'GROUP {n}'.format(n=n).center(70,'*')
print \
'pre-display'.rjust(20),\
'display'.rjust(20),\
'post-display'.rjust(20)
print \
ls_str(group.pre).rjust(20),\
ls_str(group.disp).rjust(20),\
ls_str(group.post).rjust(20)
if len(group.shapes) > 0:
print \
''.rjust(2),\
'shape id'.rjust(8),\
'dims'.rjust(10),\
'init_unit'.rjust(14),\
'end_unit'.rjust(14),\
'position'.rjust(14)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.dims).rjust(10),\
ls_str(shape.init_unit).rjust(14),\
ls_str(shape.end_unit).rjust(14),\
ls_str(shape.position).rjust(14)
print '\n',\
''.rjust(2),\
'shape id'.rjust(8),\
'colors'.rjust(27),\
'anchor'.rjust(12),\
'freq'.rjust(6),\
'phase'.rjust(7)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.cols).rjust(27),\
ls_str(shape.anchor).rjust(12),\
ls_str(shape.freq).rjust(6),\
ls_str(shape.phase).rjust(7)
display_parser = CmdParser(add_help=False, prog='display',
description='''Displays the stimulus in a
window or in fullscreen.''')
display_parser.add_argument('-s', '--save', action='store_true',
help='''save specified display flags
as default flags for project
instead of presenting stimulus''')
display_parser.add_argument('-n', '--name', metavar='FOOBAR',
help='''name of log file to be written''')
display_parser.add_argument('-r', '--repeats', metavar='N', type=int,
help='''repeatedly display specified display
groups N number of times''')
display_parser.add_argument('-wl', '--waitless', action=store_truth(),
metavar='t/f',
help='''do not add waitscreens before the
start of each repeat''')
display_parser.add_argument('-f', '--fullscreen', action=store_truth(),
metavar='t/f',
help='sets fullscreen mode, ESC to quit')
display_parser.add_argument('-p', '--priority', metavar='LEVEL',
help='''set priority while displaying,
higher priority results in
less dropped frames (choices:
0-3, low, normal, high,
realtime)''')
display_parser.add_argument('-pt', '--phototest', action=store_truth(),
metavar='t/f',
help='''draw white test rectangle in topleft
corner of screen when groups become
visible for a photodiode to detect''')
display_parser.add_argument('-pb', '--photoburst', action=store_truth(),
metavar='t/f',
help='''make checkerboards only draw first
color for one frame to facilitate
testing with a photodiode''')
display_parser.add_argument('-lt', '--logtime', action=store_truth(),
metavar='t/f',
help='output frame timestamps to a log file')
display_parser.add_argument('-ld', '--logdur', action=store_truth(),
metavar='t/f',
help='output frame durations to a log file')
display_parser.add_argument('-ss', '--trigser', action=store_truth(),
metavar='t/f',
help='''send triggers through the serial port
when shapes are being displayed''')
display_parser.add_argument('-sp', '--trigpar', action=store_truth(),
metavar='t/f',
help='''send triggers through the parallel port
when shapes are being displayed''')
display_parser.add_argument('-fpst', metavar='M', type=int,
help='''unique trigger corresponding to a
checkerboard is sent after the shape
undergoes M color flips (default:
disabled, M=0)''')
display_parser.add_argument('-fc', '--freqcheck', action=store_truth(),
metavar='t/f',
help='''only send triggers for board color
flips at the start, middle and end
of the run''')
display_parser.add_argument('-et', '--eyetrack', action=store_truth(),
metavar='t/f',
help='''use eyetracking to ensure that subject
fixates on the cross in the center''')
display_parser.add_argument('-eu', '--etuser', action=store_truth(),
metavar='t/f',
help='''allow user to select eyetracking video
source from a dialog''')
display_parser.add_argument('-ev', '--etvideo', metavar='path',
help='''path (with no spaces) to eyetracking
video file to be used as the source''')
display_parser.add_argument('-ta', '--tryagain', metavar='I', type=int,
help='''append groups during which subject
failed to fixate up to I times to the
list of groups to be displayed
(default: disabled, I=0)''')
display_parser.add_argument('-tb', '--trybreak', metavar='J', type=int,
help='''used with --tryagain, append a wait
screen to the list of groups to be
displayed after every J groups have
been appended to the list (default:
J=total number of groups)''')
display_parser.add_argument('-nl', '--nolog', action=store_truth(),
metavar='t/f',
help='''do not write a log file''')
display_parser.add_argument('order', nargs='*', metavar='id', type=int,
help='''order in which groups should be
displayed (default: random order
from list of orders if specified
in project, ascending otherwise)''')
def help_display(self):
self.__class__.display_parser.print_help()
def do_display(self, line):
"""Displays the stimulus in a window or in fullscreen"""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.display_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
if len(args.order) > 0:
for i in set(args.order):
if i >= len(self.cur_proj.groups) or i < -1:
print 'error: group', i, 'does not exist'
return
if args.eyetrack and eyetracking.available:
if not eyetracking.is_calibrated():
try:
self.do_calibrate('',query=True)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
return
if args.save:
self.cur_proj.set_display_flags(repeats=args.repeats,
waitless=args.waitless,
fullscreen=args.fullscreen,
priority=args.priority,
logtime=args.logtime,
logdur=args.logdur,
trigser=args.trigser,
trigpar=args.trigpar,
fpst=args.fpst,
freqcheck=args.freqcheck,
phototest=args.phototest,
photoburst=args.photoburst,
eyetrack=args.eyetrack,
etuser=args.etuser,
etvideo=args.etvideo,
tryagain=args.tryagain,
trybreak=args.trybreak,
nolog=args.nolog)
print "display flags saved to project"
else:
print "displaying...",
try:
self.cur_proj.display(name=args.name,
repeats=args.repeats,
waitless=args.waitless,
fullscreen=args.fullscreen,
priority=args.priority,
logtime=args.logtime,
logdur=args.logdur,
trigser=args.trigser,
trigpar=args.trigpar,
fpst=args.fpst,
freqcheck=args.freqcheck,
phototest=args.phototest,
photoburst=args.photoburst,
eyetrack=args.eyetrack,
etuser=args.etuser,
etvideo=args.etvideo,
tryagain=args.tryagain,
trybreak=args.trybreak,
nolog=args.nolog,
order=args.order)
except (IOError, NotImplementedError,
eyetracking.EyetrackingError):
print ''
print "error:", str(sys.exc_value)
- if args.priority != None:
- try:
- priority.set('normal')
- except:
- pass
+ try:
+ priority.set('normal')
+ except:
+ pass
return
print "done"
export_parser = CmdParser(add_help=False, prog='export',
description='''Exports stimulus as an image
sequence (in a folder) to the
specified directory.''')
export_parser.add_argument('-n','--nofolder',
dest='folder', action='store_false',
help='''force images not to exported in
a containing folder''')
export_parser.add_argument('-r', '--repeats', metavar='N', type=int,
help='''repeatedly export specified display
groups N number of times''')
export_parser.add_argument('duration', nargs='?',
type=to_decimal, default='Infinity',
help='''number of seconds of the stimulus
that should be exported (default:
as long as the entire stimulus)''')
export_parser.add_argument('dir', nargs='?', default=os.getcwd(),
help='''destination directory for export
(default: current working directory)''')
export_parser.add_argument('order', nargs='*', metavar='id', type=int,
help='''order in which groups should be
displayed (default: random order
from list of orders if specified
in project, ascending otherwise)''')
def help_export(self):
self.__class__.export_parser.print_help()
def do_export(self, line):
"""Exports stimulus as an image sequence to the specified directory."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.export_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.export_parser.print_usage()
return
if len(args.order) > 0:
for i in set(args.order):
if i >= len(self.cur_proj.groups) or i < -1:
print 'error: group', i, 'does not exist'
return
try:
self.cur_proj.export(repeats=args.repeats,
order=args.order,
expo_dir=args.dir,
expo_dur=args.duration,
folder=args.folder)
except IOError:
print "error:", str(sys.exc_value)
return
except core.FrameOverflowError:
print "warning:", str(sys.exc_value)
print "Are you sure you want to continue?"
while True:
try:
if self.__class__.yn_parse(raw_input()):
self.cur_proj.export(repeats=args.repeats,
order=args.order,
expo_dir=args.dir,
expo_dur=args.duration,
folder=args.folder,
force=True)
break
else:
return
except TypeError:
print str(sys.exc_value)
except EOFError:
return
print "Export done."
def do_calibrate(self, line, query=False):
"""Calibrate subject for eyetracking, or load a calibration file."""
if not eyetracking.available:
print "error: eyetracking functionality not available"
return
if query:
print "path to calibration file (leave empty for GUI tool):"
try:
path = raw_input().strip().strip('"\'')
except EOFError:
msg = "calibration cancelled"
raise eyetracking.EyetrackingError(msg)
else:
path = line.strip().strip('"\'')
if len(path) == 0:
path = None
if not eyetracking.is_source_ready():
# Select default source if none has been selected
eyetracking.select_source()
try:
eyetracking.calibrate(path)
except eyetracking.EyetrackingError:
if query:
raise
else:
print "error:", str(sys.exc_value)
return
if path!= None and len(path) > 0:
print "calibration file successfully loaded"
etsetup_parser = CmdParser(add_help=False, prog='etsetup',
description='''Set various eyetracking
parameters.''')
etsetup_parser.add_argument('-fp', '--fixperiod', type=int, metavar='MS',
help='''time in milliseconds subject
has to stare at the same spot
for fixation to be detected''')
etsetup_parser.add_argument('-fr', '--fixrange', type=float, metavar='MM',
help='''distance in mm beyond which the
eye position cannot change for
a fixation to be detected''')
etsetup_parser.add_argument('-s', '--size', metavar='WIDTH,HEIGHT',
action=store_list(2, ',', float),
help='physical screen dimensions in mm')
etsetup_parser.add_argument('-vd', '--viewdist', type=int, metavar='MM',
help='''viewing distance between subject's
eyes and the screen''')
def help_etsetup(self):
self.__class__.etsetup_parser.print_help()
def do_etsetup(self, line):
try:
args = self.__class__.etsetup_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.etsetup_parser.print_usage()
return
try:
eyetracking.setup(viewing_distance=args.viewdist,
screen_dims=args.size,
fixation_period=args.fixperiod,
fixation_range=args.fixrange)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
def do_pwd(self, line):
"""Prints the current working directory."""
print os.getcwd()
def do_cd(self, line):
"""Change working directory to specified path."""
path = line.strip().strip('"\'')
if not os.path.isdir(path):
print "error: specified path is not a directory"
return
os.chdir(path)
def do_quit(self, line):
"""Quits the program."""
if self.save_check():
return
return True
def help_EOF(self):
print "Typing {0} issues this command, which quits the program."\
.format(CMD_EOF_STRING)
def do_EOF(self, line):
"""Typing Ctrl-D issues this command, which quits the program."""
print '\r'
if self.save_check():
return
return True
def help_help(self):
print 'Prints a list of commands.'
print "Type 'help <topic>' for more details on each command."
def default(self, line):
command = line.split()[0]
print \
"'{0}' is not a checkergen command.".format(command),\
"Type 'help' for a list of commands"
diff --git a/src/core.py b/src/core.py
index 458b04e..177e3cb 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,1267 +1,1274 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import copy
import random
import itertools
from datetime import datetime
from xml.dom import minidom
import pyglet
import graphics
import priority
import trigger
import eyetracking
from utils import *
# Use OrderedDict substitute if we don't have Python 2.7
if sys.version_info < (2, 7):
from odict import OrderedDict
else:
from collections import OrderedDict
CKG_FMT = 'ckg'
LOG_FMT = 'log'
MAX_EXPORT_FRAMES = 1000
EXPORT_DIR_SUFFIX = '-anim'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
INT_HALF_PERIODS = True
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = OrderedDict([('name', 'untitled'),
('fps', 60),
('res', (800, 600)),
('bg', (127, 127, 127)),
('pre', 0),
('post', 0),
('cross_cols', ((0, 0, 0), (255, 0, 0))),
('cross_times', ('Infinity', 1)),
('orders', []),
('disp_ops', None)])
DEFAULTS['disp_ops'] = OrderedDict([('repeats', 1),
('waitless', False),
('fullscreen', False),
('priority', None),
('logtime', False),
('logdur', False),
('trigser', False),
('trigpar', False),
('fpst', 0),
('freqcheck', False),
('phototest', False),
('photoburst', False),
('eyetrack', False),
('etuser', False),
('etvideo', None),
('tryagain', 0),
('trybreak', None),
('nolog', False),
('export', False),
('expo_dir', None),
('expo_dur', None),
('folder', True)])
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def set_display_flags(self, **keywords):
"""Set default display flags for the project.
Same arguments as 'display', excluding 'name' and 'order'.
"""
for kw in keywords.keys():
if kw in self.disp_ops.keys() and keywords[kw] != None:
self.disp_ops[kw] = keywords[kw]
self._dirty = True
def set_group_orders(self, orders):
for order in orders:
for gid in order:
if gid < -1 or gid >= len(self.groups):
msg = 'invalid group id (out of range)'
raise ValueError(msg)
self.orders = orders
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
# Vars that are dicts
dicts_to_load = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_load = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
for d_name in dicts_to_load:
d = copy.deepcopy(self.__class__.DEFAULTS[d_name])
try:
d_el = [node for node in project.childNodes if
node.localName == d_name and
node.namespaceURI == XML_NAMESPACE][0]
for var in d.keys():
try:
d[var] = eval(xml_get(d_el, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}' in '{1}'".\
format(var, d_name)
print "using default value '{0}' instead...".\
format(d[var])
except IndexError:
print "warning: missing attribute set '{0}'".format(d_name)
print "using default values instead..."
setattr(self, d_name, d)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
# Vars that are dicts
dicts_to_save = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_save = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for d_name in dicts_to_save:
d_el = doc.createElement(d_name)
project.appendChild(d_el)
d = getattr(self, d_name)
for k, v in d.iteritems():
xml_set(doc, d_el, k, repr(v))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, **keywords):
"""Displays the stimulus on the screen.
name -- name that logfile will be saved with
repeats -- number of times specified order of display groups should
be repeated
waitless -- if true, no waitscreens will appear at the start of each
repeat
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
priority -- priority level to which process should be raised
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
trigser -- send triggers through serial port when each group is shown
trigpar -- send triggers through parallel port when each group is shown
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
freqcheck -- send fpst only at the start, the middle, and the end
for sanity checking of display and trigger fps
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- append a wait screen to the group queue every time
after this many groups have been appended to the queue
order -- order in which groups (specified by id) will be displayed
"""
# Create RunState
disp_ops = copy.deepcopy(self.disp_ops)
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'name' in keywords.keys() and keywords['name'] != None:
name = keywords['name']
else:
timestr = datetime.today().strftime('_%Y-%m-%d_%H-%M-%S')
name = self.name + timestr
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
waitscreen = CkgWaitScreen()
# Set order id to be sent if necessary
if order in self.orders:
runstate.events['ord_id'] = self.orders.index(order)
# Count through pre
for count in range(self.pre * self.fps):
if runstate.terminate:
break
runstate.update()
# Loop through repeats
repeats = runstate.disp_ops['repeats']
ord_len = len(runstate.order)
for i in range(repeats):
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
# Loop through display groups
runstate.events['blk_on'] = True
for n, gid in enumerate(runstate.order):
# Set flag for freqcheck
if runstate.disp_ops['freqcheck']:
if ((i == 0 and n == 0) or
(i == repeats-1 and n == ord_len-1) or
(i == repeats//2 and n == ord_len//2)):
runstate.fc_send = True
else:
runstate.fc_send = False
if gid == -1:
waitscreen.reset()
waitscreen.display(runstate)
else:
self.groups[gid].display(runstate)
- # Append failed groups
+ # Append group id and fail state
+ runstate.gids.append(gid)
+ if runstate.disp_ops['eyetrack']:
+ runstate.fails.append(runstate.true_fail)
+ # Append groups to be added
if runstate.disp_ops['eyetrack'] and runstate.true_fail:
if len(runstate.add_gids) < runstate.disp_ops['tryagain']:
runstate.add_gids.append(gid)
- else:
- runstate.fail_gids.append(gid)
runstate.events['blk_off'] = True
# Stop freqcheck before added groups
if runstate.disp_ops['freqcheck']:
runstate.fc_send = False
# Loop through added groups
if runstate.disp_ops['eyetrack']:
for blk in grouper(runstate.add_gids,
runstate.disp_ops['trybreak']):
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
runstate.events['blk_on'] = True
# Loop through display groups
for gid in blk:
if gid != None:
self.groups[gid].display(runstate)
+ # Append group id and fail state
+ runstate.gids.append(gid)
+ if runstate.disp_ops['eyetrack']:
+ runstate.fails.append(runstate.true_fail)
runstate.events['blk_off'] = True
# Count through post
for count in range(self.post * self.fps):
if runstate.terminate:
break
runstate.update()
# Stop and output log
runstate.stop()
if not runstate.disp_ops['nolog']:
runstate.log()
def export(self, **keywords):
"""Exports the stimulus as a series of images, one image per frame.
repeats -- number of times specified order of display groups should
be repeated
order -- order in which groups (specified by id) will be displayed
expo_dir -- directory to which images will be exported
expo_dur -- time in seconds to which export will be limited
folder -- if true, images will be contained in a separate folder
within export directory
force -- force export to go through even if a large number
of frames are to be exported
"""
# Create RunState
disp_ops = copy.deepcopy(self.__class__.DEFAULTS['disp_ops'])
disp_ops['export'] = True
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=self.name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
# Warn user if a lot of frames will be exported
if 'force' not in keywords.keys():
keywords['force'] = False
groups_dur = sum([self.groups[i].duration()
for i in order]) * disp_ops['repeats']
total_frames = (self.pre + groups_dur + self.post) * self.fps
frames = min(total_frames, disp_ops['expo_dur'] * self.fps)
if frames > MAX_EXPORT_FRAMES and not keywords['force']:
msg = 'large number ({0}) of frames to be exported'.\
format(int(frames))
raise FrameOverflowError(msg)
runstate.frames = frames
# Count through pre
for count in range(self.pre * self.fps):
if runstate.terminate:
break
runstate.update()
# Loop through repeats
repeats = runstate.disp_ops['repeats']
for i in range(repeats):
# Loop through display groups
for n, gid in enumerate(runstate.order):
if gid != -1:
self.groups[gid].display(runstate)
# Count through post
for count in range(self.post * self.fps):
if runstate.terminate:
break
runstate.update()
# Stop runstate
runstate.stop()
class CkgRunState:
"""Contains information about the state of a checkergen project
when it is being displayed or exported."""
DEFAULTS = dict([('name', 'untitled'),
('res', None),
('fps', None),
('bg', None),
('cross_cols', None),
('cross_times', None),
('order', []),
('disp_ops', None),
('events', None),
+ ('gids', []),
+ ('fails', []),
('add_gids', []),
- ('fail_gids', []),
('timestamps', []),
('durstamps', []),
('trigstamps', [])])
DEFAULTS['events'] = dict([('ord_id', None),
('blk_on', False),
('blk_off', False),
('track_on', False),
('track_off', False),
('fix_on', False),
('fix_off', False),
('grp_on', False),
('grp_off', False),
('sids', set())])
def __init__(self, **keywords):
"""Creates the RunState."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
def start(self):
"""Initialize all subsystems and start the run."""
if self.disp_ops == None:
msg = "RunState lacks display options"
raise ValueError(msg)
if min(self.res, self.fps, self.bg,
self.cross_cols, self.cross_times) == None:
msg = "RunState intialized with insufficent project information"
raise ValueError(msg)
self._count = 0
self._old_code = 0
self.terminate = False
# Flag used by freqcheck
self.fc_send = False
# Create fixation crosses
self.fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if self.disp_ops['phototest']:
self.test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Initialize export
if self.disp_ops['export']:
if not os.path.isdir(self.disp_ops['expo_dir']):
msg = 'export path is not a directory'
raise IOError(msg)
if self.disp_ops['folder']:
self.save_dir = os.path.join(self.disp_ops['expo_dir'],
self.name + EXPORT_DIR_SUFFIX)
else:
self.save_dir = self.disp_ops['expo_dir']
if not os.path.isdir(self.save_dir):
os.mkdir(self.save_dir)
# Initialize ports
if self.disp_ops['trigser']:
if not trigger.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trigpar']:
if not trigger.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
trigger.init(self.disp_ops['trigser'], self.disp_ops['trigpar'])
# Initialize eyetracking
if self.disp_ops['eyetrack']:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trybreak'] == None:
self.disp_ops['trybreak'] = len(self.order)
self.fixated = False
self.old_fixated = False
self.tracked = False
self.old_tracked = False
self.fix_fail = False
self.true_fail = False
eyetracking.select_source(self.disp_ops['etuser'],
self.disp_ops['etvideo'])
eyetracking.start()
# Create window if not exporting
self.scaling = False
if not self.disp_ops['export']:
# Stretch to fit screen only if project res does not
# equal screen res
if self.disp_ops['fullscreen']:
self.window = pyglet.window.Window(fullscreen=True,
visible=False)
if (self.window.width, self.window.height) != self.res:
self.scaling = True
else:
self.window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
self.keystates = pyglet.window.key.KeyStateHandler()
self.window.push_handlers(self.keystates)
# Clear window and make visible
self.window.switch_to()
graphics.set_clear_color(self.bg)
self.window.clear()
self.window.set_visible()
# Create framebuffer object for drawing unscaled or exported scene
if self.scaling or self.disp_ops['export']:
self.canvas = pyglet.image.Texture.create(*self.res)
self.fbo = graphics.Framebuffer(self.canvas)
self.fbo.start_render()
graphics.set_clear_color(self.bg)
self.fbo.clear()
# Set process priority
if self.disp_ops['priority'] != None:
- if not priority.available[sys.platform]:
- msg = "setting priority not available on {0}".\
- format(sys.platform)
- raise NotImplementedError(msg)
- else:
- try:
- priority.set(self.disp_ops['priority'])
- except ValueError:
- priority.set(int(self.disp_ops['priority']))
+ try:
+ priority.set(self.disp_ops['priority'])
+ except ValueError:
+ priority.set(int(self.disp_ops['priority']))
+ except:
+ pass
# Start timers
if self.disp_ops['logtime']:
self.timer = Timer()
self.timer.start()
if self.disp_ops['logdur']:
self.dur = Timer()
self.dur.start()
def update(self):
"""Update the RunState."""
# Check for tracking and fixation
if self.disp_ops['eyetrack']:
self.old_tracked = self.tracked
self.tracked = eyetracking.is_tracked(self.fps)
self.old_fixated = self.fixated
self.fixated = eyetracking.is_fixated(self.fps)
if self.fixated:
# Draw normal cross color if fixating
self.fix_crosses[0].draw()
else:
# Draw alternative cross color if not fixating
self.fix_crosses[1].draw()
# Update eyetracking events
if self.tracked != self.old_tracked:
if self.tracked:
self.events['track_on'] = True
else:
self.events['track_off'] = True
if self.fixated != self.old_fixated:
if self.fixated:
self.events['fix_on'] = True
else:
self.events['fix_off'] = True
# Check for failure of trial
if self.tracked and not self.fixated:
self.fix_fail = True
else:
# Change cross color based on time
if (self._count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
self.fix_crosses[0].draw()
else:
self.fix_crosses[1].draw()
if self.disp_ops['export']:
# Save current frame to file
savepath = os.path.join(
self.save_dir, '{0}{2}.{1}'.\
format(self.name, 'png',
repr(self._count).zfill(numdigits(self.frames-1))))
self.canvas.save(savepath)
else:
# Blit canvas to screen if necessary
if self.scaling:
self.fbo.end_render()
self.canvas.blit(0, 0)
self.window.switch_to()
self.window.dispatch_events()
self.window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to lists
if self.disp_ops['logtime']:
self.timestamps.append(self.timer.elapsed())
elif self.disp_ops['logdur']:
self.timestamps.append('')
if self.disp_ops['logdur']:
self.durstamps.append(self.dur.restart())
elif self.disp_ops['logtime']:
self.durstamps.append('')
# Send trigger ASAP after flip
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
if self.encode_events() != self._old_code:
trigger.send(self.disp_ops['trigser'],
self.disp_ops['trigpar'],
self.encode_events())
self._old_code = self.encode_events
# Log when triggers are sent
if self.disp_ops['logtime'] and self.encode_events() > 0:
self.trigstamps.append(self.encode_events())
else:
self.trigstamps.append('')
# Clear canvas, events, prepare for next frame
if self.disp_ops['export']:
self.fbo.clear()
else:
if self.scaling:
self.fbo.start_render()
self.fbo.clear()
else:
self.window.clear()
if self.window.has_exit:
self.terminate = True
self.events = copy.deepcopy(self.__class__.DEFAULTS['events'])
self._count += 1
# Terminate export if the time has come
if self.disp_ops['export']:
if self._count >= self.frames:
self.terminate = True
def stop(self):
"""Clean up RunState."""
if self.disp_ops['eyetrack']:
eyetracking.stop()
if self.scaling or self.disp_ops['export']:
self.fbo.delete()
del self.canvas
if not self.disp_ops['export']:
self.window.close()
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
trigger.quit(self.disp_ops['trigser'], self.disp_ops['trigpar'])
- if self.disp_ops['priority'] != None:
+ try:
priority.set('normal')
+ except:
+ pass
def encode_events(self):
"""Hard code specific trigger values for events."""
code = 0
if self.events['ord_id'] != None:
code = self.events['ord_id'] + 1
elif self.events['blk_on']:
code = 128
elif self.events['blk_off']:
code = 127
else:
mult = 0
if self.events['fix_on']:
mult = 4
elif self.events['track_on']:
mult = 3
if self.events['track_off']:
mult = 1
elif self.events['fix_off']:
mult = 2
if self.events['grp_on']:
code = 100 + mult
elif self.events['grp_off']:
code = 90 + mult
elif len(self.events['sids']) > 0:
code = ((0 in self.events['sids'])*2**0 +
(1 in self.events['sids'])*2**1 +
(2 in self.events['sids'])*2**2 +
(3 in self.events['sids'])*2**3)
code = mult*16 + code
elif mult > 0:
code = 110 + mult
return code
def log(self, path=None):
"""Write a log file for the experimental run in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, LOG_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(LOG_FMT):
path = '{0}.{1}'.format(path, LOG_FMT)
with open(path, 'wb') as logfile:
writer = csv.writer(logfile, dialect='excel-tab')
writer.writerow(['checkergen log file'])
writer.writerow(['display options:'])
writer.writerow(self.disp_ops.keys())
writer.writerow(self.disp_ops.values())
writer.writerow(['order:'] + self.order)
+ writer.writerow(['groups', 'failure'])
+ if not self.disp_ops['eyetrack']:
+ self.fails = ['NA'] * len(self.gids)
+ for i in zip(self.gids, self.fails):
+ writer.writerow(list(i))
if self.disp_ops['eyetrack']:
writer.writerow(['groups added'])
for blk in grouper(self.add_gids,
self.disp_ops['trybreak'], ''):
writer.writerow(blk)
- writer.writerow(['groups failed'])
- for blk in grouper(self.fail_gids,
- self.disp_ops['trybreak'], ''):
- writer.writerow(blk)
if self.disp_ops['logtime'] or self.disp_ops['logdur']:
stamps = [self.timestamps, self.durstamps, self.trigstamps]
writer.writerow(['timestamps', 'durations', 'triggers'])
for stamp in zip(*stamps):
writer.writerow(list(stamp))
class CkgDisplayGroup:
DEFAULTS = OrderedDict([('pre', 0), ('disp', 'Infinity'), ('post', 0)])
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets counts and all contained shapes."""
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, runstate):
"""Draws all contained shapes during the appropriate interval."""
for shape in self.shapes:
shape.draw(photoburst=runstate.disp_ops['photoburst'])
def update(self, runstate):
"""Updates contained shapes, sets event triggers."""
# Set events to be sent
if runstate.disp_ops['fpst'] > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= runstate.disp_ops['fpst']:
if not runstate.disp_ops['freqcheck'] or runstate.fc_send:
runstate.events['sids'].add(n)
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(runstate.fps)
def display(self, runstate):
"""Display the group in the context described by supplied runstate."""
self.reset()
for count in range(self.pre * runstate.fps):
if runstate.terminate:
break
runstate.update()
runstate.events['grp_on'] = True
if runstate.disp_ops['eyetrack']:
runstate.fix_fail = False
runstate.true_fail = False
for count in range(self.disp * runstate.fps):
if runstate.terminate:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
runstate.events['grp_off'] = True
if runstate.disp_ops['eyetrack']:
if runstate.fix_fail:
runstate.true_fail = True
for count in range(self.post * runstate.fps):
if runstate.terminate:
break
runstate.update()
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.steps_done = 0
def draw(self, runstate):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, runstate):
"""Checks for keypress, sends trigger upon end."""
if max([runstate.keystates[key] for
key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
def display(self, runstate):
"""Displays waitscreen in context described by supplied runstate."""
while self.steps_done < self.num_steps:
if runstate.terminate:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = OrderedDict([('dims', (5, 5)),
('init_unit', (30, 30)),
('end_unit', (50, 50)),
('position', (0, 0)),
('anchor', 'bottomleft'),
('cols', ((0, 0, 0), (255, 255, 255))),
('freq', 1),
('phase', 0)])
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
if INT_HALF_PERIODS:
frames_per_half_period = round(fps / (self.freq * 2))
degs_per_frame = 180 / to_decimal(frames_per_half_period)
else:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
anchor=self.anchor)
cur_unit_rect.col = self.cols[(i + j) % 2]
cur_unit_rect.add_to_batch(self._batches[0])
cur_unit_rect.col = self.cols[(i + j + 1) % 2]
cur_unit_rect.add_to_batch(self._batches[1])
# Increase x values
cur_unit_pos[0] += \
graphics.locations[self.anchor][0] * cur_unit[0]
cur_unit[0] += unit_grad[0]
# Reset x values
cur_unit_pos[0] = init_pos[0]
cur_unit[0] = init_unit[0]
# Increase y values
cur_unit_pos[1] += \
graphics.locations[self.anchor][1] * cur_unit[1]
cur_unit[1] += unit_grad[1]
self._computed = True
def draw(self, photoburst=False, always_compute=False):
"""Draws appropriate batch depending on current phase.
photoburst -- draw first color for only one frame for testing purposes
always_compute -- recompute what the checkerboard should look like
every frame
"""
if not self._computed or always_compute:
self.compute()
self._cur_phase %= 360
n = int(self._cur_phase // 180)
if photoburst and n == 0 and not self.flipped:
n = 1
self._batches[n].draw()
def lazydraw(self):
"""Only draws on color reversal."""
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if (cur_n != prev_n) or self._first_draw:
self.draw()
if self._first_draw:
self._first_draw = False
|
ztangent/checkergen
|
22b2888c0c052f9ebdab6d830a52ee3f55308d3c
|
Send triggers on code change, not just when code is more than 0.
|
diff --git a/src/core.py b/src/core.py
index 174cfdb..458b04e 100755
--- a/src/core.py
+++ b/src/core.py
@@ -101,1165 +101,1167 @@ class CkgProj:
('trigser', False),
('trigpar', False),
('fpst', 0),
('freqcheck', False),
('phototest', False),
('photoburst', False),
('eyetrack', False),
('etuser', False),
('etvideo', None),
('tryagain', 0),
('trybreak', None),
('nolog', False),
('export', False),
('expo_dir', None),
('expo_dur', None),
('folder', True)])
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def set_display_flags(self, **keywords):
"""Set default display flags for the project.
Same arguments as 'display', excluding 'name' and 'order'.
"""
for kw in keywords.keys():
if kw in self.disp_ops.keys() and keywords[kw] != None:
self.disp_ops[kw] = keywords[kw]
self._dirty = True
def set_group_orders(self, orders):
for order in orders:
for gid in order:
if gid < -1 or gid >= len(self.groups):
msg = 'invalid group id (out of range)'
raise ValueError(msg)
self.orders = orders
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
# Vars that are dicts
dicts_to_load = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_load = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
for d_name in dicts_to_load:
d = copy.deepcopy(self.__class__.DEFAULTS[d_name])
try:
d_el = [node for node in project.childNodes if
node.localName == d_name and
node.namespaceURI == XML_NAMESPACE][0]
for var in d.keys():
try:
d[var] = eval(xml_get(d_el, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}' in '{1}'".\
format(var, d_name)
print "using default value '{0}' instead...".\
format(d[var])
except IndexError:
print "warning: missing attribute set '{0}'".format(d_name)
print "using default values instead..."
setattr(self, d_name, d)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
# Vars that are dicts
dicts_to_save = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_save = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for d_name in dicts_to_save:
d_el = doc.createElement(d_name)
project.appendChild(d_el)
d = getattr(self, d_name)
for k, v in d.iteritems():
xml_set(doc, d_el, k, repr(v))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, **keywords):
"""Displays the stimulus on the screen.
name -- name that logfile will be saved with
repeats -- number of times specified order of display groups should
be repeated
waitless -- if true, no waitscreens will appear at the start of each
repeat
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
priority -- priority level to which process should be raised
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
trigser -- send triggers through serial port when each group is shown
trigpar -- send triggers through parallel port when each group is shown
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
freqcheck -- send fpst only at the start, the middle, and the end
for sanity checking of display and trigger fps
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- append a wait screen to the group queue every time
after this many groups have been appended to the queue
order -- order in which groups (specified by id) will be displayed
"""
# Create RunState
disp_ops = copy.deepcopy(self.disp_ops)
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'name' in keywords.keys() and keywords['name'] != None:
name = keywords['name']
else:
timestr = datetime.today().strftime('_%Y-%m-%d_%H-%M-%S')
name = self.name + timestr
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
waitscreen = CkgWaitScreen()
# Set order id to be sent if necessary
if order in self.orders:
runstate.events['ord_id'] = self.orders.index(order)
# Count through pre
for count in range(self.pre * self.fps):
if runstate.terminate:
break
runstate.update()
# Loop through repeats
repeats = runstate.disp_ops['repeats']
ord_len = len(runstate.order)
for i in range(repeats):
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
# Loop through display groups
runstate.events['blk_on'] = True
for n, gid in enumerate(runstate.order):
# Set flag for freqcheck
if runstate.disp_ops['freqcheck']:
if ((i == 0 and n == 0) or
(i == repeats-1 and n == ord_len-1) or
(i == repeats//2 and n == ord_len//2)):
runstate.fc_send = True
else:
runstate.fc_send = False
if gid == -1:
waitscreen.reset()
waitscreen.display(runstate)
else:
self.groups[gid].display(runstate)
# Append failed groups
if runstate.disp_ops['eyetrack'] and runstate.true_fail:
if len(runstate.add_gids) < runstate.disp_ops['tryagain']:
runstate.add_gids.append(gid)
else:
runstate.fail_gids.append(gid)
runstate.events['blk_off'] = True
# Stop freqcheck before added groups
if runstate.disp_ops['freqcheck']:
runstate.fc_send = False
# Loop through added groups
if runstate.disp_ops['eyetrack']:
for blk in grouper(runstate.add_gids,
runstate.disp_ops['trybreak']):
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
runstate.events['blk_on'] = True
# Loop through display groups
for gid in blk:
if gid != None:
self.groups[gid].display(runstate)
runstate.events['blk_off'] = True
# Count through post
for count in range(self.post * self.fps):
if runstate.terminate:
break
runstate.update()
# Stop and output log
runstate.stop()
if not runstate.disp_ops['nolog']:
runstate.log()
def export(self, **keywords):
"""Exports the stimulus as a series of images, one image per frame.
repeats -- number of times specified order of display groups should
be repeated
order -- order in which groups (specified by id) will be displayed
expo_dir -- directory to which images will be exported
expo_dur -- time in seconds to which export will be limited
folder -- if true, images will be contained in a separate folder
within export directory
force -- force export to go through even if a large number
of frames are to be exported
"""
# Create RunState
disp_ops = copy.deepcopy(self.__class__.DEFAULTS['disp_ops'])
disp_ops['export'] = True
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=self.name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
# Warn user if a lot of frames will be exported
if 'force' not in keywords.keys():
keywords['force'] = False
groups_dur = sum([self.groups[i].duration()
for i in order]) * disp_ops['repeats']
total_frames = (self.pre + groups_dur + self.post) * self.fps
frames = min(total_frames, disp_ops['expo_dur'] * self.fps)
if frames > MAX_EXPORT_FRAMES and not keywords['force']:
msg = 'large number ({0}) of frames to be exported'.\
format(int(frames))
raise FrameOverflowError(msg)
runstate.frames = frames
# Count through pre
for count in range(self.pre * self.fps):
if runstate.terminate:
break
runstate.update()
# Loop through repeats
repeats = runstate.disp_ops['repeats']
for i in range(repeats):
# Loop through display groups
for n, gid in enumerate(runstate.order):
if gid != -1:
self.groups[gid].display(runstate)
# Count through post
for count in range(self.post * self.fps):
if runstate.terminate:
break
runstate.update()
# Stop runstate
runstate.stop()
class CkgRunState:
"""Contains information about the state of a checkergen project
when it is being displayed or exported."""
DEFAULTS = dict([('name', 'untitled'),
('res', None),
('fps', None),
('bg', None),
('cross_cols', None),
('cross_times', None),
('order', []),
('disp_ops', None),
('events', None),
('add_gids', []),
('fail_gids', []),
('timestamps', []),
('durstamps', []),
('trigstamps', [])])
DEFAULTS['events'] = dict([('ord_id', None),
('blk_on', False),
('blk_off', False),
('track_on', False),
('track_off', False),
('fix_on', False),
('fix_off', False),
('grp_on', False),
('grp_off', False),
('sids', set())])
def __init__(self, **keywords):
"""Creates the RunState."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
def start(self):
"""Initialize all subsystems and start the run."""
if self.disp_ops == None:
msg = "RunState lacks display options"
raise ValueError(msg)
if min(self.res, self.fps, self.bg,
self.cross_cols, self.cross_times) == None:
msg = "RunState intialized with insufficent project information"
raise ValueError(msg)
self._count = 0
+ self._old_code = 0
self.terminate = False
# Flag used by freqcheck
self.fc_send = False
# Create fixation crosses
self.fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if self.disp_ops['phototest']:
self.test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Initialize export
if self.disp_ops['export']:
if not os.path.isdir(self.disp_ops['expo_dir']):
msg = 'export path is not a directory'
raise IOError(msg)
if self.disp_ops['folder']:
self.save_dir = os.path.join(self.disp_ops['expo_dir'],
self.name + EXPORT_DIR_SUFFIX)
else:
self.save_dir = self.disp_ops['expo_dir']
if not os.path.isdir(self.save_dir):
os.mkdir(self.save_dir)
# Initialize ports
if self.disp_ops['trigser']:
if not trigger.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trigpar']:
if not trigger.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
trigger.init(self.disp_ops['trigser'], self.disp_ops['trigpar'])
# Initialize eyetracking
if self.disp_ops['eyetrack']:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trybreak'] == None:
self.disp_ops['trybreak'] = len(self.order)
self.fixated = False
self.old_fixated = False
self.tracked = False
self.old_tracked = False
self.fix_fail = False
self.true_fail = False
eyetracking.select_source(self.disp_ops['etuser'],
self.disp_ops['etvideo'])
eyetracking.start()
# Create window if not exporting
self.scaling = False
if not self.disp_ops['export']:
# Stretch to fit screen only if project res does not
# equal screen res
if self.disp_ops['fullscreen']:
self.window = pyglet.window.Window(fullscreen=True,
visible=False)
if (self.window.width, self.window.height) != self.res:
self.scaling = True
else:
self.window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
self.keystates = pyglet.window.key.KeyStateHandler()
self.window.push_handlers(self.keystates)
# Clear window and make visible
self.window.switch_to()
graphics.set_clear_color(self.bg)
self.window.clear()
self.window.set_visible()
# Create framebuffer object for drawing unscaled or exported scene
if self.scaling or self.disp_ops['export']:
self.canvas = pyglet.image.Texture.create(*self.res)
self.fbo = graphics.Framebuffer(self.canvas)
self.fbo.start_render()
graphics.set_clear_color(self.bg)
self.fbo.clear()
# Set process priority
if self.disp_ops['priority'] != None:
if not priority.available[sys.platform]:
msg = "setting priority not available on {0}".\
format(sys.platform)
raise NotImplementedError(msg)
else:
try:
priority.set(self.disp_ops['priority'])
except ValueError:
priority.set(int(self.disp_ops['priority']))
# Start timers
if self.disp_ops['logtime']:
self.timer = Timer()
self.timer.start()
if self.disp_ops['logdur']:
self.dur = Timer()
self.dur.start()
def update(self):
"""Update the RunState."""
# Check for tracking and fixation
if self.disp_ops['eyetrack']:
self.old_tracked = self.tracked
self.tracked = eyetracking.is_tracked(self.fps)
self.old_fixated = self.fixated
self.fixated = eyetracking.is_fixated(self.fps)
if self.fixated:
# Draw normal cross color if fixating
self.fix_crosses[0].draw()
else:
# Draw alternative cross color if not fixating
self.fix_crosses[1].draw()
# Update eyetracking events
if self.tracked != self.old_tracked:
if self.tracked:
self.events['track_on'] = True
else:
self.events['track_off'] = True
if self.fixated != self.old_fixated:
if self.fixated:
self.events['fix_on'] = True
else:
self.events['fix_off'] = True
# Check for failure of trial
if self.tracked and not self.fixated:
self.fix_fail = True
else:
# Change cross color based on time
if (self._count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
self.fix_crosses[0].draw()
else:
self.fix_crosses[1].draw()
if self.disp_ops['export']:
# Save current frame to file
savepath = os.path.join(
self.save_dir, '{0}{2}.{1}'.\
format(self.name, 'png',
repr(self._count).zfill(numdigits(self.frames-1))))
self.canvas.save(savepath)
else:
# Blit canvas to screen if necessary
if self.scaling:
self.fbo.end_render()
self.canvas.blit(0, 0)
self.window.switch_to()
self.window.dispatch_events()
self.window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to lists
if self.disp_ops['logtime']:
self.timestamps.append(self.timer.elapsed())
elif self.disp_ops['logdur']:
self.timestamps.append('')
if self.disp_ops['logdur']:
self.durstamps.append(self.dur.restart())
elif self.disp_ops['logtime']:
self.durstamps.append('')
# Send trigger ASAP after flip
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
- if self.encode_events() > 0:
+ if self.encode_events() != self._old_code:
trigger.send(self.disp_ops['trigser'],
self.disp_ops['trigpar'],
self.encode_events())
+ self._old_code = self.encode_events
# Log when triggers are sent
if self.disp_ops['logtime'] and self.encode_events() > 0:
self.trigstamps.append(self.encode_events())
else:
self.trigstamps.append('')
# Clear canvas, events, prepare for next frame
if self.disp_ops['export']:
self.fbo.clear()
else:
if self.scaling:
self.fbo.start_render()
self.fbo.clear()
else:
self.window.clear()
if self.window.has_exit:
self.terminate = True
self.events = copy.deepcopy(self.__class__.DEFAULTS['events'])
self._count += 1
# Terminate export if the time has come
if self.disp_ops['export']:
if self._count >= self.frames:
self.terminate = True
def stop(self):
"""Clean up RunState."""
if self.disp_ops['eyetrack']:
eyetracking.stop()
if self.scaling or self.disp_ops['export']:
self.fbo.delete()
del self.canvas
if not self.disp_ops['export']:
self.window.close()
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
trigger.quit(self.disp_ops['trigser'], self.disp_ops['trigpar'])
if self.disp_ops['priority'] != None:
priority.set('normal')
def encode_events(self):
"""Hard code specific trigger values for events."""
code = 0
if self.events['ord_id'] != None:
code = self.events['ord_id'] + 1
elif self.events['blk_on']:
code = 128
elif self.events['blk_off']:
code = 127
else:
mult = 0
if self.events['fix_on']:
mult = 4
elif self.events['track_on']:
mult = 3
if self.events['track_off']:
mult = 1
elif self.events['fix_off']:
mult = 2
if self.events['grp_on']:
code = 100 + mult
elif self.events['grp_off']:
code = 90 + mult
elif len(self.events['sids']) > 0:
code = ((0 in self.events['sids'])*2**0 +
(1 in self.events['sids'])*2**1 +
(2 in self.events['sids'])*2**2 +
(3 in self.events['sids'])*2**3)
code = mult*16 + code
elif mult > 0:
code = 110 + mult
return code
def log(self, path=None):
"""Write a log file for the experimental run in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, LOG_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(LOG_FMT):
path = '{0}.{1}'.format(path, LOG_FMT)
with open(path, 'wb') as logfile:
writer = csv.writer(logfile, dialect='excel-tab')
writer.writerow(['checkergen log file'])
writer.writerow(['display options:'])
writer.writerow(self.disp_ops.keys())
writer.writerow(self.disp_ops.values())
writer.writerow(['order:'] + self.order)
if self.disp_ops['eyetrack']:
writer.writerow(['groups added'])
for blk in grouper(self.add_gids,
self.disp_ops['trybreak'], ''):
writer.writerow(blk)
writer.writerow(['groups failed'])
for blk in grouper(self.fail_gids,
self.disp_ops['trybreak'], ''):
writer.writerow(blk)
if self.disp_ops['logtime'] or self.disp_ops['logdur']:
stamps = [self.timestamps, self.durstamps, self.trigstamps]
writer.writerow(['timestamps', 'durations', 'triggers'])
for stamp in zip(*stamps):
writer.writerow(list(stamp))
class CkgDisplayGroup:
DEFAULTS = OrderedDict([('pre', 0), ('disp', 'Infinity'), ('post', 0)])
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets counts and all contained shapes."""
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, runstate):
"""Draws all contained shapes during the appropriate interval."""
for shape in self.shapes:
shape.draw(photoburst=runstate.disp_ops['photoburst'])
def update(self, runstate):
"""Updates contained shapes, sets event triggers."""
# Set events to be sent
if runstate.disp_ops['fpst'] > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= runstate.disp_ops['fpst']:
if not runstate.disp_ops['freqcheck'] or runstate.fc_send:
runstate.events['sids'].add(n)
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(runstate.fps)
def display(self, runstate):
"""Display the group in the context described by supplied runstate."""
self.reset()
for count in range(self.pre * runstate.fps):
if runstate.terminate:
break
runstate.update()
runstate.events['grp_on'] = True
if runstate.disp_ops['eyetrack']:
runstate.fix_fail = False
runstate.true_fail = False
for count in range(self.disp * runstate.fps):
if runstate.terminate:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
runstate.events['grp_off'] = True
if runstate.disp_ops['eyetrack']:
if runstate.fix_fail:
runstate.true_fail = True
for count in range(self.post * runstate.fps):
if runstate.terminate:
break
runstate.update()
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.steps_done = 0
def draw(self, runstate):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, runstate):
"""Checks for keypress, sends trigger upon end."""
if max([runstate.keystates[key] for
key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
def display(self, runstate):
"""Displays waitscreen in context described by supplied runstate."""
while self.steps_done < self.num_steps:
if runstate.terminate:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = OrderedDict([('dims', (5, 5)),
('init_unit', (30, 30)),
('end_unit', (50, 50)),
('position', (0, 0)),
('anchor', 'bottomleft'),
('cols', ((0, 0, 0), (255, 255, 255))),
('freq', 1),
('phase', 0)])
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
if INT_HALF_PERIODS:
frames_per_half_period = round(fps / (self.freq * 2))
degs_per_frame = 180 / to_decimal(frames_per_half_period)
else:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
anchor=self.anchor)
cur_unit_rect.col = self.cols[(i + j) % 2]
cur_unit_rect.add_to_batch(self._batches[0])
cur_unit_rect.col = self.cols[(i + j + 1) % 2]
cur_unit_rect.add_to_batch(self._batches[1])
# Increase x values
cur_unit_pos[0] += \
graphics.locations[self.anchor][0] * cur_unit[0]
cur_unit[0] += unit_grad[0]
# Reset x values
cur_unit_pos[0] = init_pos[0]
cur_unit[0] = init_unit[0]
# Increase y values
cur_unit_pos[1] += \
graphics.locations[self.anchor][1] * cur_unit[1]
cur_unit[1] += unit_grad[1]
self._computed = True
def draw(self, photoburst=False, always_compute=False):
"""Draws appropriate batch depending on current phase.
photoburst -- draw first color for only one frame for testing purposes
always_compute -- recompute what the checkerboard should look like
every frame
"""
if not self._computed or always_compute:
self.compute()
self._cur_phase %= 360
n = int(self._cur_phase // 180)
if photoburst and n == 0 and not self.flipped:
n = 1
self._batches[n].draw()
def lazydraw(self):
"""Only draws on color reversal."""
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if (cur_n != prev_n) or self._first_draw:
self.draw()
if self._first_draw:
self._first_draw = False
|
ztangent/checkergen
|
c4ed8ea5128d2cb60d9c03c60cb84a43aaa25b5f
|
Reimplemented export in the new style.
|
diff --git a/example.ckg b/example.ckg
index d1a89a7..6faf27e 100644
--- a/example.ckg
+++ b/example.ckg
@@ -1,76 +1,80 @@
<?xml version="1.0" ?>
<project xmlns="http://github.com/ZOMGxuan/checkergen">
<fps>Decimal('60')</fps>
<res>(800, 600)</res>
<bg>(127, 127, 127)</bg>
<pre>Decimal('0')</pre>
<post>Decimal('0')</post>
<cross_cols>((0, 0, 0), (255, 0, 0))</cross_cols>
<cross_times>(Decimal('Infinity'), Decimal('1'))</cross_times>
<orders>[]</orders>
<disp_ops>
<repeats>1</repeats>
<waitless>False</waitless>
<fullscreen>False</fullscreen>
<priority>None</priority>
<logtime>False</logtime>
<logdur>False</logdur>
<trigser>False</trigser>
<trigpar>False</trigpar>
<fpst>0</fpst>
<freqcheck>False</freqcheck>
<phototest>False</phototest>
<photoburst>False</photoburst>
<eyetrack>False</eyetrack>
<etuser>False</etuser>
<etvideo>None</etvideo>
<tryagain>0</tryagain>
<trybreak>None</trybreak>
<nolog>False</nolog>
+ <export>False</export>
+ <expo_dir>None</expo_dir>
+ <expo_dur>None</expo_dur>
+ <folder>True</folder>
</disp_ops>
<group>
<pre>Decimal('2')</pre>
<disp>Decimal('10')</disp>
<post>Decimal('2')</post>
<shape type="board">
<dims>(5, 5)</dims>
<init_unit>(Decimal('40'), Decimal('40'))</init_unit>
<end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<position>(Decimal('420'), Decimal('320'))</position>
<anchor>'bottomleft'</anchor>
<cols>((0, 0, 0), (255, 255, 255))</cols>
<freq>Decimal('1')</freq>
<phase>Decimal('0')</phase>
</shape>
<shape type="board">
<dims>(5, 5)</dims>
<init_unit>(Decimal('40'), Decimal('40'))</init_unit>
<end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<position>(Decimal('380'), Decimal('320'))</position>
<anchor>'bottomright'</anchor>
<cols>((0, 0, 0), (255, 255, 255))</cols>
<freq>Decimal('2')</freq>
<phase>Decimal('90')</phase>
</shape>
<shape type="board">
<dims>(5, 5)</dims>
<init_unit>(Decimal('40'), Decimal('40'))</init_unit>
<end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<position>(Decimal('420'), Decimal('280'))</position>
<anchor>'topleft'</anchor>
<cols>((0, 0, 0), (255, 255, 255))</cols>
<freq>Decimal('3')</freq>
<phase>Decimal('180')</phase>
</shape>
<shape type="board">
<dims>(5, 5)</dims>
<init_unit>(Decimal('40'), Decimal('40'))</init_unit>
<end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<position>(Decimal('380'), Decimal('280'))</position>
<anchor>'topright'</anchor>
<cols>((0, 0, 0), (255, 255, 255))</cols>
<freq>Decimal('4')</freq>
<phase>Decimal('270')</phase>
</shape>
</group>
</project>
diff --git a/src/cli.py b/src/cli.py
index 6de43ce..0650859 100644
--- a/src/cli.py
+++ b/src/cli.py
@@ -483,688 +483,686 @@ class CkgCmd(cmd.Cmd):
mk_parser.add_argument('end_unit', action=store_list(2, ',', to_decimal),
help='width,height of final unit cell in pixels')
mk_parser.add_argument('position', action=store_list(2, ',', to_decimal),
help='x,y position of checkerboard in pixels')
mk_parser.add_argument('anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='anchor')
mk_parser.add_argument('cols', action=store_list(2, ',', to_color, [';']),
help='''color1,color2 of the checkerboard
(color format: R;G;B,
component range from 0-255)''')
mk_parser.add_argument('freq', type=to_decimal,
help='frequency of color reversal in Hz')
mk_parser.add_argument('phase', type=to_decimal, nargs='?', default='0',
help='initial phase in degrees')
def help_mk(self):
self.__class__.mk_parser.print_help()
def do_mk(self, line):
"""Makes a checkerboard with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
if self.cur_group == None:
print 'automatically adding display group...'
self.do_mkgrp('')
try:
args = self.__class__.mk_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mk_parser.print_usage()
return
shape_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_shape = core.CheckerBoard(**shape_dict)
new_id = self.cur_proj.add_shape_to_group(self.cur_group, new_shape)
print "checkerboard", new_id, "added"
ed_parser = CmdParser(add_help=False, prog='ed',
description='''Edits attributes of checkerboards
specified by ids.''')
ed_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='''ids of checkerboards in the current
group to be edited''')
ed_parser.add_argument('--dims', action=store_list(2, ',', to_decimal),
help='checkerboard dimensions in unit cells',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--init_unit',
action=store_list(2, ',', to_decimal),
help='initial unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--end_unit',
action=store_list(2, ',', to_decimal),
help='final unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--position',
action=store_list(2, ',', to_decimal),
help='position of checkerboard in pixels',
metavar='X,Y')
ed_parser.add_argument('--anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='LOCATION')
ed_parser.add_argument('--cols', metavar='COLOR1,COLOR2',
action=store_list(2, ',', to_color, [';']),
help='''checkerboard colors (color format:
R;G;B, component range
from 0-255)''')
ed_parser.add_argument('--freq', type=to_decimal,
help='frequency of color reversal in Hz')
ed_parser.add_argument('--phase', type=to_decimal,
help='initial phase in degrees')
def help_ed(self):
self.__class__.ed_parser.print_help()
def do_ed(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, please create one first'
return
try:
args = self.__class__.ed_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ed_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_group.shapes) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_shape_attr(self.cur_group, x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.ed_parser.print_usage()
rm_parser = CmdParser(add_help=False, prog='rm',
description='''Removes checkerboards specified
by ids.''')
rm_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''ids of checkerboards in the current group
to be removed''')
rm_parser.add_argument('-a', '--all', action='store_true',
help='''remove all checkerboards in the
current group''')
def help_rm(self):
self.__class__.rm_parser.print_help()
def do_rm(self, line):
"""Removes checkerboards specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, no boards to remove'
return
try:
args = self.__class__.rm_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rm_parser.print_usage()
return
rmlist = []
if args.all:
for shape in self.cur_group.shapes:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
print "all checkerboards removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_group.shapes) or x < 0:
print "checkerboard", x, "does not exist"
continue
rmlist.append(self.cur_group.shapes[x])
print "checkerboard", x, "removed"
for shape in rmlist:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
ls_parser = CmdParser(add_help=False, prog='ls',
description='''Lists project, display group and
checkerboard settings. If no group ids
are specified, all display groups
are listed.''')
ls_parser.add_argument('gids', nargs='*', metavar='gid', type=int,
help='''ids of the display groups to be listed''')
ls_group = ls_parser.add_mutually_exclusive_group()
ls_group.add_argument('-s', '--settings', action='store_true',
help='list only project settings')
ls_group.add_argument('-g', '--groups', action='store_true',
help='list only display groups')
ls_group.add_argument('-d', '--disp_ops', action='store_true',
help='list display options')
ls_group.add_argument('-o', '--orders', action='store_true',
help='list group orderings')
def help_ls(self):
self.__class__.ls_parser.print_help()
def do_ls(self, line):
"""Lists project, display group and checkerboard settings."""
def ls_str(s, seps=[',',';']):
"""Special space-saving output formatter."""
if type(s) in [tuple, list]:
if len(seps) > 1:
newseps = seps[1:]
else:
newseps = seps
return seps[0].join([ls_str(i, newseps) for i in s])
else:
return str(s)
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.ls_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ls_parser.print_usage()
return
# Remove duplicates and ascending sort
args.gids = sorted(set(args.gids))
if len(self.cur_proj.groups) == 0:
if len(args.gids) > 0:
print 'this project has no display groups that can be listed'
return
else:
for gid in args.gids[:]:
if gid >= len(self.cur_proj.groups) or gid < 0:
args.gids.remove(gid)
print 'display group', gid, 'does not exist'
if args.gids == []:
args.gids = range(len(self.cur_proj.groups))
else:
# If any (valid) groups are specified
# don't show project settings
args.groups = True
args.show_all = not max(args.settings, args.groups,
args.disp_ops, args.orders)
if args.show_all or args.settings:
print 'PROJECT SETTINGS'.center(70,'*')
print \
'name'.rjust(16),\
'fps'.rjust(7),\
'resolution'.rjust(14),\
'bg color'.rjust(18)
print \
ls_str(self.cur_proj.name).rjust(16),\
ls_str(self.cur_proj.fps).rjust(7),\
ls_str(self.cur_proj.res).rjust(14),\
ls_str(self.cur_proj.bg).rjust(18)
print \
'pre-display'.rjust(26),\
'post-display'.rjust(26)
print \
ls_str(self.cur_proj.pre).rjust(26),\
ls_str(self.cur_proj.post).rjust(26)
print \
'cross colors'.rjust(26),\
'cross times'.rjust(26)
print \
ls_str(self.cur_proj.cross_cols).rjust(26),\
ls_str(self.cur_proj.cross_times).rjust(26)
if args.show_all:
# Insert empty line between different info sets
print ''
if args.show_all or args.disp_ops:
print 'DISPLAY OPTIONS'.center(70,'*')
for k, v in self.cur_proj.disp_ops.items():
print ''.ljust(20), ls_str(k).ljust(20), ls_str(v).ljust(20)
if args.show_all:
# Insert empty line between different info sets
print ''
if args.show_all or args.orders:
print 'GROUP ORDERINGS'.center(70,'*')
if self.cur_proj.orders == []:
order = range(len(self.cur_proj.groups))
print \
''.ljust(20),\
'default order'.ljust(20),\
ls_str(order).ljust(20)
else:
for n, order in enumerate(self.cur_proj.orders):
print \
''.ljust(20),\
'order {n}'.format(n=n).ljust(20),\
ls_str(order).ljust(20)
if args.show_all:
# Insert empty line between different info sets
print ''
if args.show_all or args.groups:
for i, n in enumerate(args.gids):
if i != 0:
# Print newline seperator between each group
print ''
group = self.cur_proj.groups[n]
print 'GROUP {n}'.format(n=n).center(70,'*')
print \
'pre-display'.rjust(20),\
'display'.rjust(20),\
'post-display'.rjust(20)
print \
ls_str(group.pre).rjust(20),\
ls_str(group.disp).rjust(20),\
ls_str(group.post).rjust(20)
if len(group.shapes) > 0:
print \
''.rjust(2),\
'shape id'.rjust(8),\
'dims'.rjust(10),\
'init_unit'.rjust(14),\
'end_unit'.rjust(14),\
'position'.rjust(14)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.dims).rjust(10),\
ls_str(shape.init_unit).rjust(14),\
ls_str(shape.end_unit).rjust(14),\
ls_str(shape.position).rjust(14)
print '\n',\
''.rjust(2),\
'shape id'.rjust(8),\
'colors'.rjust(27),\
'anchor'.rjust(12),\
'freq'.rjust(6),\
'phase'.rjust(7)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.cols).rjust(27),\
ls_str(shape.anchor).rjust(12),\
ls_str(shape.freq).rjust(6),\
ls_str(shape.phase).rjust(7)
display_parser = CmdParser(add_help=False, prog='display',
description='''Displays the stimulus in a
window or in fullscreen.''')
display_parser.add_argument('-s', '--save', action='store_true',
help='''save specified display flags
as default flags for project
instead of presenting stimulus''')
display_parser.add_argument('-n', '--name', metavar='FOOBAR',
help='''name of log file to be written''')
display_parser.add_argument('-r', '--repeats', metavar='N', type=int,
help='''repeatedly display specified display
groups N number of times''')
display_parser.add_argument('-wl', '--waitless', action=store_truth(),
metavar='t/f',
help='''do not add waitscreens before the
start of each repeat''')
display_parser.add_argument('-f', '--fullscreen', action=store_truth(),
metavar='t/f',
help='sets fullscreen mode, ESC to quit')
display_parser.add_argument('-p', '--priority', metavar='LEVEL',
help='''set priority while displaying,
higher priority results in
less dropped frames (choices:
0-3, low, normal, high,
realtime)''')
display_parser.add_argument('-pt', '--phototest', action=store_truth(),
metavar='t/f',
help='''draw white test rectangle in topleft
corner of screen when groups become
visible for a photodiode to detect''')
display_parser.add_argument('-pb', '--photoburst', action=store_truth(),
metavar='t/f',
help='''make checkerboards only draw first
color for one frame to facilitate
testing with a photodiode''')
display_parser.add_argument('-lt', '--logtime', action=store_truth(),
metavar='t/f',
help='output frame timestamps to a log file')
display_parser.add_argument('-ld', '--logdur', action=store_truth(),
metavar='t/f',
help='output frame durations to a log file')
display_parser.add_argument('-ss', '--trigser', action=store_truth(),
metavar='t/f',
help='''send triggers through the serial port
when shapes are being displayed''')
display_parser.add_argument('-sp', '--trigpar', action=store_truth(),
metavar='t/f',
help='''send triggers through the parallel port
when shapes are being displayed''')
display_parser.add_argument('-fpst', metavar='M', type=int,
help='''unique trigger corresponding to a
checkerboard is sent after the shape
undergoes M color flips (default:
disabled, M=0)''')
display_parser.add_argument('-fc', '--freqcheck', action=store_truth(),
metavar='t/f',
help='''only send triggers for board color
flips at the start, middle and end
of the run''')
display_parser.add_argument('-et', '--eyetrack', action=store_truth(),
metavar='t/f',
help='''use eyetracking to ensure that subject
fixates on the cross in the center''')
display_parser.add_argument('-eu', '--etuser', action=store_truth(),
metavar='t/f',
help='''allow user to select eyetracking video
source from a dialog''')
display_parser.add_argument('-ev', '--etvideo', metavar='path',
help='''path (with no spaces) to eyetracking
video file to be used as the source''')
display_parser.add_argument('-ta', '--tryagain', metavar='I', type=int,
help='''append groups during which subject
failed to fixate up to I times to the
list of groups to be displayed
(default: disabled, I=0)''')
display_parser.add_argument('-tb', '--trybreak', metavar='J', type=int,
help='''used with --tryagain, append a wait
screen to the list of groups to be
displayed after every J groups have
been appended to the list (default:
J=total number of groups)''')
display_parser.add_argument('-nl', '--nolog', action=store_truth(),
metavar='t/f',
help='''do not write a log file''')
display_parser.add_argument('order', nargs='*', metavar='id', type=int,
help='''order in which groups should be
displayed (default: random order
from list of orders if specified
in project, ascending otherwise)''')
def help_display(self):
self.__class__.display_parser.print_help()
def do_display(self, line):
"""Displays the stimulus in a window or in fullscreen"""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.display_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
if len(args.order) > 0:
for i in set(args.order):
if i >= len(self.cur_proj.groups) or i < -1:
print 'error: group', i, 'does not exist'
return
if args.eyetrack and eyetracking.available:
if not eyetracking.is_calibrated():
try:
self.do_calibrate('',query=True)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
return
if args.save:
self.cur_proj.set_display_flags(repeats=args.repeats,
waitless=args.waitless,
fullscreen=args.fullscreen,
priority=args.priority,
logtime=args.logtime,
logdur=args.logdur,
trigser=args.trigser,
trigpar=args.trigpar,
fpst=args.fpst,
freqcheck=args.freqcheck,
phototest=args.phototest,
photoburst=args.photoburst,
eyetrack=args.eyetrack,
etuser=args.etuser,
etvideo=args.etvideo,
tryagain=args.tryagain,
trybreak=args.trybreak,
nolog=args.nolog)
print "display flags saved to project"
else:
print "displaying...",
try:
self.cur_proj.display(name=args.name,
repeats=args.repeats,
waitless=args.waitless,
fullscreen=args.fullscreen,
priority=args.priority,
logtime=args.logtime,
logdur=args.logdur,
trigser=args.trigser,
trigpar=args.trigpar,
fpst=args.fpst,
freqcheck=args.freqcheck,
phototest=args.phototest,
photoburst=args.photoburst,
eyetrack=args.eyetrack,
etuser=args.etuser,
etvideo=args.etvideo,
tryagain=args.tryagain,
trybreak=args.trybreak,
nolog=args.nolog,
order=args.order)
except (IOError, NotImplementedError,
eyetracking.EyetrackingError):
print ''
print "error:", str(sys.exc_value)
if args.priority != None:
try:
priority.set('normal')
except:
pass
return
print "done"
export_parser = CmdParser(add_help=False, prog='export',
description='''Exports stimulus as an image
sequence (in a folder) to the
specified directory.''')
export_parser.add_argument('-n','--nofolder',
dest='folder', action='store_false',
help='''force images not to exported in
a containing folder''')
- export_parser.add_argument('-r', '--repeat', metavar='N', type=int,
+ export_parser.add_argument('-r', '--repeats', metavar='N', type=int,
help='''repeatedly export specified display
groups N number of times''')
export_parser.add_argument('duration', nargs='?',
type=to_decimal, default='Infinity',
help='''number of seconds of the stimulus
that should be exported (default:
as long as the entire stimulus)''')
export_parser.add_argument('dir', nargs='?', default=os.getcwd(),
help='''destination directory for export
(default: current working directory)''')
- export_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
- help='''list of display groups to be exported
- in the specified order (default: order
- by id, i.e. group 0 is first)''')
+ export_parser.add_argument('order', nargs='*', metavar='id', type=int,
+ help='''order in which groups should be
+ displayed (default: random order
+ from list of orders if specified
+ in project, ascending otherwise)''')
def help_export(self):
self.__class__.export_parser.print_help()
def do_export(self, line):
"""Exports stimulus as an image sequence to the specified directory."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.export_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.export_parser.print_usage()
return
- if len(args.idlist) > 0:
- for i in set(args.idlist):
- if i >= len(self.cur_proj.groups) or i < 0:
+ if len(args.order) > 0:
+ for i in set(args.order):
+ if i >= len(self.cur_proj.groups) or i < -1:
print 'error: group', i, 'does not exist'
return
- groupq = [self.cur_proj.groups[i] for i in args.idlist]
- else:
- groupq = list(self.cur_proj.groups)
- if args.repeat != None:
- groupq = list(groupq * args.repeat)
try:
- self.cur_proj.export(export_dir=args.dir,
- export_duration=args.duration,
- groupq=groupq,
+ self.cur_proj.export(repeats=args.repeats,
+ order=args.order,
+ expo_dir=args.dir,
+ expo_dur=args.duration,
folder=args.folder)
except IOError:
print "error:", str(sys.exc_value)
return
except core.FrameOverflowError:
print "warning:", str(sys.exc_value)
print "Are you sure you want to continue?"
while True:
try:
if self.__class__.yn_parse(raw_input()):
- self.cur_proj.export(export_dir=args.dir,
- export_duration=args.duration,
- groupq=groupq,
+ self.cur_proj.export(repeats=args.repeats,
+ order=args.order,
+ expo_dir=args.dir,
+ expo_dur=args.duration,
folder=args.folder,
force=True)
break
else:
return
except TypeError:
print str(sys.exc_value)
except EOFError:
return
print "Export done."
def do_calibrate(self, line, query=False):
"""Calibrate subject for eyetracking, or load a calibration file."""
if not eyetracking.available:
print "error: eyetracking functionality not available"
return
if query:
print "path to calibration file (leave empty for GUI tool):"
try:
path = raw_input().strip().strip('"\'')
except EOFError:
msg = "calibration cancelled"
raise eyetracking.EyetrackingError(msg)
else:
path = line.strip().strip('"\'')
if len(path) == 0:
path = None
if not eyetracking.is_source_ready():
# Select default source if none has been selected
eyetracking.select_source()
try:
eyetracking.calibrate(path)
except eyetracking.EyetrackingError:
if query:
raise
else:
print "error:", str(sys.exc_value)
return
if path!= None and len(path) > 0:
print "calibration file successfully loaded"
etsetup_parser = CmdParser(add_help=False, prog='etsetup',
description='''Set various eyetracking
parameters.''')
etsetup_parser.add_argument('-fp', '--fixperiod', type=int, metavar='MS',
help='''time in milliseconds subject
has to stare at the same spot
for fixation to be detected''')
etsetup_parser.add_argument('-fr', '--fixrange', type=float, metavar='MM',
help='''distance in mm beyond which the
eye position cannot change for
a fixation to be detected''')
etsetup_parser.add_argument('-s', '--size', metavar='WIDTH,HEIGHT',
action=store_list(2, ',', float),
help='physical screen dimensions in mm')
etsetup_parser.add_argument('-vd', '--viewdist', type=int, metavar='MM',
help='''viewing distance between subject's
eyes and the screen''')
def help_etsetup(self):
self.__class__.etsetup_parser.print_help()
def do_etsetup(self, line):
try:
args = self.__class__.etsetup_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.etsetup_parser.print_usage()
return
try:
eyetracking.setup(viewing_distance=args.viewdist,
screen_dims=args.size,
fixation_period=args.fixperiod,
fixation_range=args.fixrange)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
def do_pwd(self, line):
"""Prints the current working directory."""
print os.getcwd()
def do_cd(self, line):
"""Change working directory to specified path."""
path = line.strip().strip('"\'')
if not os.path.isdir(path):
print "error: specified path is not a directory"
return
os.chdir(path)
def do_quit(self, line):
"""Quits the program."""
if self.save_check():
return
return True
def help_EOF(self):
print "Typing {0} issues this command, which quits the program."\
.format(CMD_EOF_STRING)
def do_EOF(self, line):
"""Typing Ctrl-D issues this command, which quits the program."""
print '\r'
if self.save_check():
return
return True
def help_help(self):
print 'Prints a list of commands.'
print "Type 'help <topic>' for more details on each command."
def default(self, line):
command = line.split()[0]
print \
"'{0}' is not a checkergen command.".format(command),\
"Type 'help' for a list of commands"
diff --git a/src/core.py b/src/core.py
index a34cfe1..174cfdb 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,1241 +1,1265 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import copy
import random
import itertools
from datetime import datetime
from xml.dom import minidom
import pyglet
import graphics
import priority
import trigger
import eyetracking
from utils import *
# Use OrderedDict substitute if we don't have Python 2.7
if sys.version_info < (2, 7):
from odict import OrderedDict
else:
from collections import OrderedDict
CKG_FMT = 'ckg'
LOG_FMT = 'log'
-MAX_EXPORT_FRAMES = 100000
+MAX_EXPORT_FRAMES = 1000
EXPORT_DIR_SUFFIX = '-anim'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
INT_HALF_PERIODS = True
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = OrderedDict([('name', 'untitled'),
('fps', 60),
('res', (800, 600)),
('bg', (127, 127, 127)),
('pre', 0),
('post', 0),
('cross_cols', ((0, 0, 0), (255, 0, 0))),
('cross_times', ('Infinity', 1)),
('orders', []),
('disp_ops', None)])
DEFAULTS['disp_ops'] = OrderedDict([('repeats', 1),
('waitless', False),
('fullscreen', False),
('priority', None),
('logtime', False),
('logdur', False),
('trigser', False),
('trigpar', False),
('fpst', 0),
('freqcheck', False),
('phototest', False),
('photoburst', False),
('eyetrack', False),
('etuser', False),
('etvideo', None),
('tryagain', 0),
('trybreak', None),
- ('nolog', False)])
+ ('nolog', False),
+ ('export', False),
+ ('expo_dir', None),
+ ('expo_dur', None),
+ ('folder', True)])
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def set_display_flags(self, **keywords):
"""Set default display flags for the project.
Same arguments as 'display', excluding 'name' and 'order'.
"""
for kw in keywords.keys():
if kw in self.disp_ops.keys() and keywords[kw] != None:
self.disp_ops[kw] = keywords[kw]
self._dirty = True
def set_group_orders(self, orders):
for order in orders:
for gid in order:
if gid < -1 or gid >= len(self.groups):
msg = 'invalid group id (out of range)'
raise ValueError(msg)
self.orders = orders
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
# Vars that are dicts
dicts_to_load = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_load = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
for d_name in dicts_to_load:
d = copy.deepcopy(self.__class__.DEFAULTS[d_name])
try:
d_el = [node for node in project.childNodes if
node.localName == d_name and
node.namespaceURI == XML_NAMESPACE][0]
for var in d.keys():
try:
d[var] = eval(xml_get(d_el, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}' in '{1}'".\
format(var, d_name)
print "using default value '{0}' instead...".\
format(d[var])
except IndexError:
print "warning: missing attribute set '{0}'".format(d_name)
print "using default values instead..."
setattr(self, d_name, d)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
# Vars that are dicts
dicts_to_save = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_save = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for d_name in dicts_to_save:
d_el = doc.createElement(d_name)
project.appendChild(d_el)
d = getattr(self, d_name)
for k, v in d.iteritems():
xml_set(doc, d_el, k, repr(v))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, **keywords):
- """Displays the project animation on the screen.
+ """Displays the stimulus on the screen.
name -- name that logfile will be saved with
repeats -- number of times specified order of display groups should
be repeated
waitless -- if true, no waitscreens will appear at the start of each
repeat
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
priority -- priority level to which process should be raised
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
trigser -- send triggers through serial port when each group is shown
trigpar -- send triggers through parallel port when each group is shown
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
freqcheck -- send fpst only at the start, the middle, and the end
for sanity checking of display and trigger fps
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- append a wait screen to the group queue every time
after this many groups have been appended to the queue
order -- order in which groups (specified by id) will be displayed
"""
# Create RunState
disp_ops = copy.deepcopy(self.disp_ops)
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'name' in keywords.keys() and keywords['name'] != None:
name = keywords['name']
else:
timestr = datetime.today().strftime('_%Y-%m-%d_%H-%M-%S')
name = self.name + timestr
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
waitscreen = CkgWaitScreen()
# Set order id to be sent if necessary
if order in self.orders:
runstate.events['ord_id'] = self.orders.index(order)
# Count through pre
for count in range(self.pre * self.fps):
- if runstate.window.has_exit:
+ if runstate.terminate:
break
runstate.update()
# Loop through repeats
repeats = runstate.disp_ops['repeats']
ord_len = len(runstate.order)
for i in range(repeats):
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
# Loop through display groups
runstate.events['blk_on'] = True
for n, gid in enumerate(runstate.order):
# Set flag for freqcheck
if runstate.disp_ops['freqcheck']:
if ((i == 0 and n == 0) or
(i == repeats-1 and n == ord_len-1) or
(i == repeats//2 and n == ord_len//2)):
runstate.fc_send = True
else:
runstate.fc_send = False
if gid == -1:
waitscreen.reset()
waitscreen.display(runstate)
else:
self.groups[gid].display(runstate)
# Append failed groups
if runstate.disp_ops['eyetrack'] and runstate.true_fail:
if len(runstate.add_gids) < runstate.disp_ops['tryagain']:
runstate.add_gids.append(gid)
else:
runstate.fail_gids.append(gid)
runstate.events['blk_off'] = True
# Stop freqcheck before added groups
if runstate.disp_ops['freqcheck']:
runstate.fc_send = False
# Loop through added groups
if runstate.disp_ops['eyetrack']:
for blk in grouper(runstate.add_gids,
runstate.disp_ops['trybreak']):
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
runstate.events['blk_on'] = True
# Loop through display groups
for gid in blk:
if gid != None:
self.groups[gid].display(runstate)
runstate.events['blk_off'] = True
# Count through post
for count in range(self.post * self.fps):
- if runstate.window.has_exit:
+ if runstate.terminate:
break
runstate.update()
# Stop and output log
runstate.stop()
if not runstate.disp_ops['nolog']:
runstate.log()
- def export(self, export_dir, export_duration, groupq=[],
- folder=True, force=False):
- if not os.path.isdir(export_dir):
- msg = 'export path is not a directory'
- raise IOError(msg)
+ def export(self, **keywords):
+ """Exports the stimulus as a series of images, one image per frame.
- # Set-up groups and variables that control their display
- if groupq == []:
- groupq = list(self.groups)
- n = -1
- groups_duration = sum([group.duration() for group in groupq])
- groups_start = self.pre * self.fps
- groups_stop = (self.pre + groups_duration) * self.fps
- disp_end = (self.pre + groups_duration + self.post) * self.fps
- if groups_start == 0 and groups_stop > 0:
- groups_visible = True
- else:
- groups_visible = False
- count = 0
+ repeats -- number of times specified order of display groups should
+ be repeated
+
+ order -- order in which groups (specified by id) will be displayed
- # Limit export duration to display duration
- frames = export_duration * self.fps
- frames = min(frames, disp_end)
+ expo_dir -- directory to which images will be exported
- # Warn user if a lot of frames will be exported
- if frames > MAX_EXPORT_FRAMES and not force:
- msg = 'very large number ({0}) of frames to be exported'.\
- format(frames)
- raise FrameOverflowError(msg)
+ expo_dur -- time in seconds to which export will be limited
- # Create folder to store images if necessary
- if folder:
- export_dir = os.path.join(export_dir,
- self.name + EXPORT_DIR_SUFFIX)
- if not os.path.isdir(export_dir):
- os.mkdir(export_dir)
+ folder -- if true, images will be contained in a separate folder
+ within export directory
- # Create fixation crosses
- fix_crosses = [graphics.Cross([r/2 for r in self.res],
- (20, 20), col = cross_col)
- for cross_col in self.cross_cols]
-
- # Set up canvas and framebuffer object
- canvas = pyglet.image.Texture.create(*self.res)
- fbo = graphics.Framebuffer(canvas)
- fbo.start_render()
- graphics.set_clear_color(self.bg)
- fbo.clear()
-
- # Main loop
- while count < frames:
- fbo.clear()
-
- if groups_visible:
- # Get next group from queue
- if n < 0 or groupq[n].over:
- n += 1
- if n >= len(groupq):
- groups_visible = False
- else:
- groupq[n].reset()
- # Draw and then update group
- if n >= 0:
- groupq[n].draw()
- groupq[n].update(fps=self.fps, fpst=0)
-
- # Draw fixation cross based on current count
- if (count % (sum(self.cross_times) * self.fps)
- < self.cross_times[0] * self.fps):
- fix_crosses[0].draw()
- else:
- fix_crosses[1].draw()
+ force -- force export to go through even if a large number
+ of frames are to be exported
- # Save current frame to file
- savepath = \
- os.path.join(export_dir,
- '{0}{2}.{1}'.
- format(self.name, 'png',
- repr(count).zfill(numdigits(frames-1))))
- canvas.save(savepath)
-
- # Increment count and set whether groups should be shown
- count += 1
- if groups_start <= count < groups_stop:
- groups_visible = True
- else:
- groups_visible = False
+ """
+
+ # Create RunState
+ disp_ops = copy.deepcopy(self.__class__.DEFAULTS['disp_ops'])
+ disp_ops['export'] = True
+ for kw in keywords.keys():
+ if kw in disp_ops.keys() and keywords[kw] != None:
+ disp_ops[kw] = keywords[kw]
+ if 'order' in keywords.keys() and len(keywords['order']) > 0:
+ order = keywords['order']
+ elif len(self.orders) > 0:
+ order = random.choice(self.orders)
+ else:
+ order = range(len(self.groups))
+ runstate = CkgRunState(name=self.name,
+ res=self.res, fps=self.fps, bg=self.bg,
+ cross_cols=self.cross_cols,
+ cross_times=self.cross_times,
+ disp_ops=disp_ops, order=order)
+ runstate.start()
- fbo.delete()
+ # Warn user if a lot of frames will be exported
+ if 'force' not in keywords.keys():
+ keywords['force'] = False
+ groups_dur = sum([self.groups[i].duration()
+ for i in order]) * disp_ops['repeats']
+ total_frames = (self.pre + groups_dur + self.post) * self.fps
+ frames = min(total_frames, disp_ops['expo_dur'] * self.fps)
+ if frames > MAX_EXPORT_FRAMES and not keywords['force']:
+ msg = 'large number ({0}) of frames to be exported'.\
+ format(int(frames))
+ raise FrameOverflowError(msg)
+ runstate.frames = frames
+
+ # Count through pre
+ for count in range(self.pre * self.fps):
+ if runstate.terminate:
+ break
+ runstate.update()
+ # Loop through repeats
+ repeats = runstate.disp_ops['repeats']
+ for i in range(repeats):
+ # Loop through display groups
+ for n, gid in enumerate(runstate.order):
+ if gid != -1:
+ self.groups[gid].display(runstate)
+ # Count through post
+ for count in range(self.post * self.fps):
+ if runstate.terminate:
+ break
+ runstate.update()
+
+ # Stop runstate
+ runstate.stop()
class CkgRunState:
"""Contains information about the state of a checkergen project
when it is being displayed or exported."""
DEFAULTS = dict([('name', 'untitled'),
('res', None),
('fps', None),
('bg', None),
('cross_cols', None),
('cross_times', None),
('order', []),
('disp_ops', None),
('events', None),
('add_gids', []),
('fail_gids', []),
('timestamps', []),
('durstamps', []),
('trigstamps', [])])
DEFAULTS['events'] = dict([('ord_id', None),
('blk_on', False),
('blk_off', False),
('track_on', False),
('track_off', False),
('fix_on', False),
('fix_off', False),
('grp_on', False),
('grp_off', False),
('sids', set())])
def __init__(self, **keywords):
"""Creates the RunState."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
def start(self):
"""Initialize all subsystems and start the run."""
if self.disp_ops == None:
msg = "RunState lacks display options"
raise ValueError(msg)
if min(self.res, self.fps, self.bg,
self.cross_cols, self.cross_times) == None:
msg = "RunState intialized with insufficent project information"
raise ValueError(msg)
self._count = 0
+ self.terminate = False
# Flag used by freqcheck
self.fc_send = False
# Create fixation crosses
self.fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if self.disp_ops['phototest']:
self.test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
+ # Initialize export
+ if self.disp_ops['export']:
+ if not os.path.isdir(self.disp_ops['expo_dir']):
+ msg = 'export path is not a directory'
+ raise IOError(msg)
+ if self.disp_ops['folder']:
+ self.save_dir = os.path.join(self.disp_ops['expo_dir'],
+ self.name + EXPORT_DIR_SUFFIX)
+ else:
+ self.save_dir = self.disp_ops['expo_dir']
+ if not os.path.isdir(self.save_dir):
+ os.mkdir(self.save_dir)
+
# Initialize ports
if self.disp_ops['trigser']:
if not trigger.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trigpar']:
if not trigger.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
trigger.init(self.disp_ops['trigser'], self.disp_ops['trigpar'])
# Initialize eyetracking
if self.disp_ops['eyetrack']:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trybreak'] == None:
self.disp_ops['trybreak'] = len(self.order)
self.fixated = False
self.old_fixated = False
self.tracked = False
self.old_tracked = False
self.fix_fail = False
self.true_fail = False
eyetracking.select_source(self.disp_ops['etuser'],
self.disp_ops['etvideo'])
eyetracking.start()
-
- # Stretch to fit screen only if project res does not equal screen res
+
+ # Create window if not exporting
self.scaling = False
- if self.disp_ops['fullscreen']:
- self.window = pyglet.window.Window(fullscreen=True, visible=False)
- if (self.window.width, self.window.height) != self.res:
- self.scaling = True
- else:
- self.window = pyglet.window.Window(*self.res, visible=False)
+ if not self.disp_ops['export']:
+ # Stretch to fit screen only if project res does not
+ # equal screen res
+ if self.disp_ops['fullscreen']:
+ self.window = pyglet.window.Window(fullscreen=True,
+ visible=False)
+ if (self.window.width, self.window.height) != self.res:
+ self.scaling = True
+ else:
+ self.window = pyglet.window.Window(*self.res, visible=False)
- # Set up KeyStateHandler to handle keyboard input
- self.keystates = pyglet.window.key.KeyStateHandler()
- self.window.push_handlers(self.keystates)
+ # Set up KeyStateHandler to handle keyboard input
+ self.keystates = pyglet.window.key.KeyStateHandler()
+ self.window.push_handlers(self.keystates)
- # Clear window and make visible
- self.window.switch_to()
- graphics.set_clear_color(self.bg)
- self.window.clear()
- self.window.set_visible()
+ # Clear window and make visible
+ self.window.switch_to()
+ graphics.set_clear_color(self.bg)
+ self.window.clear()
+ self.window.set_visible()
- # Create framebuffer object for drawing unscaled scene
- if self.scaling:
+ # Create framebuffer object for drawing unscaled or exported scene
+ if self.scaling or self.disp_ops['export']:
self.canvas = pyglet.image.Texture.create(*self.res)
self.fbo = graphics.Framebuffer(self.canvas)
self.fbo.start_render()
graphics.set_clear_color(self.bg)
self.fbo.clear()
# Set process priority
if self.disp_ops['priority'] != None:
if not priority.available[sys.platform]:
msg = "setting priority not available on {0}".\
format(sys.platform)
raise NotImplementedError(msg)
else:
try:
priority.set(self.disp_ops['priority'])
except ValueError:
priority.set(int(self.disp_ops['priority']))
# Start timers
if self.disp_ops['logtime']:
self.timer = Timer()
self.timer.start()
if self.disp_ops['logdur']:
self.dur = Timer()
self.dur.start()
def update(self):
"""Update the RunState."""
# Check for tracking and fixation
if self.disp_ops['eyetrack']:
self.old_tracked = self.tracked
self.tracked = eyetracking.is_tracked(self.fps)
self.old_fixated = self.fixated
self.fixated = eyetracking.is_fixated(self.fps)
if self.fixated:
# Draw normal cross color if fixating
self.fix_crosses[0].draw()
else:
# Draw alternative cross color if not fixating
self.fix_crosses[1].draw()
# Update eyetracking events
if self.tracked != self.old_tracked:
if self.tracked:
self.events['track_on'] = True
else:
self.events['track_off'] = True
if self.fixated != self.old_fixated:
if self.fixated:
self.events['fix_on'] = True
else:
self.events['fix_off'] = True
# Check for failure of trial
if self.tracked and not self.fixated:
self.fix_fail = True
else:
# Change cross color based on time
if (self._count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
self.fix_crosses[0].draw()
else:
self.fix_crosses[1].draw()
- # Blit canvas to screen if necessary
- if self.scaling:
- self.fbo.end_render()
- self.canvas.blit(0, 0)
- self.window.switch_to()
- self.window.dispatch_events()
- self.window.flip()
- # Make sure everything has been drawn
- pyglet.gl.glFinish()
+ if self.disp_ops['export']:
+ # Save current frame to file
+ savepath = os.path.join(
+ self.save_dir, '{0}{2}.{1}'.\
+ format(self.name, 'png',
+ repr(self._count).zfill(numdigits(self.frames-1))))
+ self.canvas.save(savepath)
+ else:
+ # Blit canvas to screen if necessary
+ if self.scaling:
+ self.fbo.end_render()
+ self.canvas.blit(0, 0)
+ self.window.switch_to()
+ self.window.dispatch_events()
+ self.window.flip()
+ # Make sure everything has been drawn
+ pyglet.gl.glFinish()
# Append time information to lists
if self.disp_ops['logtime']:
self.timestamps.append(self.timer.elapsed())
elif self.disp_ops['logdur']:
self.timestamps.append('')
if self.disp_ops['logdur']:
self.durstamps.append(self.dur.restart())
elif self.disp_ops['logtime']:
self.durstamps.append('')
# Send trigger ASAP after flip
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
if self.encode_events() > 0:
trigger.send(self.disp_ops['trigser'],
self.disp_ops['trigpar'],
self.encode_events())
# Log when triggers are sent
if self.disp_ops['logtime'] and self.encode_events() > 0:
self.trigstamps.append(self.encode_events())
else:
self.trigstamps.append('')
# Clear canvas, events, prepare for next frame
- if self.scaling:
- self.fbo.start_render()
+ if self.disp_ops['export']:
self.fbo.clear()
else:
- self.window.clear()
+ if self.scaling:
+ self.fbo.start_render()
+ self.fbo.clear()
+ else:
+ self.window.clear()
+ if self.window.has_exit:
+ self.terminate = True
self.events = copy.deepcopy(self.__class__.DEFAULTS['events'])
self._count += 1
+
+ # Terminate export if the time has come
+ if self.disp_ops['export']:
+ if self._count >= self.frames:
+ self.terminate = True
def stop(self):
"""Clean up RunState."""
if self.disp_ops['eyetrack']:
eyetracking.stop()
- if self.scaling:
+ if self.scaling or self.disp_ops['export']:
self.fbo.delete()
del self.canvas
- self.window.close()
+ if not self.disp_ops['export']:
+ self.window.close()
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
trigger.quit(self.disp_ops['trigser'], self.disp_ops['trigpar'])
if self.disp_ops['priority'] != None:
priority.set('normal')
def encode_events(self):
"""Hard code specific trigger values for events."""
code = 0
if self.events['ord_id'] != None:
code = self.events['ord_id'] + 1
elif self.events['blk_on']:
code = 128
elif self.events['blk_off']:
code = 127
else:
mult = 0
if self.events['fix_on']:
mult = 4
elif self.events['track_on']:
mult = 3
if self.events['track_off']:
mult = 1
elif self.events['fix_off']:
mult = 2
if self.events['grp_on']:
code = 100 + mult
elif self.events['grp_off']:
code = 90 + mult
elif len(self.events['sids']) > 0:
code = ((0 in self.events['sids'])*2**0 +
(1 in self.events['sids'])*2**1 +
(2 in self.events['sids'])*2**2 +
(3 in self.events['sids'])*2**3)
code = mult*16 + code
elif mult > 0:
code = 110 + mult
return code
def log(self, path=None):
"""Write a log file for the experimental run in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, LOG_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(LOG_FMT):
path = '{0}.{1}'.format(path, LOG_FMT)
with open(path, 'wb') as logfile:
writer = csv.writer(logfile, dialect='excel-tab')
writer.writerow(['checkergen log file'])
writer.writerow(['display options:'])
writer.writerow(self.disp_ops.keys())
writer.writerow(self.disp_ops.values())
writer.writerow(['order:'] + self.order)
if self.disp_ops['eyetrack']:
writer.writerow(['groups added'])
for blk in grouper(self.add_gids,
self.disp_ops['trybreak'], ''):
writer.writerow(blk)
writer.writerow(['groups failed'])
for blk in grouper(self.fail_gids,
self.disp_ops['trybreak'], ''):
writer.writerow(blk)
if self.disp_ops['logtime'] or self.disp_ops['logdur']:
stamps = [self.timestamps, self.durstamps, self.trigstamps]
writer.writerow(['timestamps', 'durations', 'triggers'])
for stamp in zip(*stamps):
writer.writerow(list(stamp))
class CkgDisplayGroup:
DEFAULTS = OrderedDict([('pre', 0), ('disp', 'Infinity'), ('post', 0)])
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets counts and all contained shapes."""
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, runstate):
"""Draws all contained shapes during the appropriate interval."""
for shape in self.shapes:
shape.draw(photoburst=runstate.disp_ops['photoburst'])
def update(self, runstate):
"""Updates contained shapes, sets event triggers."""
# Set events to be sent
if runstate.disp_ops['fpst'] > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= runstate.disp_ops['fpst']:
if not runstate.disp_ops['freqcheck'] or runstate.fc_send:
runstate.events['sids'].add(n)
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(runstate.fps)
def display(self, runstate):
"""Display the group in the context described by supplied runstate."""
self.reset()
for count in range(self.pre * runstate.fps):
- if runstate.window.has_exit:
+ if runstate.terminate:
break
runstate.update()
runstate.events['grp_on'] = True
if runstate.disp_ops['eyetrack']:
runstate.fix_fail = False
runstate.true_fail = False
for count in range(self.disp * runstate.fps):
- if runstate.window.has_exit:
+ if runstate.terminate:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
runstate.events['grp_off'] = True
if runstate.disp_ops['eyetrack']:
if runstate.fix_fail:
runstate.true_fail = True
for count in range(self.post * runstate.fps):
- if runstate.window.has_exit:
+ if runstate.terminate:
break
runstate.update()
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.steps_done = 0
def draw(self, runstate):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, runstate):
"""Checks for keypress, sends trigger upon end."""
if max([runstate.keystates[key] for
key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
def display(self, runstate):
"""Displays waitscreen in context described by supplied runstate."""
while self.steps_done < self.num_steps:
- if runstate.window.has_exit:
+ if runstate.terminate:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = OrderedDict([('dims', (5, 5)),
('init_unit', (30, 30)),
('end_unit', (50, 50)),
('position', (0, 0)),
('anchor', 'bottomleft'),
('cols', ((0, 0, 0), (255, 255, 255))),
('freq', 1),
('phase', 0)])
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
if INT_HALF_PERIODS:
frames_per_half_period = round(fps / (self.freq * 2))
degs_per_frame = 180 / to_decimal(frames_per_half_period)
else:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
anchor=self.anchor)
cur_unit_rect.col = self.cols[(i + j) % 2]
cur_unit_rect.add_to_batch(self._batches[0])
cur_unit_rect.col = self.cols[(i + j + 1) % 2]
cur_unit_rect.add_to_batch(self._batches[1])
# Increase x values
cur_unit_pos[0] += \
graphics.locations[self.anchor][0] * cur_unit[0]
cur_unit[0] += unit_grad[0]
# Reset x values
cur_unit_pos[0] = init_pos[0]
cur_unit[0] = init_unit[0]
# Increase y values
cur_unit_pos[1] += \
graphics.locations[self.anchor][1] * cur_unit[1]
cur_unit[1] += unit_grad[1]
self._computed = True
def draw(self, photoburst=False, always_compute=False):
"""Draws appropriate batch depending on current phase.
photoburst -- draw first color for only one frame for testing purposes
always_compute -- recompute what the checkerboard should look like
every frame
"""
if not self._computed or always_compute:
self.compute()
self._cur_phase %= 360
n = int(self._cur_phase // 180)
if photoburst and n == 0 and not self.flipped:
n = 1
self._batches[n].draw()
def lazydraw(self):
"""Only draws on color reversal."""
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if (cur_n != prev_n) or self._first_draw:
self.draw()
if self._first_draw:
self._first_draw = False
|
ztangent/checkergen
|
6ffd61fb799c941318676cec3d4059621958ff77
|
Stop freqcheck before added groups.
|
diff --git a/src/core.py b/src/core.py
index 12a11fb..a34cfe1 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,968 +1,971 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import copy
import random
import itertools
from datetime import datetime
from xml.dom import minidom
import pyglet
import graphics
import priority
import trigger
import eyetracking
from utils import *
# Use OrderedDict substitute if we don't have Python 2.7
if sys.version_info < (2, 7):
from odict import OrderedDict
else:
from collections import OrderedDict
CKG_FMT = 'ckg'
LOG_FMT = 'log'
MAX_EXPORT_FRAMES = 100000
EXPORT_DIR_SUFFIX = '-anim'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
INT_HALF_PERIODS = True
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = OrderedDict([('name', 'untitled'),
('fps', 60),
('res', (800, 600)),
('bg', (127, 127, 127)),
('pre', 0),
('post', 0),
('cross_cols', ((0, 0, 0), (255, 0, 0))),
('cross_times', ('Infinity', 1)),
('orders', []),
('disp_ops', None)])
DEFAULTS['disp_ops'] = OrderedDict([('repeats', 1),
('waitless', False),
('fullscreen', False),
('priority', None),
('logtime', False),
('logdur', False),
('trigser', False),
('trigpar', False),
('fpst', 0),
('freqcheck', False),
('phototest', False),
('photoburst', False),
('eyetrack', False),
('etuser', False),
('etvideo', None),
('tryagain', 0),
('trybreak', None),
('nolog', False)])
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def set_display_flags(self, **keywords):
"""Set default display flags for the project.
Same arguments as 'display', excluding 'name' and 'order'.
"""
for kw in keywords.keys():
if kw in self.disp_ops.keys() and keywords[kw] != None:
self.disp_ops[kw] = keywords[kw]
self._dirty = True
def set_group_orders(self, orders):
for order in orders:
for gid in order:
if gid < -1 or gid >= len(self.groups):
msg = 'invalid group id (out of range)'
raise ValueError(msg)
self.orders = orders
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
# Vars that are dicts
dicts_to_load = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_load = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
for d_name in dicts_to_load:
d = copy.deepcopy(self.__class__.DEFAULTS[d_name])
try:
d_el = [node for node in project.childNodes if
node.localName == d_name and
node.namespaceURI == XML_NAMESPACE][0]
for var in d.keys():
try:
d[var] = eval(xml_get(d_el, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}' in '{1}'".\
format(var, d_name)
print "using default value '{0}' instead...".\
format(d[var])
except IndexError:
print "warning: missing attribute set '{0}'".format(d_name)
print "using default values instead..."
setattr(self, d_name, d)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
# Vars that are dicts
dicts_to_save = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_save = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for d_name in dicts_to_save:
d_el = doc.createElement(d_name)
project.appendChild(d_el)
d = getattr(self, d_name)
for k, v in d.iteritems():
xml_set(doc, d_el, k, repr(v))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, **keywords):
"""Displays the project animation on the screen.
name -- name that logfile will be saved with
repeats -- number of times specified order of display groups should
be repeated
waitless -- if true, no waitscreens will appear at the start of each
repeat
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
priority -- priority level to which process should be raised
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
trigser -- send triggers through serial port when each group is shown
trigpar -- send triggers through parallel port when each group is shown
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
freqcheck -- send fpst only at the start, the middle, and the end
for sanity checking of display and trigger fps
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- append a wait screen to the group queue every time
after this many groups have been appended to the queue
order -- order in which groups (specified by id) will be displayed
"""
# Create RunState
disp_ops = copy.deepcopy(self.disp_ops)
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'name' in keywords.keys() and keywords['name'] != None:
name = keywords['name']
else:
timestr = datetime.today().strftime('_%Y-%m-%d_%H-%M-%S')
name = self.name + timestr
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
waitscreen = CkgWaitScreen()
# Set order id to be sent if necessary
if order in self.orders:
runstate.events['ord_id'] = self.orders.index(order)
# Count through pre
for count in range(self.pre * self.fps):
if runstate.window.has_exit:
break
runstate.update()
# Loop through repeats
repeats = runstate.disp_ops['repeats']
ord_len = len(runstate.order)
for i in range(repeats):
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
# Loop through display groups
runstate.events['blk_on'] = True
for n, gid in enumerate(runstate.order):
# Set flag for freqcheck
if runstate.disp_ops['freqcheck']:
if ((i == 0 and n == 0) or
(i == repeats-1 and n == ord_len-1) or
(i == repeats//2 and n == ord_len//2)):
runstate.fc_send = True
else:
runstate.fc_send = False
if gid == -1:
waitscreen.reset()
waitscreen.display(runstate)
else:
self.groups[gid].display(runstate)
# Append failed groups
if runstate.disp_ops['eyetrack'] and runstate.true_fail:
if len(runstate.add_gids) < runstate.disp_ops['tryagain']:
runstate.add_gids.append(gid)
else:
runstate.fail_gids.append(gid)
runstate.events['blk_off'] = True
+ # Stop freqcheck before added groups
+ if runstate.disp_ops['freqcheck']:
+ runstate.fc_send = False
# Loop through added groups
if runstate.disp_ops['eyetrack']:
for blk in grouper(runstate.add_gids,
runstate.disp_ops['trybreak']):
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
runstate.events['blk_on'] = True
# Loop through display groups
for gid in blk:
if gid != None:
self.groups[gid].display(runstate)
runstate.events['blk_off'] = True
# Count through post
for count in range(self.post * self.fps):
if runstate.window.has_exit:
break
runstate.update()
# Stop and output log
runstate.stop()
if not runstate.disp_ops['nolog']:
runstate.log()
def export(self, export_dir, export_duration, groupq=[],
folder=True, force=False):
if not os.path.isdir(export_dir):
msg = 'export path is not a directory'
raise IOError(msg)
# Set-up groups and variables that control their display
if groupq == []:
groupq = list(self.groups)
n = -1
groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Limit export duration to display duration
frames = export_duration * self.fps
frames = min(frames, disp_end)
# Warn user if a lot of frames will be exported
if frames > MAX_EXPORT_FRAMES and not force:
msg = 'very large number ({0}) of frames to be exported'.\
format(frames)
raise FrameOverflowError(msg)
# Create folder to store images if necessary
if folder:
export_dir = os.path.join(export_dir,
self.name + EXPORT_DIR_SUFFIX)
if not os.path.isdir(export_dir):
os.mkdir(export_dir)
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Set up canvas and framebuffer object
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
# Main loop
while count < frames:
fbo.clear()
if groups_visible:
# Get next group from queue
if n < 0 or groupq[n].over:
n += 1
if n >= len(groupq):
groups_visible = False
else:
groupq[n].reset()
# Draw and then update group
if n >= 0:
groupq[n].draw()
groupq[n].update(fps=self.fps, fpst=0)
# Draw fixation cross based on current count
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Save current frame to file
savepath = \
os.path.join(export_dir,
'{0}{2}.{1}'.
format(self.name, 'png',
repr(count).zfill(numdigits(frames-1))))
canvas.save(savepath)
# Increment count and set whether groups should be shown
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
fbo.delete()
class CkgRunState:
"""Contains information about the state of a checkergen project
when it is being displayed or exported."""
DEFAULTS = dict([('name', 'untitled'),
('res', None),
('fps', None),
('bg', None),
('cross_cols', None),
('cross_times', None),
('order', []),
('disp_ops', None),
('events', None),
('add_gids', []),
('fail_gids', []),
('timestamps', []),
('durstamps', []),
('trigstamps', [])])
DEFAULTS['events'] = dict([('ord_id', None),
('blk_on', False),
('blk_off', False),
('track_on', False),
('track_off', False),
('fix_on', False),
('fix_off', False),
('grp_on', False),
('grp_off', False),
('sids', set())])
def __init__(self, **keywords):
"""Creates the RunState."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
def start(self):
"""Initialize all subsystems and start the run."""
if self.disp_ops == None:
msg = "RunState lacks display options"
raise ValueError(msg)
if min(self.res, self.fps, self.bg,
self.cross_cols, self.cross_times) == None:
msg = "RunState intialized with insufficent project information"
raise ValueError(msg)
self._count = 0
# Flag used by freqcheck
self.fc_send = False
# Create fixation crosses
self.fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if self.disp_ops['phototest']:
self.test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Initialize ports
if self.disp_ops['trigser']:
if not trigger.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trigpar']:
if not trigger.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
trigger.init(self.disp_ops['trigser'], self.disp_ops['trigpar'])
# Initialize eyetracking
if self.disp_ops['eyetrack']:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trybreak'] == None:
self.disp_ops['trybreak'] = len(self.order)
self.fixated = False
self.old_fixated = False
self.tracked = False
self.old_tracked = False
self.fix_fail = False
self.true_fail = False
eyetracking.select_source(self.disp_ops['etuser'],
self.disp_ops['etvideo'])
eyetracking.start()
# Stretch to fit screen only if project res does not equal screen res
self.scaling = False
if self.disp_ops['fullscreen']:
self.window = pyglet.window.Window(fullscreen=True, visible=False)
if (self.window.width, self.window.height) != self.res:
self.scaling = True
else:
self.window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
self.keystates = pyglet.window.key.KeyStateHandler()
self.window.push_handlers(self.keystates)
# Clear window and make visible
self.window.switch_to()
graphics.set_clear_color(self.bg)
self.window.clear()
self.window.set_visible()
# Create framebuffer object for drawing unscaled scene
if self.scaling:
self.canvas = pyglet.image.Texture.create(*self.res)
self.fbo = graphics.Framebuffer(self.canvas)
self.fbo.start_render()
graphics.set_clear_color(self.bg)
self.fbo.clear()
# Set process priority
if self.disp_ops['priority'] != None:
if not priority.available[sys.platform]:
msg = "setting priority not available on {0}".\
format(sys.platform)
raise NotImplementedError(msg)
else:
try:
priority.set(self.disp_ops['priority'])
except ValueError:
priority.set(int(self.disp_ops['priority']))
# Start timers
if self.disp_ops['logtime']:
self.timer = Timer()
self.timer.start()
if self.disp_ops['logdur']:
self.dur = Timer()
self.dur.start()
def update(self):
"""Update the RunState."""
# Check for tracking and fixation
if self.disp_ops['eyetrack']:
self.old_tracked = self.tracked
self.tracked = eyetracking.is_tracked(self.fps)
self.old_fixated = self.fixated
self.fixated = eyetracking.is_fixated(self.fps)
if self.fixated:
# Draw normal cross color if fixating
self.fix_crosses[0].draw()
else:
# Draw alternative cross color if not fixating
self.fix_crosses[1].draw()
# Update eyetracking events
if self.tracked != self.old_tracked:
if self.tracked:
self.events['track_on'] = True
else:
self.events['track_off'] = True
if self.fixated != self.old_fixated:
if self.fixated:
self.events['fix_on'] = True
else:
self.events['fix_off'] = True
# Check for failure of trial
if self.tracked and not self.fixated:
self.fix_fail = True
else:
# Change cross color based on time
if (self._count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
self.fix_crosses[0].draw()
else:
self.fix_crosses[1].draw()
# Blit canvas to screen if necessary
if self.scaling:
self.fbo.end_render()
self.canvas.blit(0, 0)
self.window.switch_to()
self.window.dispatch_events()
self.window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to lists
if self.disp_ops['logtime']:
self.timestamps.append(self.timer.elapsed())
elif self.disp_ops['logdur']:
self.timestamps.append('')
if self.disp_ops['logdur']:
self.durstamps.append(self.dur.restart())
elif self.disp_ops['logtime']:
self.durstamps.append('')
# Send trigger ASAP after flip
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
if self.encode_events() > 0:
trigger.send(self.disp_ops['trigser'],
self.disp_ops['trigpar'],
self.encode_events())
# Log when triggers are sent
if self.disp_ops['logtime'] and self.encode_events() > 0:
self.trigstamps.append(self.encode_events())
else:
self.trigstamps.append('')
# Clear canvas, events, prepare for next frame
if self.scaling:
self.fbo.start_render()
self.fbo.clear()
else:
self.window.clear()
self.events = copy.deepcopy(self.__class__.DEFAULTS['events'])
self._count += 1
def stop(self):
"""Clean up RunState."""
if self.disp_ops['eyetrack']:
eyetracking.stop()
if self.scaling:
self.fbo.delete()
del self.canvas
self.window.close()
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
trigger.quit(self.disp_ops['trigser'], self.disp_ops['trigpar'])
if self.disp_ops['priority'] != None:
priority.set('normal')
def encode_events(self):
"""Hard code specific trigger values for events."""
code = 0
if self.events['ord_id'] != None:
code = self.events['ord_id'] + 1
elif self.events['blk_on']:
code = 128
elif self.events['blk_off']:
code = 127
else:
mult = 0
if self.events['fix_on']:
mult = 4
elif self.events['track_on']:
mult = 3
if self.events['track_off']:
mult = 1
elif self.events['fix_off']:
mult = 2
if self.events['grp_on']:
code = 100 + mult
elif self.events['grp_off']:
code = 90 + mult
elif len(self.events['sids']) > 0:
code = ((0 in self.events['sids'])*2**0 +
(1 in self.events['sids'])*2**1 +
(2 in self.events['sids'])*2**2 +
(3 in self.events['sids'])*2**3)
code = mult*16 + code
elif mult > 0:
code = 110 + mult
return code
def log(self, path=None):
"""Write a log file for the experimental run in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, LOG_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(LOG_FMT):
path = '{0}.{1}'.format(path, LOG_FMT)
with open(path, 'wb') as logfile:
writer = csv.writer(logfile, dialect='excel-tab')
writer.writerow(['checkergen log file'])
writer.writerow(['display options:'])
writer.writerow(self.disp_ops.keys())
writer.writerow(self.disp_ops.values())
writer.writerow(['order:'] + self.order)
if self.disp_ops['eyetrack']:
writer.writerow(['groups added'])
for blk in grouper(self.add_gids,
self.disp_ops['trybreak'], ''):
writer.writerow(blk)
writer.writerow(['groups failed'])
for blk in grouper(self.fail_gids,
self.disp_ops['trybreak'], ''):
writer.writerow(blk)
if self.disp_ops['logtime'] or self.disp_ops['logdur']:
stamps = [self.timestamps, self.durstamps, self.trigstamps]
writer.writerow(['timestamps', 'durations', 'triggers'])
for stamp in zip(*stamps):
writer.writerow(list(stamp))
class CkgDisplayGroup:
DEFAULTS = OrderedDict([('pre', 0), ('disp', 'Infinity'), ('post', 0)])
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets counts and all contained shapes."""
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, runstate):
"""Draws all contained shapes during the appropriate interval."""
for shape in self.shapes:
shape.draw(photoburst=runstate.disp_ops['photoburst'])
def update(self, runstate):
"""Updates contained shapes, sets event triggers."""
# Set events to be sent
if runstate.disp_ops['fpst'] > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= runstate.disp_ops['fpst']:
if not runstate.disp_ops['freqcheck'] or runstate.fc_send:
runstate.events['sids'].add(n)
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(runstate.fps)
def display(self, runstate):
"""Display the group in the context described by supplied runstate."""
self.reset()
for count in range(self.pre * runstate.fps):
if runstate.window.has_exit:
break
runstate.update()
runstate.events['grp_on'] = True
if runstate.disp_ops['eyetrack']:
runstate.fix_fail = False
runstate.true_fail = False
for count in range(self.disp * runstate.fps):
if runstate.window.has_exit:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
runstate.events['grp_off'] = True
if runstate.disp_ops['eyetrack']:
if runstate.fix_fail:
runstate.true_fail = True
for count in range(self.post * runstate.fps):
if runstate.window.has_exit:
break
runstate.update()
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
|
ztangent/checkergen
|
bb5a503cb90a7de4df23d7dce000a049a3dc50d0
|
do_calibrate bugfix.
|
diff --git a/src/cli.py b/src/cli.py
index c9cf1bd..6de43ce 100644
--- a/src/cli.py
+++ b/src/cli.py
@@ -582,589 +582,589 @@ class CkgCmd(cmd.Cmd):
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_shape_attr(self.cur_group, x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.ed_parser.print_usage()
rm_parser = CmdParser(add_help=False, prog='rm',
description='''Removes checkerboards specified
by ids.''')
rm_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''ids of checkerboards in the current group
to be removed''')
rm_parser.add_argument('-a', '--all', action='store_true',
help='''remove all checkerboards in the
current group''')
def help_rm(self):
self.__class__.rm_parser.print_help()
def do_rm(self, line):
"""Removes checkerboards specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, no boards to remove'
return
try:
args = self.__class__.rm_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rm_parser.print_usage()
return
rmlist = []
if args.all:
for shape in self.cur_group.shapes:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
print "all checkerboards removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_group.shapes) or x < 0:
print "checkerboard", x, "does not exist"
continue
rmlist.append(self.cur_group.shapes[x])
print "checkerboard", x, "removed"
for shape in rmlist:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
ls_parser = CmdParser(add_help=False, prog='ls',
description='''Lists project, display group and
checkerboard settings. If no group ids
are specified, all display groups
are listed.''')
ls_parser.add_argument('gids', nargs='*', metavar='gid', type=int,
help='''ids of the display groups to be listed''')
ls_group = ls_parser.add_mutually_exclusive_group()
ls_group.add_argument('-s', '--settings', action='store_true',
help='list only project settings')
ls_group.add_argument('-g', '--groups', action='store_true',
help='list only display groups')
ls_group.add_argument('-d', '--disp_ops', action='store_true',
help='list display options')
ls_group.add_argument('-o', '--orders', action='store_true',
help='list group orderings')
def help_ls(self):
self.__class__.ls_parser.print_help()
def do_ls(self, line):
"""Lists project, display group and checkerboard settings."""
def ls_str(s, seps=[',',';']):
"""Special space-saving output formatter."""
if type(s) in [tuple, list]:
if len(seps) > 1:
newseps = seps[1:]
else:
newseps = seps
return seps[0].join([ls_str(i, newseps) for i in s])
else:
return str(s)
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.ls_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ls_parser.print_usage()
return
# Remove duplicates and ascending sort
args.gids = sorted(set(args.gids))
if len(self.cur_proj.groups) == 0:
if len(args.gids) > 0:
print 'this project has no display groups that can be listed'
return
else:
for gid in args.gids[:]:
if gid >= len(self.cur_proj.groups) or gid < 0:
args.gids.remove(gid)
print 'display group', gid, 'does not exist'
if args.gids == []:
args.gids = range(len(self.cur_proj.groups))
else:
# If any (valid) groups are specified
# don't show project settings
args.groups = True
args.show_all = not max(args.settings, args.groups,
args.disp_ops, args.orders)
if args.show_all or args.settings:
print 'PROJECT SETTINGS'.center(70,'*')
print \
'name'.rjust(16),\
'fps'.rjust(7),\
'resolution'.rjust(14),\
'bg color'.rjust(18)
print \
ls_str(self.cur_proj.name).rjust(16),\
ls_str(self.cur_proj.fps).rjust(7),\
ls_str(self.cur_proj.res).rjust(14),\
ls_str(self.cur_proj.bg).rjust(18)
print \
'pre-display'.rjust(26),\
'post-display'.rjust(26)
print \
ls_str(self.cur_proj.pre).rjust(26),\
ls_str(self.cur_proj.post).rjust(26)
print \
'cross colors'.rjust(26),\
'cross times'.rjust(26)
print \
ls_str(self.cur_proj.cross_cols).rjust(26),\
ls_str(self.cur_proj.cross_times).rjust(26)
if args.show_all:
# Insert empty line between different info sets
print ''
if args.show_all or args.disp_ops:
print 'DISPLAY OPTIONS'.center(70,'*')
for k, v in self.cur_proj.disp_ops.items():
print ''.ljust(20), ls_str(k).ljust(20), ls_str(v).ljust(20)
if args.show_all:
# Insert empty line between different info sets
print ''
if args.show_all or args.orders:
print 'GROUP ORDERINGS'.center(70,'*')
if self.cur_proj.orders == []:
order = range(len(self.cur_proj.groups))
print \
''.ljust(20),\
'default order'.ljust(20),\
ls_str(order).ljust(20)
else:
for n, order in enumerate(self.cur_proj.orders):
print \
''.ljust(20),\
'order {n}'.format(n=n).ljust(20),\
ls_str(order).ljust(20)
if args.show_all:
# Insert empty line between different info sets
print ''
if args.show_all or args.groups:
for i, n in enumerate(args.gids):
if i != 0:
# Print newline seperator between each group
print ''
group = self.cur_proj.groups[n]
print 'GROUP {n}'.format(n=n).center(70,'*')
print \
'pre-display'.rjust(20),\
'display'.rjust(20),\
'post-display'.rjust(20)
print \
ls_str(group.pre).rjust(20),\
ls_str(group.disp).rjust(20),\
ls_str(group.post).rjust(20)
if len(group.shapes) > 0:
print \
''.rjust(2),\
'shape id'.rjust(8),\
'dims'.rjust(10),\
'init_unit'.rjust(14),\
'end_unit'.rjust(14),\
'position'.rjust(14)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.dims).rjust(10),\
ls_str(shape.init_unit).rjust(14),\
ls_str(shape.end_unit).rjust(14),\
ls_str(shape.position).rjust(14)
print '\n',\
''.rjust(2),\
'shape id'.rjust(8),\
'colors'.rjust(27),\
'anchor'.rjust(12),\
'freq'.rjust(6),\
'phase'.rjust(7)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.cols).rjust(27),\
ls_str(shape.anchor).rjust(12),\
ls_str(shape.freq).rjust(6),\
ls_str(shape.phase).rjust(7)
display_parser = CmdParser(add_help=False, prog='display',
description='''Displays the stimulus in a
window or in fullscreen.''')
display_parser.add_argument('-s', '--save', action='store_true',
help='''save specified display flags
as default flags for project
instead of presenting stimulus''')
display_parser.add_argument('-n', '--name', metavar='FOOBAR',
help='''name of log file to be written''')
display_parser.add_argument('-r', '--repeats', metavar='N', type=int,
help='''repeatedly display specified display
groups N number of times''')
display_parser.add_argument('-wl', '--waitless', action=store_truth(),
metavar='t/f',
help='''do not add waitscreens before the
start of each repeat''')
display_parser.add_argument('-f', '--fullscreen', action=store_truth(),
metavar='t/f',
help='sets fullscreen mode, ESC to quit')
display_parser.add_argument('-p', '--priority', metavar='LEVEL',
help='''set priority while displaying,
higher priority results in
less dropped frames (choices:
0-3, low, normal, high,
realtime)''')
display_parser.add_argument('-pt', '--phototest', action=store_truth(),
metavar='t/f',
help='''draw white test rectangle in topleft
corner of screen when groups become
visible for a photodiode to detect''')
display_parser.add_argument('-pb', '--photoburst', action=store_truth(),
metavar='t/f',
help='''make checkerboards only draw first
color for one frame to facilitate
testing with a photodiode''')
display_parser.add_argument('-lt', '--logtime', action=store_truth(),
metavar='t/f',
help='output frame timestamps to a log file')
display_parser.add_argument('-ld', '--logdur', action=store_truth(),
metavar='t/f',
help='output frame durations to a log file')
display_parser.add_argument('-ss', '--trigser', action=store_truth(),
metavar='t/f',
help='''send triggers through the serial port
when shapes are being displayed''')
display_parser.add_argument('-sp', '--trigpar', action=store_truth(),
metavar='t/f',
help='''send triggers through the parallel port
when shapes are being displayed''')
display_parser.add_argument('-fpst', metavar='M', type=int,
help='''unique trigger corresponding to a
checkerboard is sent after the shape
undergoes M color flips (default:
disabled, M=0)''')
display_parser.add_argument('-fc', '--freqcheck', action=store_truth(),
metavar='t/f',
help='''only send triggers for board color
flips at the start, middle and end
of the run''')
display_parser.add_argument('-et', '--eyetrack', action=store_truth(),
metavar='t/f',
help='''use eyetracking to ensure that subject
fixates on the cross in the center''')
display_parser.add_argument('-eu', '--etuser', action=store_truth(),
metavar='t/f',
help='''allow user to select eyetracking video
source from a dialog''')
display_parser.add_argument('-ev', '--etvideo', metavar='path',
help='''path (with no spaces) to eyetracking
video file to be used as the source''')
display_parser.add_argument('-ta', '--tryagain', metavar='I', type=int,
help='''append groups during which subject
failed to fixate up to I times to the
list of groups to be displayed
(default: disabled, I=0)''')
display_parser.add_argument('-tb', '--trybreak', metavar='J', type=int,
help='''used with --tryagain, append a wait
screen to the list of groups to be
displayed after every J groups have
been appended to the list (default:
J=total number of groups)''')
display_parser.add_argument('-nl', '--nolog', action=store_truth(),
metavar='t/f',
help='''do not write a log file''')
display_parser.add_argument('order', nargs='*', metavar='id', type=int,
help='''order in which groups should be
displayed (default: random order
from list of orders if specified
in project, ascending otherwise)''')
def help_display(self):
self.__class__.display_parser.print_help()
def do_display(self, line):
"""Displays the stimulus in a window or in fullscreen"""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.display_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
if len(args.order) > 0:
for i in set(args.order):
if i >= len(self.cur_proj.groups) or i < -1:
print 'error: group', i, 'does not exist'
return
if args.eyetrack and eyetracking.available:
if not eyetracking.is_calibrated():
try:
self.do_calibrate('',query=True)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
return
if args.save:
self.cur_proj.set_display_flags(repeats=args.repeats,
waitless=args.waitless,
fullscreen=args.fullscreen,
priority=args.priority,
logtime=args.logtime,
logdur=args.logdur,
trigser=args.trigser,
trigpar=args.trigpar,
fpst=args.fpst,
freqcheck=args.freqcheck,
phototest=args.phototest,
photoburst=args.photoburst,
eyetrack=args.eyetrack,
etuser=args.etuser,
etvideo=args.etvideo,
tryagain=args.tryagain,
trybreak=args.trybreak,
nolog=args.nolog)
print "display flags saved to project"
else:
print "displaying...",
try:
self.cur_proj.display(name=args.name,
repeats=args.repeats,
waitless=args.waitless,
fullscreen=args.fullscreen,
priority=args.priority,
logtime=args.logtime,
logdur=args.logdur,
trigser=args.trigser,
trigpar=args.trigpar,
fpst=args.fpst,
freqcheck=args.freqcheck,
phototest=args.phototest,
photoburst=args.photoburst,
eyetrack=args.eyetrack,
etuser=args.etuser,
etvideo=args.etvideo,
tryagain=args.tryagain,
trybreak=args.trybreak,
nolog=args.nolog,
order=args.order)
except (IOError, NotImplementedError,
eyetracking.EyetrackingError):
print ''
print "error:", str(sys.exc_value)
if args.priority != None:
try:
priority.set('normal')
except:
pass
return
print "done"
export_parser = CmdParser(add_help=False, prog='export',
description='''Exports stimulus as an image
sequence (in a folder) to the
specified directory.''')
export_parser.add_argument('-n','--nofolder',
dest='folder', action='store_false',
help='''force images not to exported in
a containing folder''')
export_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly export specified display
groups N number of times''')
export_parser.add_argument('duration', nargs='?',
type=to_decimal, default='Infinity',
help='''number of seconds of the stimulus
that should be exported (default:
as long as the entire stimulus)''')
export_parser.add_argument('dir', nargs='?', default=os.getcwd(),
help='''destination directory for export
(default: current working directory)''')
export_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be exported
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_export(self):
self.__class__.export_parser.print_help()
def do_export(self, line):
"""Exports stimulus as an image sequence to the specified directory."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.export_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.export_parser.print_usage()
return
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < 0:
print 'error: group', i, 'does not exist'
return
groupq = [self.cur_proj.groups[i] for i in args.idlist]
else:
groupq = list(self.cur_proj.groups)
if args.repeat != None:
groupq = list(groupq * args.repeat)
try:
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
folder=args.folder)
except IOError:
print "error:", str(sys.exc_value)
return
except core.FrameOverflowError:
print "warning:", str(sys.exc_value)
print "Are you sure you want to continue?"
while True:
try:
if self.__class__.yn_parse(raw_input()):
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
folder=args.folder,
force=True)
break
else:
return
except TypeError:
print str(sys.exc_value)
except EOFError:
return
print "Export done."
def do_calibrate(self, line, query=False):
"""Calibrate subject for eyetracking, or load a calibration file."""
if not eyetracking.available:
print "error: eyetracking functionality not available"
return
if query:
print "path to calibration file (leave empty for GUI tool):"
try:
path = raw_input().strip().strip('"\'')
except EOFError:
msg = "calibration cancelled"
raise eyetracking.EyetrackingError(msg)
else:
path = line.strip().strip('"\'')
if len(path) == 0:
path = None
if not eyetracking.is_source_ready():
# Select default source if none has been selected
eyetracking.select_source()
try:
eyetracking.calibrate(path)
except eyetracking.EyetrackingError:
if query:
raise
else:
print "error:", str(sys.exc_value)
return
- if len(path) > 0:
+ if path!= None and len(path) > 0:
print "calibration file successfully loaded"
etsetup_parser = CmdParser(add_help=False, prog='etsetup',
description='''Set various eyetracking
parameters.''')
etsetup_parser.add_argument('-fp', '--fixperiod', type=int, metavar='MS',
help='''time in milliseconds subject
has to stare at the same spot
for fixation to be detected''')
etsetup_parser.add_argument('-fr', '--fixrange', type=float, metavar='MM',
help='''distance in mm beyond which the
eye position cannot change for
a fixation to be detected''')
etsetup_parser.add_argument('-s', '--size', metavar='WIDTH,HEIGHT',
action=store_list(2, ',', float),
help='physical screen dimensions in mm')
etsetup_parser.add_argument('-vd', '--viewdist', type=int, metavar='MM',
help='''viewing distance between subject's
eyes and the screen''')
def help_etsetup(self):
self.__class__.etsetup_parser.print_help()
def do_etsetup(self, line):
try:
args = self.__class__.etsetup_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.etsetup_parser.print_usage()
return
try:
eyetracking.setup(viewing_distance=args.viewdist,
screen_dims=args.size,
fixation_period=args.fixperiod,
fixation_range=args.fixrange)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
def do_pwd(self, line):
"""Prints the current working directory."""
print os.getcwd()
def do_cd(self, line):
"""Change working directory to specified path."""
path = line.strip().strip('"\'')
if not os.path.isdir(path):
print "error: specified path is not a directory"
return
os.chdir(path)
def do_quit(self, line):
"""Quits the program."""
if self.save_check():
return
return True
def help_EOF(self):
print "Typing {0} issues this command, which quits the program."\
.format(CMD_EOF_STRING)
def do_EOF(self, line):
"""Typing Ctrl-D issues this command, which quits the program."""
print '\r'
if self.save_check():
return
return True
def help_help(self):
print 'Prints a list of commands.'
print "Type 'help <topic>' for more details on each command."
def default(self, line):
command = line.split()[0]
print \
"'{0}' is not a checkergen command.".format(command),\
"Type 'help' for a list of commands"
|
ztangent/checkergen
|
3de1b0e44315c682f6df9eaf364d40d22fc17068
|
Made is_tracked and is_fixated far less flippant.
|
diff --git a/src/core.py b/src/core.py
index 6d96194..12a11fb 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,1236 +1,1233 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import copy
import random
import itertools
from datetime import datetime
from xml.dom import minidom
import pyglet
import graphics
import priority
import trigger
import eyetracking
from utils import *
# Use OrderedDict substitute if we don't have Python 2.7
if sys.version_info < (2, 7):
from odict import OrderedDict
else:
from collections import OrderedDict
CKG_FMT = 'ckg'
LOG_FMT = 'log'
MAX_EXPORT_FRAMES = 100000
EXPORT_DIR_SUFFIX = '-anim'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
INT_HALF_PERIODS = True
-FIX_POS = (0, 0)
-FIX_RANGE = (20, 20)
-FIX_PER = 350
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = OrderedDict([('name', 'untitled'),
('fps', 60),
('res', (800, 600)),
('bg', (127, 127, 127)),
('pre', 0),
('post', 0),
('cross_cols', ((0, 0, 0), (255, 0, 0))),
('cross_times', ('Infinity', 1)),
('orders', []),
('disp_ops', None)])
DEFAULTS['disp_ops'] = OrderedDict([('repeats', 1),
('waitless', False),
('fullscreen', False),
('priority', None),
('logtime', False),
('logdur', False),
('trigser', False),
('trigpar', False),
('fpst', 0),
('freqcheck', False),
('phototest', False),
('photoburst', False),
('eyetrack', False),
('etuser', False),
('etvideo', None),
('tryagain', 0),
('trybreak', None),
('nolog', False)])
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def set_display_flags(self, **keywords):
"""Set default display flags for the project.
Same arguments as 'display', excluding 'name' and 'order'.
"""
for kw in keywords.keys():
if kw in self.disp_ops.keys() and keywords[kw] != None:
self.disp_ops[kw] = keywords[kw]
self._dirty = True
def set_group_orders(self, orders):
for order in orders:
for gid in order:
if gid < -1 or gid >= len(self.groups):
msg = 'invalid group id (out of range)'
raise ValueError(msg)
self.orders = orders
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
# Vars that are dicts
dicts_to_load = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_load = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
for d_name in dicts_to_load:
d = copy.deepcopy(self.__class__.DEFAULTS[d_name])
try:
d_el = [node for node in project.childNodes if
node.localName == d_name and
node.namespaceURI == XML_NAMESPACE][0]
for var in d.keys():
try:
d[var] = eval(xml_get(d_el, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}' in '{1}'".\
format(var, d_name)
print "using default value '{0}' instead...".\
format(d[var])
except IndexError:
print "warning: missing attribute set '{0}'".format(d_name)
print "using default values instead..."
setattr(self, d_name, d)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
# Vars that are dicts
dicts_to_save = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_save = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for d_name in dicts_to_save:
d_el = doc.createElement(d_name)
project.appendChild(d_el)
d = getattr(self, d_name)
for k, v in d.iteritems():
xml_set(doc, d_el, k, repr(v))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, **keywords):
"""Displays the project animation on the screen.
name -- name that logfile will be saved with
repeats -- number of times specified order of display groups should
be repeated
waitless -- if true, no waitscreens will appear at the start of each
repeat
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
priority -- priority level to which process should be raised
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
trigser -- send triggers through serial port when each group is shown
trigpar -- send triggers through parallel port when each group is shown
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
freqcheck -- send fpst only at the start, the middle, and the end
for sanity checking of display and trigger fps
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- append a wait screen to the group queue every time
after this many groups have been appended to the queue
order -- order in which groups (specified by id) will be displayed
"""
# Create RunState
disp_ops = copy.deepcopy(self.disp_ops)
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'name' in keywords.keys() and keywords['name'] != None:
name = keywords['name']
else:
timestr = datetime.today().strftime('_%Y-%m-%d_%H-%M-%S')
name = self.name + timestr
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
waitscreen = CkgWaitScreen()
# Set order id to be sent if necessary
if order in self.orders:
runstate.events['ord_id'] = self.orders.index(order)
# Count through pre
for count in range(self.pre * self.fps):
if runstate.window.has_exit:
break
runstate.update()
# Loop through repeats
repeats = runstate.disp_ops['repeats']
ord_len = len(runstate.order)
for i in range(repeats):
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
# Loop through display groups
runstate.events['blk_on'] = True
for n, gid in enumerate(runstate.order):
# Set flag for freqcheck
if runstate.disp_ops['freqcheck']:
if ((i == 0 and n == 0) or
(i == repeats-1 and n == ord_len-1) or
(i == repeats//2 and n == ord_len//2)):
runstate.fc_send = True
else:
runstate.fc_send = False
if gid == -1:
waitscreen.reset()
waitscreen.display(runstate)
else:
self.groups[gid].display(runstate)
# Append failed groups
if runstate.disp_ops['eyetrack'] and runstate.true_fail:
if len(runstate.add_gids) < runstate.disp_ops['tryagain']:
runstate.add_gids.append(gid)
else:
runstate.fail_gids.append(gid)
runstate.events['blk_off'] = True
# Loop through added groups
if runstate.disp_ops['eyetrack']:
for blk in grouper(runstate.add_gids,
runstate.disp_ops['trybreak']):
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
runstate.events['blk_on'] = True
# Loop through display groups
for gid in blk:
if gid != None:
self.groups[gid].display(runstate)
runstate.events['blk_off'] = True
# Count through post
for count in range(self.post * self.fps):
if runstate.window.has_exit:
break
runstate.update()
# Stop and output log
runstate.stop()
if not runstate.disp_ops['nolog']:
runstate.log()
def export(self, export_dir, export_duration, groupq=[],
folder=True, force=False):
if not os.path.isdir(export_dir):
msg = 'export path is not a directory'
raise IOError(msg)
# Set-up groups and variables that control their display
if groupq == []:
groupq = list(self.groups)
n = -1
groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Limit export duration to display duration
frames = export_duration * self.fps
frames = min(frames, disp_end)
# Warn user if a lot of frames will be exported
if frames > MAX_EXPORT_FRAMES and not force:
msg = 'very large number ({0}) of frames to be exported'.\
format(frames)
raise FrameOverflowError(msg)
# Create folder to store images if necessary
if folder:
export_dir = os.path.join(export_dir,
self.name + EXPORT_DIR_SUFFIX)
if not os.path.isdir(export_dir):
os.mkdir(export_dir)
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Set up canvas and framebuffer object
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
# Main loop
while count < frames:
fbo.clear()
if groups_visible:
# Get next group from queue
if n < 0 or groupq[n].over:
n += 1
if n >= len(groupq):
groups_visible = False
else:
groupq[n].reset()
# Draw and then update group
if n >= 0:
groupq[n].draw()
groupq[n].update(fps=self.fps, fpst=0)
# Draw fixation cross based on current count
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Save current frame to file
savepath = \
os.path.join(export_dir,
'{0}{2}.{1}'.
format(self.name, 'png',
repr(count).zfill(numdigits(frames-1))))
canvas.save(savepath)
# Increment count and set whether groups should be shown
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
fbo.delete()
class CkgRunState:
"""Contains information about the state of a checkergen project
when it is being displayed or exported."""
DEFAULTS = dict([('name', 'untitled'),
('res', None),
('fps', None),
('bg', None),
('cross_cols', None),
('cross_times', None),
('order', []),
('disp_ops', None),
('events', None),
('add_gids', []),
('fail_gids', []),
('timestamps', []),
('durstamps', []),
('trigstamps', [])])
DEFAULTS['events'] = dict([('ord_id', None),
('blk_on', False),
('blk_off', False),
('track_on', False),
('track_off', False),
('fix_on', False),
('fix_off', False),
('grp_on', False),
('grp_off', False),
('sids', set())])
def __init__(self, **keywords):
"""Creates the RunState."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
def start(self):
"""Initialize all subsystems and start the run."""
if self.disp_ops == None:
msg = "RunState lacks display options"
raise ValueError(msg)
if min(self.res, self.fps, self.bg,
self.cross_cols, self.cross_times) == None:
msg = "RunState intialized with insufficent project information"
raise ValueError(msg)
self._count = 0
# Flag used by freqcheck
self.fc_send = False
# Create fixation crosses
self.fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if self.disp_ops['phototest']:
self.test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Initialize ports
if self.disp_ops['trigser']:
if not trigger.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trigpar']:
if not trigger.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
trigger.init(self.disp_ops['trigser'], self.disp_ops['trigpar'])
# Initialize eyetracking
if self.disp_ops['eyetrack']:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trybreak'] == None:
self.disp_ops['trybreak'] = len(self.order)
self.fixated = False
self.old_fixated = False
self.tracked = False
self.old_tracked = False
self.fix_fail = False
self.true_fail = False
eyetracking.select_source(self.disp_ops['etuser'],
self.disp_ops['etvideo'])
eyetracking.start()
# Stretch to fit screen only if project res does not equal screen res
self.scaling = False
if self.disp_ops['fullscreen']:
self.window = pyglet.window.Window(fullscreen=True, visible=False)
if (self.window.width, self.window.height) != self.res:
self.scaling = True
else:
self.window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
self.keystates = pyglet.window.key.KeyStateHandler()
self.window.push_handlers(self.keystates)
# Clear window and make visible
self.window.switch_to()
graphics.set_clear_color(self.bg)
self.window.clear()
self.window.set_visible()
# Create framebuffer object for drawing unscaled scene
if self.scaling:
self.canvas = pyglet.image.Texture.create(*self.res)
self.fbo = graphics.Framebuffer(self.canvas)
self.fbo.start_render()
graphics.set_clear_color(self.bg)
self.fbo.clear()
# Set process priority
if self.disp_ops['priority'] != None:
if not priority.available[sys.platform]:
msg = "setting priority not available on {0}".\
format(sys.platform)
raise NotImplementedError(msg)
else:
try:
priority.set(self.disp_ops['priority'])
except ValueError:
priority.set(int(self.disp_ops['priority']))
# Start timers
if self.disp_ops['logtime']:
self.timer = Timer()
self.timer.start()
if self.disp_ops['logdur']:
self.dur = Timer()
self.dur.start()
def update(self):
"""Update the RunState."""
# Check for tracking and fixation
if self.disp_ops['eyetrack']:
self.old_tracked = self.tracked
- self.tracked = eyetracking.is_tracked()
+ self.tracked = eyetracking.is_tracked(self.fps)
self.old_fixated = self.fixated
- self.fixated = eyetracking.is_fixated(FIX_POS, FIX_RANGE, FIX_PER)
+ self.fixated = eyetracking.is_fixated(self.fps)
if self.fixated:
# Draw normal cross color if fixating
self.fix_crosses[0].draw()
else:
# Draw alternative cross color if not fixating
self.fix_crosses[1].draw()
# Update eyetracking events
if self.tracked != self.old_tracked:
if self.tracked:
self.events['track_on'] = True
else:
self.events['track_off'] = True
if self.fixated != self.old_fixated:
if self.fixated:
self.events['fix_on'] = True
else:
self.events['fix_off'] = True
# Check for failure of trial
if self.tracked and not self.fixated:
self.fix_fail = True
else:
# Change cross color based on time
if (self._count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
self.fix_crosses[0].draw()
else:
self.fix_crosses[1].draw()
# Blit canvas to screen if necessary
if self.scaling:
self.fbo.end_render()
self.canvas.blit(0, 0)
self.window.switch_to()
self.window.dispatch_events()
self.window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to lists
if self.disp_ops['logtime']:
self.timestamps.append(self.timer.elapsed())
elif self.disp_ops['logdur']:
self.timestamps.append('')
if self.disp_ops['logdur']:
self.durstamps.append(self.dur.restart())
elif self.disp_ops['logtime']:
self.durstamps.append('')
# Send trigger ASAP after flip
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
if self.encode_events() > 0:
trigger.send(self.disp_ops['trigser'],
self.disp_ops['trigpar'],
self.encode_events())
# Log when triggers are sent
if self.disp_ops['logtime'] and self.encode_events() > 0:
self.trigstamps.append(self.encode_events())
else:
self.trigstamps.append('')
# Clear canvas, events, prepare for next frame
if self.scaling:
self.fbo.start_render()
self.fbo.clear()
else:
self.window.clear()
self.events = copy.deepcopy(self.__class__.DEFAULTS['events'])
self._count += 1
def stop(self):
"""Clean up RunState."""
if self.disp_ops['eyetrack']:
eyetracking.stop()
if self.scaling:
self.fbo.delete()
del self.canvas
self.window.close()
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
trigger.quit(self.disp_ops['trigser'], self.disp_ops['trigpar'])
if self.disp_ops['priority'] != None:
priority.set('normal')
def encode_events(self):
"""Hard code specific trigger values for events."""
code = 0
if self.events['ord_id'] != None:
code = self.events['ord_id'] + 1
elif self.events['blk_on']:
code = 128
elif self.events['blk_off']:
code = 127
else:
mult = 0
if self.events['fix_on']:
mult = 4
elif self.events['track_on']:
mult = 3
if self.events['track_off']:
mult = 1
elif self.events['fix_off']:
mult = 2
if self.events['grp_on']:
code = 100 + mult
elif self.events['grp_off']:
code = 90 + mult
elif len(self.events['sids']) > 0:
code = ((0 in self.events['sids'])*2**0 +
(1 in self.events['sids'])*2**1 +
(2 in self.events['sids'])*2**2 +
(3 in self.events['sids'])*2**3)
code = mult*16 + code
elif mult > 0:
code = 110 + mult
return code
def log(self, path=None):
"""Write a log file for the experimental run in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, LOG_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(LOG_FMT):
path = '{0}.{1}'.format(path, LOG_FMT)
with open(path, 'wb') as logfile:
writer = csv.writer(logfile, dialect='excel-tab')
writer.writerow(['checkergen log file'])
writer.writerow(['display options:'])
writer.writerow(self.disp_ops.keys())
writer.writerow(self.disp_ops.values())
writer.writerow(['order:'] + self.order)
if self.disp_ops['eyetrack']:
writer.writerow(['groups added'])
for blk in grouper(self.add_gids,
self.disp_ops['trybreak'], ''):
writer.writerow(blk)
writer.writerow(['groups failed'])
for blk in grouper(self.fail_gids,
self.disp_ops['trybreak'], ''):
writer.writerow(blk)
if self.disp_ops['logtime'] or self.disp_ops['logdur']:
stamps = [self.timestamps, self.durstamps, self.trigstamps]
writer.writerow(['timestamps', 'durations', 'triggers'])
for stamp in zip(*stamps):
writer.writerow(list(stamp))
class CkgDisplayGroup:
DEFAULTS = OrderedDict([('pre', 0), ('disp', 'Infinity'), ('post', 0)])
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets counts and all contained shapes."""
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, runstate):
"""Draws all contained shapes during the appropriate interval."""
for shape in self.shapes:
shape.draw(photoburst=runstate.disp_ops['photoburst'])
def update(self, runstate):
"""Updates contained shapes, sets event triggers."""
# Set events to be sent
if runstate.disp_ops['fpst'] > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= runstate.disp_ops['fpst']:
if not runstate.disp_ops['freqcheck'] or runstate.fc_send:
runstate.events['sids'].add(n)
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(runstate.fps)
def display(self, runstate):
"""Display the group in the context described by supplied runstate."""
self.reset()
for count in range(self.pre * runstate.fps):
if runstate.window.has_exit:
break
runstate.update()
runstate.events['grp_on'] = True
if runstate.disp_ops['eyetrack']:
runstate.fix_fail = False
runstate.true_fail = False
for count in range(self.disp * runstate.fps):
if runstate.window.has_exit:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
runstate.events['grp_off'] = True
if runstate.disp_ops['eyetrack']:
if runstate.fix_fail:
runstate.true_fail = True
for count in range(self.post * runstate.fps):
if runstate.window.has_exit:
break
runstate.update()
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.steps_done = 0
def draw(self, runstate):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, runstate):
"""Checks for keypress, sends trigger upon end."""
if max([runstate.keystates[key] for
key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
def display(self, runstate):
"""Displays waitscreen in context described by supplied runstate."""
while self.steps_done < self.num_steps:
if runstate.window.has_exit:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = OrderedDict([('dims', (5, 5)),
('init_unit', (30, 30)),
('end_unit', (50, 50)),
('position', (0, 0)),
('anchor', 'bottomleft'),
('cols', ((0, 0, 0), (255, 255, 255))),
('freq', 1),
('phase', 0)])
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
if INT_HALF_PERIODS:
frames_per_half_period = round(fps / (self.freq * 2))
degs_per_frame = 180 / to_decimal(frames_per_half_period)
else:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
anchor=self.anchor)
cur_unit_rect.col = self.cols[(i + j) % 2]
cur_unit_rect.add_to_batch(self._batches[0])
cur_unit_rect.col = self.cols[(i + j + 1) % 2]
cur_unit_rect.add_to_batch(self._batches[1])
# Increase x values
cur_unit_pos[0] += \
graphics.locations[self.anchor][0] * cur_unit[0]
cur_unit[0] += unit_grad[0]
# Reset x values
cur_unit_pos[0] = init_pos[0]
cur_unit[0] = init_unit[0]
# Increase y values
cur_unit_pos[1] += \
graphics.locations[self.anchor][1] * cur_unit[1]
cur_unit[1] += unit_grad[1]
self._computed = True
def draw(self, photoburst=False, always_compute=False):
"""Draws appropriate batch depending on current phase.
photoburst -- draw first color for only one frame for testing purposes
always_compute -- recompute what the checkerboard should look like
every frame
"""
if not self._computed or always_compute:
self.compute()
self._cur_phase %= 360
n = int(self._cur_phase // 180)
if photoburst and n == 0 and not self.flipped:
n = 1
self._batches[n].draw()
def lazydraw(self):
"""Only draws on color reversal."""
cur_n = int(self._cur_phase // 180)
diff --git a/src/eyetracking.py b/src/eyetracking.py
index 4d8b4a0..60ebc0c 100644
--- a/src/eyetracking.py
+++ b/src/eyetracking.py
@@ -1,164 +1,195 @@
"""Provides support for CRS VideoEyetracker Toolbox."""
import os.path
+from utils import *
+
+FIX_POS = (0, 0)
+FIX_RANGE = (20, 20)
+FIX_PER = 300
+TRACK_PER = 300
+
try:
import win32com.client
available = True
except ImportError:
available = False
# COM ProgID of the Toolbox
ProgID = "crsVET.VideoEyeTracker"
RecordName = "etResultSet"
# VET application object
VET = None
class EyetrackingError(Exception):
"""Raised when something goes wrong with VET."""
pass
if available:
# Try dispatching object, else unavailable
try:
from win32com.client import gencache
# Ensure makepy module is generated
gencache.EnsureModule('{248DBF0C-A874-4032-82CE-DC5B307BB6E7}',
0, 3, 11)
VET = win32com.client.Dispatch(ProgID)
DummyResultSet = win32com.client.Record(RecordName, VET)
except:
available = False
if available:
# For easier access to constants and standardization with MATLAB interface
CRS = win32com.client.constants
- lastgoodstamp = 0
+ lastfixstatus = False
+ fixcount = 0
+ lasttrackstatus = False
+ trackcount = 0
def select_source(user_select = False, path = None):
if user_select:
if not VET.SelectVideoSource(CRS.vsUserSelect, ''):
msg = 'could not select video source'
raise EyetrackingError(msg)
elif path != None:
# Open from file
if not VET.SelectVideoSource(CRS.vsFile, path):
msg = 'could not use path as video source'
raise EyetrackingError(msg)
else:
# Default to 250 Hz High Speed Camera
if not VET.SelectVideoSource(CRS.vsHighSpeedCamera250, ''):
msg = 'could not select video source'
raise EyetrackingError(msg)
def is_source_ready():
"""Returns true if a video source has been selected."""
if VET.VideoSourceType == 0:
return False
else:
return True
def show_camera():
VET.CreateCameraScreen(0)
def quit_camera():
VET.DestroyCameraScreen()
def setup(viewing_distance=None, screen_dims=None,
fixation_period=None, fixation_range=None):
"""Calibrates the display and sets fixation properties."""
if viewing_distance != None and screen_dims != None:
if len(screen_dims) != 2:
msg = 'screen_dims must be a 2-tuple'
raise ValueError(msg)
VET.SetDeviceParameters(CRS.deUser, viewing_distance,
screen_dims[0], screen_dims[1])
if fixation_period != None:
VET.FixationPeriod = fixation_period
if fixation_range != None:
VET.FixationRange = fixation_range
def calibrate(path = None):
"""Calibrate the subject.
Optionally supply a path with no spaces to a
calibration file to load."""
if not is_source_ready():
select_source()
if not VET.Tracking:
VET.ClearDataBuffer()
VET.StartTracking()
if path == None:
if not VET.Calibrate():
msg = 'calibration failed'
raise EyetrackingError(msg)
else:
if not os.path.isfile(path):
msg = 'specified file does not exist'
raise EyetrackingError(msg)
if not VET.LoadCalibrationFile(path):
msg = 'file could not be loaded'
raise EyetrackingError(msg)
if not is_calibrated():
msg = 'calibration failed'
raise EyetrackingError(msg)
def is_calibrated():
if VET.CalibrationStatus()[0] != 0:
return True
else:
return False
def start():
"""Start tracking the eye."""
global lastgoodstamp
if not is_source_ready():
select_source()
if not is_calibrated():
msg = 'subject not yet calibrated'
raise EyetrackingError(msg)
lastgoodstamp = 0
VET.ClearDataBuffer()
VET.StartTracking()
def stop():
"""Stop tracking the eye."""
VET.StopTracking()
- def is_tracked():
- """Returns true if the eye is being tracked."""
+ def is_tracked(fps, track_period=TRACK_PER):
+ """Returns true if the eye is being tracked.
+
+ fps -- frames per second at which stimulus is running
+
+ track_period -- duration in milliseconds during which eye has to
+ be consistently tracked or untracked in order for value returned
+ by this function to change
+
+ """
+ global lasttrackstatus
+ global trackcount
data = VET.GetLatestEyePosition(DummyResultSet)[1]
- return data.Tracked
+ if data.Tracked != lasttrackstatus:
+ trackcount += 1
+ else:
+ trackcount = 0
+ if trackcount >= track_period / to_decimal(1000) * fps:
+ trackcount = 0
+ lasttrackstatus = data.Tracked
+ return lasttrackstatus
- def is_fixated(fix_pos, fix_range, fix_period):
- """Checks whether subject is fixating on specificied location.
+ def is_fixated(fps, fix_pos=FIX_POS,
+ fix_range=FIX_RANGE,
+ fix_period=FIX_PER):
+ """Checks whether subject is fixating on specified location.
+
+ fps -- frames per second at which stimulus is running
fix_pos -- (x, y) position of desired fixation location in mm
from center of screen
fix_range -- (width, height) of box surrounding fix_pos within
which fixation is allowed (in mm)
- fix_period -- duration in milliseconds within which subject is
- assumed to continue fixating after fixation is detected at a
- specific time
+ fix_period -- duration in milliseconds during which eye has to
+ be consistently fixated or not fixated in order for value returned
+ by this function to change
"""
- global lastgoodstamp
- if VET.CalibrationStatus()[0] == 0:
- msg = 'subject not yet calibrated'
- raise EyetrackingError(msg)
+ global lastfixstatus
+ global fixcount
data = VET.GetLatestEyePosition(DummyResultSet)[1]
pos = (data.ScreenPositionXmm, data.ScreenPositionYmm)
diff = [abs(p - fp) for p, fp in zip(pos, fix_pos)]
+ curfixstatus = False
if data.Tracked == True:
if diff[0] < fix_range[0] and diff[1] < fix_range[1]:
- lastgoodstamp = data.TimeStamp
- return True
- elif (data.Timestamp - lastgoodstamp) <= fix_period:
- return True
- elif (data.Timestamp - lastgoodstamp) <= fix_period:
- return True
-
- return False
+ curfixstatus = True
+ if curfixstatus != lastfixstatus:
+ fixcount += 1
+ else:
+ fixcount = 0
+ if fixcount >= fix_period / to_decimal(1000) * fps:
+ fixcount = 0
+ lastfixstatus = curfixstatus
+ return lastfixstatus
|
ztangent/checkergen
|
39cc97a6c749fc0bf94f9357448bfb9c9da37364
|
Change log file format back to .log from .csv.
|
diff --git a/src/core.py b/src/core.py
index dcd91ce..6d96194 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,552 +1,552 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import copy
import random
import itertools
from datetime import datetime
from xml.dom import minidom
import pyglet
import graphics
import priority
import trigger
import eyetracking
from utils import *
# Use OrderedDict substitute if we don't have Python 2.7
if sys.version_info < (2, 7):
from odict import OrderedDict
else:
from collections import OrderedDict
CKG_FMT = 'ckg'
-LOG_FMT = 'csv'
+LOG_FMT = 'log'
MAX_EXPORT_FRAMES = 100000
EXPORT_DIR_SUFFIX = '-anim'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
INT_HALF_PERIODS = True
FIX_POS = (0, 0)
FIX_RANGE = (20, 20)
FIX_PER = 350
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = OrderedDict([('name', 'untitled'),
('fps', 60),
('res', (800, 600)),
('bg', (127, 127, 127)),
('pre', 0),
('post', 0),
('cross_cols', ((0, 0, 0), (255, 0, 0))),
('cross_times', ('Infinity', 1)),
('orders', []),
('disp_ops', None)])
DEFAULTS['disp_ops'] = OrderedDict([('repeats', 1),
('waitless', False),
('fullscreen', False),
('priority', None),
('logtime', False),
('logdur', False),
('trigser', False),
('trigpar', False),
('fpst', 0),
('freqcheck', False),
('phototest', False),
('photoburst', False),
('eyetrack', False),
('etuser', False),
('etvideo', None),
('tryagain', 0),
('trybreak', None),
('nolog', False)])
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def set_display_flags(self, **keywords):
"""Set default display flags for the project.
Same arguments as 'display', excluding 'name' and 'order'.
"""
for kw in keywords.keys():
if kw in self.disp_ops.keys() and keywords[kw] != None:
self.disp_ops[kw] = keywords[kw]
self._dirty = True
def set_group_orders(self, orders):
for order in orders:
for gid in order:
if gid < -1 or gid >= len(self.groups):
msg = 'invalid group id (out of range)'
raise ValueError(msg)
self.orders = orders
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
# Vars that are dicts
dicts_to_load = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_load = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
for d_name in dicts_to_load:
d = copy.deepcopy(self.__class__.DEFAULTS[d_name])
try:
d_el = [node for node in project.childNodes if
node.localName == d_name and
node.namespaceURI == XML_NAMESPACE][0]
for var in d.keys():
try:
d[var] = eval(xml_get(d_el, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}' in '{1}'".\
format(var, d_name)
print "using default value '{0}' instead...".\
format(d[var])
except IndexError:
print "warning: missing attribute set '{0}'".format(d_name)
print "using default values instead..."
setattr(self, d_name, d)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
# Vars that are dicts
dicts_to_save = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_save = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for d_name in dicts_to_save:
d_el = doc.createElement(d_name)
project.appendChild(d_el)
d = getattr(self, d_name)
for k, v in d.iteritems():
xml_set(doc, d_el, k, repr(v))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, **keywords):
"""Displays the project animation on the screen.
name -- name that logfile will be saved with
repeats -- number of times specified order of display groups should
be repeated
waitless -- if true, no waitscreens will appear at the start of each
repeat
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
priority -- priority level to which process should be raised
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
trigser -- send triggers through serial port when each group is shown
trigpar -- send triggers through parallel port when each group is shown
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
freqcheck -- send fpst only at the start, the middle, and the end
for sanity checking of display and trigger fps
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- append a wait screen to the group queue every time
after this many groups have been appended to the queue
order -- order in which groups (specified by id) will be displayed
"""
# Create RunState
disp_ops = copy.deepcopy(self.disp_ops)
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'name' in keywords.keys() and keywords['name'] != None:
name = keywords['name']
else:
timestr = datetime.today().strftime('_%Y-%m-%d_%H-%M-%S')
name = self.name + timestr
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
waitscreen = CkgWaitScreen()
# Set order id to be sent if necessary
if order in self.orders:
runstate.events['ord_id'] = self.orders.index(order)
# Count through pre
for count in range(self.pre * self.fps):
if runstate.window.has_exit:
break
runstate.update()
# Loop through repeats
repeats = runstate.disp_ops['repeats']
ord_len = len(runstate.order)
for i in range(repeats):
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
# Loop through display groups
runstate.events['blk_on'] = True
for n, gid in enumerate(runstate.order):
# Set flag for freqcheck
if runstate.disp_ops['freqcheck']:
if ((i == 0 and n == 0) or
(i == repeats-1 and n == ord_len-1) or
(i == repeats//2 and n == ord_len//2)):
runstate.fc_send = True
else:
runstate.fc_send = False
if gid == -1:
waitscreen.reset()
waitscreen.display(runstate)
else:
self.groups[gid].display(runstate)
# Append failed groups
if runstate.disp_ops['eyetrack'] and runstate.true_fail:
if len(runstate.add_gids) < runstate.disp_ops['tryagain']:
runstate.add_gids.append(gid)
else:
runstate.fail_gids.append(gid)
runstate.events['blk_off'] = True
# Loop through added groups
if runstate.disp_ops['eyetrack']:
for blk in grouper(runstate.add_gids,
runstate.disp_ops['trybreak']):
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
runstate.events['blk_on'] = True
# Loop through display groups
for gid in blk:
if gid != None:
self.groups[gid].display(runstate)
runstate.events['blk_off'] = True
# Count through post
for count in range(self.post * self.fps):
if runstate.window.has_exit:
break
runstate.update()
# Stop and output log
runstate.stop()
if not runstate.disp_ops['nolog']:
runstate.log()
def export(self, export_dir, export_duration, groupq=[],
folder=True, force=False):
if not os.path.isdir(export_dir):
msg = 'export path is not a directory'
raise IOError(msg)
# Set-up groups and variables that control their display
if groupq == []:
groupq = list(self.groups)
n = -1
groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Limit export duration to display duration
frames = export_duration * self.fps
frames = min(frames, disp_end)
# Warn user if a lot of frames will be exported
if frames > MAX_EXPORT_FRAMES and not force:
msg = 'very large number ({0}) of frames to be exported'.\
format(frames)
raise FrameOverflowError(msg)
# Create folder to store images if necessary
if folder:
export_dir = os.path.join(export_dir,
self.name + EXPORT_DIR_SUFFIX)
if not os.path.isdir(export_dir):
os.mkdir(export_dir)
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Set up canvas and framebuffer object
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
# Main loop
while count < frames:
fbo.clear()
if groups_visible:
# Get next group from queue
if n < 0 or groupq[n].over:
n += 1
if n >= len(groupq):
groups_visible = False
else:
groupq[n].reset()
# Draw and then update group
if n >= 0:
groupq[n].draw()
groupq[n].update(fps=self.fps, fpst=0)
# Draw fixation cross based on current count
if (count % (sum(self.cross_times) * self.fps)
|
ztangent/checkergen
|
91bbb57c931abe8bc4daeec471c42f6a4db7c5a0
|
Group orders can now be manually set or automatically generated through CLI.
|
diff --git a/src/cli.py b/src/cli.py
index 32e90e3..c9cf1bd 100644
--- a/src/cli.py
+++ b/src/cli.py
@@ -1,1141 +1,1170 @@
"""Defines command-line-interface for checkergen."""
import os
import sys
if os.name == 'posix':
import readline
import argparse
import cmd
import shlex
import core
import priority
import eyetracking
from graphics import locations
from utils import *
CMD_PROMPT = '(ckg) '
CMD_EOF_STRING = 'Ctrl-D'
if sys.platform == 'win32':
CMD_EOF_STRING = 'Ctrl-Z + Enter'
CMD_INTRO = '\n'.join(["Enter 'help' for a list of commands.",
"Enter 'quit' or {0} to exit.".format(CMD_EOF_STRING)])
-def store_tuple(nargs, sep, typecast=None, castargs=[]):
- """Returns argparse action that stores a tuple."""
- class TupleAction(argparse.Action):
+def store_list(nargs=None, sep=',', typecast=None, castargs=[]):
+ """Returns argparse action that stores a list or tuple."""
+ class ListAction(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
vallist = values.split(sep)
- if len(vallist) != nargs:
+ if nargs != None and len(vallist) != nargs:
msg = ("argument '{f}' should be a list of " +
"{nargs} values separated by '{sep}'").\
format(f=self.dest,nargs=nargs,sep=sep)
raise argparse.ArgumentError(self, msg)
if typecast != None:
for n, val in enumerate(vallist):
try:
val = typecast(*([val] + castargs))
vallist[n] = val
except (ValueError, TypeError):
msg = ("element '{val}' of argument '{f}' " +
"is of the wrong type").\
format(val=vallist[n],f=self.dest)
raise argparse.ArgumentError(self, msg)
- setattr(args, self.dest, tuple(vallist))
- return TupleAction
+ if nargs == None:
+ setattr(args, self.dest, vallist)
+ else:
+ setattr(args, self.dest, tuple(vallist))
+ return ListAction
def store_truth(y_words=['t','y','1','True','true','yes','Yes'],
n_words=['f','n','0','False','false','no','No']):
"""Returns argparse action that stores the truth based on keywords."""
class TruthAction(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
if values in y_words:
setattr(args, self.dest, True)
elif values in n_words:
setattr(args, self.dest, False)
else:
msg = 'true/false keyword unrecognized'
raise argparse.ArgumentError(self, msg)
return TruthAction
# The main parser invoked at the command-line
PARSER = argparse.ArgumentParser(
description='''Generate flashing checkerboard patterns for display
or export as a series of images, intended for use in
psychophysics experiments. Enters interactive command
line mode if no options are specified.''')
PARSER.add_argument('-c', '--cmd', dest='cmd_mode', action='store_true',
help='enter command line mode regardless of other options')
PARSER.add_argument('-d', '--display',
dest='display_flag', action='store_true',
help='displays the stimulus on the screen')
PARSER.add_argument('-e', '--export', dest='export_dur', metavar='DUR',
help='export DUR seconds of the stimulus')
PARSER.add_argument('-f', '--fullscreen', action='store_true',
help='stimulus displayed in fullscreen mode')
PARSER.add_argument('--dir', dest='export_dir',
default=os.getcwd(), metavar='PATH',
help='''destination directory for export
(default: current working directory)''')
PARSER.add_argument('path', metavar='project', nargs='?', type=file,
help='checkergen project file to open')
def process_args(args):
"""Further processes the arguments returned by the main parser."""
if args.export_dur != None:
args.export_flag = True
else:
args.export_flag = False
if not args.display_flag and not args.export_flag:
args.cmd_mode = True
if args.path != None:
if not os.path.isfile(args.path):
msg = 'error: path specified is not a file'
return msg
args.proj = core.CkgProj(path=args.path)
os.chdir(os.path.dirname(os.path.abspath(args.path)))
try:
args.group = args.proj.groups[0]
except IndexError:
args.group = None
else:
args.proj = None
args.group = None
if args.display_flag or args.export_flag:
msg = 'error: no project file specified for display or export'
return msg
class CmdParserError(Exception):
"""To be raised when CmdParser encounters an error."""
pass
class CmdParser(argparse.ArgumentParser):
"""Override ArgumentParser so that it doesn't exit the program."""
def error(self, msg):
raise CmdParserError(msg)
class CkgCmd(cmd.Cmd):
@staticmethod
def yn_parse(s):
if s in ['y', 'Y', 'yes', 'YES', 'Yes']:
return True
elif s in ['n', 'N', 'no', 'NO', 'No']:
return False
else:
msg = "only 'y','n' or variants accepted"
raise ValueError(msg)
def save_check(self, msg=None):
"""Checks and prompts the user to save if necessary."""
if self.cur_proj == None:
return
if not self.cur_proj.is_dirty():
return
if msg == None:
msg = 'Would you like to save the current project first? (y/n)'
print msg
while True:
try:
if self.__class__.yn_parse(raw_input()):
self.do_save('')
break
except TypeError:
print str(sys.exc_value)
except EOFError:
return True
def do_new(self, line):
"""Creates new project with given name (can contain whitespace)."""
name = line.strip().strip('"\'')
if len(name) == 0:
name = 'untitled'
if self.save_check():
return
self.cur_proj = core.CkgProj(name=name)
print 'project \'{0}\' created'.format(self.cur_proj.name)
def do_open(self, line):
"""Open specified project file."""
path = line.strip().strip('"\'')
if len(path) == 0:
print 'error: no path specified'
return
if self.save_check():
return
try:
self.cur_proj = core.CkgProj(path=path)
except (core.FileFormatError, IOError):
print "error:", str(sys.exc_value)
return
os.chdir(os.path.dirname(os.path.abspath(path)))
try:
self.cur_group = self.cur_proj.groups[0]
except IndexError:
self.cur_group = None
print 'project \'{0}\' loaded'.format(self.cur_proj.name)
def do_close(self, line):
"""Prompts the user to save, then closes current project."""
if self.cur_proj == None:
print 'no project to close'
return
if self.save_check():
return
self.cur_proj = None
print 'project closed'
def do_save(self, line):
"""Saves the current project to the specified path."""
if self.cur_proj == None:
print 'no project to save'
return
path = line.strip().strip('"\'')
if len(path) == 0:
path = os.getcwd()
path = os.path.abspath(path)
if os.path.isdir(path):
path = os.path.join(path,
'.'.join([self.cur_proj.name, core.CKG_FMT]))
elif os.path.isdir(os.path.dirname(path)):
pass
else:
print 'error: specified directory does not exist'
return
# project save will add file extension if necessary
try:
path = self.cur_proj.save(path)
except IOError:
print "error:", str(sys.exc_value)
return
print 'project saved to "{0}"'.format(path)
set_parser = CmdParser(add_help=False, prog='set',
description='''Sets various project settings.''')
- set_parser.add_argument('--name', help='''project name, always the same as
- the filename without
- the extension''')
- set_parser.add_argument('--fps', type=to_decimal,
+ set_parser.add_argument('-n', '--name',
+ help='''project name, always the same as the
+ filename without the extension''')
+ set_parser.add_argument('-f', '--fps', type=to_decimal,
help='''number of stimulus frames
rendered per second''')
- set_parser.add_argument('--res', action=store_tuple(2, ',', int),
+ set_parser.add_argument('-r', '--res', action=store_list(2, ',', int),
help='stimulus canvas size/resolution in pixels',
metavar='WIDTH,HEIGHT')
- set_parser.add_argument('--bg', metavar='COLOR', type=to_color,
+ set_parser.add_argument('-bg', '--bg', metavar='COLOR', type=to_color,
help='''background color of the canvas
(color format: R,G,B,
component range from 0-255)''')
- set_parser.add_argument('--pre', type=to_decimal, metavar='SECONDS',
- help='''time in seconds a blank screen will
- be shown before any display groups''')
- set_parser.add_argument('--post', type=to_decimal, metavar='SECONDS',
- help='''time in seconds a blank screen will
- be shown after all display groups''')
- set_parser.add_argument('--cross_cols', metavar='COLOR1,COLOR2',
- action=store_tuple(2, ',', to_color, [';']),
+ set_parser.add_argument('-pr', '--pre',
+ type=to_decimal, metavar='SECONDS',
+ help='''time in seconds a blank screen will
+ be shown before any display groups''')
+ set_parser.add_argument('-po', '--post',
+ type=to_decimal, metavar='SECONDS',
+ help='''time in seconds a blank screen will
+ be shown after all display groups''')
+ set_parser.add_argument('-cc', '--cross_cols', metavar='COLOR1,COLOR2',
+ action=store_list(2, ',', to_color, [';']),
help='''fixation cross coloration
(color format: R;G;B,
component range from 0-255)''')
- set_parser.add_argument('--cross_times', metavar='TIME1,TIME2',
- action=store_tuple(2, ',', to_decimal),
- help='''time in seconds each cross color
- will be displayed''')
+ set_parser.add_argument('-ct', '--cross_times', metavar='TIME1,TIME2',
+ action=store_list(2, ',', to_decimal),
+ help='''time in seconds each cross color
+ will be displayed''')
+ set_group = set_parser.add_mutually_exclusive_group()
+ set_group.add_argument('-o', '--orders', metavar='ORDER1;ORDER2;...',
+ action=store_list(None, ';', to_list, [',', int]),
+ help='''list of orders separated by semicolons
+ where each order is a list of group ids
+ separated by commas''')
+ set_group.add_argument('-go', '--genorders', action='store_true',
+ help='''automatically generate a reduced latin
+ square for use as group orders''')
def help_set(self):
self.__class__.set_parser.print_help()
def do_set(self, line):
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
try:
args = self.__class__.set_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.set_parser.print_usage()
return
names = public_dir(args)
+ names.remove('orders')
+ names.remove('genorders')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
setattr(self.cur_proj, name, val)
noflags = False
+ if args.genorders:
+ orders = cyclic_permute(range(len(self.cur_proj.groups)))
+ try:
+ self.cur_proj.set_group_orders(orders)
+ except ValueError:
+ print "error:", str(sys.exc_value)
+ noflags = False
+ elif args.orders != None:
+ try:
+ self.cur_proj.set_group_orders(args.orders)
+ except ValueError:
+ print "error:", str(sys.exc_value)
+ noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.set_parser.print_usage()
mkgrp_parser = CmdParser(add_help=False, prog='mkgrp',
formatter_class=
argparse.ArgumentDefaultsHelpFormatter,
description='''Makes a new display group
with the given parameters.''')
mkgrp_parser.add_argument('pre', type=to_decimal, default=0, nargs='?',
help='''time in seconds a blank screen will
be shown before shapes are displayed''')
mkgrp_parser.add_argument('disp', type=to_decimal,
nargs='?', default='Infinity',
help='''time in seconds shapes will be
displayed''')
mkgrp_parser.add_argument('post', type=to_decimal, default=0, nargs='?',
help='''time in seconds a blank screen will
be shown after shapes are displayed''')
def help_mkgrp(self):
self.__class__.mkgrp_parser.print_help()
def do_mkgrp(self, line):
"""Makes a display group with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
try:
args = self.__class__.mkgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mkgrp_parser.print_usage()
return
group_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_group = core.CkgDisplayGroup(**group_dict)
new_id = self.cur_proj.add_group(new_group)
print "display group", new_id, "added"
self.cur_group = new_group
print "group", new_id, "is now the current display group"
edgrp_parser = CmdParser(add_help=False, prog='edgrp',
description='''Edits attributes of display groups
specified by ids.''')
edgrp_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='ids of display groups to be edited')
edgrp_parser.add_argument('--pre', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown before shapes are displayed''')
edgrp_parser.add_argument('--disp', type=to_decimal, metavar='SECONDS',
help='''time in seconds shapes will be
displayed''')
edgrp_parser.add_argument('--post', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown after shapes are displayed''')
def help_edgrp(self):
self.__class__.edgrp_parser.print_help()
def do_edgrp(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.edgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.edgrp_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_proj.groups) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_group_attr(x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.edgrp_parser.print_usage()
rmgrp_parser = CmdParser(add_help=False, prog='rmgrp',
description='''Removes display groups specified
by ids.''')
rmgrp_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='ids of display groups to be removed')
rmgrp_parser.add_argument('-a', '--all', action='store_true',
help='remove all groups from the project')
def help_rmgrp(self):
self.__class__.rmgrp_parser.print_help()
def do_rmgrp(self, line):
"""Removes display groups specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups to remove'
return
try:
args = self.__class__.rmgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rmgrp_parser.print_usage()
return
rmlist = []
if args.all:
for group in self.cur_proj.groups[:]:
self.cur_proj.del_group(group)
print "all display groups removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_proj.groups) or x < 0:
print "display group", x, "does not exist"
continue
rmlist.append(self.cur_proj.groups[x])
print "display group", x, "removed"
for group in rmlist:
self.cur_proj.del_group(group)
# Remember to point self.cur_group somewhere sane
if self.cur_group not in self.cur_proj.groups:
if len(self.cur_proj.groups) == 0:
self.cur_group = None
else:
self.cur_group = self.cur_proj.groups[0]
print "group 0 is now the current display group"
chgrp_parser = CmdParser(add_help=False, prog='chgrp',
description='''Changes display group that is
currently active for editing.
Prints current group id if
no group id is specified''')
chgrp_parser.add_argument('gid', metavar='id', type=int, nargs='?',
help='id of display group to be made active')
def help_chgrp(self):
self.__class__.chgrp_parser.print_help()
def do_chgrp(self, line):
"""Changes group that is currently active for editing."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups that can be made active'
return
try:
args = self.__class__.chgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.chgrp_parser.print_usage()
return
if args.gid == None:
print "group",\
self.cur_proj.groups.index(self.cur_group),\
"is the current display group"
elif args.gid >= len(self.cur_proj.groups) or args.gid < 0:
print "group", args.gid, "does not exist"
else:
self.cur_group = self.cur_proj.groups[args.gid]
print "group", args.gid, "is now the current display group"
mk_parser = CmdParser(add_help=False, prog='mk',
description='''Makes a new checkerboard in the
current group with the given
parameters.''')
- mk_parser.add_argument('dims', action=store_tuple(2, ',', to_decimal),
+ mk_parser.add_argument('dims', action=store_list(2, ',', to_decimal),
help='''width,height of checkerboard in no. of
unit cells''')
- mk_parser.add_argument('init_unit', action=store_tuple(2, ',', to_decimal),
+ mk_parser.add_argument('init_unit', action=store_list(2, ',', to_decimal),
help='width,height of initial unit cell in pixels')
- mk_parser.add_argument('end_unit', action=store_tuple(2, ',', to_decimal),
+ mk_parser.add_argument('end_unit', action=store_list(2, ',', to_decimal),
help='width,height of final unit cell in pixels')
- mk_parser.add_argument('position', action=store_tuple(2, ',', to_decimal),
+ mk_parser.add_argument('position', action=store_list(2, ',', to_decimal),
help='x,y position of checkerboard in pixels')
mk_parser.add_argument('anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='anchor')
- mk_parser.add_argument('cols', action=store_tuple(2, ',', to_color, [';']),
+ mk_parser.add_argument('cols', action=store_list(2, ',', to_color, [';']),
help='''color1,color2 of the checkerboard
(color format: R;G;B,
component range from 0-255)''')
mk_parser.add_argument('freq', type=to_decimal,
help='frequency of color reversal in Hz')
mk_parser.add_argument('phase', type=to_decimal, nargs='?', default='0',
help='initial phase in degrees')
def help_mk(self):
self.__class__.mk_parser.print_help()
def do_mk(self, line):
"""Makes a checkerboard with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
if self.cur_group == None:
print 'automatically adding display group...'
self.do_mkgrp('')
try:
args = self.__class__.mk_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mk_parser.print_usage()
return
shape_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_shape = core.CheckerBoard(**shape_dict)
new_id = self.cur_proj.add_shape_to_group(self.cur_group, new_shape)
print "checkerboard", new_id, "added"
ed_parser = CmdParser(add_help=False, prog='ed',
description='''Edits attributes of checkerboards
specified by ids.''')
ed_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='''ids of checkerboards in the current
group to be edited''')
- ed_parser.add_argument('--dims', action=store_tuple(2, ',', to_decimal),
+ ed_parser.add_argument('--dims', action=store_list(2, ',', to_decimal),
help='checkerboard dimensions in unit cells',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--init_unit',
- action=store_tuple(2, ',', to_decimal),
+ action=store_list(2, ',', to_decimal),
help='initial unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--end_unit',
- action=store_tuple(2, ',', to_decimal),
+ action=store_list(2, ',', to_decimal),
help='final unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--position',
- action=store_tuple(2, ',', to_decimal),
+ action=store_list(2, ',', to_decimal),
help='position of checkerboard in pixels',
metavar='X,Y')
ed_parser.add_argument('--anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='LOCATION')
ed_parser.add_argument('--cols', metavar='COLOR1,COLOR2',
- action=store_tuple(2, ',', to_color, [';']),
+ action=store_list(2, ',', to_color, [';']),
help='''checkerboard colors (color format:
R;G;B, component range
from 0-255)''')
ed_parser.add_argument('--freq', type=to_decimal,
help='frequency of color reversal in Hz')
ed_parser.add_argument('--phase', type=to_decimal,
help='initial phase in degrees')
def help_ed(self):
self.__class__.ed_parser.print_help()
def do_ed(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, please create one first'
return
try:
args = self.__class__.ed_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ed_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_group.shapes) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_shape_attr(self.cur_group, x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.ed_parser.print_usage()
rm_parser = CmdParser(add_help=False, prog='rm',
description='''Removes checkerboards specified
by ids.''')
rm_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''ids of checkerboards in the current group
to be removed''')
rm_parser.add_argument('-a', '--all', action='store_true',
help='''remove all checkerboards in the
current group''')
def help_rm(self):
self.__class__.rm_parser.print_help()
def do_rm(self, line):
"""Removes checkerboards specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, no boards to remove'
return
try:
args = self.__class__.rm_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rm_parser.print_usage()
return
rmlist = []
if args.all:
for shape in self.cur_group.shapes:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
print "all checkerboards removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_group.shapes) or x < 0:
print "checkerboard", x, "does not exist"
continue
rmlist.append(self.cur_group.shapes[x])
print "checkerboard", x, "removed"
for shape in rmlist:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
ls_parser = CmdParser(add_help=False, prog='ls',
description='''Lists project, display group and
checkerboard settings. If no group ids
are specified, all display groups
are listed.''')
ls_parser.add_argument('gids', nargs='*', metavar='gid', type=int,
help='''ids of the display groups to be listed''')
ls_group = ls_parser.add_mutually_exclusive_group()
ls_group.add_argument('-s', '--settings', action='store_true',
help='list only project settings')
ls_group.add_argument('-g', '--groups', action='store_true',
help='list only display groups')
ls_group.add_argument('-d', '--disp_ops', action='store_true',
help='list display options')
ls_group.add_argument('-o', '--orders', action='store_true',
help='list group orderings')
def help_ls(self):
self.__class__.ls_parser.print_help()
def do_ls(self, line):
"""Lists project, display group and checkerboard settings."""
def ls_str(s, seps=[',',';']):
"""Special space-saving output formatter."""
if type(s) in [tuple, list]:
if len(seps) > 1:
newseps = seps[1:]
else:
newseps = seps
return seps[0].join([ls_str(i, newseps) for i in s])
else:
return str(s)
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.ls_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ls_parser.print_usage()
return
# Remove duplicates and ascending sort
args.gids = sorted(set(args.gids))
if len(self.cur_proj.groups) == 0:
if len(args.gids) > 0:
print 'this project has no display groups that can be listed'
return
else:
for gid in args.gids[:]:
if gid >= len(self.cur_proj.groups) or gid < 0:
args.gids.remove(gid)
print 'display group', gid, 'does not exist'
if args.gids == []:
args.gids = range(len(self.cur_proj.groups))
else:
# If any (valid) groups are specified
# don't show project settings
args.groups = True
args.show_all = not max(args.settings, args.groups,
args.disp_ops, args.orders)
if args.show_all or args.settings:
print 'PROJECT SETTINGS'.center(70,'*')
print \
'name'.rjust(16),\
'fps'.rjust(7),\
'resolution'.rjust(14),\
'bg color'.rjust(18)
print \
ls_str(self.cur_proj.name).rjust(16),\
ls_str(self.cur_proj.fps).rjust(7),\
ls_str(self.cur_proj.res).rjust(14),\
ls_str(self.cur_proj.bg).rjust(18)
print \
'pre-display'.rjust(26),\
'post-display'.rjust(26)
print \
ls_str(self.cur_proj.pre).rjust(26),\
ls_str(self.cur_proj.post).rjust(26)
print \
'cross colors'.rjust(26),\
'cross times'.rjust(26)
print \
ls_str(self.cur_proj.cross_cols).rjust(26),\
ls_str(self.cur_proj.cross_times).rjust(26)
if args.show_all:
# Insert empty line between different info sets
print ''
if args.show_all or args.disp_ops:
print 'DISPLAY OPTIONS'.center(70,'*')
for k, v in self.cur_proj.disp_ops.items():
print ''.ljust(20), ls_str(k).ljust(20), ls_str(v).ljust(20)
if args.show_all:
# Insert empty line between different info sets
print ''
if args.show_all or args.orders:
print 'GROUP ORDERINGS'.center(70,'*')
if self.cur_proj.orders == []:
order = range(len(self.cur_proj.groups))
print \
''.ljust(20),\
'default order'.ljust(20),\
ls_str(order).ljust(20)
else:
for n, order in enumerate(self.cur_proj.orders):
print \
''.ljust(20),\
'order {n}'.format(n=n).ljust(20),\
ls_str(order).ljust(20)
if args.show_all:
# Insert empty line between different info sets
print ''
if args.show_all or args.groups:
for i, n in enumerate(args.gids):
if i != 0:
# Print newline seperator between each group
print ''
group = self.cur_proj.groups[n]
print 'GROUP {n}'.format(n=n).center(70,'*')
print \
'pre-display'.rjust(20),\
'display'.rjust(20),\
'post-display'.rjust(20)
print \
ls_str(group.pre).rjust(20),\
ls_str(group.disp).rjust(20),\
ls_str(group.post).rjust(20)
if len(group.shapes) > 0:
print \
''.rjust(2),\
'shape id'.rjust(8),\
'dims'.rjust(10),\
'init_unit'.rjust(14),\
'end_unit'.rjust(14),\
'position'.rjust(14)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.dims).rjust(10),\
ls_str(shape.init_unit).rjust(14),\
ls_str(shape.end_unit).rjust(14),\
ls_str(shape.position).rjust(14)
print '\n',\
''.rjust(2),\
'shape id'.rjust(8),\
'colors'.rjust(27),\
'anchor'.rjust(12),\
'freq'.rjust(6),\
'phase'.rjust(7)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.cols).rjust(27),\
ls_str(shape.anchor).rjust(12),\
ls_str(shape.freq).rjust(6),\
ls_str(shape.phase).rjust(7)
display_parser = CmdParser(add_help=False, prog='display',
description='''Displays the stimulus in a
window or in fullscreen.''')
display_parser.add_argument('-s', '--save', action='store_true',
help='''save specified display flags
as default flags for project
instead of presenting stimulus''')
display_parser.add_argument('-n', '--name', metavar='FOOBAR',
help='''name of log file to be written''')
display_parser.add_argument('-r', '--repeats', metavar='N', type=int,
help='''repeatedly display specified display
groups N number of times''')
display_parser.add_argument('-wl', '--waitless', action=store_truth(),
metavar='t/f',
help='''do not add waitscreens before the
start of each repeat''')
display_parser.add_argument('-f', '--fullscreen', action=store_truth(),
metavar='t/f',
help='sets fullscreen mode, ESC to quit')
display_parser.add_argument('-p', '--priority', metavar='LEVEL',
help='''set priority while displaying,
higher priority results in
less dropped frames (choices:
0-3, low, normal, high,
realtime)''')
display_parser.add_argument('-pt', '--phototest', action=store_truth(),
metavar='t/f',
help='''draw white test rectangle in topleft
corner of screen when groups become
visible for a photodiode to detect''')
display_parser.add_argument('-pb', '--photoburst', action=store_truth(),
metavar='t/f',
help='''make checkerboards only draw first
color for one frame to facilitate
testing with a photodiode''')
display_parser.add_argument('-lt', '--logtime', action=store_truth(),
metavar='t/f',
help='output frame timestamps to a log file')
display_parser.add_argument('-ld', '--logdur', action=store_truth(),
metavar='t/f',
help='output frame durations to a log file')
display_parser.add_argument('-ss', '--trigser', action=store_truth(),
metavar='t/f',
help='''send triggers through the serial port
when shapes are being displayed''')
display_parser.add_argument('-sp', '--trigpar', action=store_truth(),
metavar='t/f',
help='''send triggers through the parallel port
when shapes are being displayed''')
display_parser.add_argument('-fpst', metavar='M', type=int,
help='''unique trigger corresponding to a
checkerboard is sent after the shape
undergoes M color flips (default:
disabled, M=0)''')
display_parser.add_argument('-fc', '--freqcheck', action=store_truth(),
metavar='t/f',
help='''only send triggers for board color
flips at the start, middle and end
of the run''')
display_parser.add_argument('-et', '--eyetrack', action=store_truth(),
metavar='t/f',
help='''use eyetracking to ensure that subject
fixates on the cross in the center''')
display_parser.add_argument('-eu', '--etuser', action=store_truth(),
metavar='t/f',
help='''allow user to select eyetracking video
source from a dialog''')
display_parser.add_argument('-ev', '--etvideo', metavar='path',
help='''path (with no spaces) to eyetracking
video file to be used as the source''')
display_parser.add_argument('-ta', '--tryagain', metavar='I', type=int,
help='''append groups during which subject
failed to fixate up to I times to the
list of groups to be displayed
(default: disabled, I=0)''')
display_parser.add_argument('-tb', '--trybreak', metavar='J', type=int,
help='''used with --tryagain, append a wait
screen to the list of groups to be
displayed after every J groups have
been appended to the list (default:
J=total number of groups)''')
display_parser.add_argument('-nl', '--nolog', action=store_truth(),
metavar='t/f',
help='''do not write a log file''')
display_parser.add_argument('order', nargs='*', metavar='id', type=int,
help='''order in which groups should be
displayed (default: random order
from list of orders if specified
in project, ascending otherwise)''')
def help_display(self):
self.__class__.display_parser.print_help()
def do_display(self, line):
"""Displays the stimulus in a window or in fullscreen"""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.display_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
if len(args.order) > 0:
for i in set(args.order):
if i >= len(self.cur_proj.groups) or i < -1:
print 'error: group', i, 'does not exist'
return
if args.eyetrack and eyetracking.available:
if not eyetracking.is_calibrated():
try:
self.do_calibrate('',query=True)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
return
if args.save:
self.cur_proj.set_display_flags(repeats=args.repeats,
waitless=args.waitless,
fullscreen=args.fullscreen,
priority=args.priority,
logtime=args.logtime,
logdur=args.logdur,
trigser=args.trigser,
trigpar=args.trigpar,
fpst=args.fpst,
freqcheck=args.freqcheck,
phototest=args.phototest,
photoburst=args.photoburst,
eyetrack=args.eyetrack,
etuser=args.etuser,
etvideo=args.etvideo,
tryagain=args.tryagain,
trybreak=args.trybreak,
nolog=args.nolog)
print "display flags saved to project"
else:
print "displaying...",
try:
self.cur_proj.display(name=args.name,
repeats=args.repeats,
waitless=args.waitless,
fullscreen=args.fullscreen,
priority=args.priority,
logtime=args.logtime,
logdur=args.logdur,
trigser=args.trigser,
trigpar=args.trigpar,
fpst=args.fpst,
freqcheck=args.freqcheck,
phototest=args.phototest,
photoburst=args.photoburst,
eyetrack=args.eyetrack,
etuser=args.etuser,
etvideo=args.etvideo,
tryagain=args.tryagain,
trybreak=args.trybreak,
nolog=args.nolog,
order=args.order)
except (IOError, NotImplementedError,
eyetracking.EyetrackingError):
print ''
print "error:", str(sys.exc_value)
if args.priority != None:
try:
priority.set('normal')
except:
pass
return
print "done"
export_parser = CmdParser(add_help=False, prog='export',
description='''Exports stimulus as an image
sequence (in a folder) to the
specified directory.''')
export_parser.add_argument('-n','--nofolder',
dest='folder', action='store_false',
help='''force images not to exported in
a containing folder''')
export_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly export specified display
groups N number of times''')
export_parser.add_argument('duration', nargs='?',
type=to_decimal, default='Infinity',
help='''number of seconds of the stimulus
that should be exported (default:
as long as the entire stimulus)''')
export_parser.add_argument('dir', nargs='?', default=os.getcwd(),
help='''destination directory for export
(default: current working directory)''')
export_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be exported
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_export(self):
self.__class__.export_parser.print_help()
def do_export(self, line):
"""Exports stimulus as an image sequence to the specified directory."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.export_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.export_parser.print_usage()
return
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < 0:
print 'error: group', i, 'does not exist'
return
groupq = [self.cur_proj.groups[i] for i in args.idlist]
else:
groupq = list(self.cur_proj.groups)
if args.repeat != None:
groupq = list(groupq * args.repeat)
try:
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
folder=args.folder)
except IOError:
print "error:", str(sys.exc_value)
return
except core.FrameOverflowError:
print "warning:", str(sys.exc_value)
print "Are you sure you want to continue?"
while True:
try:
if self.__class__.yn_parse(raw_input()):
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
folder=args.folder,
force=True)
break
else:
return
except TypeError:
print str(sys.exc_value)
except EOFError:
return
print "Export done."
def do_calibrate(self, line, query=False):
"""Calibrate subject for eyetracking, or load a calibration file."""
if not eyetracking.available:
print "error: eyetracking functionality not available"
return
if query:
print "path to calibration file (leave empty for GUI tool):"
try:
path = raw_input().strip().strip('"\'')
except EOFError:
msg = "calibration cancelled"
raise eyetracking.EyetrackingError(msg)
else:
path = line.strip().strip('"\'')
if len(path) == 0:
path = None
if not eyetracking.is_source_ready():
# Select default source if none has been selected
eyetracking.select_source()
try:
eyetracking.calibrate(path)
except eyetracking.EyetrackingError:
if query:
raise
else:
print "error:", str(sys.exc_value)
return
if len(path) > 0:
print "calibration file successfully loaded"
etsetup_parser = CmdParser(add_help=False, prog='etsetup',
description='''Set various eyetracking
parameters.''')
etsetup_parser.add_argument('-fp', '--fixperiod', type=int, metavar='MS',
help='''time in milliseconds subject
has to stare at the same spot
for fixation to be detected''')
etsetup_parser.add_argument('-fr', '--fixrange', type=float, metavar='MM',
help='''distance in mm beyond which the
eye position cannot change for
a fixation to be detected''')
etsetup_parser.add_argument('-s', '--size', metavar='WIDTH,HEIGHT',
- action=store_tuple(2, ',', float),
+ action=store_list(2, ',', float),
help='physical screen dimensions in mm')
etsetup_parser.add_argument('-vd', '--viewdist', type=int, metavar='MM',
help='''viewing distance between subject's
eyes and the screen''')
def help_etsetup(self):
self.__class__.etsetup_parser.print_help()
def do_etsetup(self, line):
try:
args = self.__class__.etsetup_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.etsetup_parser.print_usage()
return
try:
eyetracking.setup(viewing_distance=args.viewdist,
screen_dims=args.size,
fixation_period=args.fixperiod,
fixation_range=args.fixrange)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
def do_pwd(self, line):
"""Prints the current working directory."""
print os.getcwd()
def do_cd(self, line):
"""Change working directory to specified path."""
path = line.strip().strip('"\'')
if not os.path.isdir(path):
print "error: specified path is not a directory"
return
os.chdir(path)
def do_quit(self, line):
"""Quits the program."""
if self.save_check():
return
return True
def help_EOF(self):
print "Typing {0} issues this command, which quits the program."\
.format(CMD_EOF_STRING)
def do_EOF(self, line):
"""Typing Ctrl-D issues this command, which quits the program."""
print '\r'
if self.save_check():
return
return True
def help_help(self):
print 'Prints a list of commands.'
print "Type 'help <topic>' for more details on each command."
def default(self, line):
command = line.split()[0]
print \
"'{0}' is not a checkergen command.".format(command),\
"Type 'help' for a list of commands"
diff --git a/src/core.py b/src/core.py
index 6d7308d..dcd91ce 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,784 +1,752 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import copy
import random
import itertools
from datetime import datetime
from xml.dom import minidom
import pyglet
import graphics
import priority
import trigger
import eyetracking
from utils import *
# Use OrderedDict substitute if we don't have Python 2.7
if sys.version_info < (2, 7):
from odict import OrderedDict
else:
from collections import OrderedDict
CKG_FMT = 'ckg'
LOG_FMT = 'csv'
MAX_EXPORT_FRAMES = 100000
EXPORT_DIR_SUFFIX = '-anim'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
INT_HALF_PERIODS = True
FIX_POS = (0, 0)
FIX_RANGE = (20, 20)
FIX_PER = 350
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = OrderedDict([('name', 'untitled'),
('fps', 60),
('res', (800, 600)),
('bg', (127, 127, 127)),
('pre', 0),
('post', 0),
('cross_cols', ((0, 0, 0), (255, 0, 0))),
('cross_times', ('Infinity', 1)),
('orders', []),
('disp_ops', None)])
DEFAULTS['disp_ops'] = OrderedDict([('repeats', 1),
('waitless', False),
('fullscreen', False),
('priority', None),
('logtime', False),
('logdur', False),
('trigser', False),
('trigpar', False),
('fpst', 0),
('freqcheck', False),
('phototest', False),
('photoburst', False),
('eyetrack', False),
('etuser', False),
('etvideo', None),
('tryagain', 0),
('trybreak', None),
('nolog', False)])
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def set_display_flags(self, **keywords):
"""Set default display flags for the project.
- repeats -- number of times specified order of display groups should
- be repeated
-
- waitless -- if true, no waitscreens will appear at the start of each
- repeat
-
- fullscreen -- animation is displayed fullscreen if true, stretched
- to fit if necessary
-
- priority -- priority level to which process should be raised
-
- logtime -- timestamp of each frame is saved to a logfile if true
-
- logdur -- duration of each frame is saved to a logfile if true
-
- trigser -- send triggers through serial port when each group is shown
-
- trigpar -- send triggers through parallel port when each group is shown
-
- fpst -- flips per shape trigger, i.e. number of shape color reversals
- (flips) that occur for a unique trigger to be sent for that shape
-
- freqcheck -- send fpst only at the start, the middle, and the end
- for sanity checking of display and trigger fps
-
- phototest -- draw white rectangle in topleft corner when each group is
- shown for photodiode to detect
-
- photoburst -- make checkerboards only draw first color for one frame
-
- eyetrack -- use eyetracking to ensure subject is fixating on cross
-
- etuser -- if true, user gets to select eyetracking video source in GUI
+ Same arguments as 'display', excluding 'name' and 'order'.
- etvideo -- optional eyetracking video source file to use instead of
- live feed
-
- tryagain -- append groups during which subject failed to fixate up to
- this number of times to the group queue
-
- trybreak -- append a wait screen to the group queue every time
- after this many groups have been appended to the queue
-
"""
for kw in keywords.keys():
if kw in self.disp_ops.keys() and keywords[kw] != None:
self.disp_ops[kw] = keywords[kw]
self._dirty = True
+ def set_group_orders(self, orders):
+ for order in orders:
+ for gid in order:
+ if gid < -1 or gid >= len(self.groups):
+ msg = 'invalid group id (out of range)'
+ raise ValueError(msg)
+ self.orders = orders
+ self._dirty = True
+
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
# Vars that are dicts
dicts_to_load = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_load = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
for d_name in dicts_to_load:
d = copy.deepcopy(self.__class__.DEFAULTS[d_name])
try:
d_el = [node for node in project.childNodes if
node.localName == d_name and
node.namespaceURI == XML_NAMESPACE][0]
for var in d.keys():
try:
d[var] = eval(xml_get(d_el, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}' in '{1}'".\
format(var, d_name)
print "using default value '{0}' instead...".\
format(d[var])
except IndexError:
print "warning: missing attribute set '{0}'".format(d_name)
print "using default values instead..."
setattr(self, d_name, d)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
# Vars that are dicts
dicts_to_save = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_save = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for d_name in dicts_to_save:
d_el = doc.createElement(d_name)
project.appendChild(d_el)
d = getattr(self, d_name)
for k, v in d.iteritems():
xml_set(doc, d_el, k, repr(v))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, **keywords):
"""Displays the project animation on the screen.
name -- name that logfile will be saved with
repeats -- number of times specified order of display groups should
be repeated
waitless -- if true, no waitscreens will appear at the start of each
repeat
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
priority -- priority level to which process should be raised
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
trigser -- send triggers through serial port when each group is shown
trigpar -- send triggers through parallel port when each group is shown
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
freqcheck -- send fpst only at the start, the middle, and the end
for sanity checking of display and trigger fps
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- append a wait screen to the group queue every time
after this many groups have been appended to the queue
order -- order in which groups (specified by id) will be displayed
"""
# Create RunState
disp_ops = copy.deepcopy(self.disp_ops)
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'name' in keywords.keys() and keywords['name'] != None:
name = keywords['name']
else:
timestr = datetime.today().strftime('_%Y-%m-%d_%H-%M-%S')
name = self.name + timestr
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
waitscreen = CkgWaitScreen()
# Set order id to be sent if necessary
if order in self.orders:
runstate.events['ord_id'] = self.orders.index(order)
# Count through pre
for count in range(self.pre * self.fps):
if runstate.window.has_exit:
break
runstate.update()
# Loop through repeats
repeats = runstate.disp_ops['repeats']
ord_len = len(runstate.order)
for i in range(repeats):
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
# Loop through display groups
runstate.events['blk_on'] = True
for n, gid in enumerate(runstate.order):
# Set flag for freqcheck
if runstate.disp_ops['freqcheck']:
if ((i == 0 and n == 0) or
(i == repeats-1 and n == ord_len-1) or
(i == repeats//2 and n == ord_len//2)):
runstate.fc_send = True
else:
runstate.fc_send = False
if gid == -1:
waitscreen.reset()
waitscreen.display(runstate)
else:
self.groups[gid].display(runstate)
# Append failed groups
if runstate.disp_ops['eyetrack'] and runstate.true_fail:
if len(runstate.add_gids) < runstate.disp_ops['tryagain']:
runstate.add_gids.append(gid)
else:
runstate.fail_gids.append(gid)
runstate.events['blk_off'] = True
# Loop through added groups
if runstate.disp_ops['eyetrack']:
for blk in grouper(runstate.add_gids,
runstate.disp_ops['trybreak']):
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
runstate.events['blk_on'] = True
# Loop through display groups
for gid in blk:
if gid != None:
self.groups[gid].display(runstate)
runstate.events['blk_off'] = True
# Count through post
for count in range(self.post * self.fps):
if runstate.window.has_exit:
break
runstate.update()
# Stop and output log
runstate.stop()
if not runstate.disp_ops['nolog']:
runstate.log()
def export(self, export_dir, export_duration, groupq=[],
folder=True, force=False):
if not os.path.isdir(export_dir):
msg = 'export path is not a directory'
raise IOError(msg)
# Set-up groups and variables that control their display
if groupq == []:
groupq = list(self.groups)
n = -1
groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Limit export duration to display duration
frames = export_duration * self.fps
frames = min(frames, disp_end)
# Warn user if a lot of frames will be exported
if frames > MAX_EXPORT_FRAMES and not force:
msg = 'very large number ({0}) of frames to be exported'.\
format(frames)
raise FrameOverflowError(msg)
# Create folder to store images if necessary
if folder:
export_dir = os.path.join(export_dir,
self.name + EXPORT_DIR_SUFFIX)
if not os.path.isdir(export_dir):
os.mkdir(export_dir)
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Set up canvas and framebuffer object
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
# Main loop
while count < frames:
fbo.clear()
if groups_visible:
# Get next group from queue
if n < 0 or groupq[n].over:
n += 1
if n >= len(groupq):
groups_visible = False
else:
groupq[n].reset()
# Draw and then update group
if n >= 0:
groupq[n].draw()
groupq[n].update(fps=self.fps, fpst=0)
# Draw fixation cross based on current count
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Save current frame to file
savepath = \
os.path.join(export_dir,
'{0}{2}.{1}'.
format(self.name, 'png',
repr(count).zfill(numdigits(frames-1))))
canvas.save(savepath)
# Increment count and set whether groups should be shown
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
fbo.delete()
class CkgRunState:
"""Contains information about the state of a checkergen project
when it is being displayed or exported."""
DEFAULTS = dict([('name', 'untitled'),
('res', None),
('fps', None),
('bg', None),
('cross_cols', None),
('cross_times', None),
('order', []),
('disp_ops', None),
('events', None),
('add_gids', []),
('fail_gids', []),
('timestamps', []),
('durstamps', []),
('trigstamps', [])])
DEFAULTS['events'] = dict([('ord_id', None),
('blk_on', False),
('blk_off', False),
('track_on', False),
('track_off', False),
('fix_on', False),
('fix_off', False),
('grp_on', False),
('grp_off', False),
('sids', set())])
def __init__(self, **keywords):
"""Creates the RunState."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
def start(self):
"""Initialize all subsystems and start the run."""
if self.disp_ops == None:
msg = "RunState lacks display options"
raise ValueError(msg)
if min(self.res, self.fps, self.bg,
self.cross_cols, self.cross_times) == None:
msg = "RunState intialized with insufficent project information"
raise ValueError(msg)
self._count = 0
# Flag used by freqcheck
self.fc_send = False
# Create fixation crosses
self.fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if self.disp_ops['phototest']:
self.test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Initialize ports
if self.disp_ops['trigser']:
if not trigger.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trigpar']:
if not trigger.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
trigger.init(self.disp_ops['trigser'], self.disp_ops['trigpar'])
# Initialize eyetracking
if self.disp_ops['eyetrack']:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trybreak'] == None:
self.disp_ops['trybreak'] = len(self.order)
self.fixated = False
self.old_fixated = False
self.tracked = False
self.old_tracked = False
self.fix_fail = False
self.true_fail = False
eyetracking.select_source(self.disp_ops['etuser'],
self.disp_ops['etvideo'])
eyetracking.start()
# Stretch to fit screen only if project res does not equal screen res
self.scaling = False
if self.disp_ops['fullscreen']:
self.window = pyglet.window.Window(fullscreen=True, visible=False)
if (self.window.width, self.window.height) != self.res:
self.scaling = True
else:
self.window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
self.keystates = pyglet.window.key.KeyStateHandler()
self.window.push_handlers(self.keystates)
# Clear window and make visible
self.window.switch_to()
graphics.set_clear_color(self.bg)
self.window.clear()
self.window.set_visible()
# Create framebuffer object for drawing unscaled scene
if self.scaling:
self.canvas = pyglet.image.Texture.create(*self.res)
self.fbo = graphics.Framebuffer(self.canvas)
self.fbo.start_render()
graphics.set_clear_color(self.bg)
self.fbo.clear()
# Set process priority
if self.disp_ops['priority'] != None:
if not priority.available[sys.platform]:
msg = "setting priority not available on {0}".\
format(sys.platform)
raise NotImplementedError(msg)
else:
try:
priority.set(self.disp_ops['priority'])
except ValueError:
priority.set(int(self.disp_ops['priority']))
# Start timers
if self.disp_ops['logtime']:
self.timer = Timer()
self.timer.start()
if self.disp_ops['logdur']:
self.dur = Timer()
self.dur.start()
def update(self):
"""Update the RunState."""
# Check for tracking and fixation
if self.disp_ops['eyetrack']:
self.old_tracked = self.tracked
self.tracked = eyetracking.is_tracked()
self.old_fixated = self.fixated
self.fixated = eyetracking.is_fixated(FIX_POS, FIX_RANGE, FIX_PER)
if self.fixated:
# Draw normal cross color if fixating
self.fix_crosses[0].draw()
else:
# Draw alternative cross color if not fixating
self.fix_crosses[1].draw()
# Update eyetracking events
if self.tracked != self.old_tracked:
if self.tracked:
self.events['track_on'] = True
else:
self.events['track_off'] = True
if self.fixated != self.old_fixated:
if self.fixated:
self.events['fix_on'] = True
else:
self.events['fix_off'] = True
# Check for failure of trial
if self.tracked and not self.fixated:
self.fix_fail = True
else:
# Change cross color based on time
if (self._count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
self.fix_crosses[0].draw()
diff --git a/src/utils.py b/src/utils.py
index 2e2febd..623d62e 100644
--- a/src/utils.py
+++ b/src/utils.py
@@ -1,95 +1,103 @@
"""Utility functions and classes."""
import os
import time
import math
from decimal import *
from itertools import *
def numdigits(x):
"""Returns number of digits in a decimal integer."""
if x == 0:
return 1
elif x < 0:
x = -x
return int(math.log(x, 10)) + 1
def public_dir(obj):
"""Returns all 'public' attributes of an object"""
names = dir(obj)
for name in names[:]:
if name[0] == '_' or name[-1] == '_':
names.remove(name)
return names
def to_decimal(s):
"""ValueError raising Decimal converter."""
try:
return Decimal(s)
except (InvalidOperation, TypeError):
try:
return Decimal(str(s))
except (InvalidOperation, TypeError):
raise ValueError
def to_color(s, sep=','):
"""Tries to cast a string to a color (3-tuple)."""
c = tuple([int(x) for x in s.split(sep)])
if len(c) != 3:
raise ValueError
return c
-def cyclic_permute(self, sequence):
+def to_list(s, sep=',', typecast=None):
+ """Cast comma separated values to a list."""
+ l = s.split(sep)
+ if typecast != None:
+ l = [typecast(i) for i in l]
+ return l
+
+def cyclic_permute(sequence):
"""Return a list of all cyclic permutations of supplied sequence."""
+ n = len(sequence)
return [[sequence[i - j] for i in range(n)] for j in range(n, 0, -1)]
# From itertools documentation
def grouper(iterable, n, fillvalue=None):
"""grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"""
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
class Timer:
"""High-res timer that should be cross-platform."""
def __init__(self):
# Assigns appropriate clock function based on OS
if os.name == 'nt':
self.clock = time.clock
self.clock()
elif os.name == 'posix':
self.clock = time.time
self.running = False
def start(self):
self.start_time = self.clock()
self.running = True
def stop(self):
if not self.running:
return None
self.stop_time = self.clock()
self.running = False
return self.stop_time - self.start_time
def elapsed(self):
if not self.running:
return None
cur_time = self.clock()
return cur_time - self.start_time
def restart(self):
old_start_time = self.start_time
self.start_time = self.clock()
self.running = True
return self.start_time - old_start_time
def tick(self, fps):
"""Limits loop to specified fps. To be placed at start of loop."""
fps = float(fps)
ret = self.elapsed()
if self.elapsed() != -1:
while self.elapsed() < (1.0 / fps):
pass
self.start()
if ret != -1:
return ret * 1000
|
ztangent/checkergen
|
0a148e7de6d14f125980ea9be2170969379a439b
|
ls can now list group orders too.
|
diff --git a/src/cli.py b/src/cli.py
index 8ba0098..32e90e3 100644
--- a/src/cli.py
+++ b/src/cli.py
@@ -115,1005 +115,1027 @@ class CmdParserError(Exception):
class CmdParser(argparse.ArgumentParser):
"""Override ArgumentParser so that it doesn't exit the program."""
def error(self, msg):
raise CmdParserError(msg)
class CkgCmd(cmd.Cmd):
@staticmethod
def yn_parse(s):
if s in ['y', 'Y', 'yes', 'YES', 'Yes']:
return True
elif s in ['n', 'N', 'no', 'NO', 'No']:
return False
else:
msg = "only 'y','n' or variants accepted"
raise ValueError(msg)
def save_check(self, msg=None):
"""Checks and prompts the user to save if necessary."""
if self.cur_proj == None:
return
if not self.cur_proj.is_dirty():
return
if msg == None:
msg = 'Would you like to save the current project first? (y/n)'
print msg
while True:
try:
if self.__class__.yn_parse(raw_input()):
self.do_save('')
break
except TypeError:
print str(sys.exc_value)
except EOFError:
return True
def do_new(self, line):
"""Creates new project with given name (can contain whitespace)."""
name = line.strip().strip('"\'')
if len(name) == 0:
name = 'untitled'
if self.save_check():
return
self.cur_proj = core.CkgProj(name=name)
print 'project \'{0}\' created'.format(self.cur_proj.name)
def do_open(self, line):
"""Open specified project file."""
path = line.strip().strip('"\'')
if len(path) == 0:
print 'error: no path specified'
return
if self.save_check():
return
try:
self.cur_proj = core.CkgProj(path=path)
except (core.FileFormatError, IOError):
print "error:", str(sys.exc_value)
return
os.chdir(os.path.dirname(os.path.abspath(path)))
try:
self.cur_group = self.cur_proj.groups[0]
except IndexError:
self.cur_group = None
print 'project \'{0}\' loaded'.format(self.cur_proj.name)
def do_close(self, line):
"""Prompts the user to save, then closes current project."""
if self.cur_proj == None:
print 'no project to close'
return
if self.save_check():
return
self.cur_proj = None
print 'project closed'
def do_save(self, line):
"""Saves the current project to the specified path."""
if self.cur_proj == None:
print 'no project to save'
return
path = line.strip().strip('"\'')
if len(path) == 0:
path = os.getcwd()
path = os.path.abspath(path)
if os.path.isdir(path):
path = os.path.join(path,
'.'.join([self.cur_proj.name, core.CKG_FMT]))
elif os.path.isdir(os.path.dirname(path)):
pass
else:
print 'error: specified directory does not exist'
return
# project save will add file extension if necessary
try:
path = self.cur_proj.save(path)
except IOError:
print "error:", str(sys.exc_value)
return
print 'project saved to "{0}"'.format(path)
set_parser = CmdParser(add_help=False, prog='set',
description='''Sets various project settings.''')
set_parser.add_argument('--name', help='''project name, always the same as
the filename without
the extension''')
set_parser.add_argument('--fps', type=to_decimal,
help='''number of stimulus frames
rendered per second''')
set_parser.add_argument('--res', action=store_tuple(2, ',', int),
help='stimulus canvas size/resolution in pixels',
metavar='WIDTH,HEIGHT')
set_parser.add_argument('--bg', metavar='COLOR', type=to_color,
help='''background color of the canvas
(color format: R,G,B,
component range from 0-255)''')
set_parser.add_argument('--pre', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown before any display groups''')
set_parser.add_argument('--post', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown after all display groups''')
set_parser.add_argument('--cross_cols', metavar='COLOR1,COLOR2',
action=store_tuple(2, ',', to_color, [';']),
help='''fixation cross coloration
(color format: R;G;B,
component range from 0-255)''')
set_parser.add_argument('--cross_times', metavar='TIME1,TIME2',
action=store_tuple(2, ',', to_decimal),
help='''time in seconds each cross color
will be displayed''')
def help_set(self):
self.__class__.set_parser.print_help()
def do_set(self, line):
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
try:
args = self.__class__.set_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.set_parser.print_usage()
return
names = public_dir(args)
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
setattr(self.cur_proj, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.set_parser.print_usage()
mkgrp_parser = CmdParser(add_help=False, prog='mkgrp',
formatter_class=
argparse.ArgumentDefaultsHelpFormatter,
description='''Makes a new display group
with the given parameters.''')
mkgrp_parser.add_argument('pre', type=to_decimal, default=0, nargs='?',
help='''time in seconds a blank screen will
be shown before shapes are displayed''')
mkgrp_parser.add_argument('disp', type=to_decimal,
nargs='?', default='Infinity',
help='''time in seconds shapes will be
displayed''')
mkgrp_parser.add_argument('post', type=to_decimal, default=0, nargs='?',
help='''time in seconds a blank screen will
be shown after shapes are displayed''')
def help_mkgrp(self):
self.__class__.mkgrp_parser.print_help()
def do_mkgrp(self, line):
"""Makes a display group with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
try:
args = self.__class__.mkgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mkgrp_parser.print_usage()
return
group_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_group = core.CkgDisplayGroup(**group_dict)
new_id = self.cur_proj.add_group(new_group)
print "display group", new_id, "added"
self.cur_group = new_group
print "group", new_id, "is now the current display group"
edgrp_parser = CmdParser(add_help=False, prog='edgrp',
description='''Edits attributes of display groups
specified by ids.''')
edgrp_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='ids of display groups to be edited')
edgrp_parser.add_argument('--pre', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown before shapes are displayed''')
edgrp_parser.add_argument('--disp', type=to_decimal, metavar='SECONDS',
help='''time in seconds shapes will be
displayed''')
edgrp_parser.add_argument('--post', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown after shapes are displayed''')
def help_edgrp(self):
self.__class__.edgrp_parser.print_help()
def do_edgrp(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.edgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.edgrp_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_proj.groups) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_group_attr(x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.edgrp_parser.print_usage()
rmgrp_parser = CmdParser(add_help=False, prog='rmgrp',
description='''Removes display groups specified
by ids.''')
rmgrp_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='ids of display groups to be removed')
rmgrp_parser.add_argument('-a', '--all', action='store_true',
help='remove all groups from the project')
def help_rmgrp(self):
self.__class__.rmgrp_parser.print_help()
def do_rmgrp(self, line):
"""Removes display groups specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups to remove'
return
try:
args = self.__class__.rmgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rmgrp_parser.print_usage()
return
rmlist = []
if args.all:
for group in self.cur_proj.groups[:]:
self.cur_proj.del_group(group)
print "all display groups removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_proj.groups) or x < 0:
print "display group", x, "does not exist"
continue
rmlist.append(self.cur_proj.groups[x])
print "display group", x, "removed"
for group in rmlist:
self.cur_proj.del_group(group)
# Remember to point self.cur_group somewhere sane
if self.cur_group not in self.cur_proj.groups:
if len(self.cur_proj.groups) == 0:
self.cur_group = None
else:
self.cur_group = self.cur_proj.groups[0]
print "group 0 is now the current display group"
chgrp_parser = CmdParser(add_help=False, prog='chgrp',
description='''Changes display group that is
currently active for editing.
Prints current group id if
no group id is specified''')
chgrp_parser.add_argument('gid', metavar='id', type=int, nargs='?',
help='id of display group to be made active')
def help_chgrp(self):
self.__class__.chgrp_parser.print_help()
def do_chgrp(self, line):
"""Changes group that is currently active for editing."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups that can be made active'
return
try:
args = self.__class__.chgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.chgrp_parser.print_usage()
return
if args.gid == None:
print "group",\
self.cur_proj.groups.index(self.cur_group),\
"is the current display group"
elif args.gid >= len(self.cur_proj.groups) or args.gid < 0:
print "group", args.gid, "does not exist"
else:
self.cur_group = self.cur_proj.groups[args.gid]
print "group", args.gid, "is now the current display group"
mk_parser = CmdParser(add_help=False, prog='mk',
description='''Makes a new checkerboard in the
current group with the given
parameters.''')
mk_parser.add_argument('dims', action=store_tuple(2, ',', to_decimal),
help='''width,height of checkerboard in no. of
unit cells''')
mk_parser.add_argument('init_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of initial unit cell in pixels')
mk_parser.add_argument('end_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of final unit cell in pixels')
mk_parser.add_argument('position', action=store_tuple(2, ',', to_decimal),
help='x,y position of checkerboard in pixels')
mk_parser.add_argument('anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='anchor')
mk_parser.add_argument('cols', action=store_tuple(2, ',', to_color, [';']),
help='''color1,color2 of the checkerboard
(color format: R;G;B,
component range from 0-255)''')
mk_parser.add_argument('freq', type=to_decimal,
help='frequency of color reversal in Hz')
mk_parser.add_argument('phase', type=to_decimal, nargs='?', default='0',
help='initial phase in degrees')
def help_mk(self):
self.__class__.mk_parser.print_help()
def do_mk(self, line):
"""Makes a checkerboard with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
if self.cur_group == None:
print 'automatically adding display group...'
self.do_mkgrp('')
try:
args = self.__class__.mk_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mk_parser.print_usage()
return
shape_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_shape = core.CheckerBoard(**shape_dict)
new_id = self.cur_proj.add_shape_to_group(self.cur_group, new_shape)
print "checkerboard", new_id, "added"
ed_parser = CmdParser(add_help=False, prog='ed',
description='''Edits attributes of checkerboards
specified by ids.''')
ed_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='''ids of checkerboards in the current
group to be edited''')
ed_parser.add_argument('--dims', action=store_tuple(2, ',', to_decimal),
help='checkerboard dimensions in unit cells',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--init_unit',
action=store_tuple(2, ',', to_decimal),
help='initial unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--end_unit',
action=store_tuple(2, ',', to_decimal),
help='final unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--position',
action=store_tuple(2, ',', to_decimal),
help='position of checkerboard in pixels',
metavar='X,Y')
ed_parser.add_argument('--anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='LOCATION')
ed_parser.add_argument('--cols', metavar='COLOR1,COLOR2',
action=store_tuple(2, ',', to_color, [';']),
help='''checkerboard colors (color format:
R;G;B, component range
from 0-255)''')
ed_parser.add_argument('--freq', type=to_decimal,
help='frequency of color reversal in Hz')
ed_parser.add_argument('--phase', type=to_decimal,
help='initial phase in degrees')
def help_ed(self):
self.__class__.ed_parser.print_help()
def do_ed(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, please create one first'
return
try:
args = self.__class__.ed_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ed_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_group.shapes) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_shape_attr(self.cur_group, x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.ed_parser.print_usage()
rm_parser = CmdParser(add_help=False, prog='rm',
description='''Removes checkerboards specified
by ids.''')
rm_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''ids of checkerboards in the current group
to be removed''')
rm_parser.add_argument('-a', '--all', action='store_true',
help='''remove all checkerboards in the
current group''')
def help_rm(self):
self.__class__.rm_parser.print_help()
def do_rm(self, line):
"""Removes checkerboards specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, no boards to remove'
return
try:
args = self.__class__.rm_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rm_parser.print_usage()
return
rmlist = []
if args.all:
for shape in self.cur_group.shapes:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
print "all checkerboards removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_group.shapes) or x < 0:
print "checkerboard", x, "does not exist"
continue
rmlist.append(self.cur_group.shapes[x])
print "checkerboard", x, "removed"
for shape in rmlist:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
ls_parser = CmdParser(add_help=False, prog='ls',
description='''Lists project, display group and
checkerboard settings. If no group ids
are specified, all display groups
are listed.''')
ls_parser.add_argument('gids', nargs='*', metavar='gid', type=int,
help='''ids of the display groups to be listed''')
ls_group = ls_parser.add_mutually_exclusive_group()
ls_group.add_argument('-s', '--settings', action='store_true',
help='list only project settings')
ls_group.add_argument('-g', '--groups', action='store_true',
help='list only display groups')
ls_group.add_argument('-d', '--disp_ops', action='store_true',
help='list display options')
+ ls_group.add_argument('-o', '--orders', action='store_true',
+ help='list group orderings')
def help_ls(self):
self.__class__.ls_parser.print_help()
def do_ls(self, line):
"""Lists project, display group and checkerboard settings."""
def ls_str(s, seps=[',',';']):
"""Special space-saving output formatter."""
if type(s) in [tuple, list]:
if len(seps) > 1:
newseps = seps[1:]
else:
newseps = seps
return seps[0].join([ls_str(i, newseps) for i in s])
else:
return str(s)
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.ls_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ls_parser.print_usage()
return
# Remove duplicates and ascending sort
args.gids = sorted(set(args.gids))
if len(self.cur_proj.groups) == 0:
if len(args.gids) > 0:
print 'this project has no display groups that can be listed'
- args.settings = True
+ return
else:
for gid in args.gids[:]:
if gid >= len(self.cur_proj.groups) or gid < 0:
args.gids.remove(gid)
print 'display group', gid, 'does not exist'
if args.gids == []:
args.gids = range(len(self.cur_proj.groups))
else:
# If any (valid) groups are specified
# don't show project settings
args.groups = True
- args.show_all = not max(args.settings, args.groups, args.disp_ops)
+ args.show_all = not max(args.settings, args.groups,
+ args.disp_ops, args.orders)
if args.show_all or args.settings:
print 'PROJECT SETTINGS'.center(70,'*')
print \
'name'.rjust(16),\
'fps'.rjust(7),\
'resolution'.rjust(14),\
'bg color'.rjust(18)
print \
ls_str(self.cur_proj.name).rjust(16),\
ls_str(self.cur_proj.fps).rjust(7),\
ls_str(self.cur_proj.res).rjust(14),\
ls_str(self.cur_proj.bg).rjust(18)
print \
'pre-display'.rjust(26),\
'post-display'.rjust(26)
print \
ls_str(self.cur_proj.pre).rjust(26),\
ls_str(self.cur_proj.post).rjust(26)
print \
'cross colors'.rjust(26),\
'cross times'.rjust(26)
print \
ls_str(self.cur_proj.cross_cols).rjust(26),\
ls_str(self.cur_proj.cross_times).rjust(26)
if args.show_all:
# Insert empty line between different info sets
print ''
if args.show_all or args.disp_ops:
print 'DISPLAY OPTIONS'.center(70,'*')
for k, v in self.cur_proj.disp_ops.items():
print ''.ljust(20), ls_str(k).ljust(20), ls_str(v).ljust(20)
if args.show_all:
# Insert empty line between different info sets
print ''
+ if args.show_all or args.orders:
+ print 'GROUP ORDERINGS'.center(70,'*')
+ if self.cur_proj.orders == []:
+ order = range(len(self.cur_proj.groups))
+ print \
+ ''.ljust(20),\
+ 'default order'.ljust(20),\
+ ls_str(order).ljust(20)
+ else:
+ for n, order in enumerate(self.cur_proj.orders):
+ print \
+ ''.ljust(20),\
+ 'order {n}'.format(n=n).ljust(20),\
+ ls_str(order).ljust(20)
+
+ if args.show_all:
+ # Insert empty line between different info sets
+ print ''
+
if args.show_all or args.groups:
for i, n in enumerate(args.gids):
if i != 0:
# Print newline seperator between each group
print ''
group = self.cur_proj.groups[n]
print 'GROUP {n}'.format(n=n).center(70,'*')
print \
'pre-display'.rjust(20),\
'display'.rjust(20),\
'post-display'.rjust(20)
print \
ls_str(group.pre).rjust(20),\
ls_str(group.disp).rjust(20),\
ls_str(group.post).rjust(20)
if len(group.shapes) > 0:
print \
''.rjust(2),\
'shape id'.rjust(8),\
'dims'.rjust(10),\
'init_unit'.rjust(14),\
'end_unit'.rjust(14),\
'position'.rjust(14)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.dims).rjust(10),\
ls_str(shape.init_unit).rjust(14),\
ls_str(shape.end_unit).rjust(14),\
ls_str(shape.position).rjust(14)
print '\n',\
''.rjust(2),\
'shape id'.rjust(8),\
'colors'.rjust(27),\
'anchor'.rjust(12),\
'freq'.rjust(6),\
'phase'.rjust(7)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.cols).rjust(27),\
ls_str(shape.anchor).rjust(12),\
ls_str(shape.freq).rjust(6),\
ls_str(shape.phase).rjust(7)
display_parser = CmdParser(add_help=False, prog='display',
description='''Displays the stimulus in a
window or in fullscreen.''')
display_parser.add_argument('-s', '--save', action='store_true',
help='''save specified display flags
as default flags for project
instead of presenting stimulus''')
display_parser.add_argument('-n', '--name', metavar='FOOBAR',
help='''name of log file to be written''')
display_parser.add_argument('-r', '--repeats', metavar='N', type=int,
help='''repeatedly display specified display
groups N number of times''')
display_parser.add_argument('-wl', '--waitless', action=store_truth(),
metavar='t/f',
help='''do not add waitscreens before the
start of each repeat''')
display_parser.add_argument('-f', '--fullscreen', action=store_truth(),
metavar='t/f',
help='sets fullscreen mode, ESC to quit')
display_parser.add_argument('-p', '--priority', metavar='LEVEL',
help='''set priority while displaying,
higher priority results in
less dropped frames (choices:
0-3, low, normal, high,
realtime)''')
display_parser.add_argument('-pt', '--phototest', action=store_truth(),
metavar='t/f',
help='''draw white test rectangle in topleft
corner of screen when groups become
visible for a photodiode to detect''')
display_parser.add_argument('-pb', '--photoburst', action=store_truth(),
metavar='t/f',
help='''make checkerboards only draw first
color for one frame to facilitate
testing with a photodiode''')
display_parser.add_argument('-lt', '--logtime', action=store_truth(),
metavar='t/f',
help='output frame timestamps to a log file')
display_parser.add_argument('-ld', '--logdur', action=store_truth(),
metavar='t/f',
help='output frame durations to a log file')
display_parser.add_argument('-ss', '--trigser', action=store_truth(),
metavar='t/f',
help='''send triggers through the serial port
when shapes are being displayed''')
display_parser.add_argument('-sp', '--trigpar', action=store_truth(),
metavar='t/f',
help='''send triggers through the parallel port
when shapes are being displayed''')
display_parser.add_argument('-fpst', metavar='M', type=int,
help='''unique trigger corresponding to a
checkerboard is sent after the shape
undergoes M color flips (default:
disabled, M=0)''')
display_parser.add_argument('-fc', '--freqcheck', action=store_truth(),
metavar='t/f',
help='''only send triggers for board color
flips at the start, middle and end
of the run''')
display_parser.add_argument('-et', '--eyetrack', action=store_truth(),
metavar='t/f',
help='''use eyetracking to ensure that subject
fixates on the cross in the center''')
display_parser.add_argument('-eu', '--etuser', action=store_truth(),
metavar='t/f',
help='''allow user to select eyetracking video
source from a dialog''')
display_parser.add_argument('-ev', '--etvideo', metavar='path',
help='''path (with no spaces) to eyetracking
video file to be used as the source''')
display_parser.add_argument('-ta', '--tryagain', metavar='I', type=int,
help='''append groups during which subject
failed to fixate up to I times to the
list of groups to be displayed
(default: disabled, I=0)''')
display_parser.add_argument('-tb', '--trybreak', metavar='J', type=int,
help='''used with --tryagain, append a wait
screen to the list of groups to be
displayed after every J groups have
been appended to the list (default:
J=total number of groups)''')
display_parser.add_argument('-nl', '--nolog', action=store_truth(),
metavar='t/f',
help='''do not write a log file''')
display_parser.add_argument('order', nargs='*', metavar='id', type=int,
help='''order in which groups should be
displayed (default: random order
from list of orders if specified
in project, ascending otherwise)''')
def help_display(self):
self.__class__.display_parser.print_help()
def do_display(self, line):
"""Displays the stimulus in a window or in fullscreen"""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.display_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
if len(args.order) > 0:
for i in set(args.order):
if i >= len(self.cur_proj.groups) or i < -1:
print 'error: group', i, 'does not exist'
return
if args.eyetrack and eyetracking.available:
if not eyetracking.is_calibrated():
try:
self.do_calibrate('',query=True)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
return
if args.save:
self.cur_proj.set_display_flags(repeats=args.repeats,
waitless=args.waitless,
fullscreen=args.fullscreen,
priority=args.priority,
logtime=args.logtime,
logdur=args.logdur,
trigser=args.trigser,
trigpar=args.trigpar,
fpst=args.fpst,
freqcheck=args.freqcheck,
phototest=args.phototest,
photoburst=args.photoburst,
eyetrack=args.eyetrack,
etuser=args.etuser,
etvideo=args.etvideo,
tryagain=args.tryagain,
trybreak=args.trybreak,
nolog=args.nolog)
print "display flags saved to project"
else:
print "displaying...",
try:
self.cur_proj.display(name=args.name,
repeats=args.repeats,
waitless=args.waitless,
fullscreen=args.fullscreen,
priority=args.priority,
logtime=args.logtime,
logdur=args.logdur,
trigser=args.trigser,
trigpar=args.trigpar,
fpst=args.fpst,
freqcheck=args.freqcheck,
phototest=args.phototest,
photoburst=args.photoburst,
eyetrack=args.eyetrack,
etuser=args.etuser,
etvideo=args.etvideo,
tryagain=args.tryagain,
trybreak=args.trybreak,
nolog=args.nolog,
order=args.order)
except (IOError, NotImplementedError,
eyetracking.EyetrackingError):
print ''
print "error:", str(sys.exc_value)
if args.priority != None:
try:
priority.set('normal')
except:
pass
return
print "done"
export_parser = CmdParser(add_help=False, prog='export',
description='''Exports stimulus as an image
sequence (in a folder) to the
specified directory.''')
export_parser.add_argument('-n','--nofolder',
dest='folder', action='store_false',
help='''force images not to exported in
a containing folder''')
export_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly export specified display
groups N number of times''')
export_parser.add_argument('duration', nargs='?',
type=to_decimal, default='Infinity',
help='''number of seconds of the stimulus
that should be exported (default:
as long as the entire stimulus)''')
export_parser.add_argument('dir', nargs='?', default=os.getcwd(),
help='''destination directory for export
(default: current working directory)''')
export_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be exported
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_export(self):
self.__class__.export_parser.print_help()
def do_export(self, line):
"""Exports stimulus as an image sequence to the specified directory."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.export_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.export_parser.print_usage()
return
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < 0:
print 'error: group', i, 'does not exist'
return
groupq = [self.cur_proj.groups[i] for i in args.idlist]
else:
groupq = list(self.cur_proj.groups)
if args.repeat != None:
groupq = list(groupq * args.repeat)
try:
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
folder=args.folder)
except IOError:
print "error:", str(sys.exc_value)
return
except core.FrameOverflowError:
print "warning:", str(sys.exc_value)
print "Are you sure you want to continue?"
while True:
try:
if self.__class__.yn_parse(raw_input()):
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
folder=args.folder,
force=True)
break
else:
return
except TypeError:
print str(sys.exc_value)
except EOFError:
return
print "Export done."
def do_calibrate(self, line, query=False):
"""Calibrate subject for eyetracking, or load a calibration file."""
if not eyetracking.available:
print "error: eyetracking functionality not available"
return
if query:
print "path to calibration file (leave empty for GUI tool):"
try:
path = raw_input().strip().strip('"\'')
except EOFError:
msg = "calibration cancelled"
raise eyetracking.EyetrackingError(msg)
else:
path = line.strip().strip('"\'')
if len(path) == 0:
path = None
if not eyetracking.is_source_ready():
# Select default source if none has been selected
eyetracking.select_source()
try:
eyetracking.calibrate(path)
except eyetracking.EyetrackingError:
if query:
raise
else:
print "error:", str(sys.exc_value)
return
if len(path) > 0:
print "calibration file successfully loaded"
etsetup_parser = CmdParser(add_help=False, prog='etsetup',
description='''Set various eyetracking
parameters.''')
etsetup_parser.add_argument('-fp', '--fixperiod', type=int, metavar='MS',
help='''time in milliseconds subject
has to stare at the same spot
for fixation to be detected''')
etsetup_parser.add_argument('-fr', '--fixrange', type=float, metavar='MM',
help='''distance in mm beyond which the
eye position cannot change for
a fixation to be detected''')
etsetup_parser.add_argument('-s', '--size', metavar='WIDTH,HEIGHT',
action=store_tuple(2, ',', float),
help='physical screen dimensions in mm')
etsetup_parser.add_argument('-vd', '--viewdist', type=int, metavar='MM',
help='''viewing distance between subject's
eyes and the screen''')
def help_etsetup(self):
self.__class__.etsetup_parser.print_help()
def do_etsetup(self, line):
try:
args = self.__class__.etsetup_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.etsetup_parser.print_usage()
return
try:
eyetracking.setup(viewing_distance=args.viewdist,
screen_dims=args.size,
fixation_period=args.fixperiod,
fixation_range=args.fixrange)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
def do_pwd(self, line):
"""Prints the current working directory."""
print os.getcwd()
def do_cd(self, line):
"""Change working directory to specified path."""
path = line.strip().strip('"\'')
if not os.path.isdir(path):
print "error: specified path is not a directory"
return
os.chdir(path)
def do_quit(self, line):
"""Quits the program."""
if self.save_check():
return
return True
def help_EOF(self):
print "Typing {0} issues this command, which quits the program."\
.format(CMD_EOF_STRING)
def do_EOF(self, line):
"""Typing Ctrl-D issues this command, which quits the program."""
print '\r'
if self.save_check():
return
return True
def help_help(self):
print 'Prints a list of commands.'
print "Type 'help <topic>' for more details on each command."
def default(self, line):
command = line.split()[0]
print \
"'{0}' is not a checkergen command.".format(command),\
"Type 'help' for a list of commands"
|
ztangent/checkergen
|
171c258ac74113b93a4513602ccf8d1411a09c63
|
Display options can be listed with ls command.
|
diff --git a/src/cli.py b/src/cli.py
index a1dae74..8ba0098 100644
--- a/src/cli.py
+++ b/src/cli.py
@@ -106,1003 +106,1014 @@ def process_args(args):
args.proj = None
args.group = None
if args.display_flag or args.export_flag:
msg = 'error: no project file specified for display or export'
return msg
class CmdParserError(Exception):
"""To be raised when CmdParser encounters an error."""
pass
class CmdParser(argparse.ArgumentParser):
"""Override ArgumentParser so that it doesn't exit the program."""
def error(self, msg):
raise CmdParserError(msg)
class CkgCmd(cmd.Cmd):
@staticmethod
def yn_parse(s):
if s in ['y', 'Y', 'yes', 'YES', 'Yes']:
return True
elif s in ['n', 'N', 'no', 'NO', 'No']:
return False
else:
msg = "only 'y','n' or variants accepted"
raise ValueError(msg)
def save_check(self, msg=None):
"""Checks and prompts the user to save if necessary."""
if self.cur_proj == None:
return
if not self.cur_proj.is_dirty():
return
if msg == None:
msg = 'Would you like to save the current project first? (y/n)'
print msg
while True:
try:
if self.__class__.yn_parse(raw_input()):
self.do_save('')
break
except TypeError:
print str(sys.exc_value)
except EOFError:
return True
def do_new(self, line):
"""Creates new project with given name (can contain whitespace)."""
name = line.strip().strip('"\'')
if len(name) == 0:
name = 'untitled'
if self.save_check():
return
self.cur_proj = core.CkgProj(name=name)
print 'project \'{0}\' created'.format(self.cur_proj.name)
def do_open(self, line):
"""Open specified project file."""
path = line.strip().strip('"\'')
if len(path) == 0:
print 'error: no path specified'
return
if self.save_check():
return
try:
self.cur_proj = core.CkgProj(path=path)
except (core.FileFormatError, IOError):
print "error:", str(sys.exc_value)
return
os.chdir(os.path.dirname(os.path.abspath(path)))
try:
self.cur_group = self.cur_proj.groups[0]
except IndexError:
self.cur_group = None
print 'project \'{0}\' loaded'.format(self.cur_proj.name)
def do_close(self, line):
"""Prompts the user to save, then closes current project."""
if self.cur_proj == None:
print 'no project to close'
return
if self.save_check():
return
self.cur_proj = None
print 'project closed'
def do_save(self, line):
"""Saves the current project to the specified path."""
if self.cur_proj == None:
print 'no project to save'
return
path = line.strip().strip('"\'')
if len(path) == 0:
path = os.getcwd()
path = os.path.abspath(path)
if os.path.isdir(path):
path = os.path.join(path,
'.'.join([self.cur_proj.name, core.CKG_FMT]))
elif os.path.isdir(os.path.dirname(path)):
pass
else:
print 'error: specified directory does not exist'
return
# project save will add file extension if necessary
try:
path = self.cur_proj.save(path)
except IOError:
print "error:", str(sys.exc_value)
return
print 'project saved to "{0}"'.format(path)
set_parser = CmdParser(add_help=False, prog='set',
description='''Sets various project settings.''')
set_parser.add_argument('--name', help='''project name, always the same as
the filename without
the extension''')
set_parser.add_argument('--fps', type=to_decimal,
help='''number of stimulus frames
rendered per second''')
set_parser.add_argument('--res', action=store_tuple(2, ',', int),
help='stimulus canvas size/resolution in pixels',
metavar='WIDTH,HEIGHT')
set_parser.add_argument('--bg', metavar='COLOR', type=to_color,
help='''background color of the canvas
(color format: R,G,B,
component range from 0-255)''')
set_parser.add_argument('--pre', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown before any display groups''')
set_parser.add_argument('--post', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown after all display groups''')
set_parser.add_argument('--cross_cols', metavar='COLOR1,COLOR2',
action=store_tuple(2, ',', to_color, [';']),
help='''fixation cross coloration
(color format: R;G;B,
component range from 0-255)''')
set_parser.add_argument('--cross_times', metavar='TIME1,TIME2',
action=store_tuple(2, ',', to_decimal),
help='''time in seconds each cross color
will be displayed''')
def help_set(self):
self.__class__.set_parser.print_help()
def do_set(self, line):
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
try:
args = self.__class__.set_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.set_parser.print_usage()
return
names = public_dir(args)
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
setattr(self.cur_proj, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.set_parser.print_usage()
mkgrp_parser = CmdParser(add_help=False, prog='mkgrp',
formatter_class=
argparse.ArgumentDefaultsHelpFormatter,
description='''Makes a new display group
with the given parameters.''')
mkgrp_parser.add_argument('pre', type=to_decimal, default=0, nargs='?',
help='''time in seconds a blank screen will
be shown before shapes are displayed''')
mkgrp_parser.add_argument('disp', type=to_decimal,
nargs='?', default='Infinity',
help='''time in seconds shapes will be
displayed''')
mkgrp_parser.add_argument('post', type=to_decimal, default=0, nargs='?',
help='''time in seconds a blank screen will
be shown after shapes are displayed''')
def help_mkgrp(self):
self.__class__.mkgrp_parser.print_help()
def do_mkgrp(self, line):
"""Makes a display group with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
try:
args = self.__class__.mkgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mkgrp_parser.print_usage()
return
group_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_group = core.CkgDisplayGroup(**group_dict)
new_id = self.cur_proj.add_group(new_group)
print "display group", new_id, "added"
self.cur_group = new_group
print "group", new_id, "is now the current display group"
edgrp_parser = CmdParser(add_help=False, prog='edgrp',
description='''Edits attributes of display groups
specified by ids.''')
edgrp_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='ids of display groups to be edited')
edgrp_parser.add_argument('--pre', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown before shapes are displayed''')
edgrp_parser.add_argument('--disp', type=to_decimal, metavar='SECONDS',
help='''time in seconds shapes will be
displayed''')
edgrp_parser.add_argument('--post', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown after shapes are displayed''')
def help_edgrp(self):
self.__class__.edgrp_parser.print_help()
def do_edgrp(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.edgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.edgrp_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_proj.groups) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_group_attr(x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.edgrp_parser.print_usage()
rmgrp_parser = CmdParser(add_help=False, prog='rmgrp',
description='''Removes display groups specified
by ids.''')
rmgrp_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='ids of display groups to be removed')
rmgrp_parser.add_argument('-a', '--all', action='store_true',
help='remove all groups from the project')
def help_rmgrp(self):
self.__class__.rmgrp_parser.print_help()
def do_rmgrp(self, line):
"""Removes display groups specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups to remove'
return
try:
args = self.__class__.rmgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rmgrp_parser.print_usage()
return
rmlist = []
if args.all:
for group in self.cur_proj.groups[:]:
self.cur_proj.del_group(group)
print "all display groups removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_proj.groups) or x < 0:
print "display group", x, "does not exist"
continue
rmlist.append(self.cur_proj.groups[x])
print "display group", x, "removed"
for group in rmlist:
self.cur_proj.del_group(group)
# Remember to point self.cur_group somewhere sane
if self.cur_group not in self.cur_proj.groups:
if len(self.cur_proj.groups) == 0:
self.cur_group = None
else:
self.cur_group = self.cur_proj.groups[0]
print "group 0 is now the current display group"
chgrp_parser = CmdParser(add_help=False, prog='chgrp',
description='''Changes display group that is
currently active for editing.
Prints current group id if
no group id is specified''')
chgrp_parser.add_argument('gid', metavar='id', type=int, nargs='?',
help='id of display group to be made active')
def help_chgrp(self):
self.__class__.chgrp_parser.print_help()
def do_chgrp(self, line):
"""Changes group that is currently active for editing."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups that can be made active'
return
try:
args = self.__class__.chgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.chgrp_parser.print_usage()
return
if args.gid == None:
print "group",\
self.cur_proj.groups.index(self.cur_group),\
"is the current display group"
elif args.gid >= len(self.cur_proj.groups) or args.gid < 0:
print "group", args.gid, "does not exist"
else:
self.cur_group = self.cur_proj.groups[args.gid]
print "group", args.gid, "is now the current display group"
mk_parser = CmdParser(add_help=False, prog='mk',
description='''Makes a new checkerboard in the
current group with the given
parameters.''')
mk_parser.add_argument('dims', action=store_tuple(2, ',', to_decimal),
help='''width,height of checkerboard in no. of
unit cells''')
mk_parser.add_argument('init_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of initial unit cell in pixels')
mk_parser.add_argument('end_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of final unit cell in pixels')
mk_parser.add_argument('position', action=store_tuple(2, ',', to_decimal),
help='x,y position of checkerboard in pixels')
mk_parser.add_argument('anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='anchor')
mk_parser.add_argument('cols', action=store_tuple(2, ',', to_color, [';']),
help='''color1,color2 of the checkerboard
(color format: R;G;B,
component range from 0-255)''')
mk_parser.add_argument('freq', type=to_decimal,
help='frequency of color reversal in Hz')
mk_parser.add_argument('phase', type=to_decimal, nargs='?', default='0',
help='initial phase in degrees')
def help_mk(self):
self.__class__.mk_parser.print_help()
def do_mk(self, line):
"""Makes a checkerboard with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
if self.cur_group == None:
print 'automatically adding display group...'
self.do_mkgrp('')
try:
args = self.__class__.mk_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mk_parser.print_usage()
return
shape_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_shape = core.CheckerBoard(**shape_dict)
new_id = self.cur_proj.add_shape_to_group(self.cur_group, new_shape)
print "checkerboard", new_id, "added"
ed_parser = CmdParser(add_help=False, prog='ed',
description='''Edits attributes of checkerboards
specified by ids.''')
ed_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='''ids of checkerboards in the current
group to be edited''')
ed_parser.add_argument('--dims', action=store_tuple(2, ',', to_decimal),
help='checkerboard dimensions in unit cells',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--init_unit',
action=store_tuple(2, ',', to_decimal),
help='initial unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--end_unit',
action=store_tuple(2, ',', to_decimal),
help='final unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--position',
action=store_tuple(2, ',', to_decimal),
help='position of checkerboard in pixels',
metavar='X,Y')
ed_parser.add_argument('--anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='LOCATION')
ed_parser.add_argument('--cols', metavar='COLOR1,COLOR2',
action=store_tuple(2, ',', to_color, [';']),
help='''checkerboard colors (color format:
R;G;B, component range
from 0-255)''')
ed_parser.add_argument('--freq', type=to_decimal,
help='frequency of color reversal in Hz')
ed_parser.add_argument('--phase', type=to_decimal,
help='initial phase in degrees')
def help_ed(self):
self.__class__.ed_parser.print_help()
def do_ed(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, please create one first'
return
try:
args = self.__class__.ed_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ed_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_group.shapes) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_shape_attr(self.cur_group, x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.ed_parser.print_usage()
rm_parser = CmdParser(add_help=False, prog='rm',
description='''Removes checkerboards specified
by ids.''')
rm_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''ids of checkerboards in the current group
to be removed''')
rm_parser.add_argument('-a', '--all', action='store_true',
help='''remove all checkerboards in the
current group''')
def help_rm(self):
self.__class__.rm_parser.print_help()
def do_rm(self, line):
"""Removes checkerboards specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, no boards to remove'
return
try:
args = self.__class__.rm_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rm_parser.print_usage()
return
rmlist = []
if args.all:
for shape in self.cur_group.shapes:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
print "all checkerboards removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_group.shapes) or x < 0:
print "checkerboard", x, "does not exist"
continue
rmlist.append(self.cur_group.shapes[x])
print "checkerboard", x, "removed"
for shape in rmlist:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
ls_parser = CmdParser(add_help=False, prog='ls',
description='''Lists project, display group and
checkerboard settings. If no group ids
are specified, all display groups
are listed.''')
- ls_parser.add_argument('gidlist', nargs='*', metavar='gid', type=int,
+ ls_parser.add_argument('gids', nargs='*', metavar='gid', type=int,
help='''ids of the display groups to be listed''')
ls_group = ls_parser.add_mutually_exclusive_group()
ls_group.add_argument('-s', '--settings', action='store_true',
- help='list only project settings')
+ help='list only project settings')
ls_group.add_argument('-g', '--groups', action='store_true',
- help='list only display groups')
+ help='list only display groups')
+ ls_group.add_argument('-d', '--disp_ops', action='store_true',
+ help='list display options')
def help_ls(self):
self.__class__.ls_parser.print_help()
def do_ls(self, line):
"""Lists project, display group and checkerboard settings."""
def ls_str(s, seps=[',',';']):
"""Special space-saving output formatter."""
if type(s) in [tuple, list]:
if len(seps) > 1:
newseps = seps[1:]
else:
newseps = seps
return seps[0].join([ls_str(i, newseps) for i in s])
else:
return str(s)
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.ls_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ls_parser.print_usage()
return
# Remove duplicates and ascending sort
- args.gidlist = sorted(set(args.gidlist))
+ args.gids = sorted(set(args.gids))
if len(self.cur_proj.groups) == 0:
- if len(args.gidlist) > 0:
+ if len(args.gids) > 0:
print 'this project has no display groups that can be listed'
args.settings = True
else:
- for gid in args.gidlist[:]:
+ for gid in args.gids[:]:
if gid >= len(self.cur_proj.groups) or gid < 0:
- args.gidlist.remove(gid)
+ args.gids.remove(gid)
print 'display group', gid, 'does not exist'
- if args.gidlist == []:
- args.gidlist = range(len(self.cur_proj.groups))
+ if args.gids == []:
+ args.gids = range(len(self.cur_proj.groups))
else:
# If any (valid) groups are specified
# don't show project settings
args.groups = True
- if not args.groups:
+ args.show_all = not max(args.settings, args.groups, args.disp_ops)
+
+ if args.show_all or args.settings:
print 'PROJECT SETTINGS'.center(70,'*')
print \
'name'.rjust(16),\
'fps'.rjust(7),\
'resolution'.rjust(14),\
'bg color'.rjust(18)
print \
ls_str(self.cur_proj.name).rjust(16),\
ls_str(self.cur_proj.fps).rjust(7),\
ls_str(self.cur_proj.res).rjust(14),\
ls_str(self.cur_proj.bg).rjust(18)
print \
'pre-display'.rjust(26),\
'post-display'.rjust(26)
print \
ls_str(self.cur_proj.pre).rjust(26),\
ls_str(self.cur_proj.post).rjust(26)
print \
'cross colors'.rjust(26),\
'cross times'.rjust(26)
print \
ls_str(self.cur_proj.cross_cols).rjust(26),\
ls_str(self.cur_proj.cross_times).rjust(26)
+ if args.show_all:
+ # Insert empty line between different info sets
+ print ''
+
+ if args.show_all or args.disp_ops:
+ print 'DISPLAY OPTIONS'.center(70,'*')
+ for k, v in self.cur_proj.disp_ops.items():
+ print ''.ljust(20), ls_str(k).ljust(20), ls_str(v).ljust(20)
- if not args.settings and not args.groups:
- # Insert empty line if both groups and project
- # settings are listed
+ if args.show_all:
+ # Insert empty line between different info sets
print ''
- if not args.settings:
- for i, n in enumerate(args.gidlist):
+ if args.show_all or args.groups:
+ for i, n in enumerate(args.gids):
if i != 0:
# Print newline seperator between each group
print ''
group = self.cur_proj.groups[n]
print 'GROUP {n}'.format(n=n).center(70,'*')
print \
'pre-display'.rjust(20),\
'display'.rjust(20),\
'post-display'.rjust(20)
print \
ls_str(group.pre).rjust(20),\
ls_str(group.disp).rjust(20),\
ls_str(group.post).rjust(20)
if len(group.shapes) > 0:
print \
''.rjust(2),\
'shape id'.rjust(8),\
'dims'.rjust(10),\
'init_unit'.rjust(14),\
'end_unit'.rjust(14),\
'position'.rjust(14)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.dims).rjust(10),\
ls_str(shape.init_unit).rjust(14),\
ls_str(shape.end_unit).rjust(14),\
ls_str(shape.position).rjust(14)
print '\n',\
''.rjust(2),\
'shape id'.rjust(8),\
'colors'.rjust(27),\
'anchor'.rjust(12),\
'freq'.rjust(6),\
'phase'.rjust(7)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.cols).rjust(27),\
ls_str(shape.anchor).rjust(12),\
ls_str(shape.freq).rjust(6),\
ls_str(shape.phase).rjust(7)
display_parser = CmdParser(add_help=False, prog='display',
description='''Displays the stimulus in a
window or in fullscreen.''')
display_parser.add_argument('-s', '--save', action='store_true',
help='''save specified display flags
as default flags for project
instead of presenting stimulus''')
display_parser.add_argument('-n', '--name', metavar='FOOBAR',
help='''name of log file to be written''')
display_parser.add_argument('-r', '--repeats', metavar='N', type=int,
help='''repeatedly display specified display
groups N number of times''')
display_parser.add_argument('-wl', '--waitless', action=store_truth(),
metavar='t/f',
help='''do not add waitscreens before the
start of each repeat''')
display_parser.add_argument('-f', '--fullscreen', action=store_truth(),
metavar='t/f',
help='sets fullscreen mode, ESC to quit')
display_parser.add_argument('-p', '--priority', metavar='LEVEL',
help='''set priority while displaying,
higher priority results in
less dropped frames (choices:
0-3, low, normal, high,
realtime)''')
display_parser.add_argument('-pt', '--phototest', action=store_truth(),
metavar='t/f',
help='''draw white test rectangle in topleft
corner of screen when groups become
visible for a photodiode to detect''')
display_parser.add_argument('-pb', '--photoburst', action=store_truth(),
metavar='t/f',
help='''make checkerboards only draw first
color for one frame to facilitate
testing with a photodiode''')
display_parser.add_argument('-lt', '--logtime', action=store_truth(),
metavar='t/f',
help='output frame timestamps to a log file')
display_parser.add_argument('-ld', '--logdur', action=store_truth(),
metavar='t/f',
help='output frame durations to a log file')
display_parser.add_argument('-ss', '--trigser', action=store_truth(),
metavar='t/f',
help='''send triggers through the serial port
when shapes are being displayed''')
display_parser.add_argument('-sp', '--trigpar', action=store_truth(),
metavar='t/f',
help='''send triggers through the parallel port
when shapes are being displayed''')
display_parser.add_argument('-fpst', metavar='M', type=int,
help='''unique trigger corresponding to a
checkerboard is sent after the shape
undergoes M color flips (default:
disabled, M=0)''')
display_parser.add_argument('-fc', '--freqcheck', action=store_truth(),
metavar='t/f',
help='''only send triggers for board color
flips at the start, middle and end
of the run''')
display_parser.add_argument('-et', '--eyetrack', action=store_truth(),
metavar='t/f',
help='''use eyetracking to ensure that subject
fixates on the cross in the center''')
display_parser.add_argument('-eu', '--etuser', action=store_truth(),
metavar='t/f',
help='''allow user to select eyetracking video
source from a dialog''')
display_parser.add_argument('-ev', '--etvideo', metavar='path',
help='''path (with no spaces) to eyetracking
video file to be used as the source''')
display_parser.add_argument('-ta', '--tryagain', metavar='I', type=int,
help='''append groups during which subject
failed to fixate up to I times to the
list of groups to be displayed
(default: disabled, I=0)''')
display_parser.add_argument('-tb', '--trybreak', metavar='J', type=int,
help='''used with --tryagain, append a wait
screen to the list of groups to be
displayed after every J groups have
been appended to the list (default:
J=total number of groups)''')
display_parser.add_argument('-nl', '--nolog', action=store_truth(),
metavar='t/f',
help='''do not write a log file''')
display_parser.add_argument('order', nargs='*', metavar='id', type=int,
help='''order in which groups should be
displayed (default: random order
from list of orders if specified
in project, ascending otherwise)''')
def help_display(self):
self.__class__.display_parser.print_help()
def do_display(self, line):
"""Displays the stimulus in a window or in fullscreen"""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.display_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
if len(args.order) > 0:
for i in set(args.order):
if i >= len(self.cur_proj.groups) or i < -1:
print 'error: group', i, 'does not exist'
return
if args.eyetrack and eyetracking.available:
if not eyetracking.is_calibrated():
try:
self.do_calibrate('',query=True)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
return
if args.save:
self.cur_proj.set_display_flags(repeats=args.repeats,
waitless=args.waitless,
fullscreen=args.fullscreen,
priority=args.priority,
logtime=args.logtime,
logdur=args.logdur,
trigser=args.trigser,
trigpar=args.trigpar,
fpst=args.fpst,
freqcheck=args.freqcheck,
phototest=args.phototest,
photoburst=args.photoburst,
eyetrack=args.eyetrack,
etuser=args.etuser,
etvideo=args.etvideo,
tryagain=args.tryagain,
trybreak=args.trybreak,
nolog=args.nolog)
print "display flags saved to project"
else:
print "displaying...",
try:
self.cur_proj.display(name=args.name,
repeats=args.repeats,
waitless=args.waitless,
fullscreen=args.fullscreen,
priority=args.priority,
logtime=args.logtime,
logdur=args.logdur,
trigser=args.trigser,
trigpar=args.trigpar,
fpst=args.fpst,
freqcheck=args.freqcheck,
phototest=args.phototest,
photoburst=args.photoburst,
eyetrack=args.eyetrack,
etuser=args.etuser,
etvideo=args.etvideo,
tryagain=args.tryagain,
trybreak=args.trybreak,
nolog=args.nolog,
order=args.order)
except (IOError, NotImplementedError,
eyetracking.EyetrackingError):
print ''
print "error:", str(sys.exc_value)
if args.priority != None:
try:
priority.set('normal')
except:
pass
return
print "done"
export_parser = CmdParser(add_help=False, prog='export',
description='''Exports stimulus as an image
sequence (in a folder) to the
specified directory.''')
export_parser.add_argument('-n','--nofolder',
dest='folder', action='store_false',
help='''force images not to exported in
a containing folder''')
export_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly export specified display
groups N number of times''')
export_parser.add_argument('duration', nargs='?',
type=to_decimal, default='Infinity',
help='''number of seconds of the stimulus
that should be exported (default:
as long as the entire stimulus)''')
export_parser.add_argument('dir', nargs='?', default=os.getcwd(),
help='''destination directory for export
(default: current working directory)''')
export_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be exported
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_export(self):
self.__class__.export_parser.print_help()
def do_export(self, line):
"""Exports stimulus as an image sequence to the specified directory."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.export_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.export_parser.print_usage()
return
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < 0:
print 'error: group', i, 'does not exist'
return
groupq = [self.cur_proj.groups[i] for i in args.idlist]
else:
groupq = list(self.cur_proj.groups)
if args.repeat != None:
groupq = list(groupq * args.repeat)
try:
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
folder=args.folder)
except IOError:
print "error:", str(sys.exc_value)
return
except core.FrameOverflowError:
print "warning:", str(sys.exc_value)
print "Are you sure you want to continue?"
while True:
try:
if self.__class__.yn_parse(raw_input()):
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
folder=args.folder,
force=True)
break
else:
return
except TypeError:
print str(sys.exc_value)
except EOFError:
return
print "Export done."
def do_calibrate(self, line, query=False):
"""Calibrate subject for eyetracking, or load a calibration file."""
if not eyetracking.available:
print "error: eyetracking functionality not available"
return
if query:
print "path to calibration file (leave empty for GUI tool):"
try:
path = raw_input().strip().strip('"\'')
except EOFError:
msg = "calibration cancelled"
raise eyetracking.EyetrackingError(msg)
else:
path = line.strip().strip('"\'')
if len(path) == 0:
path = None
if not eyetracking.is_source_ready():
# Select default source if none has been selected
eyetracking.select_source()
try:
eyetracking.calibrate(path)
except eyetracking.EyetrackingError:
if query:
raise
else:
print "error:", str(sys.exc_value)
return
if len(path) > 0:
print "calibration file successfully loaded"
etsetup_parser = CmdParser(add_help=False, prog='etsetup',
description='''Set various eyetracking
parameters.''')
etsetup_parser.add_argument('-fp', '--fixperiod', type=int, metavar='MS',
help='''time in milliseconds subject
has to stare at the same spot
for fixation to be detected''')
etsetup_parser.add_argument('-fr', '--fixrange', type=float, metavar='MM',
help='''distance in mm beyond which the
eye position cannot change for
a fixation to be detected''')
etsetup_parser.add_argument('-s', '--size', metavar='WIDTH,HEIGHT',
action=store_tuple(2, ',', float),
help='physical screen dimensions in mm')
etsetup_parser.add_argument('-vd', '--viewdist', type=int, metavar='MM',
help='''viewing distance between subject's
eyes and the screen''')
def help_etsetup(self):
self.__class__.etsetup_parser.print_help()
def do_etsetup(self, line):
try:
args = self.__class__.etsetup_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.etsetup_parser.print_usage()
return
try:
eyetracking.setup(viewing_distance=args.viewdist,
screen_dims=args.size,
fixation_period=args.fixperiod,
fixation_range=args.fixrange)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
def do_pwd(self, line):
"""Prints the current working directory."""
print os.getcwd()
def do_cd(self, line):
"""Change working directory to specified path."""
path = line.strip().strip('"\'')
if not os.path.isdir(path):
print "error: specified path is not a directory"
return
os.chdir(path)
def do_quit(self, line):
"""Quits the program."""
if self.save_check():
return
return True
def help_EOF(self):
print "Typing {0} issues this command, which quits the program."\
.format(CMD_EOF_STRING)
def do_EOF(self, line):
"""Typing Ctrl-D issues this command, which quits the program."""
print '\r'
if self.save_check():
return
return True
def help_help(self):
print 'Prints a list of commands.'
print "Type 'help <topic>' for more details on each command."
def default(self, line):
command = line.split()[0]
print \
"'{0}' is not a checkergen command.".format(command),\
"Type 'help' for a list of commands"
|
ztangent/checkergen
|
32d135dc7068dcd9ad9686f1cd4809e1d55951b8
|
Added ability to set display flags.
|
diff --git a/example.ckg b/example.ckg
index 262799c..d1a89a7 100644
--- a/example.ckg
+++ b/example.ckg
@@ -1,77 +1,76 @@
<?xml version="1.0" ?>
<project xmlns="http://github.com/ZOMGxuan/checkergen">
<fps>Decimal('60')</fps>
<res>(800, 600)</res>
<bg>(127, 127, 127)</bg>
- <export_fmt>'png'</export_fmt>
<pre>Decimal('0')</pre>
<post>Decimal('0')</post>
<cross_cols>((0, 0, 0), (255, 0, 0))</cross_cols>
<cross_times>(Decimal('Infinity'), Decimal('1'))</cross_times>
<orders>[]</orders>
<disp_ops>
<repeats>1</repeats>
<waitless>False</waitless>
<fullscreen>False</fullscreen>
<priority>None</priority>
<logtime>False</logtime>
<logdur>False</logdur>
<trigser>False</trigser>
<trigpar>False</trigpar>
<fpst>0</fpst>
<freqcheck>False</freqcheck>
<phototest>False</phototest>
<photoburst>False</photoburst>
<eyetrack>False</eyetrack>
<etuser>False</etuser>
<etvideo>None</etvideo>
<tryagain>0</tryagain>
<trybreak>None</trybreak>
<nolog>False</nolog>
</disp_ops>
<group>
<pre>Decimal('2')</pre>
<disp>Decimal('10')</disp>
<post>Decimal('2')</post>
<shape type="board">
<dims>(5, 5)</dims>
<init_unit>(Decimal('40'), Decimal('40'))</init_unit>
<end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<position>(Decimal('420'), Decimal('320'))</position>
<anchor>'bottomleft'</anchor>
<cols>((0, 0, 0), (255, 255, 255))</cols>
<freq>Decimal('1')</freq>
<phase>Decimal('0')</phase>
</shape>
<shape type="board">
<dims>(5, 5)</dims>
<init_unit>(Decimal('40'), Decimal('40'))</init_unit>
<end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<position>(Decimal('380'), Decimal('320'))</position>
<anchor>'bottomright'</anchor>
<cols>((0, 0, 0), (255, 255, 255))</cols>
<freq>Decimal('2')</freq>
<phase>Decimal('90')</phase>
</shape>
<shape type="board">
<dims>(5, 5)</dims>
<init_unit>(Decimal('40'), Decimal('40'))</init_unit>
<end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<position>(Decimal('420'), Decimal('280'))</position>
<anchor>'topleft'</anchor>
<cols>((0, 0, 0), (255, 255, 255))</cols>
<freq>Decimal('3')</freq>
<phase>Decimal('180')</phase>
</shape>
<shape type="board">
<dims>(5, 5)</dims>
<init_unit>(Decimal('40'), Decimal('40'))</init_unit>
<end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<position>(Decimal('380'), Decimal('280'))</position>
<anchor>'topright'</anchor>
<cols>((0, 0, 0), (255, 255, 255))</cols>
<freq>Decimal('4')</freq>
<phase>Decimal('270')</phase>
</shape>
</group>
</project>
diff --git a/src/cli.py b/src/cli.py
index 95de2fb..a1dae74 100644
--- a/src/cli.py
+++ b/src/cli.py
@@ -1,1081 +1,1108 @@
"""Defines command-line-interface for checkergen."""
import os
import sys
if os.name == 'posix':
import readline
import argparse
import cmd
import shlex
import core
import priority
import eyetracking
from graphics import locations
from utils import *
CMD_PROMPT = '(ckg) '
CMD_EOF_STRING = 'Ctrl-D'
if sys.platform == 'win32':
CMD_EOF_STRING = 'Ctrl-Z + Enter'
CMD_INTRO = '\n'.join(["Enter 'help' for a list of commands.",
"Enter 'quit' or {0} to exit.".format(CMD_EOF_STRING)])
def store_tuple(nargs, sep, typecast=None, castargs=[]):
"""Returns argparse action that stores a tuple."""
class TupleAction(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
vallist = values.split(sep)
if len(vallist) != nargs:
msg = ("argument '{f}' should be a list of " +
"{nargs} values separated by '{sep}'").\
format(f=self.dest,nargs=nargs,sep=sep)
raise argparse.ArgumentError(self, msg)
if typecast != None:
for n, val in enumerate(vallist):
try:
val = typecast(*([val] + castargs))
vallist[n] = val
except (ValueError, TypeError):
msg = ("element '{val}' of argument '{f}' " +
"is of the wrong type").\
format(val=vallist[n],f=self.dest)
raise argparse.ArgumentError(self, msg)
setattr(args, self.dest, tuple(vallist))
return TupleAction
-def store_truth(y_words=['t','y'], n_words=['f', 'n']):
+def store_truth(y_words=['t','y','1','True','true','yes','Yes'],
+ n_words=['f','n','0','False','false','no','No']):
"""Returns argparse action that stores the truth based on keywords."""
class TruthAction(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
if values in y_words:
setattr(args, self.dest, True)
elif values in n_words:
setattr(args, self.dest, False)
else:
msg = 'true/false keyword unrecognized'
raise argparse.ArgumentError(self, msg)
return TruthAction
# The main parser invoked at the command-line
PARSER = argparse.ArgumentParser(
description='''Generate flashing checkerboard patterns for display
or export as a series of images, intended for use in
psychophysics experiments. Enters interactive command
line mode if no options are specified.''')
PARSER.add_argument('-c', '--cmd', dest='cmd_mode', action='store_true',
help='enter command line mode regardless of other options')
PARSER.add_argument('-d', '--display',
dest='display_flag', action='store_true',
- help='displays the animation on the screen')
+ help='displays the stimulus on the screen')
PARSER.add_argument('-e', '--export', dest='export_dur', metavar='DUR',
- help='export DUR seconds of the project animation')
+ help='export DUR seconds of the stimulus')
PARSER.add_argument('-f', '--fullscreen', action='store_true',
- help='animation displayed in fullscreen mode')
+ help='stimulus displayed in fullscreen mode')
PARSER.add_argument('--dir', dest='export_dir',
default=os.getcwd(), metavar='PATH',
help='''destination directory for export
(default: current working directory)''')
PARSER.add_argument('path', metavar='project', nargs='?', type=file,
help='checkergen project file to open')
def process_args(args):
"""Further processes the arguments returned by the main parser."""
if args.export_dur != None:
args.export_flag = True
else:
args.export_flag = False
if not args.display_flag and not args.export_flag:
args.cmd_mode = True
if args.path != None:
if not os.path.isfile(args.path):
msg = 'error: path specified is not a file'
return msg
args.proj = core.CkgProj(path=args.path)
os.chdir(os.path.dirname(os.path.abspath(args.path)))
try:
args.group = args.proj.groups[0]
except IndexError:
args.group = None
else:
args.proj = None
args.group = None
if args.display_flag or args.export_flag:
msg = 'error: no project file specified for display or export'
return msg
class CmdParserError(Exception):
"""To be raised when CmdParser encounters an error."""
pass
class CmdParser(argparse.ArgumentParser):
"""Override ArgumentParser so that it doesn't exit the program."""
def error(self, msg):
raise CmdParserError(msg)
class CkgCmd(cmd.Cmd):
@staticmethod
def yn_parse(s):
if s in ['y', 'Y', 'yes', 'YES', 'Yes']:
return True
elif s in ['n', 'N', 'no', 'NO', 'No']:
return False
else:
msg = "only 'y','n' or variants accepted"
raise ValueError(msg)
def save_check(self, msg=None):
"""Checks and prompts the user to save if necessary."""
if self.cur_proj == None:
return
if not self.cur_proj.is_dirty():
return
if msg == None:
msg = 'Would you like to save the current project first? (y/n)'
print msg
while True:
try:
if self.__class__.yn_parse(raw_input()):
self.do_save('')
break
except TypeError:
print str(sys.exc_value)
except EOFError:
return True
def do_new(self, line):
"""Creates new project with given name (can contain whitespace)."""
name = line.strip().strip('"\'')
if len(name) == 0:
name = 'untitled'
if self.save_check():
return
self.cur_proj = core.CkgProj(name=name)
print 'project \'{0}\' created'.format(self.cur_proj.name)
def do_open(self, line):
"""Open specified project file."""
path = line.strip().strip('"\'')
if len(path) == 0:
print 'error: no path specified'
return
if self.save_check():
return
try:
self.cur_proj = core.CkgProj(path=path)
except (core.FileFormatError, IOError):
print "error:", str(sys.exc_value)
return
os.chdir(os.path.dirname(os.path.abspath(path)))
try:
self.cur_group = self.cur_proj.groups[0]
except IndexError:
self.cur_group = None
print 'project \'{0}\' loaded'.format(self.cur_proj.name)
def do_close(self, line):
"""Prompts the user to save, then closes current project."""
if self.cur_proj == None:
print 'no project to close'
return
if self.save_check():
return
self.cur_proj = None
print 'project closed'
def do_save(self, line):
"""Saves the current project to the specified path."""
if self.cur_proj == None:
print 'no project to save'
return
path = line.strip().strip('"\'')
if len(path) == 0:
path = os.getcwd()
path = os.path.abspath(path)
if os.path.isdir(path):
path = os.path.join(path,
'.'.join([self.cur_proj.name, core.CKG_FMT]))
elif os.path.isdir(os.path.dirname(path)):
pass
else:
print 'error: specified directory does not exist'
return
# project save will add file extension if necessary
try:
path = self.cur_proj.save(path)
except IOError:
print "error:", str(sys.exc_value)
return
print 'project saved to "{0}"'.format(path)
set_parser = CmdParser(add_help=False, prog='set',
description='''Sets various project settings.''')
set_parser.add_argument('--name', help='''project name, always the same as
the filename without
the extension''')
set_parser.add_argument('--fps', type=to_decimal,
- help='''number of animation frames
+ help='''number of stimulus frames
rendered per second''')
set_parser.add_argument('--res', action=store_tuple(2, ',', int),
- help='animation canvas size/resolution in pixels',
+ help='stimulus canvas size/resolution in pixels',
metavar='WIDTH,HEIGHT')
set_parser.add_argument('--bg', metavar='COLOR', type=to_color,
help='''background color of the canvas
(color format: R,G,B,
component range from 0-255)''')
set_parser.add_argument('--pre', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown before any display groups''')
set_parser.add_argument('--post', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown after all display groups''')
set_parser.add_argument('--cross_cols', metavar='COLOR1,COLOR2',
action=store_tuple(2, ',', to_color, [';']),
help='''fixation cross coloration
(color format: R;G;B,
component range from 0-255)''')
set_parser.add_argument('--cross_times', metavar='TIME1,TIME2',
action=store_tuple(2, ',', to_decimal),
help='''time in seconds each cross color
will be displayed''')
def help_set(self):
self.__class__.set_parser.print_help()
def do_set(self, line):
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
try:
args = self.__class__.set_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.set_parser.print_usage()
return
names = public_dir(args)
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
setattr(self.cur_proj, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.set_parser.print_usage()
mkgrp_parser = CmdParser(add_help=False, prog='mkgrp',
formatter_class=
argparse.ArgumentDefaultsHelpFormatter,
description='''Makes a new display group
with the given parameters.''')
mkgrp_parser.add_argument('pre', type=to_decimal, default=0, nargs='?',
help='''time in seconds a blank screen will
be shown before shapes are displayed''')
mkgrp_parser.add_argument('disp', type=to_decimal,
nargs='?', default='Infinity',
help='''time in seconds shapes will be
displayed''')
mkgrp_parser.add_argument('post', type=to_decimal, default=0, nargs='?',
help='''time in seconds a blank screen will
be shown after shapes are displayed''')
def help_mkgrp(self):
self.__class__.mkgrp_parser.print_help()
def do_mkgrp(self, line):
"""Makes a display group with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
try:
args = self.__class__.mkgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mkgrp_parser.print_usage()
return
group_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_group = core.CkgDisplayGroup(**group_dict)
new_id = self.cur_proj.add_group(new_group)
print "display group", new_id, "added"
self.cur_group = new_group
print "group", new_id, "is now the current display group"
edgrp_parser = CmdParser(add_help=False, prog='edgrp',
description='''Edits attributes of display groups
specified by ids.''')
edgrp_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='ids of display groups to be edited')
edgrp_parser.add_argument('--pre', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown before shapes are displayed''')
edgrp_parser.add_argument('--disp', type=to_decimal, metavar='SECONDS',
help='''time in seconds shapes will be
displayed''')
edgrp_parser.add_argument('--post', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown after shapes are displayed''')
def help_edgrp(self):
self.__class__.edgrp_parser.print_help()
def do_edgrp(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.edgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.edgrp_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_proj.groups) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_group_attr(x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.edgrp_parser.print_usage()
rmgrp_parser = CmdParser(add_help=False, prog='rmgrp',
description='''Removes display groups specified
by ids.''')
rmgrp_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='ids of display groups to be removed')
rmgrp_parser.add_argument('-a', '--all', action='store_true',
help='remove all groups from the project')
def help_rmgrp(self):
self.__class__.rmgrp_parser.print_help()
def do_rmgrp(self, line):
"""Removes display groups specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups to remove'
return
try:
args = self.__class__.rmgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rmgrp_parser.print_usage()
return
rmlist = []
if args.all:
for group in self.cur_proj.groups[:]:
self.cur_proj.del_group(group)
print "all display groups removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_proj.groups) or x < 0:
print "display group", x, "does not exist"
continue
rmlist.append(self.cur_proj.groups[x])
print "display group", x, "removed"
for group in rmlist:
self.cur_proj.del_group(group)
# Remember to point self.cur_group somewhere sane
if self.cur_group not in self.cur_proj.groups:
if len(self.cur_proj.groups) == 0:
self.cur_group = None
else:
self.cur_group = self.cur_proj.groups[0]
print "group 0 is now the current display group"
chgrp_parser = CmdParser(add_help=False, prog='chgrp',
description='''Changes display group that is
currently active for editing.
Prints current group id if
no group id is specified''')
chgrp_parser.add_argument('gid', metavar='id', type=int, nargs='?',
help='id of display group to be made active')
def help_chgrp(self):
self.__class__.chgrp_parser.print_help()
def do_chgrp(self, line):
"""Changes group that is currently active for editing."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups that can be made active'
return
try:
args = self.__class__.chgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.chgrp_parser.print_usage()
return
if args.gid == None:
print "group",\
self.cur_proj.groups.index(self.cur_group),\
"is the current display group"
elif args.gid >= len(self.cur_proj.groups) or args.gid < 0:
print "group", args.gid, "does not exist"
else:
self.cur_group = self.cur_proj.groups[args.gid]
print "group", args.gid, "is now the current display group"
mk_parser = CmdParser(add_help=False, prog='mk',
description='''Makes a new checkerboard in the
current group with the given
parameters.''')
mk_parser.add_argument('dims', action=store_tuple(2, ',', to_decimal),
help='''width,height of checkerboard in no. of
unit cells''')
mk_parser.add_argument('init_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of initial unit cell in pixels')
mk_parser.add_argument('end_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of final unit cell in pixels')
mk_parser.add_argument('position', action=store_tuple(2, ',', to_decimal),
help='x,y position of checkerboard in pixels')
mk_parser.add_argument('anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='anchor')
mk_parser.add_argument('cols', action=store_tuple(2, ',', to_color, [';']),
help='''color1,color2 of the checkerboard
(color format: R;G;B,
component range from 0-255)''')
mk_parser.add_argument('freq', type=to_decimal,
help='frequency of color reversal in Hz')
mk_parser.add_argument('phase', type=to_decimal, nargs='?', default='0',
- help='initial phase of animation in degrees')
+ help='initial phase in degrees')
def help_mk(self):
self.__class__.mk_parser.print_help()
def do_mk(self, line):
"""Makes a checkerboard with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
if self.cur_group == None:
print 'automatically adding display group...'
self.do_mkgrp('')
try:
args = self.__class__.mk_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mk_parser.print_usage()
return
shape_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_shape = core.CheckerBoard(**shape_dict)
new_id = self.cur_proj.add_shape_to_group(self.cur_group, new_shape)
print "checkerboard", new_id, "added"
ed_parser = CmdParser(add_help=False, prog='ed',
description='''Edits attributes of checkerboards
specified by ids.''')
ed_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='''ids of checkerboards in the current
group to be edited''')
ed_parser.add_argument('--dims', action=store_tuple(2, ',', to_decimal),
help='checkerboard dimensions in unit cells',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--init_unit',
action=store_tuple(2, ',', to_decimal),
help='initial unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--end_unit',
action=store_tuple(2, ',', to_decimal),
help='final unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--position',
action=store_tuple(2, ',', to_decimal),
help='position of checkerboard in pixels',
metavar='X,Y')
ed_parser.add_argument('--anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='LOCATION')
ed_parser.add_argument('--cols', metavar='COLOR1,COLOR2',
action=store_tuple(2, ',', to_color, [';']),
help='''checkerboard colors (color format:
R;G;B, component range
from 0-255)''')
ed_parser.add_argument('--freq', type=to_decimal,
help='frequency of color reversal in Hz')
ed_parser.add_argument('--phase', type=to_decimal,
- help='initial phase of animation in degrees')
+ help='initial phase in degrees')
def help_ed(self):
self.__class__.ed_parser.print_help()
def do_ed(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, please create one first'
return
try:
args = self.__class__.ed_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ed_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_group.shapes) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_shape_attr(self.cur_group, x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.ed_parser.print_usage()
rm_parser = CmdParser(add_help=False, prog='rm',
description='''Removes checkerboards specified
by ids.''')
rm_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''ids of checkerboards in the current group
to be removed''')
rm_parser.add_argument('-a', '--all', action='store_true',
help='''remove all checkerboards in the
current group''')
def help_rm(self):
self.__class__.rm_parser.print_help()
def do_rm(self, line):
"""Removes checkerboards specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, no boards to remove'
return
try:
args = self.__class__.rm_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rm_parser.print_usage()
return
rmlist = []
if args.all:
for shape in self.cur_group.shapes:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
print "all checkerboards removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_group.shapes) or x < 0:
print "checkerboard", x, "does not exist"
continue
rmlist.append(self.cur_group.shapes[x])
print "checkerboard", x, "removed"
for shape in rmlist:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
ls_parser = CmdParser(add_help=False, prog='ls',
description='''Lists project, display group and
checkerboard settings. If no group ids
are specified, all display groups
are listed.''')
ls_parser.add_argument('gidlist', nargs='*', metavar='gid', type=int,
help='''ids of the display groups to be listed''')
ls_group = ls_parser.add_mutually_exclusive_group()
ls_group.add_argument('-s', '--settings', action='store_true',
help='list only project settings')
ls_group.add_argument('-g', '--groups', action='store_true',
help='list only display groups')
def help_ls(self):
self.__class__.ls_parser.print_help()
def do_ls(self, line):
"""Lists project, display group and checkerboard settings."""
def ls_str(s, seps=[',',';']):
"""Special space-saving output formatter."""
if type(s) in [tuple, list]:
if len(seps) > 1:
newseps = seps[1:]
else:
newseps = seps
return seps[0].join([ls_str(i, newseps) for i in s])
else:
return str(s)
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.ls_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ls_parser.print_usage()
return
# Remove duplicates and ascending sort
args.gidlist = sorted(set(args.gidlist))
if len(self.cur_proj.groups) == 0:
if len(args.gidlist) > 0:
print 'this project has no display groups that can be listed'
args.settings = True
else:
for gid in args.gidlist[:]:
if gid >= len(self.cur_proj.groups) or gid < 0:
args.gidlist.remove(gid)
print 'display group', gid, 'does not exist'
if args.gidlist == []:
args.gidlist = range(len(self.cur_proj.groups))
else:
# If any (valid) groups are specified
# don't show project settings
args.groups = True
if not args.groups:
print 'PROJECT SETTINGS'.center(70,'*')
print \
'name'.rjust(16),\
'fps'.rjust(7),\
'resolution'.rjust(14),\
'bg color'.rjust(18)
print \
ls_str(self.cur_proj.name).rjust(16),\
ls_str(self.cur_proj.fps).rjust(7),\
ls_str(self.cur_proj.res).rjust(14),\
ls_str(self.cur_proj.bg).rjust(18)
print \
'pre-display'.rjust(26),\
'post-display'.rjust(26)
print \
ls_str(self.cur_proj.pre).rjust(26),\
ls_str(self.cur_proj.post).rjust(26)
print \
'cross colors'.rjust(26),\
'cross times'.rjust(26)
print \
ls_str(self.cur_proj.cross_cols).rjust(26),\
ls_str(self.cur_proj.cross_times).rjust(26)
if not args.settings and not args.groups:
# Insert empty line if both groups and project
# settings are listed
print ''
if not args.settings:
for i, n in enumerate(args.gidlist):
if i != 0:
# Print newline seperator between each group
print ''
group = self.cur_proj.groups[n]
print 'GROUP {n}'.format(n=n).center(70,'*')
print \
'pre-display'.rjust(20),\
'display'.rjust(20),\
'post-display'.rjust(20)
print \
ls_str(group.pre).rjust(20),\
ls_str(group.disp).rjust(20),\
ls_str(group.post).rjust(20)
if len(group.shapes) > 0:
print \
''.rjust(2),\
'shape id'.rjust(8),\
'dims'.rjust(10),\
'init_unit'.rjust(14),\
'end_unit'.rjust(14),\
'position'.rjust(14)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.dims).rjust(10),\
ls_str(shape.init_unit).rjust(14),\
ls_str(shape.end_unit).rjust(14),\
ls_str(shape.position).rjust(14)
print '\n',\
''.rjust(2),\
'shape id'.rjust(8),\
'colors'.rjust(27),\
'anchor'.rjust(12),\
'freq'.rjust(6),\
'phase'.rjust(7)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.cols).rjust(27),\
ls_str(shape.anchor).rjust(12),\
ls_str(shape.freq).rjust(6),\
ls_str(shape.phase).rjust(7)
display_parser = CmdParser(add_help=False, prog='display',
- description='''Displays the animation in a
+ description='''Displays the stimulus in a
window or in fullscreen.''')
+ display_parser.add_argument('-s', '--save', action='store_true',
+ help='''save specified display flags
+ as default flags for project
+ instead of presenting stimulus''')
display_parser.add_argument('-n', '--name', metavar='FOOBAR',
help='''name of log file to be written''')
display_parser.add_argument('-r', '--repeats', metavar='N', type=int,
help='''repeatedly display specified display
groups N number of times''')
display_parser.add_argument('-wl', '--waitless', action=store_truth(),
metavar='t/f',
help='''do not add waitscreens before the
start of each repeat''')
display_parser.add_argument('-f', '--fullscreen', action=store_truth(),
metavar='t/f',
help='sets fullscreen mode, ESC to quit')
display_parser.add_argument('-p', '--priority', metavar='LEVEL',
help='''set priority while displaying,
higher priority results in
less dropped frames (choices:
0-3, low, normal, high,
realtime)''')
display_parser.add_argument('-pt', '--phototest', action=store_truth(),
metavar='t/f',
help='''draw white test rectangle in topleft
corner of screen when groups become
visible for a photodiode to detect''')
display_parser.add_argument('-pb', '--photoburst', action=store_truth(),
metavar='t/f',
help='''make checkerboards only draw first
color for one frame to facilitate
testing with a photodiode''')
display_parser.add_argument('-lt', '--logtime', action=store_truth(),
metavar='t/f',
help='output frame timestamps to a log file')
display_parser.add_argument('-ld', '--logdur', action=store_truth(),
metavar='t/f',
help='output frame durations to a log file')
display_parser.add_argument('-ss', '--trigser', action=store_truth(),
metavar='t/f',
help='''send triggers through the serial port
when shapes are being displayed''')
display_parser.add_argument('-sp', '--trigpar', action=store_truth(),
metavar='t/f',
help='''send triggers through the parallel port
when shapes are being displayed''')
display_parser.add_argument('-fpst', metavar='M', type=int,
help='''unique trigger corresponding to a
checkerboard is sent after the shape
undergoes M color flips (default:
disabled, M=0)''')
display_parser.add_argument('-fc', '--freqcheck', action=store_truth(),
metavar='t/f',
help='''only send triggers for board color
flips at the start, middle and end
of the run''')
display_parser.add_argument('-et', '--eyetrack', action=store_truth(),
metavar='t/f',
help='''use eyetracking to ensure that subject
fixates on the cross in the center''')
display_parser.add_argument('-eu', '--etuser', action=store_truth(),
metavar='t/f',
help='''allow user to select eyetracking video
source from a dialog''')
display_parser.add_argument('-ev', '--etvideo', metavar='path',
help='''path (with no spaces) to eyetracking
video file to be used as the source''')
display_parser.add_argument('-ta', '--tryagain', metavar='I', type=int,
help='''append groups during which subject
failed to fixate up to I times to the
list of groups to be displayed
(default: disabled, I=0)''')
display_parser.add_argument('-tb', '--trybreak', metavar='J', type=int,
help='''used with --tryagain, append a wait
screen to the list of groups to be
displayed after every J groups have
been appended to the list (default:
J=total number of groups)''')
display_parser.add_argument('-nl', '--nolog', action=store_truth(),
metavar='t/f',
help='''do not write a log file''')
display_parser.add_argument('order', nargs='*', metavar='id', type=int,
help='''order in which groups should be
displayed (default: random order
from list of orders if specified
in project, ascending otherwise)''')
def help_display(self):
self.__class__.display_parser.print_help()
def do_display(self, line):
- """Displays the animation in a window or in fullscreen"""
+ """Displays the stimulus in a window or in fullscreen"""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.display_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
if len(args.order) > 0:
for i in set(args.order):
if i >= len(self.cur_proj.groups) or i < -1:
print 'error: group', i, 'does not exist'
return
if args.eyetrack and eyetracking.available:
if not eyetracking.is_calibrated():
try:
self.do_calibrate('',query=True)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
return
- print "displaying...",
- try:
- self.cur_proj.display(name=args.name,
- repeats=args.repeats,
- waitless=args.waitless,
- fullscreen=args.fullscreen,
- priority=args.priority,
- logtime=args.logtime,
- logdur=args.logdur,
- trigser=args.trigser,
- trigpar=args.trigpar,
- fpst=args.fpst,
- freqcheck=args.freqcheck,
- phototest=args.phototest,
- photoburst=args.photoburst,
- eyetrack=args.eyetrack,
- etuser=args.etuser,
- etvideo=args.etvideo,
- tryagain=args.tryagain,
- trybreak=args.trybreak,
- nolog=args.nolog,
- order=args.order)
- except (IOError, NotImplementedError, eyetracking.EyetrackingError):
- print ''
- print "error:", str(sys.exc_value)
- if args.priority != None:
- try:
- priority.set('normal')
- except:
- pass
- return
- print "done"
+ if args.save:
+ self.cur_proj.set_display_flags(repeats=args.repeats,
+ waitless=args.waitless,
+ fullscreen=args.fullscreen,
+ priority=args.priority,
+ logtime=args.logtime,
+ logdur=args.logdur,
+ trigser=args.trigser,
+ trigpar=args.trigpar,
+ fpst=args.fpst,
+ freqcheck=args.freqcheck,
+ phototest=args.phototest,
+ photoburst=args.photoburst,
+ eyetrack=args.eyetrack,
+ etuser=args.etuser,
+ etvideo=args.etvideo,
+ tryagain=args.tryagain,
+ trybreak=args.trybreak,
+ nolog=args.nolog)
+ print "display flags saved to project"
+ else:
+ print "displaying...",
+ try:
+ self.cur_proj.display(name=args.name,
+ repeats=args.repeats,
+ waitless=args.waitless,
+ fullscreen=args.fullscreen,
+ priority=args.priority,
+ logtime=args.logtime,
+ logdur=args.logdur,
+ trigser=args.trigser,
+ trigpar=args.trigpar,
+ fpst=args.fpst,
+ freqcheck=args.freqcheck,
+ phototest=args.phototest,
+ photoburst=args.photoburst,
+ eyetrack=args.eyetrack,
+ etuser=args.etuser,
+ etvideo=args.etvideo,
+ tryagain=args.tryagain,
+ trybreak=args.trybreak,
+ nolog=args.nolog,
+ order=args.order)
+ except (IOError, NotImplementedError,
+ eyetracking.EyetrackingError):
+ print ''
+ print "error:", str(sys.exc_value)
+ if args.priority != None:
+ try:
+ priority.set('normal')
+ except:
+ pass
+ return
+ print "done"
export_parser = CmdParser(add_help=False, prog='export',
- description='''Exports animation as an image
+ description='''Exports stimulus as an image
sequence (in a folder) to the
specified directory.''')
export_parser.add_argument('-n','--nofolder',
dest='folder', action='store_false',
help='''force images not to exported in
a containing folder''')
export_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly export specified display
groups N number of times''')
export_parser.add_argument('duration', nargs='?',
type=to_decimal, default='Infinity',
- help='''number of seconds of the animation
+ help='''number of seconds of the stimulus
that should be exported (default:
- as long as the entire animation)''')
+ as long as the entire stimulus)''')
export_parser.add_argument('dir', nargs='?', default=os.getcwd(),
help='''destination directory for export
(default: current working directory)''')
export_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be exported
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_export(self):
self.__class__.export_parser.print_help()
def do_export(self, line):
- """Exports animation an image sequence to the specified directory."""
+ """Exports stimulus as an image sequence to the specified directory."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.export_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.export_parser.print_usage()
return
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < 0:
print 'error: group', i, 'does not exist'
return
groupq = [self.cur_proj.groups[i] for i in args.idlist]
else:
groupq = list(self.cur_proj.groups)
if args.repeat != None:
groupq = list(groupq * args.repeat)
try:
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
folder=args.folder)
except IOError:
print "error:", str(sys.exc_value)
return
except core.FrameOverflowError:
print "warning:", str(sys.exc_value)
print "Are you sure you want to continue?"
while True:
try:
if self.__class__.yn_parse(raw_input()):
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
folder=args.folder,
force=True)
break
else:
return
except TypeError:
print str(sys.exc_value)
except EOFError:
return
print "Export done."
def do_calibrate(self, line, query=False):
"""Calibrate subject for eyetracking, or load a calibration file."""
if not eyetracking.available:
print "error: eyetracking functionality not available"
return
if query:
print "path to calibration file (leave empty for GUI tool):"
try:
path = raw_input().strip().strip('"\'')
except EOFError:
msg = "calibration cancelled"
raise eyetracking.EyetrackingError(msg)
else:
path = line.strip().strip('"\'')
if len(path) == 0:
path = None
if not eyetracking.is_source_ready():
# Select default source if none has been selected
eyetracking.select_source()
try:
eyetracking.calibrate(path)
except eyetracking.EyetrackingError:
if query:
raise
else:
print "error:", str(sys.exc_value)
return
if len(path) > 0:
print "calibration file successfully loaded"
etsetup_parser = CmdParser(add_help=False, prog='etsetup',
description='''Set various eyetracking
parameters.''')
etsetup_parser.add_argument('-fp', '--fixperiod', type=int, metavar='MS',
help='''time in milliseconds subject
has to stare at the same spot
for fixation to be detected''')
etsetup_parser.add_argument('-fr', '--fixrange', type=float, metavar='MM',
help='''distance in mm beyond which the
eye position cannot change for
a fixation to be detected''')
etsetup_parser.add_argument('-s', '--size', metavar='WIDTH,HEIGHT',
action=store_tuple(2, ',', float),
help='physical screen dimensions in mm')
etsetup_parser.add_argument('-vd', '--viewdist', type=int, metavar='MM',
help='''viewing distance between subject's
eyes and the screen''')
def help_etsetup(self):
self.__class__.etsetup_parser.print_help()
def do_etsetup(self, line):
try:
args = self.__class__.etsetup_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.etsetup_parser.print_usage()
return
try:
eyetracking.setup(viewing_distance=args.viewdist,
screen_dims=args.size,
fixation_period=args.fixperiod,
fixation_range=args.fixrange)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
def do_pwd(self, line):
"""Prints the current working directory."""
print os.getcwd()
def do_cd(self, line):
"""Change working directory to specified path."""
path = line.strip().strip('"\'')
if not os.path.isdir(path):
print "error: specified path is not a directory"
return
os.chdir(path)
def do_quit(self, line):
"""Quits the program."""
if self.save_check():
return
return True
def help_EOF(self):
print "Typing {0} issues this command, which quits the program."\
.format(CMD_EOF_STRING)
def do_EOF(self, line):
"""Typing Ctrl-D issues this command, which quits the program."""
print '\r'
if self.save_check():
return
return True
def help_help(self):
print 'Prints a list of commands.'
print "Type 'help <topic>' for more details on each command."
def default(self, line):
command = line.split()[0]
print \
"'{0}' is not a checkergen command.".format(command),\
"Type 'help' for a list of commands"
diff --git a/src/core.py b/src/core.py
index 04aa867..6d7308d 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,731 +1,784 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import copy
import random
import itertools
from datetime import datetime
from xml.dom import minidom
import pyglet
import graphics
import priority
import trigger
import eyetracking
from utils import *
# Use OrderedDict substitute if we don't have Python 2.7
if sys.version_info < (2, 7):
from odict import OrderedDict
else:
from collections import OrderedDict
CKG_FMT = 'ckg'
LOG_FMT = 'csv'
MAX_EXPORT_FRAMES = 100000
EXPORT_DIR_SUFFIX = '-anim'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
INT_HALF_PERIODS = True
FIX_POS = (0, 0)
FIX_RANGE = (20, 20)
FIX_PER = 350
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = OrderedDict([('name', 'untitled'),
('fps', 60),
('res', (800, 600)),
('bg', (127, 127, 127)),
('pre', 0),
('post', 0),
('cross_cols', ((0, 0, 0), (255, 0, 0))),
('cross_times', ('Infinity', 1)),
('orders', []),
('disp_ops', None)])
DEFAULTS['disp_ops'] = OrderedDict([('repeats', 1),
('waitless', False),
('fullscreen', False),
('priority', None),
('logtime', False),
('logdur', False),
('trigser', False),
('trigpar', False),
('fpst', 0),
('freqcheck', False),
('phototest', False),
('photoburst', False),
('eyetrack', False),
('etuser', False),
('etvideo', None),
('tryagain', 0),
('trybreak', None),
('nolog', False)])
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
+ def set_display_flags(self, **keywords):
+ """Set default display flags for the project.
+
+ repeats -- number of times specified order of display groups should
+ be repeated
+
+ waitless -- if true, no waitscreens will appear at the start of each
+ repeat
+
+ fullscreen -- animation is displayed fullscreen if true, stretched
+ to fit if necessary
+
+ priority -- priority level to which process should be raised
+
+ logtime -- timestamp of each frame is saved to a logfile if true
+
+ logdur -- duration of each frame is saved to a logfile if true
+
+ trigser -- send triggers through serial port when each group is shown
+
+ trigpar -- send triggers through parallel port when each group is shown
+
+ fpst -- flips per shape trigger, i.e. number of shape color reversals
+ (flips) that occur for a unique trigger to be sent for that shape
+
+ freqcheck -- send fpst only at the start, the middle, and the end
+ for sanity checking of display and trigger fps
+
+ phototest -- draw white rectangle in topleft corner when each group is
+ shown for photodiode to detect
+
+ photoburst -- make checkerboards only draw first color for one frame
+
+ eyetrack -- use eyetracking to ensure subject is fixating on cross
+
+ etuser -- if true, user gets to select eyetracking video source in GUI
+
+ etvideo -- optional eyetracking video source file to use instead of
+ live feed
+
+ tryagain -- append groups during which subject failed to fixate up to
+ this number of times to the group queue
+
+ trybreak -- append a wait screen to the group queue every time
+ after this many groups have been appended to the queue
+
+ """
+
+ for kw in keywords.keys():
+ if kw in self.disp_ops.keys() and keywords[kw] != None:
+ self.disp_ops[kw] = keywords[kw]
+ self._dirty = True
+
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
# Vars that are dicts
dicts_to_load = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_load = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
for d_name in dicts_to_load:
d = copy.deepcopy(self.__class__.DEFAULTS[d_name])
try:
d_el = [node for node in project.childNodes if
node.localName == d_name and
node.namespaceURI == XML_NAMESPACE][0]
for var in d.keys():
try:
d[var] = eval(xml_get(d_el, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}' in '{1}'".\
format(var, d_name)
print "using default value '{0}' instead...".\
format(d[var])
except IndexError:
print "warning: missing attribute set '{0}'".format(d_name)
print "using default values instead..."
setattr(self, d_name, d)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
# Vars that are dicts
dicts_to_save = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_save = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for d_name in dicts_to_save:
d_el = doc.createElement(d_name)
project.appendChild(d_el)
d = getattr(self, d_name)
for k, v in d.iteritems():
xml_set(doc, d_el, k, repr(v))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, **keywords):
"""Displays the project animation on the screen.
name -- name that logfile will be saved with
repeats -- number of times specified order of display groups should
be repeated
waitless -- if true, no waitscreens will appear at the start of each
repeat
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
priority -- priority level to which process should be raised
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
trigser -- send triggers through serial port when each group is shown
trigpar -- send triggers through parallel port when each group is shown
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
freqcheck -- send fpst only at the start, the middle, and the end
for sanity checking of display and trigger fps
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- append a wait screen to the group queue every time
after this many groups have been appended to the queue
order -- order in which groups (specified by id) will be displayed
"""
# Create RunState
disp_ops = copy.deepcopy(self.disp_ops)
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'name' in keywords.keys() and keywords['name'] != None:
name = keywords['name']
else:
timestr = datetime.today().strftime('_%Y-%m-%d_%H-%M-%S')
name = self.name + timestr
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
waitscreen = CkgWaitScreen()
# Set order id to be sent if necessary
if order in self.orders:
runstate.events['ord_id'] = self.orders.index(order)
# Count through pre
for count in range(self.pre * self.fps):
if runstate.window.has_exit:
break
runstate.update()
# Loop through repeats
repeats = runstate.disp_ops['repeats']
ord_len = len(runstate.order)
for i in range(repeats):
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
# Loop through display groups
runstate.events['blk_on'] = True
for n, gid in enumerate(runstate.order):
# Set flag for freqcheck
if runstate.disp_ops['freqcheck']:
if ((i == 0 and n == 0) or
(i == repeats-1 and n == ord_len-1) or
(i == repeats//2 and n == ord_len//2)):
runstate.fc_send = True
else:
runstate.fc_send = False
if gid == -1:
waitscreen.reset()
waitscreen.display(runstate)
else:
self.groups[gid].display(runstate)
# Append failed groups
if runstate.disp_ops['eyetrack'] and runstate.true_fail:
if len(runstate.add_gids) < runstate.disp_ops['tryagain']:
runstate.add_gids.append(gid)
else:
runstate.fail_gids.append(gid)
runstate.events['blk_off'] = True
# Loop through added groups
if runstate.disp_ops['eyetrack']:
for blk in grouper(runstate.add_gids,
runstate.disp_ops['trybreak']):
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
runstate.events['blk_on'] = True
# Loop through display groups
for gid in blk:
if gid != None:
self.groups[gid].display(runstate)
runstate.events['blk_off'] = True
# Count through post
for count in range(self.post * self.fps):
if runstate.window.has_exit:
break
runstate.update()
# Stop and output log
runstate.stop()
if not runstate.disp_ops['nolog']:
runstate.log()
def export(self, export_dir, export_duration, groupq=[],
folder=True, force=False):
if not os.path.isdir(export_dir):
msg = 'export path is not a directory'
raise IOError(msg)
# Set-up groups and variables that control their display
if groupq == []:
groupq = list(self.groups)
n = -1
groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Limit export duration to display duration
frames = export_duration * self.fps
frames = min(frames, disp_end)
# Warn user if a lot of frames will be exported
if frames > MAX_EXPORT_FRAMES and not force:
msg = 'very large number ({0}) of frames to be exported'.\
format(frames)
raise FrameOverflowError(msg)
# Create folder to store images if necessary
if folder:
export_dir = os.path.join(export_dir,
self.name + EXPORT_DIR_SUFFIX)
if not os.path.isdir(export_dir):
os.mkdir(export_dir)
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Set up canvas and framebuffer object
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
# Main loop
while count < frames:
fbo.clear()
if groups_visible:
# Get next group from queue
if n < 0 or groupq[n].over:
n += 1
if n >= len(groupq):
groups_visible = False
else:
groupq[n].reset()
# Draw and then update group
if n >= 0:
groupq[n].draw()
groupq[n].update(fps=self.fps, fpst=0)
# Draw fixation cross based on current count
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Save current frame to file
savepath = \
os.path.join(export_dir,
'{0}{2}.{1}'.
format(self.name, 'png',
repr(count).zfill(numdigits(frames-1))))
canvas.save(savepath)
# Increment count and set whether groups should be shown
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
fbo.delete()
class CkgRunState:
"""Contains information about the state of a checkergen project
when it is being displayed or exported."""
DEFAULTS = dict([('name', 'untitled'),
('res', None),
('fps', None),
('bg', None),
('cross_cols', None),
('cross_times', None),
('order', []),
('disp_ops', None),
('events', None),
('add_gids', []),
('fail_gids', []),
('timestamps', []),
('durstamps', []),
('trigstamps', [])])
DEFAULTS['events'] = dict([('ord_id', None),
('blk_on', False),
('blk_off', False),
('track_on', False),
('track_off', False),
('fix_on', False),
('fix_off', False),
('grp_on', False),
('grp_off', False),
('sids', set())])
def __init__(self, **keywords):
"""Creates the RunState."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
def start(self):
"""Initialize all subsystems and start the run."""
if self.disp_ops == None:
msg = "RunState lacks display options"
raise ValueError(msg)
if min(self.res, self.fps, self.bg,
self.cross_cols, self.cross_times) == None:
msg = "RunState intialized with insufficent project information"
raise ValueError(msg)
self._count = 0
# Flag used by freqcheck
self.fc_send = False
# Create fixation crosses
self.fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if self.disp_ops['phototest']:
self.test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Initialize ports
if self.disp_ops['trigser']:
if not trigger.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trigpar']:
if not trigger.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
trigger.init(self.disp_ops['trigser'], self.disp_ops['trigpar'])
# Initialize eyetracking
if self.disp_ops['eyetrack']:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trybreak'] == None:
self.disp_ops['trybreak'] = len(self.order)
self.fixated = False
self.old_fixated = False
self.tracked = False
self.old_tracked = False
self.fix_fail = False
self.true_fail = False
eyetracking.select_source(self.disp_ops['etuser'],
self.disp_ops['etvideo'])
eyetracking.start()
# Stretch to fit screen only if project res does not equal screen res
self.scaling = False
if self.disp_ops['fullscreen']:
self.window = pyglet.window.Window(fullscreen=True, visible=False)
if (self.window.width, self.window.height) != self.res:
self.scaling = True
else:
self.window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
self.keystates = pyglet.window.key.KeyStateHandler()
self.window.push_handlers(self.keystates)
# Clear window and make visible
self.window.switch_to()
graphics.set_clear_color(self.bg)
self.window.clear()
self.window.set_visible()
# Create framebuffer object for drawing unscaled scene
if self.scaling:
self.canvas = pyglet.image.Texture.create(*self.res)
self.fbo = graphics.Framebuffer(self.canvas)
self.fbo.start_render()
graphics.set_clear_color(self.bg)
self.fbo.clear()
# Set process priority
if self.disp_ops['priority'] != None:
if not priority.available[sys.platform]:
msg = "setting priority not available on {0}".\
format(sys.platform)
raise NotImplementedError(msg)
else:
try:
priority.set(self.disp_ops['priority'])
except ValueError:
priority.set(int(self.disp_ops['priority']))
# Start timers
if self.disp_ops['logtime']:
self.timer = Timer()
self.timer.start()
if self.disp_ops['logdur']:
self.dur = Timer()
self.dur.start()
def update(self):
"""Update the RunState."""
# Check for tracking and fixation
if self.disp_ops['eyetrack']:
self.old_tracked = self.tracked
self.tracked = eyetracking.is_tracked()
self.old_fixated = self.fixated
self.fixated = eyetracking.is_fixated(FIX_POS, FIX_RANGE, FIX_PER)
if self.fixated:
# Draw normal cross color if fixating
self.fix_crosses[0].draw()
else:
# Draw alternative cross color if not fixating
self.fix_crosses[1].draw()
# Update eyetracking events
if self.tracked != self.old_tracked:
if self.tracked:
self.events['track_on'] = True
else:
self.events['track_off'] = True
if self.fixated != self.old_fixated:
if self.fixated:
self.events['fix_on'] = True
else:
self.events['fix_off'] = True
# Check for failure of trial
if self.tracked and not self.fixated:
self.fix_fail = True
else:
# Change cross color based on time
if (self._count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
self.fix_crosses[0].draw()
|
ztangent/checkergen
|
98ce7937788ef28c29168b3ebd6137f25e6db554
|
Removed defunct export_fmt property.
|
diff --git a/src/cli.py b/src/cli.py
index 24efd31..95de2fb 100644
--- a/src/cli.py
+++ b/src/cli.py
@@ -1,1093 +1,1081 @@
"""Defines command-line-interface for checkergen."""
import os
import sys
if os.name == 'posix':
import readline
import argparse
import cmd
import shlex
import core
import priority
import eyetracking
from graphics import locations
from utils import *
CMD_PROMPT = '(ckg) '
CMD_EOF_STRING = 'Ctrl-D'
if sys.platform == 'win32':
CMD_EOF_STRING = 'Ctrl-Z + Enter'
CMD_INTRO = '\n'.join(["Enter 'help' for a list of commands.",
"Enter 'quit' or {0} to exit.".format(CMD_EOF_STRING)])
def store_tuple(nargs, sep, typecast=None, castargs=[]):
"""Returns argparse action that stores a tuple."""
class TupleAction(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
vallist = values.split(sep)
if len(vallist) != nargs:
msg = ("argument '{f}' should be a list of " +
"{nargs} values separated by '{sep}'").\
format(f=self.dest,nargs=nargs,sep=sep)
raise argparse.ArgumentError(self, msg)
if typecast != None:
for n, val in enumerate(vallist):
try:
val = typecast(*([val] + castargs))
vallist[n] = val
except (ValueError, TypeError):
msg = ("element '{val}' of argument '{f}' " +
"is of the wrong type").\
format(val=vallist[n],f=self.dest)
raise argparse.ArgumentError(self, msg)
setattr(args, self.dest, tuple(vallist))
return TupleAction
def store_truth(y_words=['t','y'], n_words=['f', 'n']):
"""Returns argparse action that stores the truth based on keywords."""
class TruthAction(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
if values in y_words:
setattr(args, self.dest, True)
elif values in n_words:
setattr(args, self.dest, False)
else:
msg = 'true/false keyword unrecognized'
raise argparse.ArgumentError(self, msg)
return TruthAction
# The main parser invoked at the command-line
PARSER = argparse.ArgumentParser(
description='''Generate flashing checkerboard patterns for display
or export as a series of images, intended for use in
psychophysics experiments. Enters interactive command
line mode if no options are specified.''')
PARSER.add_argument('-c', '--cmd', dest='cmd_mode', action='store_true',
help='enter command line mode regardless of other options')
PARSER.add_argument('-d', '--display',
dest='display_flag', action='store_true',
help='displays the animation on the screen')
PARSER.add_argument('-e', '--export', dest='export_dur', metavar='DUR',
help='export DUR seconds of the project animation')
PARSER.add_argument('-f', '--fullscreen', action='store_true',
help='animation displayed in fullscreen mode')
-# PARSER.add_argument('--fmt', dest='export_fmt', choices=core.EXPORT_FMTS,
-# help='image format for animation to be exported as')
PARSER.add_argument('--dir', dest='export_dir',
default=os.getcwd(), metavar='PATH',
help='''destination directory for export
(default: current working directory)''')
PARSER.add_argument('path', metavar='project', nargs='?', type=file,
help='checkergen project file to open')
def process_args(args):
"""Further processes the arguments returned by the main parser."""
if args.export_dur != None:
args.export_flag = True
else:
args.export_flag = False
if not args.display_flag and not args.export_flag:
args.cmd_mode = True
if args.path != None:
if not os.path.isfile(args.path):
msg = 'error: path specified is not a file'
return msg
args.proj = core.CkgProj(path=args.path)
os.chdir(os.path.dirname(os.path.abspath(args.path)))
try:
args.group = args.proj.groups[0]
except IndexError:
args.group = None
else:
args.proj = None
args.group = None
if args.display_flag or args.export_flag:
msg = 'error: no project file specified for display or export'
return msg
class CmdParserError(Exception):
"""To be raised when CmdParser encounters an error."""
pass
class CmdParser(argparse.ArgumentParser):
"""Override ArgumentParser so that it doesn't exit the program."""
def error(self, msg):
raise CmdParserError(msg)
class CkgCmd(cmd.Cmd):
@staticmethod
def yn_parse(s):
if s in ['y', 'Y', 'yes', 'YES', 'Yes']:
return True
elif s in ['n', 'N', 'no', 'NO', 'No']:
return False
else:
msg = "only 'y','n' or variants accepted"
raise ValueError(msg)
def save_check(self, msg=None):
"""Checks and prompts the user to save if necessary."""
if self.cur_proj == None:
return
if not self.cur_proj.is_dirty():
return
if msg == None:
msg = 'Would you like to save the current project first? (y/n)'
print msg
while True:
try:
if self.__class__.yn_parse(raw_input()):
self.do_save('')
break
except TypeError:
print str(sys.exc_value)
except EOFError:
return True
def do_new(self, line):
"""Creates new project with given name (can contain whitespace)."""
name = line.strip().strip('"\'')
if len(name) == 0:
name = 'untitled'
if self.save_check():
return
self.cur_proj = core.CkgProj(name=name)
print 'project \'{0}\' created'.format(self.cur_proj.name)
def do_open(self, line):
"""Open specified project file."""
path = line.strip().strip('"\'')
if len(path) == 0:
print 'error: no path specified'
return
if self.save_check():
return
try:
self.cur_proj = core.CkgProj(path=path)
except (core.FileFormatError, IOError):
print "error:", str(sys.exc_value)
return
os.chdir(os.path.dirname(os.path.abspath(path)))
try:
self.cur_group = self.cur_proj.groups[0]
except IndexError:
self.cur_group = None
print 'project \'{0}\' loaded'.format(self.cur_proj.name)
def do_close(self, line):
"""Prompts the user to save, then closes current project."""
if self.cur_proj == None:
print 'no project to close'
return
if self.save_check():
return
self.cur_proj = None
print 'project closed'
def do_save(self, line):
"""Saves the current project to the specified path."""
if self.cur_proj == None:
print 'no project to save'
return
path = line.strip().strip('"\'')
if len(path) == 0:
path = os.getcwd()
path = os.path.abspath(path)
if os.path.isdir(path):
path = os.path.join(path,
'.'.join([self.cur_proj.name, core.CKG_FMT]))
elif os.path.isdir(os.path.dirname(path)):
pass
else:
print 'error: specified directory does not exist'
return
# project save will add file extension if necessary
try:
path = self.cur_proj.save(path)
except IOError:
print "error:", str(sys.exc_value)
return
print 'project saved to "{0}"'.format(path)
set_parser = CmdParser(add_help=False, prog='set',
description='''Sets various project settings.''')
set_parser.add_argument('--name', help='''project name, always the same as
the filename without
the extension''')
set_parser.add_argument('--fps', type=to_decimal,
help='''number of animation frames
rendered per second''')
set_parser.add_argument('--res', action=store_tuple(2, ',', int),
help='animation canvas size/resolution in pixels',
metavar='WIDTH,HEIGHT')
set_parser.add_argument('--bg', metavar='COLOR', type=to_color,
help='''background color of the canvas
(color format: R,G,B,
component range from 0-255)''')
- # set_parser.add_argument('--fmt', dest='export_fmt',
- # choices=core.EXPORT_FMTS,
- # help='''image format for animation
- # to be exported as''')
set_parser.add_argument('--pre', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown before any display groups''')
set_parser.add_argument('--post', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown after all display groups''')
set_parser.add_argument('--cross_cols', metavar='COLOR1,COLOR2',
action=store_tuple(2, ',', to_color, [';']),
help='''fixation cross coloration
(color format: R;G;B,
component range from 0-255)''')
set_parser.add_argument('--cross_times', metavar='TIME1,TIME2',
action=store_tuple(2, ',', to_decimal),
help='''time in seconds each cross color
will be displayed''')
def help_set(self):
self.__class__.set_parser.print_help()
def do_set(self, line):
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
try:
args = self.__class__.set_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.set_parser.print_usage()
return
names = public_dir(args)
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
setattr(self.cur_proj, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.set_parser.print_usage()
mkgrp_parser = CmdParser(add_help=False, prog='mkgrp',
formatter_class=
argparse.ArgumentDefaultsHelpFormatter,
description='''Makes a new display group
with the given parameters.''')
mkgrp_parser.add_argument('pre', type=to_decimal, default=0, nargs='?',
help='''time in seconds a blank screen will
be shown before shapes are displayed''')
mkgrp_parser.add_argument('disp', type=to_decimal,
nargs='?', default='Infinity',
help='''time in seconds shapes will be
displayed''')
mkgrp_parser.add_argument('post', type=to_decimal, default=0, nargs='?',
help='''time in seconds a blank screen will
be shown after shapes are displayed''')
def help_mkgrp(self):
self.__class__.mkgrp_parser.print_help()
def do_mkgrp(self, line):
"""Makes a display group with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
try:
args = self.__class__.mkgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mkgrp_parser.print_usage()
return
group_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_group = core.CkgDisplayGroup(**group_dict)
new_id = self.cur_proj.add_group(new_group)
print "display group", new_id, "added"
self.cur_group = new_group
print "group", new_id, "is now the current display group"
edgrp_parser = CmdParser(add_help=False, prog='edgrp',
description='''Edits attributes of display groups
specified by ids.''')
edgrp_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='ids of display groups to be edited')
edgrp_parser.add_argument('--pre', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown before shapes are displayed''')
edgrp_parser.add_argument('--disp', type=to_decimal, metavar='SECONDS',
help='''time in seconds shapes will be
displayed''')
edgrp_parser.add_argument('--post', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown after shapes are displayed''')
def help_edgrp(self):
self.__class__.edgrp_parser.print_help()
def do_edgrp(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.edgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.edgrp_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_proj.groups) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_group_attr(x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.edgrp_parser.print_usage()
rmgrp_parser = CmdParser(add_help=False, prog='rmgrp',
description='''Removes display groups specified
by ids.''')
rmgrp_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='ids of display groups to be removed')
rmgrp_parser.add_argument('-a', '--all', action='store_true',
help='remove all groups from the project')
def help_rmgrp(self):
self.__class__.rmgrp_parser.print_help()
def do_rmgrp(self, line):
"""Removes display groups specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups to remove'
return
try:
args = self.__class__.rmgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rmgrp_parser.print_usage()
return
rmlist = []
if args.all:
for group in self.cur_proj.groups[:]:
self.cur_proj.del_group(group)
print "all display groups removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_proj.groups) or x < 0:
print "display group", x, "does not exist"
continue
rmlist.append(self.cur_proj.groups[x])
print "display group", x, "removed"
for group in rmlist:
self.cur_proj.del_group(group)
# Remember to point self.cur_group somewhere sane
if self.cur_group not in self.cur_proj.groups:
if len(self.cur_proj.groups) == 0:
self.cur_group = None
else:
self.cur_group = self.cur_proj.groups[0]
print "group 0 is now the current display group"
chgrp_parser = CmdParser(add_help=False, prog='chgrp',
description='''Changes display group that is
currently active for editing.
Prints current group id if
no group id is specified''')
chgrp_parser.add_argument('gid', metavar='id', type=int, nargs='?',
help='id of display group to be made active')
def help_chgrp(self):
self.__class__.chgrp_parser.print_help()
def do_chgrp(self, line):
"""Changes group that is currently active for editing."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups that can be made active'
return
try:
args = self.__class__.chgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.chgrp_parser.print_usage()
return
if args.gid == None:
print "group",\
self.cur_proj.groups.index(self.cur_group),\
"is the current display group"
elif args.gid >= len(self.cur_proj.groups) or args.gid < 0:
print "group", args.gid, "does not exist"
else:
self.cur_group = self.cur_proj.groups[args.gid]
print "group", args.gid, "is now the current display group"
mk_parser = CmdParser(add_help=False, prog='mk',
description='''Makes a new checkerboard in the
current group with the given
parameters.''')
mk_parser.add_argument('dims', action=store_tuple(2, ',', to_decimal),
help='''width,height of checkerboard in no. of
unit cells''')
mk_parser.add_argument('init_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of initial unit cell in pixels')
mk_parser.add_argument('end_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of final unit cell in pixels')
mk_parser.add_argument('position', action=store_tuple(2, ',', to_decimal),
help='x,y position of checkerboard in pixels')
mk_parser.add_argument('anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='anchor')
mk_parser.add_argument('cols', action=store_tuple(2, ',', to_color, [';']),
help='''color1,color2 of the checkerboard
(color format: R;G;B,
component range from 0-255)''')
mk_parser.add_argument('freq', type=to_decimal,
help='frequency of color reversal in Hz')
mk_parser.add_argument('phase', type=to_decimal, nargs='?', default='0',
help='initial phase of animation in degrees')
def help_mk(self):
self.__class__.mk_parser.print_help()
def do_mk(self, line):
"""Makes a checkerboard with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
if self.cur_group == None:
print 'automatically adding display group...'
self.do_mkgrp('')
try:
args = self.__class__.mk_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mk_parser.print_usage()
return
shape_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_shape = core.CheckerBoard(**shape_dict)
new_id = self.cur_proj.add_shape_to_group(self.cur_group, new_shape)
print "checkerboard", new_id, "added"
ed_parser = CmdParser(add_help=False, prog='ed',
description='''Edits attributes of checkerboards
specified by ids.''')
ed_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='''ids of checkerboards in the current
group to be edited''')
ed_parser.add_argument('--dims', action=store_tuple(2, ',', to_decimal),
help='checkerboard dimensions in unit cells',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--init_unit',
action=store_tuple(2, ',', to_decimal),
help='initial unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--end_unit',
action=store_tuple(2, ',', to_decimal),
help='final unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--position',
action=store_tuple(2, ',', to_decimal),
help='position of checkerboard in pixels',
metavar='X,Y')
ed_parser.add_argument('--anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='LOCATION')
ed_parser.add_argument('--cols', metavar='COLOR1,COLOR2',
action=store_tuple(2, ',', to_color, [';']),
help='''checkerboard colors (color format:
R;G;B, component range
from 0-255)''')
ed_parser.add_argument('--freq', type=to_decimal,
help='frequency of color reversal in Hz')
ed_parser.add_argument('--phase', type=to_decimal,
help='initial phase of animation in degrees')
def help_ed(self):
self.__class__.ed_parser.print_help()
def do_ed(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, please create one first'
return
try:
args = self.__class__.ed_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ed_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_group.shapes) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_shape_attr(self.cur_group, x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.ed_parser.print_usage()
rm_parser = CmdParser(add_help=False, prog='rm',
description='''Removes checkerboards specified
by ids.''')
rm_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''ids of checkerboards in the current group
to be removed''')
rm_parser.add_argument('-a', '--all', action='store_true',
help='''remove all checkerboards in the
current group''')
def help_rm(self):
self.__class__.rm_parser.print_help()
def do_rm(self, line):
"""Removes checkerboards specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, no boards to remove'
return
try:
args = self.__class__.rm_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rm_parser.print_usage()
return
rmlist = []
if args.all:
for shape in self.cur_group.shapes:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
print "all checkerboards removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_group.shapes) or x < 0:
print "checkerboard", x, "does not exist"
continue
rmlist.append(self.cur_group.shapes[x])
print "checkerboard", x, "removed"
for shape in rmlist:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
ls_parser = CmdParser(add_help=False, prog='ls',
description='''Lists project, display group and
checkerboard settings. If no group ids
are specified, all display groups
are listed.''')
ls_parser.add_argument('gidlist', nargs='*', metavar='gid', type=int,
help='''ids of the display groups to be listed''')
ls_group = ls_parser.add_mutually_exclusive_group()
ls_group.add_argument('-s', '--settings', action='store_true',
help='list only project settings')
ls_group.add_argument('-g', '--groups', action='store_true',
help='list only display groups')
def help_ls(self):
self.__class__.ls_parser.print_help()
def do_ls(self, line):
"""Lists project, display group and checkerboard settings."""
def ls_str(s, seps=[',',';']):
"""Special space-saving output formatter."""
if type(s) in [tuple, list]:
if len(seps) > 1:
newseps = seps[1:]
else:
newseps = seps
return seps[0].join([ls_str(i, newseps) for i in s])
else:
return str(s)
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.ls_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ls_parser.print_usage()
return
# Remove duplicates and ascending sort
args.gidlist = sorted(set(args.gidlist))
if len(self.cur_proj.groups) == 0:
if len(args.gidlist) > 0:
print 'this project has no display groups that can be listed'
args.settings = True
else:
for gid in args.gidlist[:]:
if gid >= len(self.cur_proj.groups) or gid < 0:
args.gidlist.remove(gid)
print 'display group', gid, 'does not exist'
if args.gidlist == []:
args.gidlist = range(len(self.cur_proj.groups))
else:
# If any (valid) groups are specified
# don't show project settings
args.groups = True
if not args.groups:
print 'PROJECT SETTINGS'.center(70,'*')
print \
'name'.rjust(16),\
'fps'.rjust(7),\
'resolution'.rjust(14),\
'bg color'.rjust(18)
- # 'format'.rjust(7)
print \
ls_str(self.cur_proj.name).rjust(16),\
ls_str(self.cur_proj.fps).rjust(7),\
ls_str(self.cur_proj.res).rjust(14),\
ls_str(self.cur_proj.bg).rjust(18)
- # ls_str(self.cur_proj.export_fmt).rjust(7)
print \
'pre-display'.rjust(26),\
'post-display'.rjust(26)
print \
ls_str(self.cur_proj.pre).rjust(26),\
ls_str(self.cur_proj.post).rjust(26)
print \
'cross colors'.rjust(26),\
'cross times'.rjust(26)
print \
ls_str(self.cur_proj.cross_cols).rjust(26),\
ls_str(self.cur_proj.cross_times).rjust(26)
if not args.settings and not args.groups:
# Insert empty line if both groups and project
# settings are listed
print ''
if not args.settings:
for i, n in enumerate(args.gidlist):
if i != 0:
# Print newline seperator between each group
print ''
group = self.cur_proj.groups[n]
print 'GROUP {n}'.format(n=n).center(70,'*')
print \
'pre-display'.rjust(20),\
'display'.rjust(20),\
'post-display'.rjust(20)
print \
ls_str(group.pre).rjust(20),\
ls_str(group.disp).rjust(20),\
ls_str(group.post).rjust(20)
if len(group.shapes) > 0:
print \
''.rjust(2),\
'shape id'.rjust(8),\
'dims'.rjust(10),\
'init_unit'.rjust(14),\
'end_unit'.rjust(14),\
'position'.rjust(14)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.dims).rjust(10),\
ls_str(shape.init_unit).rjust(14),\
ls_str(shape.end_unit).rjust(14),\
ls_str(shape.position).rjust(14)
print '\n',\
''.rjust(2),\
'shape id'.rjust(8),\
'colors'.rjust(27),\
'anchor'.rjust(12),\
'freq'.rjust(6),\
'phase'.rjust(7)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.cols).rjust(27),\
ls_str(shape.anchor).rjust(12),\
ls_str(shape.freq).rjust(6),\
ls_str(shape.phase).rjust(7)
display_parser = CmdParser(add_help=False, prog='display',
description='''Displays the animation in a
window or in fullscreen.''')
display_parser.add_argument('-n', '--name', metavar='FOOBAR',
help='''name of log file to be written''')
display_parser.add_argument('-r', '--repeats', metavar='N', type=int,
help='''repeatedly display specified display
groups N number of times''')
display_parser.add_argument('-wl', '--waitless', action=store_truth(),
metavar='t/f',
help='''do not add waitscreens before the
start of each repeat''')
display_parser.add_argument('-f', '--fullscreen', action=store_truth(),
metavar='t/f',
help='sets fullscreen mode, ESC to quit')
display_parser.add_argument('-p', '--priority', metavar='LEVEL',
help='''set priority while displaying,
higher priority results in
less dropped frames (choices:
0-3, low, normal, high,
realtime)''')
display_parser.add_argument('-pt', '--phototest', action=store_truth(),
metavar='t/f',
help='''draw white test rectangle in topleft
corner of screen when groups become
visible for a photodiode to detect''')
display_parser.add_argument('-pb', '--photoburst', action=store_truth(),
metavar='t/f',
help='''make checkerboards only draw first
color for one frame to facilitate
testing with a photodiode''')
display_parser.add_argument('-lt', '--logtime', action=store_truth(),
metavar='t/f',
help='output frame timestamps to a log file')
display_parser.add_argument('-ld', '--logdur', action=store_truth(),
metavar='t/f',
help='output frame durations to a log file')
display_parser.add_argument('-ss', '--trigser', action=store_truth(),
metavar='t/f',
help='''send triggers through the serial port
when shapes are being displayed''')
display_parser.add_argument('-sp', '--trigpar', action=store_truth(),
metavar='t/f',
help='''send triggers through the parallel port
when shapes are being displayed''')
display_parser.add_argument('-fpst', metavar='M', type=int,
help='''unique trigger corresponding to a
checkerboard is sent after the shape
undergoes M color flips (default:
disabled, M=0)''')
display_parser.add_argument('-fc', '--freqcheck', action=store_truth(),
metavar='t/f',
help='''only send triggers for board color
flips at the start, middle and end
of the run''')
display_parser.add_argument('-et', '--eyetrack', action=store_truth(),
metavar='t/f',
help='''use eyetracking to ensure that subject
fixates on the cross in the center''')
display_parser.add_argument('-eu', '--etuser', action=store_truth(),
metavar='t/f',
help='''allow user to select eyetracking video
source from a dialog''')
display_parser.add_argument('-ev', '--etvideo', metavar='path',
help='''path (with no spaces) to eyetracking
video file to be used as the source''')
display_parser.add_argument('-ta', '--tryagain', metavar='I', type=int,
help='''append groups during which subject
failed to fixate up to I times to the
list of groups to be displayed
(default: disabled, I=0)''')
display_parser.add_argument('-tb', '--trybreak', metavar='J', type=int,
help='''used with --tryagain, append a wait
screen to the list of groups to be
displayed after every J groups have
been appended to the list (default:
J=total number of groups)''')
display_parser.add_argument('-nl', '--nolog', action=store_truth(),
metavar='t/f',
help='''do not write a log file''')
display_parser.add_argument('order', nargs='*', metavar='id', type=int,
help='''order in which groups should be
displayed (default: random order
from list of orders if specified
in project, ascending otherwise)''')
def help_display(self):
self.__class__.display_parser.print_help()
def do_display(self, line):
"""Displays the animation in a window or in fullscreen"""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.display_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
if len(args.order) > 0:
for i in set(args.order):
if i >= len(self.cur_proj.groups) or i < -1:
print 'error: group', i, 'does not exist'
return
if args.eyetrack and eyetracking.available:
if not eyetracking.is_calibrated():
try:
self.do_calibrate('',query=True)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
return
print "displaying...",
try:
self.cur_proj.display(name=args.name,
repeats=args.repeats,
waitless=args.waitless,
fullscreen=args.fullscreen,
priority=args.priority,
logtime=args.logtime,
logdur=args.logdur,
trigser=args.trigser,
trigpar=args.trigpar,
fpst=args.fpst,
freqcheck=args.freqcheck,
phototest=args.phototest,
photoburst=args.photoburst,
eyetrack=args.eyetrack,
etuser=args.etuser,
etvideo=args.etvideo,
tryagain=args.tryagain,
trybreak=args.trybreak,
nolog=args.nolog,
order=args.order)
except (IOError, NotImplementedError, eyetracking.EyetrackingError):
print ''
print "error:", str(sys.exc_value)
if args.priority != None:
try:
priority.set('normal')
except:
pass
return
print "done"
export_parser = CmdParser(add_help=False, prog='export',
description='''Exports animation as an image
sequence (in a folder) to the
specified directory.''')
- # export_parser.add_argument('--fmt', dest='export_fmt',
- # choices=core.EXPORT_FMTS,
- # help='image format for export')
export_parser.add_argument('-n','--nofolder',
dest='folder', action='store_false',
help='''force images not to exported in
a containing folder''')
export_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly export specified display
groups N number of times''')
export_parser.add_argument('duration', nargs='?',
type=to_decimal, default='Infinity',
help='''number of seconds of the animation
that should be exported (default:
as long as the entire animation)''')
export_parser.add_argument('dir', nargs='?', default=os.getcwd(),
help='''destination directory for export
(default: current working directory)''')
export_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be exported
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_export(self):
self.__class__.export_parser.print_help()
def do_export(self, line):
"""Exports animation an image sequence to the specified directory."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.export_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.export_parser.print_usage()
return
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < 0:
print 'error: group', i, 'does not exist'
return
groupq = [self.cur_proj.groups[i] for i in args.idlist]
else:
groupq = list(self.cur_proj.groups)
if args.repeat != None:
groupq = list(groupq * args.repeat)
try:
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
folder=args.folder)
except IOError:
print "error:", str(sys.exc_value)
return
except core.FrameOverflowError:
print "warning:", str(sys.exc_value)
print "Are you sure you want to continue?"
while True:
try:
if self.__class__.yn_parse(raw_input()):
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
- export_fmt=None,
folder=args.folder,
force=True)
break
else:
return
except TypeError:
print str(sys.exc_value)
except EOFError:
return
print "Export done."
def do_calibrate(self, line, query=False):
"""Calibrate subject for eyetracking, or load a calibration file."""
if not eyetracking.available:
print "error: eyetracking functionality not available"
return
if query:
print "path to calibration file (leave empty for GUI tool):"
try:
path = raw_input().strip().strip('"\'')
except EOFError:
msg = "calibration cancelled"
raise eyetracking.EyetrackingError(msg)
else:
path = line.strip().strip('"\'')
if len(path) == 0:
path = None
if not eyetracking.is_source_ready():
# Select default source if none has been selected
eyetracking.select_source()
try:
eyetracking.calibrate(path)
except eyetracking.EyetrackingError:
if query:
raise
else:
print "error:", str(sys.exc_value)
return
if len(path) > 0:
print "calibration file successfully loaded"
etsetup_parser = CmdParser(add_help=False, prog='etsetup',
description='''Set various eyetracking
parameters.''')
etsetup_parser.add_argument('-fp', '--fixperiod', type=int, metavar='MS',
help='''time in milliseconds subject
has to stare at the same spot
for fixation to be detected''')
etsetup_parser.add_argument('-fr', '--fixrange', type=float, metavar='MM',
help='''distance in mm beyond which the
eye position cannot change for
a fixation to be detected''')
etsetup_parser.add_argument('-s', '--size', metavar='WIDTH,HEIGHT',
action=store_tuple(2, ',', float),
help='physical screen dimensions in mm')
etsetup_parser.add_argument('-vd', '--viewdist', type=int, metavar='MM',
help='''viewing distance between subject's
eyes and the screen''')
def help_etsetup(self):
self.__class__.etsetup_parser.print_help()
def do_etsetup(self, line):
try:
args = self.__class__.etsetup_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.etsetup_parser.print_usage()
return
try:
eyetracking.setup(viewing_distance=args.viewdist,
screen_dims=args.size,
fixation_period=args.fixperiod,
fixation_range=args.fixrange)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
def do_pwd(self, line):
"""Prints the current working directory."""
print os.getcwd()
def do_cd(self, line):
"""Change working directory to specified path."""
path = line.strip().strip('"\'')
if not os.path.isdir(path):
print "error: specified path is not a directory"
return
os.chdir(path)
def do_quit(self, line):
"""Quits the program."""
if self.save_check():
return
return True
def help_EOF(self):
print "Typing {0} issues this command, which quits the program."\
.format(CMD_EOF_STRING)
def do_EOF(self, line):
"""Typing Ctrl-D issues this command, which quits the program."""
print '\r'
if self.save_check():
return
return True
def help_help(self):
print 'Prints a list of commands.'
print "Type 'help <topic>' for more details on each command."
def default(self, line):
command = line.split()[0]
print \
"'{0}' is not a checkergen command.".format(command),\
"Type 'help' for a list of commands"
diff --git a/src/core.py b/src/core.py
index c88c742..04aa867 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,1063 +1,1053 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import copy
import random
import itertools
from datetime import datetime
from xml.dom import minidom
import pyglet
import graphics
import priority
import trigger
import eyetracking
from utils import *
# Use OrderedDict substitute if we don't have Python 2.7
if sys.version_info < (2, 7):
from odict import OrderedDict
else:
from collections import OrderedDict
CKG_FMT = 'ckg'
LOG_FMT = 'csv'
-XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
MAX_EXPORT_FRAMES = 100000
-INT_HALF_PERIODS = True
-EXPORT_FMTS = ['png']
EXPORT_DIR_SUFFIX = '-anim'
+XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
+INT_HALF_PERIODS = True
FIX_POS = (0, 0)
FIX_RANGE = (20, 20)
FIX_PER = 350
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = OrderedDict([('name', 'untitled'),
('fps', 60),
('res', (800, 600)),
('bg', (127, 127, 127)),
- ('export_fmt', 'png'),
('pre', 0),
('post', 0),
('cross_cols', ((0, 0, 0), (255, 0, 0))),
('cross_times', ('Infinity', 1)),
('orders', []),
('disp_ops', None)])
DEFAULTS['disp_ops'] = OrderedDict([('repeats', 1),
('waitless', False),
('fullscreen', False),
('priority', None),
('logtime', False),
('logdur', False),
('trigser', False),
('trigpar', False),
('fpst', 0),
('freqcheck', False),
('phototest', False),
('photoburst', False),
('eyetrack', False),
('etuser', False),
('etvideo', None),
('tryagain', 0),
('trybreak', None),
('nolog', False)])
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
- export_fmt -- image format for animation to be exported as
-
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
- elif name == 'export_fmt':
- if value not in EXPORT_FMTS:
- msg = 'image format not recognized or supported'
- raise FileFormatError(msg)
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
# Vars that are dicts
dicts_to_load = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_load = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
for d_name in dicts_to_load:
d = copy.deepcopy(self.__class__.DEFAULTS[d_name])
try:
d_el = [node for node in project.childNodes if
node.localName == d_name and
node.namespaceURI == XML_NAMESPACE][0]
for var in d.keys():
try:
d[var] = eval(xml_get(d_el, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}' in '{1}'".\
format(var, d_name)
print "using default value '{0}' instead...".\
format(d[var])
except IndexError:
print "warning: missing attribute set '{0}'".format(d_name)
print "using default values instead..."
setattr(self, d_name, d)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
# Vars that are dicts
dicts_to_save = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_save = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for d_name in dicts_to_save:
d_el = doc.createElement(d_name)
project.appendChild(d_el)
d = getattr(self, d_name)
for k, v in d.iteritems():
xml_set(doc, d_el, k, repr(v))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, **keywords):
"""Displays the project animation on the screen.
name -- name that logfile will be saved with
repeats -- number of times specified order of display groups should
be repeated
waitless -- if true, no waitscreens will appear at the start of each
repeat
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
priority -- priority level to which process should be raised
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
trigser -- send triggers through serial port when each group is shown
trigpar -- send triggers through parallel port when each group is shown
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
freqcheck -- send fpst only at the start, the middle, and the end
for sanity checking of display and trigger fps
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- append a wait screen to the group queue every time
after this many groups have been appended to the queue
order -- order in which groups (specified by id) will be displayed
"""
# Create RunState
disp_ops = copy.deepcopy(self.disp_ops)
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'name' in keywords.keys() and keywords['name'] != None:
name = keywords['name']
else:
timestr = datetime.today().strftime('_%Y-%m-%d_%H-%M-%S')
name = self.name + timestr
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
waitscreen = CkgWaitScreen()
# Set order id to be sent if necessary
if order in self.orders:
runstate.events['ord_id'] = self.orders.index(order)
# Count through pre
for count in range(self.pre * self.fps):
if runstate.window.has_exit:
break
runstate.update()
# Loop through repeats
repeats = runstate.disp_ops['repeats']
ord_len = len(runstate.order)
for i in range(repeats):
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
# Loop through display groups
runstate.events['blk_on'] = True
for n, gid in enumerate(runstate.order):
# Set flag for freqcheck
if runstate.disp_ops['freqcheck']:
if ((i == 0 and n == 0) or
(i == repeats-1 and n == ord_len-1) or
(i == repeats//2 and n == ord_len//2)):
runstate.fc_send = True
else:
runstate.fc_send = False
if gid == -1:
waitscreen.reset()
waitscreen.display(runstate)
else:
self.groups[gid].display(runstate)
# Append failed groups
if runstate.disp_ops['eyetrack'] and runstate.true_fail:
if len(runstate.add_gids) < runstate.disp_ops['tryagain']:
runstate.add_gids.append(gid)
else:
runstate.fail_gids.append(gid)
runstate.events['blk_off'] = True
# Loop through added groups
if runstate.disp_ops['eyetrack']:
for blk in grouper(runstate.add_gids,
runstate.disp_ops['trybreak']):
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
runstate.events['blk_on'] = True
# Loop through display groups
for gid in blk:
if gid != None:
self.groups[gid].display(runstate)
runstate.events['blk_off'] = True
# Count through post
for count in range(self.post * self.fps):
if runstate.window.has_exit:
break
runstate.update()
# Stop and output log
runstate.stop()
if not runstate.disp_ops['nolog']:
runstate.log()
def export(self, export_dir, export_duration, groupq=[],
- export_fmt=None, folder=True, force=False):
+ folder=True, force=False):
if not os.path.isdir(export_dir):
msg = 'export path is not a directory'
raise IOError(msg)
- if export_fmt == None:
- export_fmt = self.export_fmt
# Set-up groups and variables that control their display
if groupq == []:
groupq = list(self.groups)
n = -1
groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Limit export duration to display duration
frames = export_duration * self.fps
frames = min(frames, disp_end)
# Warn user if a lot of frames will be exported
if frames > MAX_EXPORT_FRAMES and not force:
msg = 'very large number ({0}) of frames to be exported'.\
format(frames)
raise FrameOverflowError(msg)
# Create folder to store images if necessary
if folder:
export_dir = os.path.join(export_dir,
self.name + EXPORT_DIR_SUFFIX)
if not os.path.isdir(export_dir):
os.mkdir(export_dir)
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Set up canvas and framebuffer object
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
# Main loop
while count < frames:
fbo.clear()
if groups_visible:
# Get next group from queue
if n < 0 or groupq[n].over:
n += 1
if n >= len(groupq):
groups_visible = False
else:
groupq[n].reset()
# Draw and then update group
if n >= 0:
groupq[n].draw()
groupq[n].update(fps=self.fps, fpst=0)
# Draw fixation cross based on current count
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Save current frame to file
savepath = \
os.path.join(export_dir,
'{0}{2}.{1}'.
- format(self.name, export_fmt,
+ format(self.name, 'png',
repr(count).zfill(numdigits(frames-1))))
canvas.save(savepath)
# Increment count and set whether groups should be shown
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
fbo.delete()
class CkgRunState:
"""Contains information about the state of a checkergen project
when it is being displayed or exported."""
DEFAULTS = dict([('name', 'untitled'),
('res', None),
('fps', None),
('bg', None),
('cross_cols', None),
('cross_times', None),
('order', []),
('disp_ops', None),
('events', None),
('add_gids', []),
('fail_gids', []),
('timestamps', []),
('durstamps', []),
('trigstamps', [])])
DEFAULTS['events'] = dict([('ord_id', None),
('blk_on', False),
('blk_off', False),
('track_on', False),
('track_off', False),
('fix_on', False),
('fix_off', False),
('grp_on', False),
('grp_off', False),
('sids', set())])
def __init__(self, **keywords):
"""Creates the RunState."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
def start(self):
"""Initialize all subsystems and start the run."""
if self.disp_ops == None:
msg = "RunState lacks display options"
raise ValueError(msg)
if min(self.res, self.fps, self.bg,
self.cross_cols, self.cross_times) == None:
msg = "RunState intialized with insufficent project information"
raise ValueError(msg)
self._count = 0
# Flag used by freqcheck
self.fc_send = False
# Create fixation crosses
self.fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if self.disp_ops['phototest']:
self.test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Initialize ports
if self.disp_ops['trigser']:
if not trigger.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trigpar']:
if not trigger.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
trigger.init(self.disp_ops['trigser'], self.disp_ops['trigpar'])
# Initialize eyetracking
if self.disp_ops['eyetrack']:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trybreak'] == None:
self.disp_ops['trybreak'] = len(self.order)
self.fixated = False
self.old_fixated = False
self.tracked = False
self.old_tracked = False
self.fix_fail = False
self.true_fail = False
eyetracking.select_source(self.disp_ops['etuser'],
self.disp_ops['etvideo'])
eyetracking.start()
# Stretch to fit screen only if project res does not equal screen res
self.scaling = False
if self.disp_ops['fullscreen']:
self.window = pyglet.window.Window(fullscreen=True, visible=False)
if (self.window.width, self.window.height) != self.res:
self.scaling = True
else:
self.window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
self.keystates = pyglet.window.key.KeyStateHandler()
self.window.push_handlers(self.keystates)
# Clear window and make visible
self.window.switch_to()
graphics.set_clear_color(self.bg)
self.window.clear()
self.window.set_visible()
# Create framebuffer object for drawing unscaled scene
if self.scaling:
self.canvas = pyglet.image.Texture.create(*self.res)
self.fbo = graphics.Framebuffer(self.canvas)
self.fbo.start_render()
graphics.set_clear_color(self.bg)
self.fbo.clear()
# Set process priority
if self.disp_ops['priority'] != None:
if not priority.available[sys.platform]:
msg = "setting priority not available on {0}".\
format(sys.platform)
raise NotImplementedError(msg)
else:
try:
priority.set(self.disp_ops['priority'])
except ValueError:
priority.set(int(self.disp_ops['priority']))
# Start timers
if self.disp_ops['logtime']:
self.timer = Timer()
self.timer.start()
if self.disp_ops['logdur']:
self.dur = Timer()
self.dur.start()
def update(self):
"""Update the RunState."""
# Check for tracking and fixation
if self.disp_ops['eyetrack']:
self.old_tracked = self.tracked
self.tracked = eyetracking.is_tracked()
self.old_fixated = self.fixated
self.fixated = eyetracking.is_fixated(FIX_POS, FIX_RANGE, FIX_PER)
if self.fixated:
# Draw normal cross color if fixating
self.fix_crosses[0].draw()
else:
# Draw alternative cross color if not fixating
self.fix_crosses[1].draw()
# Update eyetracking events
if self.tracked != self.old_tracked:
if self.tracked:
self.events['track_on'] = True
else:
self.events['track_off'] = True
if self.fixated != self.old_fixated:
if self.fixated:
self.events['fix_on'] = True
else:
self.events['fix_off'] = True
# Check for failure of trial
if self.tracked and not self.fixated:
self.fix_fail = True
else:
# Change cross color based on time
if (self._count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
self.fix_crosses[0].draw()
else:
self.fix_crosses[1].draw()
# Blit canvas to screen if necessary
if self.scaling:
self.fbo.end_render()
self.canvas.blit(0, 0)
self.window.switch_to()
self.window.dispatch_events()
self.window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to lists
if self.disp_ops['logtime']:
self.timestamps.append(self.timer.elapsed())
elif self.disp_ops['logdur']:
self.timestamps.append('')
if self.disp_ops['logdur']:
self.durstamps.append(self.dur.restart())
elif self.disp_ops['logtime']:
self.durstamps.append('')
# Send trigger ASAP after flip
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
if self.encode_events() > 0:
trigger.send(self.disp_ops['trigser'],
self.disp_ops['trigpar'],
self.encode_events())
# Log when triggers are sent
if self.disp_ops['logtime'] and self.encode_events() > 0:
self.trigstamps.append(self.encode_events())
else:
self.trigstamps.append('')
# Clear canvas, events, prepare for next frame
if self.scaling:
self.fbo.start_render()
self.fbo.clear()
else:
self.window.clear()
self.events = copy.deepcopy(self.__class__.DEFAULTS['events'])
self._count += 1
def stop(self):
"""Clean up RunState."""
if self.disp_ops['eyetrack']:
eyetracking.stop()
if self.scaling:
self.fbo.delete()
del self.canvas
self.window.close()
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
trigger.quit(self.disp_ops['trigser'], self.disp_ops['trigpar'])
if self.disp_ops['priority'] != None:
priority.set('normal')
def encode_events(self):
"""Hard code specific trigger values for events."""
code = 0
if self.events['ord_id'] != None:
code = self.events['ord_id'] + 1
elif self.events['blk_on']:
code = 128
elif self.events['blk_off']:
code = 127
else:
mult = 0
if self.events['fix_on']:
mult = 4
elif self.events['track_on']:
mult = 3
if self.events['track_off']:
mult = 1
elif self.events['fix_off']:
mult = 2
if self.events['grp_on']:
code = 100 + mult
elif self.events['grp_off']:
code = 90 + mult
elif len(self.events['sids']) > 0:
code = ((0 in self.events['sids'])*2**0 +
(1 in self.events['sids'])*2**1 +
(2 in self.events['sids'])*2**2 +
(3 in self.events['sids'])*2**3)
code = mult*16 + code
elif mult > 0:
code = 110 + mult
return code
def log(self, path=None):
"""Write a log file for the experimental run in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, LOG_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(LOG_FMT):
path = '{0}.{1}'.format(path, LOG_FMT)
with open(path, 'wb') as logfile:
writer = csv.writer(logfile, dialect='excel-tab')
writer.writerow(['checkergen log file'])
writer.writerow(['display options:'])
writer.writerow(self.disp_ops.keys())
writer.writerow(self.disp_ops.values())
writer.writerow(['order:'] + self.order)
if self.disp_ops['eyetrack']:
writer.writerow(['groups added'])
for blk in grouper(self.add_gids,
self.disp_ops['trybreak'], ''):
writer.writerow(blk)
writer.writerow(['groups failed'])
for blk in grouper(self.fail_gids,
self.disp_ops['trybreak'], ''):
writer.writerow(blk)
if self.disp_ops['logtime'] or self.disp_ops['logdur']:
stamps = [self.timestamps, self.durstamps, self.trigstamps]
writer.writerow(['timestamps', 'durations', 'triggers'])
for stamp in zip(*stamps):
writer.writerow(list(stamp))
class CkgDisplayGroup:
DEFAULTS = OrderedDict([('pre', 0), ('disp', 'Infinity'), ('post', 0)])
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets counts and all contained shapes."""
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, runstate):
"""Draws all contained shapes during the appropriate interval."""
for shape in self.shapes:
shape.draw(photoburst=runstate.disp_ops['photoburst'])
def update(self, runstate):
"""Updates contained shapes, sets event triggers."""
# Set events to be sent
if runstate.disp_ops['fpst'] > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= runstate.disp_ops['fpst']:
if not runstate.disp_ops['freqcheck'] or runstate.fc_send:
runstate.events['sids'].add(n)
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(runstate.fps)
def display(self, runstate):
"""Display the group in the context described by supplied runstate."""
self.reset()
for count in range(self.pre * runstate.fps):
if runstate.window.has_exit:
break
runstate.update()
runstate.events['grp_on'] = True
if runstate.disp_ops['eyetrack']:
runstate.fix_fail = False
runstate.true_fail = False
for count in range(self.disp * runstate.fps):
if runstate.window.has_exit:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
runstate.events['grp_off'] = True
if runstate.disp_ops['eyetrack']:
if runstate.fix_fail:
runstate.true_fail = True
for count in range(self.post * runstate.fps):
if runstate.window.has_exit:
break
runstate.update()
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.steps_done = 0
def draw(self, runstate):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, runstate):
"""Checks for keypress, sends trigger upon end."""
if max([runstate.keystates[key] for
key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
def display(self, runstate):
"""Displays waitscreen in context described by supplied runstate."""
while self.steps_done < self.num_steps:
if runstate.window.has_exit:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = OrderedDict([('dims', (5, 5)),
('init_unit', (30, 30)),
('end_unit', (50, 50)),
|
ztangent/checkergen
|
33c0336474bfac648a7823f2939c853faca57d15
|
Eyetracking and typo fixes. Eyetracking triggers confirmed to work.
|
diff --git a/src/cli.py b/src/cli.py
index 689dc32..24efd31 100644
--- a/src/cli.py
+++ b/src/cli.py
@@ -311,784 +311,783 @@ class CkgCmd(cmd.Cmd):
print "display group", new_id, "added"
self.cur_group = new_group
print "group", new_id, "is now the current display group"
edgrp_parser = CmdParser(add_help=False, prog='edgrp',
description='''Edits attributes of display groups
specified by ids.''')
edgrp_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='ids of display groups to be edited')
edgrp_parser.add_argument('--pre', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown before shapes are displayed''')
edgrp_parser.add_argument('--disp', type=to_decimal, metavar='SECONDS',
help='''time in seconds shapes will be
displayed''')
edgrp_parser.add_argument('--post', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown after shapes are displayed''')
def help_edgrp(self):
self.__class__.edgrp_parser.print_help()
def do_edgrp(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.edgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.edgrp_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_proj.groups) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_group_attr(x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.edgrp_parser.print_usage()
rmgrp_parser = CmdParser(add_help=False, prog='rmgrp',
description='''Removes display groups specified
by ids.''')
rmgrp_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='ids of display groups to be removed')
rmgrp_parser.add_argument('-a', '--all', action='store_true',
help='remove all groups from the project')
def help_rmgrp(self):
self.__class__.rmgrp_parser.print_help()
def do_rmgrp(self, line):
"""Removes display groups specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups to remove'
return
try:
args = self.__class__.rmgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rmgrp_parser.print_usage()
return
rmlist = []
if args.all:
for group in self.cur_proj.groups[:]:
self.cur_proj.del_group(group)
print "all display groups removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_proj.groups) or x < 0:
print "display group", x, "does not exist"
continue
rmlist.append(self.cur_proj.groups[x])
print "display group", x, "removed"
for group in rmlist:
self.cur_proj.del_group(group)
# Remember to point self.cur_group somewhere sane
if self.cur_group not in self.cur_proj.groups:
if len(self.cur_proj.groups) == 0:
self.cur_group = None
else:
self.cur_group = self.cur_proj.groups[0]
print "group 0 is now the current display group"
chgrp_parser = CmdParser(add_help=False, prog='chgrp',
description='''Changes display group that is
currently active for editing.
Prints current group id if
no group id is specified''')
chgrp_parser.add_argument('gid', metavar='id', type=int, nargs='?',
help='id of display group to be made active')
def help_chgrp(self):
self.__class__.chgrp_parser.print_help()
def do_chgrp(self, line):
"""Changes group that is currently active for editing."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups that can be made active'
return
try:
args = self.__class__.chgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.chgrp_parser.print_usage()
return
if args.gid == None:
print "group",\
self.cur_proj.groups.index(self.cur_group),\
"is the current display group"
elif args.gid >= len(self.cur_proj.groups) or args.gid < 0:
print "group", args.gid, "does not exist"
else:
self.cur_group = self.cur_proj.groups[args.gid]
print "group", args.gid, "is now the current display group"
mk_parser = CmdParser(add_help=False, prog='mk',
description='''Makes a new checkerboard in the
current group with the given
parameters.''')
mk_parser.add_argument('dims', action=store_tuple(2, ',', to_decimal),
help='''width,height of checkerboard in no. of
unit cells''')
mk_parser.add_argument('init_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of initial unit cell in pixels')
mk_parser.add_argument('end_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of final unit cell in pixels')
mk_parser.add_argument('position', action=store_tuple(2, ',', to_decimal),
help='x,y position of checkerboard in pixels')
mk_parser.add_argument('anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='anchor')
mk_parser.add_argument('cols', action=store_tuple(2, ',', to_color, [';']),
help='''color1,color2 of the checkerboard
(color format: R;G;B,
component range from 0-255)''')
mk_parser.add_argument('freq', type=to_decimal,
help='frequency of color reversal in Hz')
mk_parser.add_argument('phase', type=to_decimal, nargs='?', default='0',
help='initial phase of animation in degrees')
def help_mk(self):
self.__class__.mk_parser.print_help()
def do_mk(self, line):
"""Makes a checkerboard with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
if self.cur_group == None:
print 'automatically adding display group...'
self.do_mkgrp('')
try:
args = self.__class__.mk_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mk_parser.print_usage()
return
shape_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_shape = core.CheckerBoard(**shape_dict)
new_id = self.cur_proj.add_shape_to_group(self.cur_group, new_shape)
print "checkerboard", new_id, "added"
ed_parser = CmdParser(add_help=False, prog='ed',
description='''Edits attributes of checkerboards
specified by ids.''')
ed_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='''ids of checkerboards in the current
group to be edited''')
ed_parser.add_argument('--dims', action=store_tuple(2, ',', to_decimal),
help='checkerboard dimensions in unit cells',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--init_unit',
action=store_tuple(2, ',', to_decimal),
help='initial unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--end_unit',
action=store_tuple(2, ',', to_decimal),
help='final unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--position',
action=store_tuple(2, ',', to_decimal),
help='position of checkerboard in pixels',
metavar='X,Y')
ed_parser.add_argument('--anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='LOCATION')
ed_parser.add_argument('--cols', metavar='COLOR1,COLOR2',
action=store_tuple(2, ',', to_color, [';']),
help='''checkerboard colors (color format:
R;G;B, component range
from 0-255)''')
ed_parser.add_argument('--freq', type=to_decimal,
help='frequency of color reversal in Hz')
ed_parser.add_argument('--phase', type=to_decimal,
help='initial phase of animation in degrees')
def help_ed(self):
self.__class__.ed_parser.print_help()
def do_ed(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, please create one first'
return
try:
args = self.__class__.ed_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ed_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_group.shapes) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_shape_attr(self.cur_group, x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.ed_parser.print_usage()
rm_parser = CmdParser(add_help=False, prog='rm',
description='''Removes checkerboards specified
by ids.''')
rm_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''ids of checkerboards in the current group
to be removed''')
rm_parser.add_argument('-a', '--all', action='store_true',
help='''remove all checkerboards in the
current group''')
def help_rm(self):
self.__class__.rm_parser.print_help()
def do_rm(self, line):
"""Removes checkerboards specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, no boards to remove'
return
try:
args = self.__class__.rm_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rm_parser.print_usage()
return
rmlist = []
if args.all:
for shape in self.cur_group.shapes:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
print "all checkerboards removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_group.shapes) or x < 0:
print "checkerboard", x, "does not exist"
continue
rmlist.append(self.cur_group.shapes[x])
print "checkerboard", x, "removed"
for shape in rmlist:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
ls_parser = CmdParser(add_help=False, prog='ls',
description='''Lists project, display group and
checkerboard settings. If no group ids
are specified, all display groups
are listed.''')
ls_parser.add_argument('gidlist', nargs='*', metavar='gid', type=int,
help='''ids of the display groups to be listed''')
ls_group = ls_parser.add_mutually_exclusive_group()
ls_group.add_argument('-s', '--settings', action='store_true',
help='list only project settings')
ls_group.add_argument('-g', '--groups', action='store_true',
help='list only display groups')
def help_ls(self):
self.__class__.ls_parser.print_help()
def do_ls(self, line):
"""Lists project, display group and checkerboard settings."""
def ls_str(s, seps=[',',';']):
"""Special space-saving output formatter."""
if type(s) in [tuple, list]:
if len(seps) > 1:
newseps = seps[1:]
else:
newseps = seps
return seps[0].join([ls_str(i, newseps) for i in s])
else:
return str(s)
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.ls_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ls_parser.print_usage()
return
# Remove duplicates and ascending sort
args.gidlist = sorted(set(args.gidlist))
if len(self.cur_proj.groups) == 0:
if len(args.gidlist) > 0:
print 'this project has no display groups that can be listed'
args.settings = True
else:
for gid in args.gidlist[:]:
if gid >= len(self.cur_proj.groups) or gid < 0:
args.gidlist.remove(gid)
print 'display group', gid, 'does not exist'
if args.gidlist == []:
args.gidlist = range(len(self.cur_proj.groups))
else:
# If any (valid) groups are specified
# don't show project settings
args.groups = True
if not args.groups:
print 'PROJECT SETTINGS'.center(70,'*')
print \
'name'.rjust(16),\
'fps'.rjust(7),\
'resolution'.rjust(14),\
'bg color'.rjust(18)
# 'format'.rjust(7)
print \
ls_str(self.cur_proj.name).rjust(16),\
ls_str(self.cur_proj.fps).rjust(7),\
ls_str(self.cur_proj.res).rjust(14),\
ls_str(self.cur_proj.bg).rjust(18)
# ls_str(self.cur_proj.export_fmt).rjust(7)
print \
'pre-display'.rjust(26),\
'post-display'.rjust(26)
print \
ls_str(self.cur_proj.pre).rjust(26),\
ls_str(self.cur_proj.post).rjust(26)
print \
'cross colors'.rjust(26),\
'cross times'.rjust(26)
print \
ls_str(self.cur_proj.cross_cols).rjust(26),\
ls_str(self.cur_proj.cross_times).rjust(26)
if not args.settings and not args.groups:
# Insert empty line if both groups and project
# settings are listed
print ''
if not args.settings:
for i, n in enumerate(args.gidlist):
if i != 0:
# Print newline seperator between each group
print ''
group = self.cur_proj.groups[n]
print 'GROUP {n}'.format(n=n).center(70,'*')
print \
'pre-display'.rjust(20),\
'display'.rjust(20),\
'post-display'.rjust(20)
print \
ls_str(group.pre).rjust(20),\
ls_str(group.disp).rjust(20),\
ls_str(group.post).rjust(20)
if len(group.shapes) > 0:
print \
''.rjust(2),\
'shape id'.rjust(8),\
'dims'.rjust(10),\
'init_unit'.rjust(14),\
'end_unit'.rjust(14),\
'position'.rjust(14)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.dims).rjust(10),\
ls_str(shape.init_unit).rjust(14),\
ls_str(shape.end_unit).rjust(14),\
ls_str(shape.position).rjust(14)
print '\n',\
''.rjust(2),\
'shape id'.rjust(8),\
'colors'.rjust(27),\
'anchor'.rjust(12),\
'freq'.rjust(6),\
'phase'.rjust(7)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.cols).rjust(27),\
ls_str(shape.anchor).rjust(12),\
ls_str(shape.freq).rjust(6),\
ls_str(shape.phase).rjust(7)
display_parser = CmdParser(add_help=False, prog='display',
description='''Displays the animation in a
window or in fullscreen.''')
display_parser.add_argument('-n', '--name', metavar='FOOBAR',
help='''name of log file to be written''')
display_parser.add_argument('-r', '--repeats', metavar='N', type=int,
help='''repeatedly display specified display
groups N number of times''')
display_parser.add_argument('-wl', '--waitless', action=store_truth(),
metavar='t/f',
help='''do not add waitscreens before the
start of each repeat''')
display_parser.add_argument('-f', '--fullscreen', action=store_truth(),
metavar='t/f',
help='sets fullscreen mode, ESC to quit')
display_parser.add_argument('-p', '--priority', metavar='LEVEL',
help='''set priority while displaying,
higher priority results in
less dropped frames (choices:
0-3, low, normal, high,
realtime)''')
display_parser.add_argument('-pt', '--phototest', action=store_truth(),
metavar='t/f',
help='''draw white test rectangle in topleft
corner of screen when groups become
visible for a photodiode to detect''')
display_parser.add_argument('-pb', '--photoburst', action=store_truth(),
metavar='t/f',
help='''make checkerboards only draw first
color for one frame to facilitate
testing with a photodiode''')
display_parser.add_argument('-lt', '--logtime', action=store_truth(),
metavar='t/f',
help='output frame timestamps to a log file')
display_parser.add_argument('-ld', '--logdur', action=store_truth(),
metavar='t/f',
help='output frame durations to a log file')
display_parser.add_argument('-ss', '--trigser', action=store_truth(),
metavar='t/f',
help='''send triggers through the serial port
when shapes are being displayed''')
display_parser.add_argument('-sp', '--trigpar', action=store_truth(),
metavar='t/f',
help='''send triggers through the parallel port
when shapes are being displayed''')
display_parser.add_argument('-fpst', metavar='M', type=int,
help='''unique trigger corresponding to a
checkerboard is sent after the shape
undergoes M color flips (default:
disabled, M=0)''')
display_parser.add_argument('-fc', '--freqcheck', action=store_truth(),
metavar='t/f',
help='''only send triggers for board color
flips at the start, middle and end
of the run''')
display_parser.add_argument('-et', '--eyetrack', action=store_truth(),
metavar='t/f',
help='''use eyetracking to ensure that subject
fixates on the cross in the center''')
display_parser.add_argument('-eu', '--etuser', action=store_truth(),
metavar='t/f',
help='''allow user to select eyetracking video
source from a dialog''')
display_parser.add_argument('-ev', '--etvideo', metavar='path',
help='''path (with no spaces) to eyetracking
video file to be used as the source''')
- display_parser.add_argument('-ta', '--tryagain', metavar='I',
- type=int, default=0,
+ display_parser.add_argument('-ta', '--tryagain', metavar='I', type=int,
help='''append groups during which subject
failed to fixate up to I times to the
list of groups to be displayed
(default: disabled, I=0)''')
display_parser.add_argument('-tb', '--trybreak', metavar='J', type=int,
help='''used with --tryagain, append a wait
screen to the list of groups to be
displayed after every J groups have
been appended to the list (default:
J=total number of groups)''')
display_parser.add_argument('-nl', '--nolog', action=store_truth(),
metavar='t/f',
help='''do not write a log file''')
display_parser.add_argument('order', nargs='*', metavar='id', type=int,
help='''order in which groups should be
displayed (default: random order
from list of orders if specified
in project, ascending otherwise)''')
def help_display(self):
self.__class__.display_parser.print_help()
def do_display(self, line):
"""Displays the animation in a window or in fullscreen"""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.display_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
if len(args.order) > 0:
for i in set(args.order):
if i >= len(self.cur_proj.groups) or i < -1:
print 'error: group', i, 'does not exist'
return
if args.eyetrack and eyetracking.available:
if not eyetracking.is_calibrated():
try:
self.do_calibrate('',query=True)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
return
print "displaying...",
try:
self.cur_proj.display(name=args.name,
repeats=args.repeats,
waitless=args.waitless,
fullscreen=args.fullscreen,
priority=args.priority,
logtime=args.logtime,
logdur=args.logdur,
trigser=args.trigser,
trigpar=args.trigpar,
fpst=args.fpst,
freqcheck=args.freqcheck,
phototest=args.phototest,
photoburst=args.photoburst,
eyetrack=args.eyetrack,
etuser=args.etuser,
etvideo=args.etvideo,
tryagain=args.tryagain,
trybreak=args.trybreak,
nolog=args.nolog,
order=args.order)
except (IOError, NotImplementedError, eyetracking.EyetrackingError):
print ''
print "error:", str(sys.exc_value)
if args.priority != None:
try:
priority.set('normal')
except:
pass
return
print "done"
export_parser = CmdParser(add_help=False, prog='export',
description='''Exports animation as an image
sequence (in a folder) to the
specified directory.''')
# export_parser.add_argument('--fmt', dest='export_fmt',
# choices=core.EXPORT_FMTS,
# help='image format for export')
export_parser.add_argument('-n','--nofolder',
dest='folder', action='store_false',
help='''force images not to exported in
a containing folder''')
export_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly export specified display
groups N number of times''')
export_parser.add_argument('duration', nargs='?',
type=to_decimal, default='Infinity',
help='''number of seconds of the animation
that should be exported (default:
as long as the entire animation)''')
export_parser.add_argument('dir', nargs='?', default=os.getcwd(),
help='''destination directory for export
(default: current working directory)''')
export_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be exported
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_export(self):
self.__class__.export_parser.print_help()
def do_export(self, line):
"""Exports animation an image sequence to the specified directory."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.export_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.export_parser.print_usage()
return
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < 0:
print 'error: group', i, 'does not exist'
return
groupq = [self.cur_proj.groups[i] for i in args.idlist]
else:
groupq = list(self.cur_proj.groups)
if args.repeat != None:
groupq = list(groupq * args.repeat)
try:
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
folder=args.folder)
except IOError:
print "error:", str(sys.exc_value)
return
except core.FrameOverflowError:
print "warning:", str(sys.exc_value)
print "Are you sure you want to continue?"
while True:
try:
if self.__class__.yn_parse(raw_input()):
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
export_fmt=None,
folder=args.folder,
force=True)
break
else:
return
except TypeError:
print str(sys.exc_value)
except EOFError:
return
print "Export done."
def do_calibrate(self, line, query=False):
"""Calibrate subject for eyetracking, or load a calibration file."""
if not eyetracking.available:
print "error: eyetracking functionality not available"
return
if query:
print "path to calibration file (leave empty for GUI tool):"
try:
path = raw_input().strip().strip('"\'')
except EOFError:
msg = "calibration cancelled"
raise eyetracking.EyetrackingError(msg)
else:
path = line.strip().strip('"\'')
if len(path) == 0:
path = None
if not eyetracking.is_source_ready():
# Select default source if none has been selected
eyetracking.select_source()
try:
eyetracking.calibrate(path)
except eyetracking.EyetrackingError:
if query:
raise
else:
print "error:", str(sys.exc_value)
return
if len(path) > 0:
print "calibration file successfully loaded"
etsetup_parser = CmdParser(add_help=False, prog='etsetup',
description='''Set various eyetracking
parameters.''')
etsetup_parser.add_argument('-fp', '--fixperiod', type=int, metavar='MS',
help='''time in milliseconds subject
has to stare at the same spot
for fixation to be detected''')
etsetup_parser.add_argument('-fr', '--fixrange', type=float, metavar='MM',
help='''distance in mm beyond which the
eye position cannot change for
a fixation to be detected''')
etsetup_parser.add_argument('-s', '--size', metavar='WIDTH,HEIGHT',
action=store_tuple(2, ',', float),
help='physical screen dimensions in mm')
etsetup_parser.add_argument('-vd', '--viewdist', type=int, metavar='MM',
help='''viewing distance between subject's
eyes and the screen''')
def help_etsetup(self):
self.__class__.etsetup_parser.print_help()
def do_etsetup(self, line):
try:
args = self.__class__.etsetup_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.etsetup_parser.print_usage()
return
try:
eyetracking.setup(viewing_distance=args.viewdist,
screen_dims=args.size,
fixation_period=args.fixperiod,
fixation_range=args.fixrange)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
def do_pwd(self, line):
"""Prints the current working directory."""
print os.getcwd()
def do_cd(self, line):
"""Change working directory to specified path."""
path = line.strip().strip('"\'')
if not os.path.isdir(path):
print "error: specified path is not a directory"
return
os.chdir(path)
def do_quit(self, line):
"""Quits the program."""
if self.save_check():
return
return True
def help_EOF(self):
print "Typing {0} issues this command, which quits the program."\
.format(CMD_EOF_STRING)
def do_EOF(self, line):
"""Typing Ctrl-D issues this command, which quits the program."""
print '\r'
if self.save_check():
return
return True
def help_help(self):
print 'Prints a list of commands.'
print "Type 'help <topic>' for more details on each command."
def default(self, line):
command = line.split()[0]
print \
"'{0}' is not a checkergen command.".format(command),\
"Type 'help' for a list of commands"
diff --git a/src/core.py b/src/core.py
index b4c0974..c88c742 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,1230 +1,1230 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import copy
import random
import itertools
from datetime import datetime
from xml.dom import minidom
import pyglet
import graphics
import priority
import trigger
import eyetracking
from utils import *
# Use OrderedDict substitute if we don't have Python 2.7
if sys.version_info < (2, 7):
from odict import OrderedDict
else:
from collections import OrderedDict
CKG_FMT = 'ckg'
LOG_FMT = 'csv'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
MAX_EXPORT_FRAMES = 100000
INT_HALF_PERIODS = True
EXPORT_FMTS = ['png']
EXPORT_DIR_SUFFIX = '-anim'
FIX_POS = (0, 0)
FIX_RANGE = (20, 20)
FIX_PER = 350
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = OrderedDict([('name', 'untitled'),
('fps', 60),
('res', (800, 600)),
('bg', (127, 127, 127)),
('export_fmt', 'png'),
('pre', 0),
('post', 0),
('cross_cols', ((0, 0, 0), (255, 0, 0))),
('cross_times', ('Infinity', 1)),
('orders', []),
('disp_ops', None)])
DEFAULTS['disp_ops'] = OrderedDict([('repeats', 1),
('waitless', False),
('fullscreen', False),
('priority', None),
('logtime', False),
('logdur', False),
('trigser', False),
('trigpar', False),
('fpst', 0),
('freqcheck', False),
('phototest', False),
('photoburst', False),
('eyetrack', False),
('etuser', False),
('etvideo', None),
('tryagain', 0),
('trybreak', None),
('nolog', False)])
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
export_fmt -- image format for animation to be exported as
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'export_fmt':
if value not in EXPORT_FMTS:
msg = 'image format not recognized or supported'
raise FileFormatError(msg)
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
# Vars that are dicts
dicts_to_load = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_load = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
for d_name in dicts_to_load:
- d = self.__class__.DEFAULTS[d_name]
+ d = copy.deepcopy(self.__class__.DEFAULTS[d_name])
try:
d_el = [node for node in project.childNodes if
node.localName == d_name and
node.namespaceURI == XML_NAMESPACE][0]
for var in d.keys():
try:
d[var] = eval(xml_get(d_el, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}' in '{1}'".\
format(var, d_name)
print "using default value '{0}' instead...".\
format(d[var])
except IndexError:
print "warning: missing attribute set '{0}'".format(d_name)
print "using default values instead..."
setattr(self, d_name, d)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
# Vars that are dicts
dicts_to_save = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_save = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for d_name in dicts_to_save:
d_el = doc.createElement(d_name)
project.appendChild(d_el)
d = getattr(self, d_name)
for k, v in d.iteritems():
xml_set(doc, d_el, k, repr(v))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, **keywords):
"""Displays the project animation on the screen.
name -- name that logfile will be saved with
repeats -- number of times specified order of display groups should
be repeated
waitless -- if true, no waitscreens will appear at the start of each
repeat
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
priority -- priority level to which process should be raised
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
trigser -- send triggers through serial port when each group is shown
trigpar -- send triggers through parallel port when each group is shown
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
freqcheck -- send fpst only at the start, the middle, and the end
for sanity checking of display and trigger fps
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- append a wait screen to the group queue every time
after this many groups have been appended to the queue
order -- order in which groups (specified by id) will be displayed
"""
# Create RunState
disp_ops = copy.deepcopy(self.disp_ops)
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'name' in keywords.keys() and keywords['name'] != None:
name = keywords['name']
else:
timestr = datetime.today().strftime('_%Y-%m-%d_%H-%M-%S')
name = self.name + timestr
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
waitscreen = CkgWaitScreen()
# Set order id to be sent if necessary
if order in self.orders:
runstate.events['ord_id'] = self.orders.index(order)
# Count through pre
for count in range(self.pre * self.fps):
if runstate.window.has_exit:
break
runstate.update()
# Loop through repeats
repeats = runstate.disp_ops['repeats']
ord_len = len(runstate.order)
for i in range(repeats):
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
# Loop through display groups
runstate.events['blk_on'] = True
for n, gid in enumerate(runstate.order):
# Set flag for freqcheck
if runstate.disp_ops['freqcheck']:
if ((i == 0 and n == 0) or
(i == repeats-1 and n == ord_len-1) or
(i == repeats//2 and n == ord_len//2)):
runstate.fc_send = True
else:
runstate.fc_send = False
if gid == -1:
waitscreen.reset()
waitscreen.display(runstate)
else:
self.groups[gid].display(runstate)
# Append failed groups
- if runstate.disp_ops['eyetrack'] and runstate.truefail:
+ if runstate.disp_ops['eyetrack'] and runstate.true_fail:
if len(runstate.add_gids) < runstate.disp_ops['tryagain']:
runstate.add_gids.append(gid)
else:
runstate.fail_gids.append(gid)
runstate.events['blk_off'] = True
# Loop through added groups
if runstate.disp_ops['eyetrack']:
for blk in grouper(runstate.add_gids,
runstate.disp_ops['trybreak']):
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
runstate.events['blk_on'] = True
# Loop through display groups
for gid in blk:
if gid != None:
self.groups[gid].display(runstate)
runstate.events['blk_off'] = True
# Count through post
for count in range(self.post * self.fps):
if runstate.window.has_exit:
break
runstate.update()
# Stop and output log
runstate.stop()
if not runstate.disp_ops['nolog']:
runstate.log()
def export(self, export_dir, export_duration, groupq=[],
export_fmt=None, folder=True, force=False):
if not os.path.isdir(export_dir):
msg = 'export path is not a directory'
raise IOError(msg)
if export_fmt == None:
export_fmt = self.export_fmt
# Set-up groups and variables that control their display
if groupq == []:
groupq = list(self.groups)
n = -1
groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Limit export duration to display duration
frames = export_duration * self.fps
frames = min(frames, disp_end)
# Warn user if a lot of frames will be exported
if frames > MAX_EXPORT_FRAMES and not force:
msg = 'very large number ({0}) of frames to be exported'.\
format(frames)
raise FrameOverflowError(msg)
# Create folder to store images if necessary
if folder:
export_dir = os.path.join(export_dir,
self.name + EXPORT_DIR_SUFFIX)
if not os.path.isdir(export_dir):
os.mkdir(export_dir)
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Set up canvas and framebuffer object
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
# Main loop
while count < frames:
fbo.clear()
if groups_visible:
# Get next group from queue
if n < 0 or groupq[n].over:
n += 1
if n >= len(groupq):
groups_visible = False
else:
groupq[n].reset()
# Draw and then update group
if n >= 0:
groupq[n].draw()
groupq[n].update(fps=self.fps, fpst=0)
# Draw fixation cross based on current count
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Save current frame to file
savepath = \
os.path.join(export_dir,
'{0}{2}.{1}'.
format(self.name, export_fmt,
repr(count).zfill(numdigits(frames-1))))
canvas.save(savepath)
# Increment count and set whether groups should be shown
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
fbo.delete()
class CkgRunState:
"""Contains information about the state of a checkergen project
when it is being displayed or exported."""
DEFAULTS = dict([('name', 'untitled'),
('res', None),
('fps', None),
('bg', None),
('cross_cols', None),
('cross_times', None),
('order', []),
('disp_ops', None),
('events', None),
('add_gids', []),
('fail_gids', []),
('timestamps', []),
('durstamps', []),
('trigstamps', [])])
DEFAULTS['events'] = dict([('ord_id', None),
('blk_on', False),
('blk_off', False),
('track_on', False),
('track_off', False),
('fix_on', False),
('fix_off', False),
('grp_on', False),
('grp_off', False),
('sids', set())])
def __init__(self, **keywords):
"""Creates the RunState."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
def start(self):
"""Initialize all subsystems and start the run."""
if self.disp_ops == None:
msg = "RunState lacks display options"
raise ValueError(msg)
if min(self.res, self.fps, self.bg,
self.cross_cols, self.cross_times) == None:
msg = "RunState intialized with insufficent project information"
raise ValueError(msg)
self._count = 0
# Flag used by freqcheck
self.fc_send = False
# Create fixation crosses
self.fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if self.disp_ops['phototest']:
self.test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Initialize ports
if self.disp_ops['trigser']:
if not trigger.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trigpar']:
if not trigger.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
trigger.init(self.disp_ops['trigser'], self.disp_ops['trigpar'])
# Initialize eyetracking
if self.disp_ops['eyetrack']:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trybreak'] == None:
self.disp_ops['trybreak'] = len(self.order)
self.fixated = False
self.old_fixated = False
self.tracked = False
self.old_tracked = False
self.fix_fail = False
self.true_fail = False
eyetracking.select_source(self.disp_ops['etuser'],
self.disp_ops['etvideo'])
eyetracking.start()
# Stretch to fit screen only if project res does not equal screen res
self.scaling = False
if self.disp_ops['fullscreen']:
self.window = pyglet.window.Window(fullscreen=True, visible=False)
if (self.window.width, self.window.height) != self.res:
self.scaling = True
else:
self.window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
self.keystates = pyglet.window.key.KeyStateHandler()
self.window.push_handlers(self.keystates)
# Clear window and make visible
self.window.switch_to()
graphics.set_clear_color(self.bg)
self.window.clear()
self.window.set_visible()
# Create framebuffer object for drawing unscaled scene
if self.scaling:
self.canvas = pyglet.image.Texture.create(*self.res)
self.fbo = graphics.Framebuffer(self.canvas)
self.fbo.start_render()
graphics.set_clear_color(self.bg)
self.fbo.clear()
# Set process priority
if self.disp_ops['priority'] != None:
if not priority.available[sys.platform]:
msg = "setting priority not available on {0}".\
format(sys.platform)
raise NotImplementedError(msg)
else:
try:
priority.set(self.disp_ops['priority'])
except ValueError:
priority.set(int(self.disp_ops['priority']))
# Start timers
if self.disp_ops['logtime']:
self.timer = Timer()
self.timer.start()
if self.disp_ops['logdur']:
self.dur = Timer()
self.dur.start()
def update(self):
"""Update the RunState."""
# Check for tracking and fixation
if self.disp_ops['eyetrack']:
self.old_tracked = self.tracked
self.tracked = eyetracking.is_tracked()
self.old_fixated = self.fixated
self.fixated = eyetracking.is_fixated(FIX_POS, FIX_RANGE, FIX_PER)
if self.fixated:
# Draw normal cross color if fixating
self.fix_crosses[0].draw()
else:
# Draw alternative cross color if not fixating
self.fix_crosses[1].draw()
# Update eyetracking events
if self.tracked != self.old_tracked:
if self.tracked:
self.events['track_on'] = True
else:
self.events['track_off'] = True
if self.fixated != self.old_fixated:
if self.fixated:
self.events['fix_on'] = True
else:
self.events['fix_off'] = True
# Check for failure of trial
if self.tracked and not self.fixated:
self.fix_fail = True
else:
# Change cross color based on time
if (self._count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
self.fix_crosses[0].draw()
else:
self.fix_crosses[1].draw()
# Blit canvas to screen if necessary
if self.scaling:
self.fbo.end_render()
self.canvas.blit(0, 0)
self.window.switch_to()
self.window.dispatch_events()
self.window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to lists
if self.disp_ops['logtime']:
self.timestamps.append(self.timer.elapsed())
elif self.disp_ops['logdur']:
self.timestamps.append('')
if self.disp_ops['logdur']:
self.durstamps.append(self.dur.restart())
elif self.disp_ops['logtime']:
self.durstamps.append('')
# Send trigger ASAP after flip
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
if self.encode_events() > 0:
trigger.send(self.disp_ops['trigser'],
self.disp_ops['trigpar'],
self.encode_events())
# Log when triggers are sent
if self.disp_ops['logtime'] and self.encode_events() > 0:
self.trigstamps.append(self.encode_events())
else:
self.trigstamps.append('')
# Clear canvas, events, prepare for next frame
if self.scaling:
self.fbo.start_render()
self.fbo.clear()
else:
self.window.clear()
self.events = copy.deepcopy(self.__class__.DEFAULTS['events'])
self._count += 1
def stop(self):
"""Clean up RunState."""
if self.disp_ops['eyetrack']:
eyetracking.stop()
if self.scaling:
self.fbo.delete()
del self.canvas
self.window.close()
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
trigger.quit(self.disp_ops['trigser'], self.disp_ops['trigpar'])
if self.disp_ops['priority'] != None:
priority.set('normal')
def encode_events(self):
"""Hard code specific trigger values for events."""
code = 0
if self.events['ord_id'] != None:
code = self.events['ord_id'] + 1
elif self.events['blk_on']:
code = 128
elif self.events['blk_off']:
code = 127
else:
mult = 0
if self.events['fix_on']:
mult = 4
elif self.events['track_on']:
mult = 3
if self.events['track_off']:
mult = 1
elif self.events['fix_off']:
mult = 2
if self.events['grp_on']:
code = 100 + mult
elif self.events['grp_off']:
code = 90 + mult
elif len(self.events['sids']) > 0:
code = ((0 in self.events['sids'])*2**0 +
(1 in self.events['sids'])*2**1 +
(2 in self.events['sids'])*2**2 +
(3 in self.events['sids'])*2**3)
code = mult*16 + code
elif mult > 0:
code = 110 + mult
return code
def log(self, path=None):
"""Write a log file for the experimental run in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, LOG_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(LOG_FMT):
path = '{0}.{1}'.format(path, LOG_FMT)
with open(path, 'wb') as logfile:
writer = csv.writer(logfile, dialect='excel-tab')
writer.writerow(['checkergen log file'])
writer.writerow(['display options:'])
writer.writerow(self.disp_ops.keys())
writer.writerow(self.disp_ops.values())
writer.writerow(['order:'] + self.order)
if self.disp_ops['eyetrack']:
- write.writerow(['groups added'])
+ writer.writerow(['groups added'])
for blk in grouper(self.add_gids,
self.disp_ops['trybreak'], ''):
- write.writerow(blk)
- write.writerow(['groups failed'])
+ writer.writerow(blk)
+ writer.writerow(['groups failed'])
for blk in grouper(self.fail_gids,
self.disp_ops['trybreak'], ''):
- write.writerow(blk)
+ writer.writerow(blk)
if self.disp_ops['logtime'] or self.disp_ops['logdur']:
stamps = [self.timestamps, self.durstamps, self.trigstamps]
writer.writerow(['timestamps', 'durations', 'triggers'])
for stamp in zip(*stamps):
writer.writerow(list(stamp))
class CkgDisplayGroup:
DEFAULTS = OrderedDict([('pre', 0), ('disp', 'Infinity'), ('post', 0)])
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets counts and all contained shapes."""
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, runstate):
"""Draws all contained shapes during the appropriate interval."""
for shape in self.shapes:
shape.draw(photoburst=runstate.disp_ops['photoburst'])
def update(self, runstate):
"""Updates contained shapes, sets event triggers."""
# Set events to be sent
if runstate.disp_ops['fpst'] > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= runstate.disp_ops['fpst']:
if not runstate.disp_ops['freqcheck'] or runstate.fc_send:
runstate.events['sids'].add(n)
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(runstate.fps)
def display(self, runstate):
"""Display the group in the context described by supplied runstate."""
self.reset()
for count in range(self.pre * runstate.fps):
if runstate.window.has_exit:
break
runstate.update()
runstate.events['grp_on'] = True
if runstate.disp_ops['eyetrack']:
runstate.fix_fail = False
- renstate.true_fail = False
+ runstate.true_fail = False
for count in range(self.disp * runstate.fps):
if runstate.window.has_exit:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
runstate.events['grp_off'] = True
if runstate.disp_ops['eyetrack']:
if runstate.fix_fail:
runstate.true_fail = True
for count in range(self.post * runstate.fps):
if runstate.window.has_exit:
break
runstate.update()
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.steps_done = 0
def draw(self, runstate):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, runstate):
"""Checks for keypress, sends trigger upon end."""
if max([runstate.keystates[key] for
key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
def display(self, runstate):
"""Displays waitscreen in context described by supplied runstate."""
while self.steps_done < self.num_steps:
if runstate.window.has_exit:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = OrderedDict([('dims', (5, 5)),
('init_unit', (30, 30)),
('end_unit', (50, 50)),
('position', (0, 0)),
('anchor', 'bottomleft'),
('cols', ((0, 0, 0), (255, 255, 255))),
('freq', 1),
('phase', 0)])
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
if INT_HALF_PERIODS:
frames_per_half_period = round(fps / (self.freq * 2))
degs_per_frame = 180 / to_decimal(frames_per_half_period)
else:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
anchor=self.anchor)
cur_unit_rect.col = self.cols[(i + j) % 2]
cur_unit_rect.add_to_batch(self._batches[0])
cur_unit_rect.col = self.cols[(i + j + 1) % 2]
cur_unit_rect.add_to_batch(self._batches[1])
# Increase x values
cur_unit_pos[0] += \
graphics.locations[self.anchor][0] * cur_unit[0]
cur_unit[0] += unit_grad[0]
# Reset x values
cur_unit_pos[0] = init_pos[0]
cur_unit[0] = init_unit[0]
# Increase y values
cur_unit_pos[1] += \
graphics.locations[self.anchor][1] * cur_unit[1]
cur_unit[1] += unit_grad[1]
self._computed = True
def draw(self, photoburst=False, always_compute=False):
"""Draws appropriate batch depending on current phase.
photoburst -- draw first color for only one frame for testing purposes
always_compute -- recompute what the checkerboard should look like
every frame
"""
if not self._computed or always_compute:
self.compute()
self._cur_phase %= 360
n = int(self._cur_phase // 180)
if photoburst and n == 0 and not self.flipped:
n = 1
self._batches[n].draw()
def lazydraw(self):
"""Only draws on color reversal."""
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if (cur_n != prev_n) or self._first_draw:
self.draw()
if self._first_draw:
self._first_draw = False
|
ztangent/checkergen
|
cf9ee07ebde7079f6a8f3614f03cad557803a346
|
Allow user to specify true/false for display flags.
|
diff --git a/src/cli.py b/src/cli.py
index d992125..689dc32 100644
--- a/src/cli.py
+++ b/src/cli.py
@@ -1,1069 +1,1094 @@
"""Defines command-line-interface for checkergen."""
import os
import sys
if os.name == 'posix':
import readline
import argparse
import cmd
import shlex
import core
import priority
import eyetracking
from graphics import locations
from utils import *
CMD_PROMPT = '(ckg) '
CMD_EOF_STRING = 'Ctrl-D'
if sys.platform == 'win32':
CMD_EOF_STRING = 'Ctrl-Z + Enter'
CMD_INTRO = '\n'.join(["Enter 'help' for a list of commands.",
"Enter 'quit' or {0} to exit.".format(CMD_EOF_STRING)])
def store_tuple(nargs, sep, typecast=None, castargs=[]):
"""Returns argparse action that stores a tuple."""
class TupleAction(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
vallist = values.split(sep)
if len(vallist) != nargs:
msg = ("argument '{f}' should be a list of " +
"{nargs} values separated by '{sep}'").\
format(f=self.dest,nargs=nargs,sep=sep)
raise argparse.ArgumentError(self, msg)
if typecast != None:
for n, val in enumerate(vallist):
try:
val = typecast(*([val] + castargs))
vallist[n] = val
except (ValueError, TypeError):
msg = ("element '{val}' of argument '{f}' " +
"is of the wrong type").\
format(val=vallist[n],f=self.dest)
raise argparse.ArgumentError(self, msg)
setattr(args, self.dest, tuple(vallist))
return TupleAction
+def store_truth(y_words=['t','y'], n_words=['f', 'n']):
+ """Returns argparse action that stores the truth based on keywords."""
+ class TruthAction(argparse.Action):
+ def __call__(self, parser, args, values, option_string=None):
+ if values in y_words:
+ setattr(args, self.dest, True)
+ elif values in n_words:
+ setattr(args, self.dest, False)
+ else:
+ msg = 'true/false keyword unrecognized'
+ raise argparse.ArgumentError(self, msg)
+ return TruthAction
+
# The main parser invoked at the command-line
PARSER = argparse.ArgumentParser(
description='''Generate flashing checkerboard patterns for display
or export as a series of images, intended for use in
psychophysics experiments. Enters interactive command
line mode if no options are specified.''')
PARSER.add_argument('-c', '--cmd', dest='cmd_mode', action='store_true',
help='enter command line mode regardless of other options')
PARSER.add_argument('-d', '--display',
dest='display_flag', action='store_true',
help='displays the animation on the screen')
PARSER.add_argument('-e', '--export', dest='export_dur', metavar='DUR',
help='export DUR seconds of the project animation')
PARSER.add_argument('-f', '--fullscreen', action='store_true',
help='animation displayed in fullscreen mode')
# PARSER.add_argument('--fmt', dest='export_fmt', choices=core.EXPORT_FMTS,
# help='image format for animation to be exported as')
PARSER.add_argument('--dir', dest='export_dir',
default=os.getcwd(), metavar='PATH',
help='''destination directory for export
(default: current working directory)''')
PARSER.add_argument('path', metavar='project', nargs='?', type=file,
help='checkergen project file to open')
def process_args(args):
"""Further processes the arguments returned by the main parser."""
if args.export_dur != None:
args.export_flag = True
else:
args.export_flag = False
if not args.display_flag and not args.export_flag:
args.cmd_mode = True
if args.path != None:
if not os.path.isfile(args.path):
msg = 'error: path specified is not a file'
return msg
args.proj = core.CkgProj(path=args.path)
os.chdir(os.path.dirname(os.path.abspath(args.path)))
try:
args.group = args.proj.groups[0]
except IndexError:
args.group = None
else:
args.proj = None
args.group = None
if args.display_flag or args.export_flag:
msg = 'error: no project file specified for display or export'
return msg
class CmdParserError(Exception):
"""To be raised when CmdParser encounters an error."""
pass
class CmdParser(argparse.ArgumentParser):
"""Override ArgumentParser so that it doesn't exit the program."""
def error(self, msg):
raise CmdParserError(msg)
class CkgCmd(cmd.Cmd):
@staticmethod
def yn_parse(s):
if s in ['y', 'Y', 'yes', 'YES', 'Yes']:
return True
elif s in ['n', 'N', 'no', 'NO', 'No']:
return False
else:
msg = "only 'y','n' or variants accepted"
raise ValueError(msg)
def save_check(self, msg=None):
"""Checks and prompts the user to save if necessary."""
if self.cur_proj == None:
return
if not self.cur_proj.is_dirty():
return
if msg == None:
msg = 'Would you like to save the current project first? (y/n)'
print msg
while True:
try:
if self.__class__.yn_parse(raw_input()):
self.do_save('')
break
except TypeError:
print str(sys.exc_value)
except EOFError:
return True
def do_new(self, line):
"""Creates new project with given name (can contain whitespace)."""
name = line.strip().strip('"\'')
if len(name) == 0:
name = 'untitled'
if self.save_check():
return
self.cur_proj = core.CkgProj(name=name)
print 'project \'{0}\' created'.format(self.cur_proj.name)
def do_open(self, line):
"""Open specified project file."""
path = line.strip().strip('"\'')
if len(path) == 0:
print 'error: no path specified'
return
if self.save_check():
return
try:
self.cur_proj = core.CkgProj(path=path)
except (core.FileFormatError, IOError):
print "error:", str(sys.exc_value)
return
os.chdir(os.path.dirname(os.path.abspath(path)))
try:
self.cur_group = self.cur_proj.groups[0]
except IndexError:
self.cur_group = None
print 'project \'{0}\' loaded'.format(self.cur_proj.name)
def do_close(self, line):
"""Prompts the user to save, then closes current project."""
if self.cur_proj == None:
print 'no project to close'
return
if self.save_check():
return
self.cur_proj = None
print 'project closed'
def do_save(self, line):
"""Saves the current project to the specified path."""
if self.cur_proj == None:
print 'no project to save'
return
path = line.strip().strip('"\'')
if len(path) == 0:
path = os.getcwd()
path = os.path.abspath(path)
if os.path.isdir(path):
path = os.path.join(path,
'.'.join([self.cur_proj.name, core.CKG_FMT]))
elif os.path.isdir(os.path.dirname(path)):
pass
else:
print 'error: specified directory does not exist'
return
# project save will add file extension if necessary
try:
path = self.cur_proj.save(path)
except IOError:
print "error:", str(sys.exc_value)
return
print 'project saved to "{0}"'.format(path)
set_parser = CmdParser(add_help=False, prog='set',
description='''Sets various project settings.''')
set_parser.add_argument('--name', help='''project name, always the same as
the filename without
the extension''')
set_parser.add_argument('--fps', type=to_decimal,
help='''number of animation frames
rendered per second''')
set_parser.add_argument('--res', action=store_tuple(2, ',', int),
help='animation canvas size/resolution in pixels',
metavar='WIDTH,HEIGHT')
set_parser.add_argument('--bg', metavar='COLOR', type=to_color,
help='''background color of the canvas
(color format: R,G,B,
component range from 0-255)''')
# set_parser.add_argument('--fmt', dest='export_fmt',
# choices=core.EXPORT_FMTS,
# help='''image format for animation
# to be exported as''')
set_parser.add_argument('--pre', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown before any display groups''')
set_parser.add_argument('--post', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown after all display groups''')
set_parser.add_argument('--cross_cols', metavar='COLOR1,COLOR2',
action=store_tuple(2, ',', to_color, [';']),
help='''fixation cross coloration
(color format: R;G;B,
component range from 0-255)''')
set_parser.add_argument('--cross_times', metavar='TIME1,TIME2',
action=store_tuple(2, ',', to_decimal),
help='''time in seconds each cross color
will be displayed''')
def help_set(self):
self.__class__.set_parser.print_help()
def do_set(self, line):
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
try:
args = self.__class__.set_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.set_parser.print_usage()
return
names = public_dir(args)
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
setattr(self.cur_proj, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.set_parser.print_usage()
mkgrp_parser = CmdParser(add_help=False, prog='mkgrp',
formatter_class=
argparse.ArgumentDefaultsHelpFormatter,
description='''Makes a new display group
with the given parameters.''')
mkgrp_parser.add_argument('pre', type=to_decimal, default=0, nargs='?',
help='''time in seconds a blank screen will
be shown before shapes are displayed''')
mkgrp_parser.add_argument('disp', type=to_decimal,
nargs='?', default='Infinity',
help='''time in seconds shapes will be
displayed''')
mkgrp_parser.add_argument('post', type=to_decimal, default=0, nargs='?',
help='''time in seconds a blank screen will
be shown after shapes are displayed''')
def help_mkgrp(self):
self.__class__.mkgrp_parser.print_help()
def do_mkgrp(self, line):
"""Makes a display group with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
try:
args = self.__class__.mkgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mkgrp_parser.print_usage()
return
group_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_group = core.CkgDisplayGroup(**group_dict)
new_id = self.cur_proj.add_group(new_group)
print "display group", new_id, "added"
self.cur_group = new_group
print "group", new_id, "is now the current display group"
edgrp_parser = CmdParser(add_help=False, prog='edgrp',
description='''Edits attributes of display groups
specified by ids.''')
edgrp_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='ids of display groups to be edited')
edgrp_parser.add_argument('--pre', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown before shapes are displayed''')
edgrp_parser.add_argument('--disp', type=to_decimal, metavar='SECONDS',
help='''time in seconds shapes will be
displayed''')
edgrp_parser.add_argument('--post', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown after shapes are displayed''')
def help_edgrp(self):
self.__class__.edgrp_parser.print_help()
def do_edgrp(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.edgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.edgrp_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_proj.groups) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_group_attr(x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.edgrp_parser.print_usage()
rmgrp_parser = CmdParser(add_help=False, prog='rmgrp',
description='''Removes display groups specified
by ids.''')
rmgrp_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='ids of display groups to be removed')
rmgrp_parser.add_argument('-a', '--all', action='store_true',
help='remove all groups from the project')
def help_rmgrp(self):
self.__class__.rmgrp_parser.print_help()
def do_rmgrp(self, line):
"""Removes display groups specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups to remove'
return
try:
args = self.__class__.rmgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rmgrp_parser.print_usage()
return
rmlist = []
if args.all:
for group in self.cur_proj.groups[:]:
self.cur_proj.del_group(group)
print "all display groups removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_proj.groups) or x < 0:
print "display group", x, "does not exist"
continue
rmlist.append(self.cur_proj.groups[x])
print "display group", x, "removed"
for group in rmlist:
self.cur_proj.del_group(group)
# Remember to point self.cur_group somewhere sane
if self.cur_group not in self.cur_proj.groups:
if len(self.cur_proj.groups) == 0:
self.cur_group = None
else:
self.cur_group = self.cur_proj.groups[0]
print "group 0 is now the current display group"
chgrp_parser = CmdParser(add_help=False, prog='chgrp',
description='''Changes display group that is
currently active for editing.
Prints current group id if
no group id is specified''')
chgrp_parser.add_argument('gid', metavar='id', type=int, nargs='?',
help='id of display group to be made active')
def help_chgrp(self):
self.__class__.chgrp_parser.print_help()
def do_chgrp(self, line):
"""Changes group that is currently active for editing."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups that can be made active'
return
try:
args = self.__class__.chgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.chgrp_parser.print_usage()
return
if args.gid == None:
print "group",\
self.cur_proj.groups.index(self.cur_group),\
"is the current display group"
elif args.gid >= len(self.cur_proj.groups) or args.gid < 0:
print "group", args.gid, "does not exist"
else:
self.cur_group = self.cur_proj.groups[args.gid]
print "group", args.gid, "is now the current display group"
mk_parser = CmdParser(add_help=False, prog='mk',
description='''Makes a new checkerboard in the
current group with the given
parameters.''')
mk_parser.add_argument('dims', action=store_tuple(2, ',', to_decimal),
help='''width,height of checkerboard in no. of
unit cells''')
mk_parser.add_argument('init_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of initial unit cell in pixels')
mk_parser.add_argument('end_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of final unit cell in pixels')
mk_parser.add_argument('position', action=store_tuple(2, ',', to_decimal),
help='x,y position of checkerboard in pixels')
mk_parser.add_argument('anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='anchor')
mk_parser.add_argument('cols', action=store_tuple(2, ',', to_color, [';']),
help='''color1,color2 of the checkerboard
(color format: R;G;B,
component range from 0-255)''')
mk_parser.add_argument('freq', type=to_decimal,
help='frequency of color reversal in Hz')
mk_parser.add_argument('phase', type=to_decimal, nargs='?', default='0',
help='initial phase of animation in degrees')
def help_mk(self):
self.__class__.mk_parser.print_help()
def do_mk(self, line):
"""Makes a checkerboard with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
if self.cur_group == None:
print 'automatically adding display group...'
self.do_mkgrp('')
try:
args = self.__class__.mk_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mk_parser.print_usage()
return
shape_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_shape = core.CheckerBoard(**shape_dict)
new_id = self.cur_proj.add_shape_to_group(self.cur_group, new_shape)
print "checkerboard", new_id, "added"
ed_parser = CmdParser(add_help=False, prog='ed',
description='''Edits attributes of checkerboards
specified by ids.''')
ed_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='''ids of checkerboards in the current
group to be edited''')
ed_parser.add_argument('--dims', action=store_tuple(2, ',', to_decimal),
help='checkerboard dimensions in unit cells',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--init_unit',
action=store_tuple(2, ',', to_decimal),
help='initial unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--end_unit',
action=store_tuple(2, ',', to_decimal),
help='final unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--position',
action=store_tuple(2, ',', to_decimal),
help='position of checkerboard in pixels',
metavar='X,Y')
ed_parser.add_argument('--anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='LOCATION')
ed_parser.add_argument('--cols', metavar='COLOR1,COLOR2',
action=store_tuple(2, ',', to_color, [';']),
help='''checkerboard colors (color format:
R;G;B, component range
from 0-255)''')
ed_parser.add_argument('--freq', type=to_decimal,
help='frequency of color reversal in Hz')
ed_parser.add_argument('--phase', type=to_decimal,
help='initial phase of animation in degrees')
def help_ed(self):
self.__class__.ed_parser.print_help()
def do_ed(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, please create one first'
return
try:
args = self.__class__.ed_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ed_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_group.shapes) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_shape_attr(self.cur_group, x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.ed_parser.print_usage()
rm_parser = CmdParser(add_help=False, prog='rm',
description='''Removes checkerboards specified
by ids.''')
rm_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''ids of checkerboards in the current group
to be removed''')
rm_parser.add_argument('-a', '--all', action='store_true',
help='''remove all checkerboards in the
current group''')
def help_rm(self):
self.__class__.rm_parser.print_help()
def do_rm(self, line):
"""Removes checkerboards specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, no boards to remove'
return
try:
args = self.__class__.rm_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rm_parser.print_usage()
return
rmlist = []
if args.all:
for shape in self.cur_group.shapes:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
print "all checkerboards removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_group.shapes) or x < 0:
print "checkerboard", x, "does not exist"
continue
rmlist.append(self.cur_group.shapes[x])
print "checkerboard", x, "removed"
for shape in rmlist:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
ls_parser = CmdParser(add_help=False, prog='ls',
description='''Lists project, display group and
checkerboard settings. If no group ids
are specified, all display groups
are listed.''')
ls_parser.add_argument('gidlist', nargs='*', metavar='gid', type=int,
help='''ids of the display groups to be listed''')
ls_group = ls_parser.add_mutually_exclusive_group()
ls_group.add_argument('-s', '--settings', action='store_true',
help='list only project settings')
ls_group.add_argument('-g', '--groups', action='store_true',
help='list only display groups')
def help_ls(self):
self.__class__.ls_parser.print_help()
def do_ls(self, line):
"""Lists project, display group and checkerboard settings."""
def ls_str(s, seps=[',',';']):
"""Special space-saving output formatter."""
if type(s) in [tuple, list]:
if len(seps) > 1:
newseps = seps[1:]
else:
newseps = seps
return seps[0].join([ls_str(i, newseps) for i in s])
else:
return str(s)
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.ls_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ls_parser.print_usage()
return
# Remove duplicates and ascending sort
args.gidlist = sorted(set(args.gidlist))
if len(self.cur_proj.groups) == 0:
if len(args.gidlist) > 0:
print 'this project has no display groups that can be listed'
args.settings = True
else:
for gid in args.gidlist[:]:
if gid >= len(self.cur_proj.groups) or gid < 0:
args.gidlist.remove(gid)
print 'display group', gid, 'does not exist'
if args.gidlist == []:
args.gidlist = range(len(self.cur_proj.groups))
else:
# If any (valid) groups are specified
# don't show project settings
args.groups = True
if not args.groups:
print 'PROJECT SETTINGS'.center(70,'*')
print \
'name'.rjust(16),\
'fps'.rjust(7),\
'resolution'.rjust(14),\
'bg color'.rjust(18)
# 'format'.rjust(7)
print \
ls_str(self.cur_proj.name).rjust(16),\
ls_str(self.cur_proj.fps).rjust(7),\
ls_str(self.cur_proj.res).rjust(14),\
ls_str(self.cur_proj.bg).rjust(18)
# ls_str(self.cur_proj.export_fmt).rjust(7)
print \
'pre-display'.rjust(26),\
'post-display'.rjust(26)
print \
ls_str(self.cur_proj.pre).rjust(26),\
ls_str(self.cur_proj.post).rjust(26)
print \
'cross colors'.rjust(26),\
'cross times'.rjust(26)
print \
ls_str(self.cur_proj.cross_cols).rjust(26),\
ls_str(self.cur_proj.cross_times).rjust(26)
if not args.settings and not args.groups:
# Insert empty line if both groups and project
# settings are listed
print ''
if not args.settings:
for i, n in enumerate(args.gidlist):
if i != 0:
# Print newline seperator between each group
print ''
group = self.cur_proj.groups[n]
print 'GROUP {n}'.format(n=n).center(70,'*')
print \
'pre-display'.rjust(20),\
'display'.rjust(20),\
'post-display'.rjust(20)
print \
ls_str(group.pre).rjust(20),\
ls_str(group.disp).rjust(20),\
ls_str(group.post).rjust(20)
if len(group.shapes) > 0:
print \
''.rjust(2),\
'shape id'.rjust(8),\
'dims'.rjust(10),\
'init_unit'.rjust(14),\
'end_unit'.rjust(14),\
'position'.rjust(14)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.dims).rjust(10),\
ls_str(shape.init_unit).rjust(14),\
ls_str(shape.end_unit).rjust(14),\
ls_str(shape.position).rjust(14)
print '\n',\
''.rjust(2),\
'shape id'.rjust(8),\
'colors'.rjust(27),\
'anchor'.rjust(12),\
'freq'.rjust(6),\
'phase'.rjust(7)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.cols).rjust(27),\
ls_str(shape.anchor).rjust(12),\
ls_str(shape.freq).rjust(6),\
ls_str(shape.phase).rjust(7)
display_parser = CmdParser(add_help=False, prog='display',
description='''Displays the animation in a
window or in fullscreen.''')
display_parser.add_argument('-n', '--name', metavar='FOOBAR',
help='''name of log file to be written''')
display_parser.add_argument('-r', '--repeats', metavar='N', type=int,
help='''repeatedly display specified display
groups N number of times''')
- display_parser.add_argument('-wl', '--waitless', action='store_true',
+ display_parser.add_argument('-wl', '--waitless', action=store_truth(),
+ metavar='t/f',
help='''do not add waitscreens before the
start of each repeat''')
- display_parser.add_argument('-f', '--fullscreen', action='store_true',
+ display_parser.add_argument('-f', '--fullscreen', action=store_truth(),
+ metavar='t/f',
help='sets fullscreen mode, ESC to quit')
display_parser.add_argument('-p', '--priority', metavar='LEVEL',
help='''set priority while displaying,
higher priority results in
less dropped frames (choices:
0-3, low, normal, high,
realtime)''')
- display_parser.add_argument('-pt', '--phototest', action='store_true',
+ display_parser.add_argument('-pt', '--phototest', action=store_truth(),
+ metavar='t/f',
help='''draw white test rectangle in topleft
corner of screen when groups become
visible for a photodiode to detect''')
- display_parser.add_argument('-pb', '--photoburst', action='store_true',
+ display_parser.add_argument('-pb', '--photoburst', action=store_truth(),
+ metavar='t/f',
help='''make checkerboards only draw first
color for one frame to facilitate
testing with a photodiode''')
- display_parser.add_argument('-lt', '--logtime', action='store_true',
+ display_parser.add_argument('-lt', '--logtime', action=store_truth(),
+ metavar='t/f',
help='output frame timestamps to a log file')
- display_parser.add_argument('-ld', '--logdur', action='store_true',
+ display_parser.add_argument('-ld', '--logdur', action=store_truth(),
+ metavar='t/f',
help='output frame durations to a log file')
- display_parser.add_argument('-ss', '--trigser', action='store_true',
+ display_parser.add_argument('-ss', '--trigser', action=store_truth(),
+ metavar='t/f',
help='''send triggers through the serial port
when shapes are being displayed''')
- display_parser.add_argument('-sp', '--trigpar', action='store_true',
+ display_parser.add_argument('-sp', '--trigpar', action=store_truth(),
+ metavar='t/f',
help='''send triggers through the parallel port
when shapes are being displayed''')
display_parser.add_argument('-fpst', metavar='M', type=int,
help='''unique trigger corresponding to a
checkerboard is sent after the shape
undergoes M color flips (default:
disabled, M=0)''')
- display_parser.add_argument('-fc', '--freqcheck', action='store_true',
+ display_parser.add_argument('-fc', '--freqcheck', action=store_truth(),
+ metavar='t/f',
help='''only send triggers for board color
flips at the start, middle and end
of the run''')
- display_parser.add_argument('-et', '--eyetrack', action='store_true',
+ display_parser.add_argument('-et', '--eyetrack', action=store_truth(),
+ metavar='t/f',
help='''use eyetracking to ensure that subject
fixates on the cross in the center''')
- display_parser.add_argument('-eu', '--etuser', action='store_true',
+ display_parser.add_argument('-eu', '--etuser', action=store_truth(),
+ metavar='t/f',
help='''allow user to select eyetracking video
source from a dialog''')
display_parser.add_argument('-ev', '--etvideo', metavar='path',
help='''path (with no spaces) to eyetracking
video file to be used as the source''')
display_parser.add_argument('-ta', '--tryagain', metavar='I',
type=int, default=0,
help='''append groups during which subject
failed to fixate up to I times to the
list of groups to be displayed
(default: disabled, I=0)''')
display_parser.add_argument('-tb', '--trybreak', metavar='J', type=int,
help='''used with --tryagain, append a wait
screen to the list of groups to be
displayed after every J groups have
been appended to the list (default:
J=total number of groups)''')
- display_parser.add_argument('-nl', '--nolog', action='store_true',
+ display_parser.add_argument('-nl', '--nolog', action=store_truth(),
+ metavar='t/f',
help='''do not write a log file''')
display_parser.add_argument('order', nargs='*', metavar='id', type=int,
help='''order in which groups should be
displayed (default: random order
from list of orders if specified
in project, ascending otherwise)''')
def help_display(self):
self.__class__.display_parser.print_help()
def do_display(self, line):
"""Displays the animation in a window or in fullscreen"""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.display_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
if len(args.order) > 0:
for i in set(args.order):
if i >= len(self.cur_proj.groups) or i < -1:
print 'error: group', i, 'does not exist'
return
if args.eyetrack and eyetracking.available:
if not eyetracking.is_calibrated():
try:
self.do_calibrate('',query=True)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
return
print "displaying...",
try:
self.cur_proj.display(name=args.name,
repeats=args.repeats,
waitless=args.waitless,
fullscreen=args.fullscreen,
priority=args.priority,
logtime=args.logtime,
logdur=args.logdur,
trigser=args.trigser,
trigpar=args.trigpar,
fpst=args.fpst,
freqcheck=args.freqcheck,
phototest=args.phototest,
photoburst=args.photoburst,
eyetrack=args.eyetrack,
etuser=args.etuser,
etvideo=args.etvideo,
tryagain=args.tryagain,
trybreak=args.trybreak,
nolog=args.nolog,
order=args.order)
except (IOError, NotImplementedError, eyetracking.EyetrackingError):
print ''
print "error:", str(sys.exc_value)
if args.priority != None:
try:
priority.set('normal')
except:
pass
return
print "done"
export_parser = CmdParser(add_help=False, prog='export',
description='''Exports animation as an image
sequence (in a folder) to the
specified directory.''')
# export_parser.add_argument('--fmt', dest='export_fmt',
# choices=core.EXPORT_FMTS,
# help='image format for export')
export_parser.add_argument('-n','--nofolder',
dest='folder', action='store_false',
help='''force images not to exported in
a containing folder''')
export_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly export specified display
groups N number of times''')
export_parser.add_argument('duration', nargs='?',
type=to_decimal, default='Infinity',
help='''number of seconds of the animation
that should be exported (default:
as long as the entire animation)''')
export_parser.add_argument('dir', nargs='?', default=os.getcwd(),
help='''destination directory for export
(default: current working directory)''')
export_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be exported
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_export(self):
self.__class__.export_parser.print_help()
def do_export(self, line):
"""Exports animation an image sequence to the specified directory."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.export_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.export_parser.print_usage()
return
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < 0:
print 'error: group', i, 'does not exist'
return
groupq = [self.cur_proj.groups[i] for i in args.idlist]
else:
groupq = list(self.cur_proj.groups)
if args.repeat != None:
groupq = list(groupq * args.repeat)
try:
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
folder=args.folder)
except IOError:
print "error:", str(sys.exc_value)
return
except core.FrameOverflowError:
print "warning:", str(sys.exc_value)
print "Are you sure you want to continue?"
while True:
try:
if self.__class__.yn_parse(raw_input()):
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
export_fmt=None,
folder=args.folder,
force=True)
break
else:
return
except TypeError:
print str(sys.exc_value)
except EOFError:
return
print "Export done."
def do_calibrate(self, line, query=False):
"""Calibrate subject for eyetracking, or load a calibration file."""
if not eyetracking.available:
print "error: eyetracking functionality not available"
return
if query:
print "path to calibration file (leave empty for GUI tool):"
try:
path = raw_input().strip().strip('"\'')
except EOFError:
msg = "calibration cancelled"
raise eyetracking.EyetrackingError(msg)
else:
path = line.strip().strip('"\'')
if len(path) == 0:
path = None
if not eyetracking.is_source_ready():
# Select default source if none has been selected
eyetracking.select_source()
try:
eyetracking.calibrate(path)
except eyetracking.EyetrackingError:
if query:
raise
else:
print "error:", str(sys.exc_value)
return
if len(path) > 0:
print "calibration file successfully loaded"
etsetup_parser = CmdParser(add_help=False, prog='etsetup',
description='''Set various eyetracking
parameters.''')
etsetup_parser.add_argument('-fp', '--fixperiod', type=int, metavar='MS',
help='''time in milliseconds subject
has to stare at the same spot
for fixation to be detected''')
etsetup_parser.add_argument('-fr', '--fixrange', type=float, metavar='MM',
help='''distance in mm beyond which the
eye position cannot change for
a fixation to be detected''')
etsetup_parser.add_argument('-s', '--size', metavar='WIDTH,HEIGHT',
action=store_tuple(2, ',', float),
help='physical screen dimensions in mm')
etsetup_parser.add_argument('-vd', '--viewdist', type=int, metavar='MM',
help='''viewing distance between subject's
eyes and the screen''')
def help_etsetup(self):
self.__class__.etsetup_parser.print_help()
def do_etsetup(self, line):
try:
args = self.__class__.etsetup_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.etsetup_parser.print_usage()
return
try:
eyetracking.setup(viewing_distance=args.viewdist,
screen_dims=args.size,
fixation_period=args.fixperiod,
fixation_range=args.fixrange)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
def do_pwd(self, line):
"""Prints the current working directory."""
print os.getcwd()
def do_cd(self, line):
"""Change working directory to specified path."""
path = line.strip().strip('"\'')
if not os.path.isdir(path):
print "error: specified path is not a directory"
return
os.chdir(path)
def do_quit(self, line):
"""Quits the program."""
if self.save_check():
return
return True
def help_EOF(self):
print "Typing {0} issues this command, which quits the program."\
.format(CMD_EOF_STRING)
def do_EOF(self, line):
"""Typing Ctrl-D issues this command, which quits the program."""
print '\r'
if self.save_check():
return
return True
def help_help(self):
print 'Prints a list of commands.'
print "Type 'help <topic>' for more details on each command."
def default(self, line):
command = line.split()[0]
print \
"'{0}' is not a checkergen command.".format(command),\
"Type 'help' for a list of commands"
diff --git a/src/core.py b/src/core.py
index 6137bc5..b4c0974 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,1228 +1,1230 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import copy
import random
import itertools
from datetime import datetime
from xml.dom import minidom
import pyglet
import graphics
import priority
import trigger
import eyetracking
from utils import *
# Use OrderedDict substitute if we don't have Python 2.7
if sys.version_info < (2, 7):
from odict import OrderedDict
else:
from collections import OrderedDict
CKG_FMT = 'ckg'
LOG_FMT = 'csv'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
MAX_EXPORT_FRAMES = 100000
INT_HALF_PERIODS = True
EXPORT_FMTS = ['png']
EXPORT_DIR_SUFFIX = '-anim'
FIX_POS = (0, 0)
FIX_RANGE = (20, 20)
FIX_PER = 350
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = OrderedDict([('name', 'untitled'),
('fps', 60),
('res', (800, 600)),
('bg', (127, 127, 127)),
('export_fmt', 'png'),
('pre', 0),
('post', 0),
('cross_cols', ((0, 0, 0), (255, 0, 0))),
('cross_times', ('Infinity', 1)),
('orders', []),
('disp_ops', None)])
DEFAULTS['disp_ops'] = OrderedDict([('repeats', 1),
('waitless', False),
('fullscreen', False),
('priority', None),
('logtime', False),
('logdur', False),
('trigser', False),
('trigpar', False),
('fpst', 0),
('freqcheck', False),
('phototest', False),
('photoburst', False),
('eyetrack', False),
('etuser', False),
('etvideo', None),
('tryagain', 0),
('trybreak', None),
('nolog', False)])
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
export_fmt -- image format for animation to be exported as
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'export_fmt':
if value not in EXPORT_FMTS:
msg = 'image format not recognized or supported'
raise FileFormatError(msg)
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
# Vars that are dicts
dicts_to_load = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_load = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
for d_name in dicts_to_load:
d = self.__class__.DEFAULTS[d_name]
try:
d_el = [node for node in project.childNodes if
node.localName == d_name and
node.namespaceURI == XML_NAMESPACE][0]
for var in d.keys():
try:
d[var] = eval(xml_get(d_el, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}' in '{1}'".\
format(var, d_name)
print "using default value '{0}' instead...".\
format(d[var])
except IndexError:
print "warning: missing attribute set '{0}'".format(d_name)
print "using default values instead..."
setattr(self, d_name, d)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
# Vars that are dicts
dicts_to_save = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_save = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for d_name in dicts_to_save:
d_el = doc.createElement(d_name)
project.appendChild(d_el)
d = getattr(self, d_name)
for k, v in d.iteritems():
xml_set(doc, d_el, k, repr(v))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, **keywords):
"""Displays the project animation on the screen.
name -- name that logfile will be saved with
repeats -- number of times specified order of display groups should
be repeated
waitless -- if true, no waitscreens will appear at the start of each
repeat
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
priority -- priority level to which process should be raised
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
trigser -- send triggers through serial port when each group is shown
trigpar -- send triggers through parallel port when each group is shown
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
freqcheck -- send fpst only at the start, the middle, and the end
for sanity checking of display and trigger fps
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- append a wait screen to the group queue every time
after this many groups have been appended to the queue
order -- order in which groups (specified by id) will be displayed
"""
# Create RunState
- disp_ops = self.disp_ops
+ disp_ops = copy.deepcopy(self.disp_ops)
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'name' in keywords.keys() and keywords['name'] != None:
name = keywords['name']
else:
timestr = datetime.today().strftime('_%Y-%m-%d_%H-%M-%S')
name = self.name + timestr
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
waitscreen = CkgWaitScreen()
# Set order id to be sent if necessary
if order in self.orders:
runstate.events['ord_id'] = self.orders.index(order)
# Count through pre
for count in range(self.pre * self.fps):
if runstate.window.has_exit:
break
runstate.update()
# Loop through repeats
repeats = runstate.disp_ops['repeats']
ord_len = len(runstate.order)
for i in range(repeats):
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
# Loop through display groups
runstate.events['blk_on'] = True
for n, gid in enumerate(runstate.order):
# Set flag for freqcheck
if runstate.disp_ops['freqcheck']:
if ((i == 0 and n == 0) or
(i == repeats-1 and n == ord_len-1) or
(i == repeats//2 and n == ord_len//2)):
runstate.fc_send = True
else:
runstate.fc_send = False
if gid == -1:
waitscreen.reset()
waitscreen.display(runstate)
else:
self.groups[gid].display(runstate)
# Append failed groups
if runstate.disp_ops['eyetrack'] and runstate.truefail:
if len(runstate.add_gids) < runstate.disp_ops['tryagain']:
runstate.add_gids.append(gid)
else:
runstate.fail_gids.append(gid)
runstate.events['blk_off'] = True
# Loop through added groups
if runstate.disp_ops['eyetrack']:
for blk in grouper(runstate.add_gids,
runstate.disp_ops['trybreak']):
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
runstate.events['blk_on'] = True
# Loop through display groups
for gid in blk:
if gid != None:
self.groups[gid].display(runstate)
runstate.events['blk_off'] = True
# Count through post
for count in range(self.post * self.fps):
if runstate.window.has_exit:
break
runstate.update()
# Stop and output log
runstate.stop()
if not runstate.disp_ops['nolog']:
runstate.log()
def export(self, export_dir, export_duration, groupq=[],
export_fmt=None, folder=True, force=False):
if not os.path.isdir(export_dir):
msg = 'export path is not a directory'
raise IOError(msg)
if export_fmt == None:
export_fmt = self.export_fmt
# Set-up groups and variables that control their display
if groupq == []:
groupq = list(self.groups)
n = -1
groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Limit export duration to display duration
frames = export_duration * self.fps
frames = min(frames, disp_end)
# Warn user if a lot of frames will be exported
if frames > MAX_EXPORT_FRAMES and not force:
msg = 'very large number ({0}) of frames to be exported'.\
format(frames)
raise FrameOverflowError(msg)
# Create folder to store images if necessary
if folder:
export_dir = os.path.join(export_dir,
self.name + EXPORT_DIR_SUFFIX)
if not os.path.isdir(export_dir):
os.mkdir(export_dir)
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Set up canvas and framebuffer object
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
# Main loop
while count < frames:
fbo.clear()
if groups_visible:
# Get next group from queue
if n < 0 or groupq[n].over:
n += 1
if n >= len(groupq):
groups_visible = False
else:
groupq[n].reset()
# Draw and then update group
if n >= 0:
groupq[n].draw()
groupq[n].update(fps=self.fps, fpst=0)
# Draw fixation cross based on current count
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Save current frame to file
savepath = \
os.path.join(export_dir,
'{0}{2}.{1}'.
format(self.name, export_fmt,
repr(count).zfill(numdigits(frames-1))))
canvas.save(savepath)
# Increment count and set whether groups should be shown
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
fbo.delete()
class CkgRunState:
"""Contains information about the state of a checkergen project
when it is being displayed or exported."""
DEFAULTS = dict([('name', 'untitled'),
('res', None),
('fps', None),
('bg', None),
('cross_cols', None),
('cross_times', None),
('order', []),
('disp_ops', None),
('events', None),
('add_gids', []),
('fail_gids', []),
('timestamps', []),
('durstamps', []),
('trigstamps', [])])
DEFAULTS['events'] = dict([('ord_id', None),
('blk_on', False),
('blk_off', False),
('track_on', False),
('track_off', False),
('fix_on', False),
('fix_off', False),
('grp_on', False),
('grp_off', False),
('sids', set())])
def __init__(self, **keywords):
"""Creates the RunState."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
def start(self):
"""Initialize all subsystems and start the run."""
if self.disp_ops == None:
msg = "RunState lacks display options"
raise ValueError(msg)
if min(self.res, self.fps, self.bg,
self.cross_cols, self.cross_times) == None:
msg = "RunState intialized with insufficent project information"
raise ValueError(msg)
self._count = 0
# Flag used by freqcheck
self.fc_send = False
# Create fixation crosses
self.fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if self.disp_ops['phototest']:
self.test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Initialize ports
if self.disp_ops['trigser']:
if not trigger.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trigpar']:
if not trigger.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
trigger.init(self.disp_ops['trigser'], self.disp_ops['trigpar'])
# Initialize eyetracking
if self.disp_ops['eyetrack']:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trybreak'] == None:
self.disp_ops['trybreak'] = len(self.order)
self.fixated = False
self.old_fixated = False
self.tracked = False
self.old_tracked = False
self.fix_fail = False
self.true_fail = False
eyetracking.select_source(self.disp_ops['etuser'],
self.disp_ops['etvideo'])
eyetracking.start()
# Stretch to fit screen only if project res does not equal screen res
self.scaling = False
if self.disp_ops['fullscreen']:
self.window = pyglet.window.Window(fullscreen=True, visible=False)
if (self.window.width, self.window.height) != self.res:
self.scaling = True
else:
self.window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
self.keystates = pyglet.window.key.KeyStateHandler()
self.window.push_handlers(self.keystates)
# Clear window and make visible
self.window.switch_to()
graphics.set_clear_color(self.bg)
self.window.clear()
self.window.set_visible()
# Create framebuffer object for drawing unscaled scene
if self.scaling:
self.canvas = pyglet.image.Texture.create(*self.res)
self.fbo = graphics.Framebuffer(self.canvas)
self.fbo.start_render()
graphics.set_clear_color(self.bg)
self.fbo.clear()
# Set process priority
if self.disp_ops['priority'] != None:
if not priority.available[sys.platform]:
msg = "setting priority not available on {0}".\
format(sys.platform)
raise NotImplementedError(msg)
else:
try:
priority.set(self.disp_ops['priority'])
except ValueError:
priority.set(int(self.disp_ops['priority']))
# Start timers
if self.disp_ops['logtime']:
self.timer = Timer()
self.timer.start()
if self.disp_ops['logdur']:
self.dur = Timer()
self.dur.start()
def update(self):
"""Update the RunState."""
# Check for tracking and fixation
if self.disp_ops['eyetrack']:
self.old_tracked = self.tracked
self.tracked = eyetracking.is_tracked()
self.old_fixated = self.fixated
self.fixated = eyetracking.is_fixated(FIX_POS, FIX_RANGE, FIX_PER)
if self.fixated:
# Draw normal cross color if fixating
self.fix_crosses[0].draw()
else:
# Draw alternative cross color if not fixating
self.fix_crosses[1].draw()
# Update eyetracking events
if self.tracked != self.old_tracked:
if self.tracked:
self.events['track_on'] = True
else:
self.events['track_off'] = True
if self.fixated != self.old_fixated:
if self.fixated:
self.events['fix_on'] = True
else:
self.events['fix_off'] = True
# Check for failure of trial
if self.tracked and not self.fixated:
self.fix_fail = True
else:
# Change cross color based on time
if (self._count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
self.fix_crosses[0].draw()
else:
self.fix_crosses[1].draw()
# Blit canvas to screen if necessary
if self.scaling:
self.fbo.end_render()
self.canvas.blit(0, 0)
self.window.switch_to()
self.window.dispatch_events()
self.window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to lists
if self.disp_ops['logtime']:
self.timestamps.append(self.timer.elapsed())
elif self.disp_ops['logdur']:
self.timestamps.append('')
if self.disp_ops['logdur']:
self.durstamps.append(self.dur.restart())
elif self.disp_ops['logtime']:
self.durstamps.append('')
# Send trigger ASAP after flip
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
if self.encode_events() > 0:
- trigger.send(trigser, trigpar, self.encode_events())
+ trigger.send(self.disp_ops['trigser'],
+ self.disp_ops['trigpar'],
+ self.encode_events())
# Log when triggers are sent
if self.disp_ops['logtime'] and self.encode_events() > 0:
self.trigstamps.append(self.encode_events())
else:
self.trigstamps.append('')
# Clear canvas, events, prepare for next frame
if self.scaling:
self.fbo.start_render()
self.fbo.clear()
else:
self.window.clear()
self.events = copy.deepcopy(self.__class__.DEFAULTS['events'])
self._count += 1
def stop(self):
"""Clean up RunState."""
if self.disp_ops['eyetrack']:
eyetracking.stop()
if self.scaling:
self.fbo.delete()
del self.canvas
self.window.close()
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
- trigger.quit(trigser, trigpar)
+ trigger.quit(self.disp_ops['trigser'], self.disp_ops['trigpar'])
if self.disp_ops['priority'] != None:
priority.set('normal')
def encode_events(self):
"""Hard code specific trigger values for events."""
code = 0
if self.events['ord_id'] != None:
code = self.events['ord_id'] + 1
elif self.events['blk_on']:
code = 128
elif self.events['blk_off']:
code = 127
else:
mult = 0
if self.events['fix_on']:
mult = 4
elif self.events['track_on']:
mult = 3
if self.events['track_off']:
mult = 1
elif self.events['fix_off']:
mult = 2
if self.events['grp_on']:
code = 100 + mult
elif self.events['grp_off']:
code = 90 + mult
elif len(self.events['sids']) > 0:
code = ((0 in self.events['sids'])*2**0 +
(1 in self.events['sids'])*2**1 +
(2 in self.events['sids'])*2**2 +
(3 in self.events['sids'])*2**3)
code = mult*16 + code
elif mult > 0:
code = 110 + mult
return code
def log(self, path=None):
"""Write a log file for the experimental run in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, LOG_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(LOG_FMT):
path = '{0}.{1}'.format(path, LOG_FMT)
with open(path, 'wb') as logfile:
writer = csv.writer(logfile, dialect='excel-tab')
writer.writerow(['checkergen log file'])
writer.writerow(['display options:'])
writer.writerow(self.disp_ops.keys())
writer.writerow(self.disp_ops.values())
writer.writerow(['order:'] + self.order)
if self.disp_ops['eyetrack']:
write.writerow(['groups added'])
for blk in grouper(self.add_gids,
self.disp_ops['trybreak'], ''):
write.writerow(blk)
write.writerow(['groups failed'])
for blk in grouper(self.fail_gids,
self.disp_ops['trybreak'], ''):
write.writerow(blk)
if self.disp_ops['logtime'] or self.disp_ops['logdur']:
stamps = [self.timestamps, self.durstamps, self.trigstamps]
writer.writerow(['timestamps', 'durations', 'triggers'])
for stamp in zip(*stamps):
writer.writerow(list(stamp))
class CkgDisplayGroup:
DEFAULTS = OrderedDict([('pre', 0), ('disp', 'Infinity'), ('post', 0)])
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets counts and all contained shapes."""
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, runstate):
"""Draws all contained shapes during the appropriate interval."""
for shape in self.shapes:
shape.draw(photoburst=runstate.disp_ops['photoburst'])
def update(self, runstate):
"""Updates contained shapes, sets event triggers."""
# Set events to be sent
if runstate.disp_ops['fpst'] > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= runstate.disp_ops['fpst']:
if not runstate.disp_ops['freqcheck'] or runstate.fc_send:
runstate.events['sids'].add(n)
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(runstate.fps)
def display(self, runstate):
"""Display the group in the context described by supplied runstate."""
self.reset()
for count in range(self.pre * runstate.fps):
if runstate.window.has_exit:
break
runstate.update()
runstate.events['grp_on'] = True
if runstate.disp_ops['eyetrack']:
runstate.fix_fail = False
renstate.true_fail = False
for count in range(self.disp * runstate.fps):
if runstate.window.has_exit:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
runstate.events['grp_off'] = True
if runstate.disp_ops['eyetrack']:
if runstate.fix_fail:
runstate.true_fail = True
for count in range(self.post * runstate.fps):
if runstate.window.has_exit:
break
runstate.update()
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.steps_done = 0
def draw(self, runstate):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, runstate):
"""Checks for keypress, sends trigger upon end."""
if max([runstate.keystates[key] for
key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
def display(self, runstate):
"""Displays waitscreen in context described by supplied runstate."""
while self.steps_done < self.num_steps:
if runstate.window.has_exit:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = OrderedDict([('dims', (5, 5)),
('init_unit', (30, 30)),
('end_unit', (50, 50)),
('position', (0, 0)),
('anchor', 'bottomleft'),
('cols', ((0, 0, 0), (255, 255, 255))),
('freq', 1),
('phase', 0)])
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
if INT_HALF_PERIODS:
frames_per_half_period = round(fps / (self.freq * 2))
degs_per_frame = 180 / to_decimal(frames_per_half_period)
else:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
anchor=self.anchor)
cur_unit_rect.col = self.cols[(i + j) % 2]
cur_unit_rect.add_to_batch(self._batches[0])
cur_unit_rect.col = self.cols[(i + j + 1) % 2]
cur_unit_rect.add_to_batch(self._batches[1])
# Increase x values
cur_unit_pos[0] += \
graphics.locations[self.anchor][0] * cur_unit[0]
cur_unit[0] += unit_grad[0]
# Reset x values
cur_unit_pos[0] = init_pos[0]
cur_unit[0] = init_unit[0]
# Increase y values
cur_unit_pos[1] += \
graphics.locations[self.anchor][1] * cur_unit[1]
cur_unit[1] += unit_grad[1]
self._computed = True
def draw(self, photoburst=False, always_compute=False):
"""Draws appropriate batch depending on current phase.
photoburst -- draw first color for only one frame for testing purposes
always_compute -- recompute what the checkerboard should look like
every frame
"""
if not self._computed or always_compute:
self.compute()
self._cur_phase %= 360
n = int(self._cur_phase // 180)
if photoburst and n == 0 and not self.flipped:
n = 1
self._batches[n].draw()
def lazydraw(self):
"""Only draws on color reversal."""
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if (cur_n != prev_n) or self._first_draw:
self.draw()
if self._first_draw:
self._first_draw = False
|
ztangent/checkergen
|
6d45be48160a89dba4ab2fa69943f69cc614986f
|
Type check fix when setting priority.
|
diff --git a/src/core.py b/src/core.py
index 6427ece..6137bc5 100755
--- a/src/core.py
+++ b/src/core.py
@@ -180,1027 +180,1028 @@ class CkgProj:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
# Vars that are dicts
dicts_to_load = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_load = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
for d_name in dicts_to_load:
d = self.__class__.DEFAULTS[d_name]
try:
d_el = [node for node in project.childNodes if
node.localName == d_name and
node.namespaceURI == XML_NAMESPACE][0]
for var in d.keys():
try:
d[var] = eval(xml_get(d_el, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}' in '{1}'".\
format(var, d_name)
print "using default value '{0}' instead...".\
format(d[var])
except IndexError:
print "warning: missing attribute set '{0}'".format(d_name)
print "using default values instead..."
setattr(self, d_name, d)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
# Vars that are dicts
dicts_to_save = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_save = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for d_name in dicts_to_save:
d_el = doc.createElement(d_name)
project.appendChild(d_el)
d = getattr(self, d_name)
for k, v in d.iteritems():
xml_set(doc, d_el, k, repr(v))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, **keywords):
"""Displays the project animation on the screen.
name -- name that logfile will be saved with
repeats -- number of times specified order of display groups should
be repeated
waitless -- if true, no waitscreens will appear at the start of each
repeat
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
priority -- priority level to which process should be raised
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
trigser -- send triggers through serial port when each group is shown
trigpar -- send triggers through parallel port when each group is shown
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
freqcheck -- send fpst only at the start, the middle, and the end
for sanity checking of display and trigger fps
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- append a wait screen to the group queue every time
after this many groups have been appended to the queue
order -- order in which groups (specified by id) will be displayed
"""
# Create RunState
disp_ops = self.disp_ops
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'name' in keywords.keys() and keywords['name'] != None:
name = keywords['name']
else:
timestr = datetime.today().strftime('_%Y-%m-%d_%H-%M-%S')
name = self.name + timestr
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
waitscreen = CkgWaitScreen()
# Set order id to be sent if necessary
if order in self.orders:
runstate.events['ord_id'] = self.orders.index(order)
# Count through pre
for count in range(self.pre * self.fps):
if runstate.window.has_exit:
break
runstate.update()
# Loop through repeats
repeats = runstate.disp_ops['repeats']
ord_len = len(runstate.order)
for i in range(repeats):
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
# Loop through display groups
runstate.events['blk_on'] = True
for n, gid in enumerate(runstate.order):
# Set flag for freqcheck
if runstate.disp_ops['freqcheck']:
if ((i == 0 and n == 0) or
(i == repeats-1 and n == ord_len-1) or
(i == repeats//2 and n == ord_len//2)):
runstate.fc_send = True
else:
runstate.fc_send = False
if gid == -1:
waitscreen.reset()
waitscreen.display(runstate)
else:
self.groups[gid].display(runstate)
# Append failed groups
if runstate.disp_ops['eyetrack'] and runstate.truefail:
if len(runstate.add_gids) < runstate.disp_ops['tryagain']:
runstate.add_gids.append(gid)
else:
runstate.fail_gids.append(gid)
runstate.events['blk_off'] = True
# Loop through added groups
if runstate.disp_ops['eyetrack']:
for blk in grouper(runstate.add_gids,
runstate.disp_ops['trybreak']):
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
runstate.events['blk_on'] = True
# Loop through display groups
for gid in blk:
if gid != None:
self.groups[gid].display(runstate)
runstate.events['blk_off'] = True
# Count through post
for count in range(self.post * self.fps):
if runstate.window.has_exit:
break
runstate.update()
# Stop and output log
runstate.stop()
if not runstate.disp_ops['nolog']:
runstate.log()
def export(self, export_dir, export_duration, groupq=[],
export_fmt=None, folder=True, force=False):
if not os.path.isdir(export_dir):
msg = 'export path is not a directory'
raise IOError(msg)
if export_fmt == None:
export_fmt = self.export_fmt
# Set-up groups and variables that control their display
if groupq == []:
groupq = list(self.groups)
n = -1
groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Limit export duration to display duration
frames = export_duration * self.fps
frames = min(frames, disp_end)
# Warn user if a lot of frames will be exported
if frames > MAX_EXPORT_FRAMES and not force:
msg = 'very large number ({0}) of frames to be exported'.\
format(frames)
raise FrameOverflowError(msg)
# Create folder to store images if necessary
if folder:
export_dir = os.path.join(export_dir,
self.name + EXPORT_DIR_SUFFIX)
if not os.path.isdir(export_dir):
os.mkdir(export_dir)
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Set up canvas and framebuffer object
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
# Main loop
while count < frames:
fbo.clear()
if groups_visible:
# Get next group from queue
if n < 0 or groupq[n].over:
n += 1
if n >= len(groupq):
groups_visible = False
else:
groupq[n].reset()
# Draw and then update group
if n >= 0:
groupq[n].draw()
groupq[n].update(fps=self.fps, fpst=0)
# Draw fixation cross based on current count
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Save current frame to file
savepath = \
os.path.join(export_dir,
'{0}{2}.{1}'.
format(self.name, export_fmt,
repr(count).zfill(numdigits(frames-1))))
canvas.save(savepath)
# Increment count and set whether groups should be shown
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
fbo.delete()
class CkgRunState:
"""Contains information about the state of a checkergen project
when it is being displayed or exported."""
DEFAULTS = dict([('name', 'untitled'),
('res', None),
('fps', None),
('bg', None),
('cross_cols', None),
('cross_times', None),
('order', []),
('disp_ops', None),
('events', None),
('add_gids', []),
('fail_gids', []),
('timestamps', []),
('durstamps', []),
('trigstamps', [])])
DEFAULTS['events'] = dict([('ord_id', None),
('blk_on', False),
('blk_off', False),
('track_on', False),
('track_off', False),
('fix_on', False),
('fix_off', False),
('grp_on', False),
('grp_off', False),
('sids', set())])
def __init__(self, **keywords):
"""Creates the RunState."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
def start(self):
"""Initialize all subsystems and start the run."""
if self.disp_ops == None:
msg = "RunState lacks display options"
raise ValueError(msg)
if min(self.res, self.fps, self.bg,
self.cross_cols, self.cross_times) == None:
msg = "RunState intialized with insufficent project information"
raise ValueError(msg)
self._count = 0
# Flag used by freqcheck
self.fc_send = False
# Create fixation crosses
self.fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if self.disp_ops['phototest']:
self.test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Initialize ports
if self.disp_ops['trigser']:
if not trigger.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trigpar']:
if not trigger.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
trigger.init(self.disp_ops['trigser'], self.disp_ops['trigpar'])
# Initialize eyetracking
if self.disp_ops['eyetrack']:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trybreak'] == None:
self.disp_ops['trybreak'] = len(self.order)
self.fixated = False
self.old_fixated = False
self.tracked = False
self.old_tracked = False
self.fix_fail = False
self.true_fail = False
eyetracking.select_source(self.disp_ops['etuser'],
self.disp_ops['etvideo'])
eyetracking.start()
# Stretch to fit screen only if project res does not equal screen res
self.scaling = False
if self.disp_ops['fullscreen']:
self.window = pyglet.window.Window(fullscreen=True, visible=False)
if (self.window.width, self.window.height) != self.res:
self.scaling = True
else:
self.window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
self.keystates = pyglet.window.key.KeyStateHandler()
self.window.push_handlers(self.keystates)
# Clear window and make visible
self.window.switch_to()
graphics.set_clear_color(self.bg)
self.window.clear()
self.window.set_visible()
# Create framebuffer object for drawing unscaled scene
if self.scaling:
self.canvas = pyglet.image.Texture.create(*self.res)
self.fbo = graphics.Framebuffer(self.canvas)
self.fbo.start_render()
graphics.set_clear_color(self.bg)
self.fbo.clear()
# Set process priority
if self.disp_ops['priority'] != None:
if not priority.available[sys.platform]:
msg = "setting priority not available on {0}".\
format(sys.platform)
raise NotImplementedError(msg)
else:
- if self.disp_ops['priority'].isdigit():
- self.disp_ops['priority'] = int(self.disp_ops['priority'])
- priority.set(self.disp_ops['priority'])
+ try:
+ priority.set(self.disp_ops['priority'])
+ except ValueError:
+ priority.set(int(self.disp_ops['priority']))
# Start timers
if self.disp_ops['logtime']:
self.timer = Timer()
self.timer.start()
if self.disp_ops['logdur']:
self.dur = Timer()
self.dur.start()
def update(self):
"""Update the RunState."""
# Check for tracking and fixation
if self.disp_ops['eyetrack']:
self.old_tracked = self.tracked
self.tracked = eyetracking.is_tracked()
self.old_fixated = self.fixated
self.fixated = eyetracking.is_fixated(FIX_POS, FIX_RANGE, FIX_PER)
if self.fixated:
# Draw normal cross color if fixating
self.fix_crosses[0].draw()
else:
# Draw alternative cross color if not fixating
self.fix_crosses[1].draw()
# Update eyetracking events
if self.tracked != self.old_tracked:
if self.tracked:
self.events['track_on'] = True
else:
self.events['track_off'] = True
if self.fixated != self.old_fixated:
if self.fixated:
self.events['fix_on'] = True
else:
self.events['fix_off'] = True
# Check for failure of trial
if self.tracked and not self.fixated:
self.fix_fail = True
else:
# Change cross color based on time
if (self._count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
self.fix_crosses[0].draw()
else:
self.fix_crosses[1].draw()
# Blit canvas to screen if necessary
if self.scaling:
self.fbo.end_render()
self.canvas.blit(0, 0)
self.window.switch_to()
self.window.dispatch_events()
self.window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to lists
if self.disp_ops['logtime']:
self.timestamps.append(self.timer.elapsed())
elif self.disp_ops['logdur']:
self.timestamps.append('')
if self.disp_ops['logdur']:
self.durstamps.append(self.dur.restart())
elif self.disp_ops['logtime']:
self.durstamps.append('')
# Send trigger ASAP after flip
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
if self.encode_events() > 0:
trigger.send(trigser, trigpar, self.encode_events())
# Log when triggers are sent
if self.disp_ops['logtime'] and self.encode_events() > 0:
self.trigstamps.append(self.encode_events())
else:
self.trigstamps.append('')
# Clear canvas, events, prepare for next frame
if self.scaling:
self.fbo.start_render()
self.fbo.clear()
else:
self.window.clear()
self.events = copy.deepcopy(self.__class__.DEFAULTS['events'])
self._count += 1
def stop(self):
"""Clean up RunState."""
if self.disp_ops['eyetrack']:
eyetracking.stop()
if self.scaling:
self.fbo.delete()
del self.canvas
self.window.close()
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
trigger.quit(trigser, trigpar)
if self.disp_ops['priority'] != None:
priority.set('normal')
def encode_events(self):
"""Hard code specific trigger values for events."""
code = 0
if self.events['ord_id'] != None:
code = self.events['ord_id'] + 1
elif self.events['blk_on']:
code = 128
elif self.events['blk_off']:
code = 127
else:
mult = 0
if self.events['fix_on']:
mult = 4
elif self.events['track_on']:
mult = 3
if self.events['track_off']:
mult = 1
elif self.events['fix_off']:
mult = 2
if self.events['grp_on']:
code = 100 + mult
elif self.events['grp_off']:
code = 90 + mult
elif len(self.events['sids']) > 0:
code = ((0 in self.events['sids'])*2**0 +
(1 in self.events['sids'])*2**1 +
(2 in self.events['sids'])*2**2 +
(3 in self.events['sids'])*2**3)
code = mult*16 + code
elif mult > 0:
code = 110 + mult
return code
def log(self, path=None):
"""Write a log file for the experimental run in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, LOG_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(LOG_FMT):
path = '{0}.{1}'.format(path, LOG_FMT)
with open(path, 'wb') as logfile:
writer = csv.writer(logfile, dialect='excel-tab')
writer.writerow(['checkergen log file'])
writer.writerow(['display options:'])
writer.writerow(self.disp_ops.keys())
writer.writerow(self.disp_ops.values())
writer.writerow(['order:'] + self.order)
if self.disp_ops['eyetrack']:
write.writerow(['groups added'])
for blk in grouper(self.add_gids,
self.disp_ops['trybreak'], ''):
write.writerow(blk)
write.writerow(['groups failed'])
for blk in grouper(self.fail_gids,
self.disp_ops['trybreak'], ''):
write.writerow(blk)
if self.disp_ops['logtime'] or self.disp_ops['logdur']:
stamps = [self.timestamps, self.durstamps, self.trigstamps]
writer.writerow(['timestamps', 'durations', 'triggers'])
for stamp in zip(*stamps):
writer.writerow(list(stamp))
class CkgDisplayGroup:
DEFAULTS = OrderedDict([('pre', 0), ('disp', 'Infinity'), ('post', 0)])
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets counts and all contained shapes."""
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, runstate):
"""Draws all contained shapes during the appropriate interval."""
for shape in self.shapes:
shape.draw(photoburst=runstate.disp_ops['photoburst'])
def update(self, runstate):
"""Updates contained shapes, sets event triggers."""
# Set events to be sent
if runstate.disp_ops['fpst'] > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= runstate.disp_ops['fpst']:
if not runstate.disp_ops['freqcheck'] or runstate.fc_send:
runstate.events['sids'].add(n)
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(runstate.fps)
def display(self, runstate):
"""Display the group in the context described by supplied runstate."""
self.reset()
for count in range(self.pre * runstate.fps):
if runstate.window.has_exit:
break
runstate.update()
runstate.events['grp_on'] = True
if runstate.disp_ops['eyetrack']:
runstate.fix_fail = False
renstate.true_fail = False
for count in range(self.disp * runstate.fps):
if runstate.window.has_exit:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
runstate.events['grp_off'] = True
if runstate.disp_ops['eyetrack']:
if runstate.fix_fail:
runstate.true_fail = True
for count in range(self.post * runstate.fps):
if runstate.window.has_exit:
break
runstate.update()
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.steps_done = 0
def draw(self, runstate):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, runstate):
"""Checks for keypress, sends trigger upon end."""
if max([runstate.keystates[key] for
key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
def display(self, runstate):
"""Displays waitscreen in context described by supplied runstate."""
while self.steps_done < self.num_steps:
if runstate.window.has_exit:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = OrderedDict([('dims', (5, 5)),
('init_unit', (30, 30)),
('end_unit', (50, 50)),
('position', (0, 0)),
('anchor', 'bottomleft'),
('cols', ((0, 0, 0), (255, 255, 255))),
('freq', 1),
('phase', 0)])
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
if INT_HALF_PERIODS:
frames_per_half_period = round(fps / (self.freq * 2))
degs_per_frame = 180 / to_decimal(frames_per_half_period)
else:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
anchor=self.anchor)
cur_unit_rect.col = self.cols[(i + j) % 2]
cur_unit_rect.add_to_batch(self._batches[0])
cur_unit_rect.col = self.cols[(i + j + 1) % 2]
cur_unit_rect.add_to_batch(self._batches[1])
# Increase x values
cur_unit_pos[0] += \
graphics.locations[self.anchor][0] * cur_unit[0]
cur_unit[0] += unit_grad[0]
# Reset x values
cur_unit_pos[0] = init_pos[0]
cur_unit[0] = init_unit[0]
# Increase y values
cur_unit_pos[1] += \
graphics.locations[self.anchor][1] * cur_unit[1]
cur_unit[1] += unit_grad[1]
self._computed = True
def draw(self, photoburst=False, always_compute=False):
"""Draws appropriate batch depending on current phase.
photoburst -- draw first color for only one frame for testing purposes
|
ztangent/checkergen
|
3058edb8c082e715dc5933db7b9e0c67348b904d
|
Add missing freqcheck field to example.ckg.y
|
diff --git a/example.ckg b/example.ckg
index d366c5e..262799c 100644
--- a/example.ckg
+++ b/example.ckg
@@ -1,76 +1,77 @@
<?xml version="1.0" ?>
<project xmlns="http://github.com/ZOMGxuan/checkergen">
<fps>Decimal('60')</fps>
<res>(800, 600)</res>
<bg>(127, 127, 127)</bg>
<export_fmt>'png'</export_fmt>
<pre>Decimal('0')</pre>
<post>Decimal('0')</post>
<cross_cols>((0, 0, 0), (255, 0, 0))</cross_cols>
<cross_times>(Decimal('Infinity'), Decimal('1'))</cross_times>
<orders>[]</orders>
<disp_ops>
<repeats>1</repeats>
<waitless>False</waitless>
<fullscreen>False</fullscreen>
<priority>None</priority>
<logtime>False</logtime>
<logdur>False</logdur>
<trigser>False</trigser>
<trigpar>False</trigpar>
<fpst>0</fpst>
+ <freqcheck>False</freqcheck>
<phototest>False</phototest>
<photoburst>False</photoburst>
<eyetrack>False</eyetrack>
<etuser>False</etuser>
<etvideo>None</etvideo>
<tryagain>0</tryagain>
<trybreak>None</trybreak>
<nolog>False</nolog>
</disp_ops>
<group>
<pre>Decimal('2')</pre>
<disp>Decimal('10')</disp>
<post>Decimal('2')</post>
<shape type="board">
<dims>(5, 5)</dims>
<init_unit>(Decimal('40'), Decimal('40'))</init_unit>
<end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<position>(Decimal('420'), Decimal('320'))</position>
<anchor>'bottomleft'</anchor>
<cols>((0, 0, 0), (255, 255, 255))</cols>
<freq>Decimal('1')</freq>
<phase>Decimal('0')</phase>
</shape>
<shape type="board">
<dims>(5, 5)</dims>
<init_unit>(Decimal('40'), Decimal('40'))</init_unit>
<end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<position>(Decimal('380'), Decimal('320'))</position>
<anchor>'bottomright'</anchor>
<cols>((0, 0, 0), (255, 255, 255))</cols>
<freq>Decimal('2')</freq>
<phase>Decimal('90')</phase>
</shape>
<shape type="board">
<dims>(5, 5)</dims>
<init_unit>(Decimal('40'), Decimal('40'))</init_unit>
<end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<position>(Decimal('420'), Decimal('280'))</position>
<anchor>'topleft'</anchor>
<cols>((0, 0, 0), (255, 255, 255))</cols>
<freq>Decimal('3')</freq>
<phase>Decimal('180')</phase>
</shape>
<shape type="board">
<dims>(5, 5)</dims>
<init_unit>(Decimal('40'), Decimal('40'))</init_unit>
<end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<position>(Decimal('380'), Decimal('280'))</position>
<anchor>'topright'</anchor>
<cols>((0, 0, 0), (255, 255, 255))</cols>
<freq>Decimal('4')</freq>
<phase>Decimal('270')</phase>
</shape>
</group>
</project>
|
ztangent/checkergen
|
2035a3ed4af1734af5824fa92e23c94cee379cd9
|
Freqcheck functionality added and working.
|
diff --git a/src/cli.py b/src/cli.py
index 9a4f5a1..d992125 100644
--- a/src/cli.py
+++ b/src/cli.py
@@ -274,791 +274,796 @@ class CkgCmd(cmd.Cmd):
help='''time in seconds shapes will be
displayed''')
mkgrp_parser.add_argument('post', type=to_decimal, default=0, nargs='?',
help='''time in seconds a blank screen will
be shown after shapes are displayed''')
def help_mkgrp(self):
self.__class__.mkgrp_parser.print_help()
def do_mkgrp(self, line):
"""Makes a display group with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
try:
args = self.__class__.mkgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mkgrp_parser.print_usage()
return
group_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_group = core.CkgDisplayGroup(**group_dict)
new_id = self.cur_proj.add_group(new_group)
print "display group", new_id, "added"
self.cur_group = new_group
print "group", new_id, "is now the current display group"
edgrp_parser = CmdParser(add_help=False, prog='edgrp',
description='''Edits attributes of display groups
specified by ids.''')
edgrp_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='ids of display groups to be edited')
edgrp_parser.add_argument('--pre', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown before shapes are displayed''')
edgrp_parser.add_argument('--disp', type=to_decimal, metavar='SECONDS',
help='''time in seconds shapes will be
displayed''')
edgrp_parser.add_argument('--post', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown after shapes are displayed''')
def help_edgrp(self):
self.__class__.edgrp_parser.print_help()
def do_edgrp(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.edgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.edgrp_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_proj.groups) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_group_attr(x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.edgrp_parser.print_usage()
rmgrp_parser = CmdParser(add_help=False, prog='rmgrp',
description='''Removes display groups specified
by ids.''')
rmgrp_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='ids of display groups to be removed')
rmgrp_parser.add_argument('-a', '--all', action='store_true',
help='remove all groups from the project')
def help_rmgrp(self):
self.__class__.rmgrp_parser.print_help()
def do_rmgrp(self, line):
"""Removes display groups specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups to remove'
return
try:
args = self.__class__.rmgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rmgrp_parser.print_usage()
return
rmlist = []
if args.all:
for group in self.cur_proj.groups[:]:
self.cur_proj.del_group(group)
print "all display groups removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_proj.groups) or x < 0:
print "display group", x, "does not exist"
continue
rmlist.append(self.cur_proj.groups[x])
print "display group", x, "removed"
for group in rmlist:
self.cur_proj.del_group(group)
# Remember to point self.cur_group somewhere sane
if self.cur_group not in self.cur_proj.groups:
if len(self.cur_proj.groups) == 0:
self.cur_group = None
else:
self.cur_group = self.cur_proj.groups[0]
print "group 0 is now the current display group"
chgrp_parser = CmdParser(add_help=False, prog='chgrp',
description='''Changes display group that is
currently active for editing.
Prints current group id if
no group id is specified''')
chgrp_parser.add_argument('gid', metavar='id', type=int, nargs='?',
help='id of display group to be made active')
def help_chgrp(self):
self.__class__.chgrp_parser.print_help()
def do_chgrp(self, line):
"""Changes group that is currently active for editing."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups that can be made active'
return
try:
args = self.__class__.chgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.chgrp_parser.print_usage()
return
if args.gid == None:
print "group",\
self.cur_proj.groups.index(self.cur_group),\
"is the current display group"
elif args.gid >= len(self.cur_proj.groups) or args.gid < 0:
print "group", args.gid, "does not exist"
else:
self.cur_group = self.cur_proj.groups[args.gid]
print "group", args.gid, "is now the current display group"
mk_parser = CmdParser(add_help=False, prog='mk',
description='''Makes a new checkerboard in the
current group with the given
parameters.''')
mk_parser.add_argument('dims', action=store_tuple(2, ',', to_decimal),
help='''width,height of checkerboard in no. of
unit cells''')
mk_parser.add_argument('init_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of initial unit cell in pixels')
mk_parser.add_argument('end_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of final unit cell in pixels')
mk_parser.add_argument('position', action=store_tuple(2, ',', to_decimal),
help='x,y position of checkerboard in pixels')
mk_parser.add_argument('anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='anchor')
mk_parser.add_argument('cols', action=store_tuple(2, ',', to_color, [';']),
help='''color1,color2 of the checkerboard
(color format: R;G;B,
component range from 0-255)''')
mk_parser.add_argument('freq', type=to_decimal,
help='frequency of color reversal in Hz')
mk_parser.add_argument('phase', type=to_decimal, nargs='?', default='0',
help='initial phase of animation in degrees')
def help_mk(self):
self.__class__.mk_parser.print_help()
def do_mk(self, line):
"""Makes a checkerboard with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
if self.cur_group == None:
print 'automatically adding display group...'
self.do_mkgrp('')
try:
args = self.__class__.mk_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mk_parser.print_usage()
return
shape_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_shape = core.CheckerBoard(**shape_dict)
new_id = self.cur_proj.add_shape_to_group(self.cur_group, new_shape)
print "checkerboard", new_id, "added"
ed_parser = CmdParser(add_help=False, prog='ed',
description='''Edits attributes of checkerboards
specified by ids.''')
ed_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='''ids of checkerboards in the current
group to be edited''')
ed_parser.add_argument('--dims', action=store_tuple(2, ',', to_decimal),
help='checkerboard dimensions in unit cells',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--init_unit',
action=store_tuple(2, ',', to_decimal),
help='initial unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--end_unit',
action=store_tuple(2, ',', to_decimal),
help='final unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--position',
action=store_tuple(2, ',', to_decimal),
help='position of checkerboard in pixels',
metavar='X,Y')
ed_parser.add_argument('--anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='LOCATION')
ed_parser.add_argument('--cols', metavar='COLOR1,COLOR2',
action=store_tuple(2, ',', to_color, [';']),
help='''checkerboard colors (color format:
R;G;B, component range
from 0-255)''')
ed_parser.add_argument('--freq', type=to_decimal,
help='frequency of color reversal in Hz')
ed_parser.add_argument('--phase', type=to_decimal,
help='initial phase of animation in degrees')
def help_ed(self):
self.__class__.ed_parser.print_help()
def do_ed(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, please create one first'
return
try:
args = self.__class__.ed_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ed_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_group.shapes) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_shape_attr(self.cur_group, x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.ed_parser.print_usage()
rm_parser = CmdParser(add_help=False, prog='rm',
description='''Removes checkerboards specified
by ids.''')
rm_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''ids of checkerboards in the current group
to be removed''')
rm_parser.add_argument('-a', '--all', action='store_true',
help='''remove all checkerboards in the
current group''')
def help_rm(self):
self.__class__.rm_parser.print_help()
def do_rm(self, line):
"""Removes checkerboards specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, no boards to remove'
return
try:
args = self.__class__.rm_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rm_parser.print_usage()
return
rmlist = []
if args.all:
for shape in self.cur_group.shapes:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
print "all checkerboards removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_group.shapes) or x < 0:
print "checkerboard", x, "does not exist"
continue
rmlist.append(self.cur_group.shapes[x])
print "checkerboard", x, "removed"
for shape in rmlist:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
ls_parser = CmdParser(add_help=False, prog='ls',
description='''Lists project, display group and
checkerboard settings. If no group ids
are specified, all display groups
are listed.''')
ls_parser.add_argument('gidlist', nargs='*', metavar='gid', type=int,
help='''ids of the display groups to be listed''')
ls_group = ls_parser.add_mutually_exclusive_group()
ls_group.add_argument('-s', '--settings', action='store_true',
help='list only project settings')
ls_group.add_argument('-g', '--groups', action='store_true',
help='list only display groups')
def help_ls(self):
self.__class__.ls_parser.print_help()
def do_ls(self, line):
"""Lists project, display group and checkerboard settings."""
def ls_str(s, seps=[',',';']):
"""Special space-saving output formatter."""
if type(s) in [tuple, list]:
if len(seps) > 1:
newseps = seps[1:]
else:
newseps = seps
return seps[0].join([ls_str(i, newseps) for i in s])
else:
return str(s)
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.ls_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ls_parser.print_usage()
return
# Remove duplicates and ascending sort
args.gidlist = sorted(set(args.gidlist))
if len(self.cur_proj.groups) == 0:
if len(args.gidlist) > 0:
print 'this project has no display groups that can be listed'
args.settings = True
else:
for gid in args.gidlist[:]:
if gid >= len(self.cur_proj.groups) or gid < 0:
args.gidlist.remove(gid)
print 'display group', gid, 'does not exist'
if args.gidlist == []:
args.gidlist = range(len(self.cur_proj.groups))
else:
# If any (valid) groups are specified
# don't show project settings
args.groups = True
if not args.groups:
print 'PROJECT SETTINGS'.center(70,'*')
print \
'name'.rjust(16),\
'fps'.rjust(7),\
'resolution'.rjust(14),\
'bg color'.rjust(18)
# 'format'.rjust(7)
print \
ls_str(self.cur_proj.name).rjust(16),\
ls_str(self.cur_proj.fps).rjust(7),\
ls_str(self.cur_proj.res).rjust(14),\
ls_str(self.cur_proj.bg).rjust(18)
# ls_str(self.cur_proj.export_fmt).rjust(7)
print \
'pre-display'.rjust(26),\
'post-display'.rjust(26)
print \
ls_str(self.cur_proj.pre).rjust(26),\
ls_str(self.cur_proj.post).rjust(26)
print \
'cross colors'.rjust(26),\
'cross times'.rjust(26)
print \
ls_str(self.cur_proj.cross_cols).rjust(26),\
ls_str(self.cur_proj.cross_times).rjust(26)
if not args.settings and not args.groups:
# Insert empty line if both groups and project
# settings are listed
print ''
if not args.settings:
for i, n in enumerate(args.gidlist):
if i != 0:
# Print newline seperator between each group
print ''
group = self.cur_proj.groups[n]
print 'GROUP {n}'.format(n=n).center(70,'*')
print \
'pre-display'.rjust(20),\
'display'.rjust(20),\
'post-display'.rjust(20)
print \
ls_str(group.pre).rjust(20),\
ls_str(group.disp).rjust(20),\
ls_str(group.post).rjust(20)
if len(group.shapes) > 0:
print \
''.rjust(2),\
'shape id'.rjust(8),\
'dims'.rjust(10),\
'init_unit'.rjust(14),\
'end_unit'.rjust(14),\
'position'.rjust(14)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.dims).rjust(10),\
ls_str(shape.init_unit).rjust(14),\
ls_str(shape.end_unit).rjust(14),\
ls_str(shape.position).rjust(14)
print '\n',\
''.rjust(2),\
'shape id'.rjust(8),\
'colors'.rjust(27),\
'anchor'.rjust(12),\
'freq'.rjust(6),\
'phase'.rjust(7)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.cols).rjust(27),\
ls_str(shape.anchor).rjust(12),\
ls_str(shape.freq).rjust(6),\
ls_str(shape.phase).rjust(7)
display_parser = CmdParser(add_help=False, prog='display',
description='''Displays the animation in a
window or in fullscreen.''')
display_parser.add_argument('-n', '--name', metavar='FOOBAR',
help='''name of log file to be written''')
display_parser.add_argument('-r', '--repeats', metavar='N', type=int,
help='''repeatedly display specified display
groups N number of times''')
display_parser.add_argument('-wl', '--waitless', action='store_true',
help='''do not add waitscreens before the
start of each repeat''')
display_parser.add_argument('-f', '--fullscreen', action='store_true',
help='sets fullscreen mode, ESC to quit')
display_parser.add_argument('-p', '--priority', metavar='LEVEL',
help='''set priority while displaying,
higher priority results in
less dropped frames (choices:
0-3, low, normal, high,
realtime)''')
display_parser.add_argument('-pt', '--phototest', action='store_true',
help='''draw white test rectangle in topleft
corner of screen when groups become
visible for a photodiode to detect''')
display_parser.add_argument('-pb', '--photoburst', action='store_true',
help='''make checkerboards only draw first
color for one frame to facilitate
testing with a photodiode''')
display_parser.add_argument('-lt', '--logtime', action='store_true',
help='output frame timestamps to a log file')
display_parser.add_argument('-ld', '--logdur', action='store_true',
help='output frame durations to a log file')
display_parser.add_argument('-ss', '--trigser', action='store_true',
help='''send triggers through the serial port
when shapes are being displayed''')
display_parser.add_argument('-sp', '--trigpar', action='store_true',
help='''send triggers through the parallel port
when shapes are being displayed''')
display_parser.add_argument('-fpst', metavar='M', type=int,
help='''unique trigger corresponding to a
checkerboard is sent after the shape
undergoes M color flips (default:
disabled, M=0)''')
+ display_parser.add_argument('-fc', '--freqcheck', action='store_true',
+ help='''only send triggers for board color
+ flips at the start, middle and end
+ of the run''')
display_parser.add_argument('-et', '--eyetrack', action='store_true',
help='''use eyetracking to ensure that subject
fixates on the cross in the center''')
display_parser.add_argument('-eu', '--etuser', action='store_true',
help='''allow user to select eyetracking video
source from a dialog''')
display_parser.add_argument('-ev', '--etvideo', metavar='path',
help='''path (with no spaces) to eyetracking
video file to be used as the source''')
display_parser.add_argument('-ta', '--tryagain', metavar='I',
type=int, default=0,
help='''append groups during which subject
failed to fixate up to I times to the
list of groups to be displayed
(default: disabled, I=0)''')
display_parser.add_argument('-tb', '--trybreak', metavar='J', type=int,
help='''used with --tryagain, append a wait
screen to the list of groups to be
displayed after every J groups have
been appended to the list (default:
J=total number of groups)''')
display_parser.add_argument('-nl', '--nolog', action='store_true',
help='''do not write a log file''')
display_parser.add_argument('order', nargs='*', metavar='id', type=int,
help='''order in which groups should be
displayed (default: random order
from list of orders if specified
in project, ascending otherwise)''')
def help_display(self):
self.__class__.display_parser.print_help()
def do_display(self, line):
"""Displays the animation in a window or in fullscreen"""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.display_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
if len(args.order) > 0:
for i in set(args.order):
if i >= len(self.cur_proj.groups) or i < -1:
print 'error: group', i, 'does not exist'
return
if args.eyetrack and eyetracking.available:
if not eyetracking.is_calibrated():
try:
self.do_calibrate('',query=True)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
return
print "displaying...",
try:
self.cur_proj.display(name=args.name,
repeats=args.repeats,
waitless=args.waitless,
fullscreen=args.fullscreen,
priority=args.priority,
logtime=args.logtime,
logdur=args.logdur,
trigser=args.trigser,
trigpar=args.trigpar,
fpst=args.fpst,
+ freqcheck=args.freqcheck,
phototest=args.phototest,
photoburst=args.photoburst,
eyetrack=args.eyetrack,
etuser=args.etuser,
etvideo=args.etvideo,
tryagain=args.tryagain,
trybreak=args.trybreak,
nolog=args.nolog,
order=args.order)
except (IOError, NotImplementedError, eyetracking.EyetrackingError):
print ''
print "error:", str(sys.exc_value)
if args.priority != None:
try:
priority.set('normal')
except:
pass
return
print "done"
export_parser = CmdParser(add_help=False, prog='export',
description='''Exports animation as an image
sequence (in a folder) to the
specified directory.''')
# export_parser.add_argument('--fmt', dest='export_fmt',
# choices=core.EXPORT_FMTS,
# help='image format for export')
export_parser.add_argument('-n','--nofolder',
dest='folder', action='store_false',
help='''force images not to exported in
a containing folder''')
export_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly export specified display
groups N number of times''')
export_parser.add_argument('duration', nargs='?',
type=to_decimal, default='Infinity',
help='''number of seconds of the animation
that should be exported (default:
as long as the entire animation)''')
export_parser.add_argument('dir', nargs='?', default=os.getcwd(),
help='''destination directory for export
(default: current working directory)''')
export_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be exported
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_export(self):
self.__class__.export_parser.print_help()
def do_export(self, line):
"""Exports animation an image sequence to the specified directory."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.export_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.export_parser.print_usage()
return
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < 0:
print 'error: group', i, 'does not exist'
return
groupq = [self.cur_proj.groups[i] for i in args.idlist]
else:
groupq = list(self.cur_proj.groups)
if args.repeat != None:
groupq = list(groupq * args.repeat)
try:
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
folder=args.folder)
except IOError:
print "error:", str(sys.exc_value)
return
except core.FrameOverflowError:
print "warning:", str(sys.exc_value)
print "Are you sure you want to continue?"
while True:
try:
if self.__class__.yn_parse(raw_input()):
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
export_fmt=None,
folder=args.folder,
force=True)
break
else:
return
except TypeError:
print str(sys.exc_value)
except EOFError:
return
print "Export done."
def do_calibrate(self, line, query=False):
"""Calibrate subject for eyetracking, or load a calibration file."""
if not eyetracking.available:
print "error: eyetracking functionality not available"
return
if query:
print "path to calibration file (leave empty for GUI tool):"
try:
path = raw_input().strip().strip('"\'')
except EOFError:
msg = "calibration cancelled"
raise eyetracking.EyetrackingError(msg)
else:
path = line.strip().strip('"\'')
if len(path) == 0:
path = None
if not eyetracking.is_source_ready():
# Select default source if none has been selected
eyetracking.select_source()
try:
eyetracking.calibrate(path)
except eyetracking.EyetrackingError:
if query:
raise
else:
print "error:", str(sys.exc_value)
return
if len(path) > 0:
print "calibration file successfully loaded"
etsetup_parser = CmdParser(add_help=False, prog='etsetup',
description='''Set various eyetracking
parameters.''')
etsetup_parser.add_argument('-fp', '--fixperiod', type=int, metavar='MS',
help='''time in milliseconds subject
has to stare at the same spot
for fixation to be detected''')
etsetup_parser.add_argument('-fr', '--fixrange', type=float, metavar='MM',
help='''distance in mm beyond which the
eye position cannot change for
a fixation to be detected''')
etsetup_parser.add_argument('-s', '--size', metavar='WIDTH,HEIGHT',
action=store_tuple(2, ',', float),
help='physical screen dimensions in mm')
etsetup_parser.add_argument('-vd', '--viewdist', type=int, metavar='MM',
help='''viewing distance between subject's
eyes and the screen''')
def help_etsetup(self):
self.__class__.etsetup_parser.print_help()
def do_etsetup(self, line):
try:
args = self.__class__.etsetup_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.etsetup_parser.print_usage()
return
try:
eyetracking.setup(viewing_distance=args.viewdist,
screen_dims=args.size,
fixation_period=args.fixperiod,
fixation_range=args.fixrange)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
def do_pwd(self, line):
"""Prints the current working directory."""
print os.getcwd()
def do_cd(self, line):
"""Change working directory to specified path."""
path = line.strip().strip('"\'')
if not os.path.isdir(path):
print "error: specified path is not a directory"
return
os.chdir(path)
def do_quit(self, line):
"""Quits the program."""
if self.save_check():
return
return True
def help_EOF(self):
print "Typing {0} issues this command, which quits the program."\
.format(CMD_EOF_STRING)
def do_EOF(self, line):
"""Typing Ctrl-D issues this command, which quits the program."""
print '\r'
if self.save_check():
return
return True
def help_help(self):
print 'Prints a list of commands.'
print "Type 'help <topic>' for more details on each command."
def default(self, line):
command = line.split()[0]
print \
"'{0}' is not a checkergen command.".format(command),\
"Type 'help' for a list of commands"
diff --git a/src/core.py b/src/core.py
index 29870f5..6427ece 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,1209 +1,1227 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import copy
import random
import itertools
from datetime import datetime
from xml.dom import minidom
import pyglet
import graphics
import priority
import trigger
import eyetracking
from utils import *
# Use OrderedDict substitute if we don't have Python 2.7
if sys.version_info < (2, 7):
from odict import OrderedDict
else:
from collections import OrderedDict
CKG_FMT = 'ckg'
LOG_FMT = 'csv'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
MAX_EXPORT_FRAMES = 100000
INT_HALF_PERIODS = True
EXPORT_FMTS = ['png']
EXPORT_DIR_SUFFIX = '-anim'
FIX_POS = (0, 0)
FIX_RANGE = (20, 20)
FIX_PER = 350
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = OrderedDict([('name', 'untitled'),
('fps', 60),
('res', (800, 600)),
('bg', (127, 127, 127)),
('export_fmt', 'png'),
('pre', 0),
('post', 0),
('cross_cols', ((0, 0, 0), (255, 0, 0))),
('cross_times', ('Infinity', 1)),
('orders', []),
('disp_ops', None)])
DEFAULTS['disp_ops'] = OrderedDict([('repeats', 1),
('waitless', False),
('fullscreen', False),
('priority', None),
('logtime', False),
('logdur', False),
('trigser', False),
('trigpar', False),
('fpst', 0),
+ ('freqcheck', False),
('phototest', False),
('photoburst', False),
('eyetrack', False),
('etuser', False),
('etvideo', None),
('tryagain', 0),
('trybreak', None),
('nolog', False)])
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
export_fmt -- image format for animation to be exported as
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'export_fmt':
if value not in EXPORT_FMTS:
msg = 'image format not recognized or supported'
raise FileFormatError(msg)
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
# Vars that are dicts
dicts_to_load = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_load = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
for d_name in dicts_to_load:
d = self.__class__.DEFAULTS[d_name]
try:
d_el = [node for node in project.childNodes if
node.localName == d_name and
node.namespaceURI == XML_NAMESPACE][0]
for var in d.keys():
try:
d[var] = eval(xml_get(d_el, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}' in '{1}'".\
format(var, d_name)
print "using default value '{0}' instead...".\
format(d[var])
except IndexError:
print "warning: missing attribute set '{0}'".format(d_name)
print "using default values instead..."
setattr(self, d_name, d)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
# Vars that are dicts
dicts_to_save = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_save = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for d_name in dicts_to_save:
d_el = doc.createElement(d_name)
project.appendChild(d_el)
d = getattr(self, d_name)
for k, v in d.iteritems():
xml_set(doc, d_el, k, repr(v))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, **keywords):
"""Displays the project animation on the screen.
name -- name that logfile will be saved with
repeats -- number of times specified order of display groups should
be repeated
waitless -- if true, no waitscreens will appear at the start of each
repeat
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
priority -- priority level to which process should be raised
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
trigser -- send triggers through serial port when each group is shown
trigpar -- send triggers through parallel port when each group is shown
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
+ freqcheck -- send fpst only at the start, the middle, and the end
+ for sanity checking of display and trigger fps
+
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- append a wait screen to the group queue every time
after this many groups have been appended to the queue
order -- order in which groups (specified by id) will be displayed
"""
# Create RunState
disp_ops = self.disp_ops
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'name' in keywords.keys() and keywords['name'] != None:
name = keywords['name']
else:
timestr = datetime.today().strftime('_%Y-%m-%d_%H-%M-%S')
name = self.name + timestr
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
waitscreen = CkgWaitScreen()
# Set order id to be sent if necessary
if order in self.orders:
runstate.events['ord_id'] = self.orders.index(order)
# Count through pre
for count in range(self.pre * self.fps):
if runstate.window.has_exit:
break
runstate.update()
# Loop through repeats
- for i in range(runstate.disp_ops['repeats']):
+ repeats = runstate.disp_ops['repeats']
+ ord_len = len(runstate.order)
+ for i in range(repeats):
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
# Loop through display groups
runstate.events['blk_on'] = True
- for gid in runstate.order:
+ for n, gid in enumerate(runstate.order):
+ # Set flag for freqcheck
+ if runstate.disp_ops['freqcheck']:
+ if ((i == 0 and n == 0) or
+ (i == repeats-1 and n == ord_len-1) or
+ (i == repeats//2 and n == ord_len//2)):
+ runstate.fc_send = True
+ else:
+ runstate.fc_send = False
if gid == -1:
waitscreen.reset()
waitscreen.display(runstate)
else:
self.groups[gid].display(runstate)
# Append failed groups
if runstate.disp_ops['eyetrack'] and runstate.truefail:
if len(runstate.add_gids) < runstate.disp_ops['tryagain']:
runstate.add_gids.append(gid)
else:
runstate.fail_gids.append(gid)
runstate.events['blk_off'] = True
# Loop through added groups
if runstate.disp_ops['eyetrack']:
for blk in grouper(runstate.add_gids,
runstate.disp_ops['trybreak']):
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
runstate.events['blk_on'] = True
# Loop through display groups
for gid in blk:
if gid != None:
self.groups[gid].display(runstate)
runstate.events['blk_off'] = True
# Count through post
for count in range(self.post * self.fps):
if runstate.window.has_exit:
break
runstate.update()
# Stop and output log
runstate.stop()
if not runstate.disp_ops['nolog']:
runstate.log()
def export(self, export_dir, export_duration, groupq=[],
export_fmt=None, folder=True, force=False):
if not os.path.isdir(export_dir):
msg = 'export path is not a directory'
raise IOError(msg)
if export_fmt == None:
export_fmt = self.export_fmt
# Set-up groups and variables that control their display
if groupq == []:
groupq = list(self.groups)
n = -1
groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Limit export duration to display duration
frames = export_duration * self.fps
frames = min(frames, disp_end)
# Warn user if a lot of frames will be exported
if frames > MAX_EXPORT_FRAMES and not force:
msg = 'very large number ({0}) of frames to be exported'.\
format(frames)
raise FrameOverflowError(msg)
# Create folder to store images if necessary
if folder:
export_dir = os.path.join(export_dir,
self.name + EXPORT_DIR_SUFFIX)
if not os.path.isdir(export_dir):
os.mkdir(export_dir)
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Set up canvas and framebuffer object
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
# Main loop
while count < frames:
fbo.clear()
if groups_visible:
# Get next group from queue
if n < 0 or groupq[n].over:
n += 1
if n >= len(groupq):
groups_visible = False
else:
groupq[n].reset()
# Draw and then update group
if n >= 0:
groupq[n].draw()
groupq[n].update(fps=self.fps, fpst=0)
# Draw fixation cross based on current count
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Save current frame to file
savepath = \
os.path.join(export_dir,
'{0}{2}.{1}'.
format(self.name, export_fmt,
repr(count).zfill(numdigits(frames-1))))
canvas.save(savepath)
# Increment count and set whether groups should be shown
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
fbo.delete()
class CkgRunState:
"""Contains information about the state of a checkergen project
when it is being displayed or exported."""
DEFAULTS = dict([('name', 'untitled'),
('res', None),
('fps', None),
('bg', None),
('cross_cols', None),
('cross_times', None),
('order', []),
('disp_ops', None),
('events', None),
('add_gids', []),
('fail_gids', []),
('timestamps', []),
('durstamps', []),
('trigstamps', [])])
DEFAULTS['events'] = dict([('ord_id', None),
('blk_on', False),
('blk_off', False),
('track_on', False),
('track_off', False),
('fix_on', False),
('fix_off', False),
('grp_on', False),
('grp_off', False),
('sids', set())])
def __init__(self, **keywords):
"""Creates the RunState."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
def start(self):
"""Initialize all subsystems and start the run."""
if self.disp_ops == None:
msg = "RunState lacks display options"
raise ValueError(msg)
if min(self.res, self.fps, self.bg,
self.cross_cols, self.cross_times) == None:
msg = "RunState intialized with insufficent project information"
raise ValueError(msg)
self._count = 0
+ # Flag used by freqcheck
+ self.fc_send = False
+
# Create fixation crosses
self.fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if self.disp_ops['phototest']:
self.test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Initialize ports
if self.disp_ops['trigser']:
if not trigger.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trigpar']:
if not trigger.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
trigger.init(self.disp_ops['trigser'], self.disp_ops['trigpar'])
# Initialize eyetracking
if self.disp_ops['eyetrack']:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trybreak'] == None:
self.disp_ops['trybreak'] = len(self.order)
self.fixated = False
self.old_fixated = False
self.tracked = False
self.old_tracked = False
self.fix_fail = False
self.true_fail = False
eyetracking.select_source(self.disp_ops['etuser'],
self.disp_ops['etvideo'])
eyetracking.start()
# Stretch to fit screen only if project res does not equal screen res
self.scaling = False
if self.disp_ops['fullscreen']:
self.window = pyglet.window.Window(fullscreen=True, visible=False)
if (self.window.width, self.window.height) != self.res:
self.scaling = True
else:
self.window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
self.keystates = pyglet.window.key.KeyStateHandler()
self.window.push_handlers(self.keystates)
# Clear window and make visible
self.window.switch_to()
graphics.set_clear_color(self.bg)
self.window.clear()
self.window.set_visible()
# Create framebuffer object for drawing unscaled scene
if self.scaling:
self.canvas = pyglet.image.Texture.create(*self.res)
self.fbo = graphics.Framebuffer(self.canvas)
self.fbo.start_render()
graphics.set_clear_color(self.bg)
self.fbo.clear()
# Set process priority
if self.disp_ops['priority'] != None:
if not priority.available[sys.platform]:
msg = "setting priority not available on {0}".\
format(sys.platform)
raise NotImplementedError(msg)
else:
if self.disp_ops['priority'].isdigit():
self.disp_ops['priority'] = int(self.disp_ops['priority'])
priority.set(self.disp_ops['priority'])
# Start timers
if self.disp_ops['logtime']:
self.timer = Timer()
self.timer.start()
if self.disp_ops['logdur']:
self.dur = Timer()
self.dur.start()
def update(self):
"""Update the RunState."""
# Check for tracking and fixation
if self.disp_ops['eyetrack']:
self.old_tracked = self.tracked
self.tracked = eyetracking.is_tracked()
self.old_fixated = self.fixated
self.fixated = eyetracking.is_fixated(FIX_POS, FIX_RANGE, FIX_PER)
if self.fixated:
# Draw normal cross color if fixating
self.fix_crosses[0].draw()
else:
# Draw alternative cross color if not fixating
self.fix_crosses[1].draw()
# Update eyetracking events
if self.tracked != self.old_tracked:
if self.tracked:
self.events['track_on'] = True
else:
self.events['track_off'] = True
if self.fixated != self.old_fixated:
if self.fixated:
self.events['fix_on'] = True
else:
self.events['fix_off'] = True
# Check for failure of trial
if self.tracked and not self.fixated:
self.fix_fail = True
else:
# Change cross color based on time
if (self._count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
self.fix_crosses[0].draw()
else:
self.fix_crosses[1].draw()
# Blit canvas to screen if necessary
if self.scaling:
self.fbo.end_render()
self.canvas.blit(0, 0)
self.window.switch_to()
self.window.dispatch_events()
self.window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to lists
if self.disp_ops['logtime']:
self.timestamps.append(self.timer.elapsed())
elif self.disp_ops['logdur']:
self.timestamps.append('')
if self.disp_ops['logdur']:
self.durstamps.append(self.dur.restart())
elif self.disp_ops['logtime']:
self.durstamps.append('')
# Send trigger ASAP after flip
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
if self.encode_events() > 0:
trigger.send(trigser, trigpar, self.encode_events())
# Log when triggers are sent
if self.disp_ops['logtime'] and self.encode_events() > 0:
self.trigstamps.append(self.encode_events())
else:
self.trigstamps.append('')
# Clear canvas, events, prepare for next frame
if self.scaling:
self.fbo.start_render()
self.fbo.clear()
else:
self.window.clear()
self.events = copy.deepcopy(self.__class__.DEFAULTS['events'])
self._count += 1
def stop(self):
"""Clean up RunState."""
if self.disp_ops['eyetrack']:
eyetracking.stop()
if self.scaling:
self.fbo.delete()
del self.canvas
self.window.close()
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
trigger.quit(trigser, trigpar)
if self.disp_ops['priority'] != None:
priority.set('normal')
def encode_events(self):
"""Hard code specific trigger values for events."""
code = 0
if self.events['ord_id'] != None:
code = self.events['ord_id'] + 1
elif self.events['blk_on']:
code = 128
elif self.events['blk_off']:
code = 127
else:
mult = 0
if self.events['fix_on']:
mult = 4
elif self.events['track_on']:
mult = 3
if self.events['track_off']:
mult = 1
elif self.events['fix_off']:
mult = 2
if self.events['grp_on']:
code = 100 + mult
elif self.events['grp_off']:
code = 90 + mult
elif len(self.events['sids']) > 0:
code = ((0 in self.events['sids'])*2**0 +
(1 in self.events['sids'])*2**1 +
(2 in self.events['sids'])*2**2 +
(3 in self.events['sids'])*2**3)
- code = mult * 16 + (code + 1)
+ code = mult*16 + code
elif mult > 0:
code = 110 + mult
return code
def log(self, path=None):
"""Write a log file for the experimental run in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, LOG_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(LOG_FMT):
path = '{0}.{1}'.format(path, LOG_FMT)
with open(path, 'wb') as logfile:
writer = csv.writer(logfile, dialect='excel-tab')
writer.writerow(['checkergen log file'])
writer.writerow(['display options:'])
writer.writerow(self.disp_ops.keys())
writer.writerow(self.disp_ops.values())
writer.writerow(['order:'] + self.order)
if self.disp_ops['eyetrack']:
write.writerow(['groups added'])
for blk in grouper(self.add_gids,
self.disp_ops['trybreak'], ''):
write.writerow(blk)
write.writerow(['groups failed'])
for blk in grouper(self.fail_gids,
self.disp_ops['trybreak'], ''):
write.writerow(blk)
if self.disp_ops['logtime'] or self.disp_ops['logdur']:
stamps = [self.timestamps, self.durstamps, self.trigstamps]
writer.writerow(['timestamps', 'durations', 'triggers'])
for stamp in zip(*stamps):
writer.writerow(list(stamp))
class CkgDisplayGroup:
DEFAULTS = OrderedDict([('pre', 0), ('disp', 'Infinity'), ('post', 0)])
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets counts and all contained shapes."""
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, runstate):
"""Draws all contained shapes during the appropriate interval."""
for shape in self.shapes:
shape.draw(photoburst=runstate.disp_ops['photoburst'])
def update(self, runstate):
"""Updates contained shapes, sets event triggers."""
# Set events to be sent
if runstate.disp_ops['fpst'] > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= runstate.disp_ops['fpst']:
- runstate.events['sids'].add(n)
+ if not runstate.disp_ops['freqcheck'] or runstate.fc_send:
+ runstate.events['sids'].add(n)
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(runstate.fps)
def display(self, runstate):
"""Display the group in the context described by supplied runstate."""
self.reset()
for count in range(self.pre * runstate.fps):
if runstate.window.has_exit:
break
runstate.update()
runstate.events['grp_on'] = True
if runstate.disp_ops['eyetrack']:
runstate.fix_fail = False
renstate.true_fail = False
for count in range(self.disp * runstate.fps):
if runstate.window.has_exit:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
runstate.events['grp_off'] = True
if runstate.disp_ops['eyetrack']:
if runstate.fix_fail:
runstate.true_fail = True
for count in range(self.post * runstate.fps):
if runstate.window.has_exit:
break
runstate.update()
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.steps_done = 0
def draw(self, runstate):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, runstate):
"""Checks for keypress, sends trigger upon end."""
if max([runstate.keystates[key] for
key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
def display(self, runstate):
"""Displays waitscreen in context described by supplied runstate."""
while self.steps_done < self.num_steps:
if runstate.window.has_exit:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = OrderedDict([('dims', (5, 5)),
('init_unit', (30, 30)),
('end_unit', (50, 50)),
('position', (0, 0)),
('anchor', 'bottomleft'),
('cols', ((0, 0, 0), (255, 255, 255))),
('freq', 1),
('phase', 0)])
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
if INT_HALF_PERIODS:
frames_per_half_period = round(fps / (self.freq * 2))
degs_per_frame = 180 / to_decimal(frames_per_half_period)
else:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
anchor=self.anchor)
cur_unit_rect.col = self.cols[(i + j) % 2]
cur_unit_rect.add_to_batch(self._batches[0])
cur_unit_rect.col = self.cols[(i + j + 1) % 2]
cur_unit_rect.add_to_batch(self._batches[1])
# Increase x values
cur_unit_pos[0] += \
graphics.locations[self.anchor][0] * cur_unit[0]
cur_unit[0] += unit_grad[0]
# Reset x values
cur_unit_pos[0] = init_pos[0]
cur_unit[0] = init_unit[0]
# Increase y values
cur_unit_pos[1] += \
graphics.locations[self.anchor][1] * cur_unit[1]
cur_unit[1] += unit_grad[1]
self._computed = True
def draw(self, photoburst=False, always_compute=False):
"""Draws appropriate batch depending on current phase.
photoburst -- draw first color for only one frame for testing purposes
always_compute -- recompute what the checkerboard should look like
every frame
"""
if not self._computed or always_compute:
self.compute()
self._cur_phase %= 360
n = int(self._cur_phase // 180)
if photoburst and n == 0 and not self.flipped:
n = 1
self._batches[n].draw()
def lazydraw(self):
"""Only draws on color reversal."""
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if (cur_n != prev_n) or self._first_draw:
self.draw()
if self._first_draw:
self._first_draw = False
|
ztangent/checkergen
|
932f8e447d97300f9398bd1039c4162050c0b76f
|
New triggering system tested and working, start using deepcopy.
|
diff --git a/src/core.py b/src/core.py
index 50e6ec5..29870f5 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,1208 +1,1209 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
+import copy
import random
import itertools
from datetime import datetime
from xml.dom import minidom
import pyglet
import graphics
import priority
import trigger
import eyetracking
from utils import *
# Use OrderedDict substitute if we don't have Python 2.7
if sys.version_info < (2, 7):
from odict import OrderedDict
else:
from collections import OrderedDict
CKG_FMT = 'ckg'
LOG_FMT = 'csv'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
MAX_EXPORT_FRAMES = 100000
INT_HALF_PERIODS = True
EXPORT_FMTS = ['png']
EXPORT_DIR_SUFFIX = '-anim'
FIX_POS = (0, 0)
FIX_RANGE = (20, 20)
FIX_PER = 350
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = OrderedDict([('name', 'untitled'),
('fps', 60),
('res', (800, 600)),
('bg', (127, 127, 127)),
('export_fmt', 'png'),
('pre', 0),
('post', 0),
('cross_cols', ((0, 0, 0), (255, 0, 0))),
('cross_times', ('Infinity', 1)),
('orders', []),
('disp_ops', None)])
DEFAULTS['disp_ops'] = OrderedDict([('repeats', 1),
('waitless', False),
('fullscreen', False),
('priority', None),
('logtime', False),
('logdur', False),
('trigser', False),
('trigpar', False),
('fpst', 0),
('phototest', False),
('photoburst', False),
('eyetrack', False),
('etuser', False),
('etvideo', None),
('tryagain', 0),
('trybreak', None),
('nolog', False)])
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
export_fmt -- image format for animation to be exported as
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
- setattr(self, kw, self.__class__.DEFAULTS[kw])
+ setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'export_fmt':
if value not in EXPORT_FMTS:
msg = 'image format not recognized or supported'
raise FileFormatError(msg)
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
# Vars that are dicts
dicts_to_load = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_load = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
for d_name in dicts_to_load:
d = self.__class__.DEFAULTS[d_name]
try:
d_el = [node for node in project.childNodes if
node.localName == d_name and
node.namespaceURI == XML_NAMESPACE][0]
for var in d.keys():
try:
d[var] = eval(xml_get(d_el, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}' in '{1}'".\
format(var, d_name)
print "using default value '{0}' instead...".\
format(d[var])
except IndexError:
print "warning: missing attribute set '{0}'".format(d_name)
print "using default values instead..."
setattr(self, d_name, d)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
# Vars that are dicts
dicts_to_save = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_save = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for d_name in dicts_to_save:
d_el = doc.createElement(d_name)
project.appendChild(d_el)
d = getattr(self, d_name)
for k, v in d.iteritems():
xml_set(doc, d_el, k, repr(v))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, **keywords):
"""Displays the project animation on the screen.
name -- name that logfile will be saved with
repeats -- number of times specified order of display groups should
be repeated
waitless -- if true, no waitscreens will appear at the start of each
repeat
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
priority -- priority level to which process should be raised
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
trigser -- send triggers through serial port when each group is shown
trigpar -- send triggers through parallel port when each group is shown
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- append a wait screen to the group queue every time
after this many groups have been appended to the queue
order -- order in which groups (specified by id) will be displayed
"""
# Create RunState
disp_ops = self.disp_ops
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'name' in keywords.keys() and keywords['name'] != None:
name = keywords['name']
else:
timestr = datetime.today().strftime('_%Y-%m-%d_%H-%M-%S')
name = self.name + timestr
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
waitscreen = CkgWaitScreen()
# Set order id to be sent if necessary
if order in self.orders:
runstate.events['ord_id'] = self.orders.index(order)
# Count through pre
for count in range(self.pre * self.fps):
if runstate.window.has_exit:
break
runstate.update()
# Loop through repeats
for i in range(runstate.disp_ops['repeats']):
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
# Loop through display groups
runstate.events['blk_on'] = True
for gid in runstate.order:
if gid == -1:
waitscreen.reset()
waitscreen.display(runstate)
else:
self.groups[gid].display(runstate)
# Append failed groups
if runstate.disp_ops['eyetrack'] and runstate.truefail:
if len(runstate.add_gids) < runstate.disp_ops['tryagain']:
runstate.add_gids.append(gid)
else:
runstate.fail_gids.append(gid)
runstate.events['blk_off'] = True
# Loop through added groups
if runstate.disp_ops['eyetrack']:
for blk in grouper(runstate.add_gids,
runstate.disp_ops['trybreak']):
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
runstate.events['blk_on'] = True
# Loop through display groups
for gid in blk:
if gid != None:
self.groups[gid].display(runstate)
- runstate.events['blk_on'] = True
+ runstate.events['blk_off'] = True
# Count through post
for count in range(self.post * self.fps):
if runstate.window.has_exit:
break
runstate.update()
# Stop and output log
runstate.stop()
if not runstate.disp_ops['nolog']:
runstate.log()
def export(self, export_dir, export_duration, groupq=[],
export_fmt=None, folder=True, force=False):
if not os.path.isdir(export_dir):
msg = 'export path is not a directory'
raise IOError(msg)
if export_fmt == None:
export_fmt = self.export_fmt
# Set-up groups and variables that control their display
if groupq == []:
groupq = list(self.groups)
n = -1
groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Limit export duration to display duration
frames = export_duration * self.fps
frames = min(frames, disp_end)
# Warn user if a lot of frames will be exported
if frames > MAX_EXPORT_FRAMES and not force:
msg = 'very large number ({0}) of frames to be exported'.\
format(frames)
raise FrameOverflowError(msg)
# Create folder to store images if necessary
if folder:
export_dir = os.path.join(export_dir,
self.name + EXPORT_DIR_SUFFIX)
if not os.path.isdir(export_dir):
os.mkdir(export_dir)
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Set up canvas and framebuffer object
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
# Main loop
while count < frames:
fbo.clear()
if groups_visible:
# Get next group from queue
if n < 0 or groupq[n].over:
n += 1
if n >= len(groupq):
groups_visible = False
else:
groupq[n].reset()
# Draw and then update group
if n >= 0:
groupq[n].draw()
groupq[n].update(fps=self.fps, fpst=0)
# Draw fixation cross based on current count
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Save current frame to file
savepath = \
os.path.join(export_dir,
'{0}{2}.{1}'.
format(self.name, export_fmt,
repr(count).zfill(numdigits(frames-1))))
canvas.save(savepath)
# Increment count and set whether groups should be shown
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
fbo.delete()
class CkgRunState:
"""Contains information about the state of a checkergen project
when it is being displayed or exported."""
DEFAULTS = dict([('name', 'untitled'),
('res', None),
('fps', None),
('bg', None),
('cross_cols', None),
('cross_times', None),
('order', []),
('disp_ops', None),
('events', None),
('add_gids', []),
('fail_gids', []),
('timestamps', []),
('durstamps', []),
('trigstamps', [])])
DEFAULTS['events'] = dict([('ord_id', None),
('blk_on', False),
('blk_off', False),
('track_on', False),
('track_off', False),
('fix_on', False),
('fix_off', False),
('grp_on', False),
('grp_off', False),
('sids', set())])
def __init__(self, **keywords):
"""Creates the RunState."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
- setattr(self, kw, self.__class__.DEFAULTS[kw])
+ setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
def start(self):
"""Initialize all subsystems and start the run."""
if self.disp_ops == None:
msg = "RunState lacks display options"
raise ValueError(msg)
if min(self.res, self.fps, self.bg,
self.cross_cols, self.cross_times) == None:
msg = "RunState intialized with insufficent project information"
raise ValueError(msg)
self._count = 0
# Create fixation crosses
self.fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if self.disp_ops['phototest']:
self.test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Initialize ports
if self.disp_ops['trigser']:
if not trigger.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trigpar']:
if not trigger.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
trigger.init(self.disp_ops['trigser'], self.disp_ops['trigpar'])
# Initialize eyetracking
if self.disp_ops['eyetrack']:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trybreak'] == None:
self.disp_ops['trybreak'] = len(self.order)
self.fixated = False
self.old_fixated = False
self.tracked = False
self.old_tracked = False
self.fix_fail = False
self.true_fail = False
eyetracking.select_source(self.disp_ops['etuser'],
self.disp_ops['etvideo'])
eyetracking.start()
# Stretch to fit screen only if project res does not equal screen res
self.scaling = False
if self.disp_ops['fullscreen']:
self.window = pyglet.window.Window(fullscreen=True, visible=False)
if (self.window.width, self.window.height) != self.res:
self.scaling = True
else:
self.window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
self.keystates = pyglet.window.key.KeyStateHandler()
self.window.push_handlers(self.keystates)
# Clear window and make visible
self.window.switch_to()
graphics.set_clear_color(self.bg)
self.window.clear()
self.window.set_visible()
# Create framebuffer object for drawing unscaled scene
if self.scaling:
self.canvas = pyglet.image.Texture.create(*self.res)
self.fbo = graphics.Framebuffer(self.canvas)
self.fbo.start_render()
graphics.set_clear_color(self.bg)
self.fbo.clear()
# Set process priority
if self.disp_ops['priority'] != None:
if not priority.available[sys.platform]:
msg = "setting priority not available on {0}".\
format(sys.platform)
raise NotImplementedError(msg)
else:
if self.disp_ops['priority'].isdigit():
self.disp_ops['priority'] = int(self.disp_ops['priority'])
priority.set(self.disp_ops['priority'])
# Start timers
if self.disp_ops['logtime']:
self.timer = Timer()
self.timer.start()
if self.disp_ops['logdur']:
self.dur = Timer()
self.dur.start()
def update(self):
"""Update the RunState."""
# Check for tracking and fixation
if self.disp_ops['eyetrack']:
self.old_tracked = self.tracked
self.tracked = eyetracking.is_tracked()
self.old_fixated = self.fixated
self.fixated = eyetracking.is_fixated(FIX_POS, FIX_RANGE, FIX_PER)
if self.fixated:
# Draw normal cross color if fixating
self.fix_crosses[0].draw()
else:
# Draw alternative cross color if not fixating
self.fix_crosses[1].draw()
# Update eyetracking events
if self.tracked != self.old_tracked:
if self.tracked:
self.events['track_on'] = True
else:
self.events['track_off'] = True
if self.fixated != self.old_fixated:
if self.fixated:
self.events['fix_on'] = True
else:
self.events['fix_off'] = True
# Check for failure of trial
if self.tracked and not self.fixated:
self.fix_fail = True
else:
# Change cross color based on time
if (self._count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
self.fix_crosses[0].draw()
else:
self.fix_crosses[1].draw()
# Blit canvas to screen if necessary
if self.scaling:
self.fbo.end_render()
self.canvas.blit(0, 0)
self.window.switch_to()
self.window.dispatch_events()
self.window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to lists
if self.disp_ops['logtime']:
self.timestamps.append(self.timer.elapsed())
elif self.disp_ops['logdur']:
self.timestamps.append('')
if self.disp_ops['logdur']:
self.durstamps.append(self.dur.restart())
elif self.disp_ops['logtime']:
self.durstamps.append('')
# Send trigger ASAP after flip
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
if self.encode_events() > 0:
trigger.send(trigser, trigpar, self.encode_events())
# Log when triggers are sent
if self.disp_ops['logtime'] and self.encode_events() > 0:
self.trigstamps.append(self.encode_events())
else:
self.trigstamps.append('')
# Clear canvas, events, prepare for next frame
if self.scaling:
self.fbo.start_render()
self.fbo.clear()
else:
self.window.clear()
- self.events = self.__class__.DEFAULTS['events']
+ self.events = copy.deepcopy(self.__class__.DEFAULTS['events'])
self._count += 1
def stop(self):
"""Clean up RunState."""
if self.disp_ops['eyetrack']:
eyetracking.stop()
if self.scaling:
self.fbo.delete()
del self.canvas
self.window.close()
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
trigger.quit(trigser, trigpar)
if self.disp_ops['priority'] != None:
priority.set('normal')
def encode_events(self):
"""Hard code specific trigger values for events."""
code = 0
if self.events['ord_id'] != None:
code = self.events['ord_id'] + 1
elif self.events['blk_on']:
code = 128
elif self.events['blk_off']:
code = 127
else:
mult = 0
if self.events['fix_on']:
mult = 4
elif self.events['track_on']:
mult = 3
if self.events['track_off']:
mult = 1
elif self.events['fix_off']:
mult = 2
if self.events['grp_on']:
code = 100 + mult
elif self.events['grp_off']:
code = 90 + mult
elif len(self.events['sids']) > 0:
code = ((0 in self.events['sids'])*2**0 +
(1 in self.events['sids'])*2**1 +
(2 in self.events['sids'])*2**2 +
(3 in self.events['sids'])*2**3)
code = mult * 16 + (code + 1)
- else:
+ elif mult > 0:
code = 110 + mult
return code
def log(self, path=None):
"""Write a log file for the experimental run in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, LOG_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(LOG_FMT):
path = '{0}.{1}'.format(path, LOG_FMT)
with open(path, 'wb') as logfile:
writer = csv.writer(logfile, dialect='excel-tab')
writer.writerow(['checkergen log file'])
writer.writerow(['display options:'])
writer.writerow(self.disp_ops.keys())
writer.writerow(self.disp_ops.values())
writer.writerow(['order:'] + self.order)
if self.disp_ops['eyetrack']:
write.writerow(['groups added'])
for blk in grouper(self.add_gids,
self.disp_ops['trybreak'], ''):
write.writerow(blk)
write.writerow(['groups failed'])
for blk in grouper(self.fail_gids,
self.disp_ops['trybreak'], ''):
write.writerow(blk)
if self.disp_ops['logtime'] or self.disp_ops['logdur']:
stamps = [self.timestamps, self.durstamps, self.trigstamps]
writer.writerow(['timestamps', 'durations', 'triggers'])
for stamp in zip(*stamps):
writer.writerow(list(stamp))
class CkgDisplayGroup:
DEFAULTS = OrderedDict([('pre', 0), ('disp', 'Infinity'), ('post', 0)])
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
- setattr(self, kw, self.__class__.DEFAULTS[kw])
+ setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets counts and all contained shapes."""
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, runstate):
"""Draws all contained shapes during the appropriate interval."""
for shape in self.shapes:
shape.draw(photoburst=runstate.disp_ops['photoburst'])
def update(self, runstate):
"""Updates contained shapes, sets event triggers."""
# Set events to be sent
if runstate.disp_ops['fpst'] > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
- if self._flip_count[n] >= fpst:
+ if self._flip_count[n] >= runstate.disp_ops['fpst']:
runstate.events['sids'].add(n)
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(runstate.fps)
def display(self, runstate):
"""Display the group in the context described by supplied runstate."""
self.reset()
for count in range(self.pre * runstate.fps):
if runstate.window.has_exit:
break
runstate.update()
- runstate.events['blk_on'] = True
+ runstate.events['grp_on'] = True
if runstate.disp_ops['eyetrack']:
runstate.fix_fail = False
renstate.true_fail = False
for count in range(self.disp * runstate.fps):
if runstate.window.has_exit:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
- runstate.events['blk_off'] = True
+ runstate.events['grp_off'] = True
if runstate.disp_ops['eyetrack']:
if runstate.fix_fail:
runstate.true_fail = True
for count in range(self.post * runstate.fps):
if runstate.window.has_exit:
break
runstate.update()
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
- setattr(self, kw, self.__class__.DEFAULTS[kw])
+ setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.steps_done = 0
def draw(self, runstate):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, runstate):
"""Checks for keypress, sends trigger upon end."""
if max([runstate.keystates[key] for
key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
def display(self, runstate):
"""Displays waitscreen in context described by supplied runstate."""
while self.steps_done < self.num_steps:
if runstate.window.has_exit:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = OrderedDict([('dims', (5, 5)),
('init_unit', (30, 30)),
('end_unit', (50, 50)),
('position', (0, 0)),
('anchor', 'bottomleft'),
('cols', ((0, 0, 0), (255, 255, 255))),
('freq', 1),
('phase', 0)])
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
- setattr(self, kw, self.__class__.DEFAULTS[kw])
+ setattr(self, kw, copy.deepcopy(self.__class__.DEFAULTS[kw]))
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
if INT_HALF_PERIODS:
frames_per_half_period = round(fps / (self.freq * 2))
degs_per_frame = 180 / to_decimal(frames_per_half_period)
else:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
anchor=self.anchor)
cur_unit_rect.col = self.cols[(i + j) % 2]
cur_unit_rect.add_to_batch(self._batches[0])
cur_unit_rect.col = self.cols[(i + j + 1) % 2]
cur_unit_rect.add_to_batch(self._batches[1])
# Increase x values
cur_unit_pos[0] += \
graphics.locations[self.anchor][0] * cur_unit[0]
cur_unit[0] += unit_grad[0]
# Reset x values
cur_unit_pos[0] = init_pos[0]
cur_unit[0] = init_unit[0]
# Increase y values
cur_unit_pos[1] += \
graphics.locations[self.anchor][1] * cur_unit[1]
cur_unit[1] += unit_grad[1]
self._computed = True
def draw(self, photoburst=False, always_compute=False):
"""Draws appropriate batch depending on current phase.
photoburst -- draw first color for only one frame for testing purposes
always_compute -- recompute what the checkerboard should look like
every frame
"""
if not self._computed or always_compute:
self.compute()
self._cur_phase %= 360
n = int(self._cur_phase // 180)
if photoburst and n == 0 and not self.flipped:
n = 1
self._batches[n].draw()
def lazydraw(self):
"""Only draws on color reversal."""
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if (cur_n != prev_n) or self._first_draw:
self.draw()
if self._first_draw:
self._first_draw = False
|
ztangent/checkergen
|
dcf83f4a40b579a9b3dd19d002968fd1963a5b59
|
New encoding and triggering system implemented.
|
diff --git a/src/core.py b/src/core.py
index 6d6d518..50e6ec5 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,1172 +1,1208 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import random
import itertools
from datetime import datetime
from xml.dom import minidom
import pyglet
import graphics
import priority
import trigger
import eyetracking
from utils import *
# Use OrderedDict substitute if we don't have Python 2.7
if sys.version_info < (2, 7):
from odict import OrderedDict
else:
from collections import OrderedDict
CKG_FMT = 'ckg'
LOG_FMT = 'csv'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
MAX_EXPORT_FRAMES = 100000
INT_HALF_PERIODS = True
EXPORT_FMTS = ['png']
EXPORT_DIR_SUFFIX = '-anim'
FIX_POS = (0, 0)
FIX_RANGE = (20, 20)
FIX_PER = 350
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = OrderedDict([('name', 'untitled'),
('fps', 60),
('res', (800, 600)),
('bg', (127, 127, 127)),
('export_fmt', 'png'),
('pre', 0),
('post', 0),
('cross_cols', ((0, 0, 0), (255, 0, 0))),
('cross_times', ('Infinity', 1)),
('orders', []),
('disp_ops', None)])
DEFAULTS['disp_ops'] = OrderedDict([('repeats', 1),
('waitless', False),
('fullscreen', False),
('priority', None),
('logtime', False),
('logdur', False),
('trigser', False),
('trigpar', False),
('fpst', 0),
('phototest', False),
('photoburst', False),
('eyetrack', False),
('etuser', False),
('etvideo', None),
('tryagain', 0),
('trybreak', None),
('nolog', False)])
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
export_fmt -- image format for animation to be exported as
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'export_fmt':
if value not in EXPORT_FMTS:
msg = 'image format not recognized or supported'
raise FileFormatError(msg)
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
# Vars that are dicts
dicts_to_load = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_load = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
for d_name in dicts_to_load:
d = self.__class__.DEFAULTS[d_name]
try:
d_el = [node for node in project.childNodes if
node.localName == d_name and
node.namespaceURI == XML_NAMESPACE][0]
for var in d.keys():
try:
d[var] = eval(xml_get(d_el, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}' in '{1}'".\
format(var, d_name)
print "using default value '{0}' instead...".\
format(d[var])
except IndexError:
print "warning: missing attribute set '{0}'".format(d_name)
print "using default values instead..."
setattr(self, d_name, d)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
# Vars that are dicts
dicts_to_save = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_save = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for d_name in dicts_to_save:
d_el = doc.createElement(d_name)
project.appendChild(d_el)
d = getattr(self, d_name)
for k, v in d.iteritems():
xml_set(doc, d_el, k, repr(v))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, **keywords):
"""Displays the project animation on the screen.
name -- name that logfile will be saved with
repeats -- number of times specified order of display groups should
be repeated
waitless -- if true, no waitscreens will appear at the start of each
repeat
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
priority -- priority level to which process should be raised
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
trigser -- send triggers through serial port when each group is shown
trigpar -- send triggers through parallel port when each group is shown
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- append a wait screen to the group queue every time
after this many groups have been appended to the queue
order -- order in which groups (specified by id) will be displayed
"""
# Create RunState
disp_ops = self.disp_ops
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'name' in keywords.keys() and keywords['name'] != None:
name = keywords['name']
else:
timestr = datetime.today().strftime('_%Y-%m-%d_%H-%M-%S')
name = self.name + timestr
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
waitscreen = CkgWaitScreen()
+ # Set order id to be sent if necessary
+ if order in self.orders:
+ runstate.events['ord_id'] = self.orders.index(order)
# Count through pre
for count in range(self.pre * self.fps):
if runstate.window.has_exit:
break
runstate.update()
# Loop through repeats
for i in range(runstate.disp_ops['repeats']):
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
# Loop through display groups
runstate.events['blk_on'] = True
for gid in runstate.order:
if gid == -1:
waitscreen.reset()
waitscreen.display(runstate)
else:
self.groups[gid].display(runstate)
# Append failed groups
if runstate.disp_ops['eyetrack'] and runstate.truefail:
if len(runstate.add_gids) < runstate.disp_ops['tryagain']:
runstate.add_gids.append(gid)
else:
runstate.fail_gids.append(gid)
runstate.events['blk_off'] = True
# Loop through added groups
if runstate.disp_ops['eyetrack']:
for blk in grouper(runstate.add_gids,
runstate.disp_ops['trybreak']):
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
runstate.events['blk_on'] = True
# Loop through display groups
for gid in blk:
if gid != None:
self.groups[gid].display(runstate)
runstate.events['blk_on'] = True
# Count through post
for count in range(self.post * self.fps):
if runstate.window.has_exit:
break
runstate.update()
# Stop and output log
runstate.stop()
if not runstate.disp_ops['nolog']:
runstate.log()
def export(self, export_dir, export_duration, groupq=[],
export_fmt=None, folder=True, force=False):
if not os.path.isdir(export_dir):
msg = 'export path is not a directory'
raise IOError(msg)
if export_fmt == None:
export_fmt = self.export_fmt
# Set-up groups and variables that control their display
if groupq == []:
groupq = list(self.groups)
n = -1
groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Limit export duration to display duration
frames = export_duration * self.fps
frames = min(frames, disp_end)
# Warn user if a lot of frames will be exported
if frames > MAX_EXPORT_FRAMES and not force:
msg = 'very large number ({0}) of frames to be exported'.\
format(frames)
raise FrameOverflowError(msg)
# Create folder to store images if necessary
if folder:
export_dir = os.path.join(export_dir,
self.name + EXPORT_DIR_SUFFIX)
if not os.path.isdir(export_dir):
os.mkdir(export_dir)
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Set up canvas and framebuffer object
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
# Main loop
while count < frames:
fbo.clear()
if groups_visible:
# Get next group from queue
if n < 0 or groupq[n].over:
n += 1
if n >= len(groupq):
groups_visible = False
else:
groupq[n].reset()
# Draw and then update group
if n >= 0:
groupq[n].draw()
groupq[n].update(fps=self.fps, fpst=0)
# Draw fixation cross based on current count
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Save current frame to file
savepath = \
os.path.join(export_dir,
'{0}{2}.{1}'.
format(self.name, export_fmt,
repr(count).zfill(numdigits(frames-1))))
canvas.save(savepath)
# Increment count and set whether groups should be shown
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
fbo.delete()
class CkgRunState:
"""Contains information about the state of a checkergen project
when it is being displayed or exported."""
DEFAULTS = dict([('name', 'untitled'),
('res', None),
('fps', None),
('bg', None),
('cross_cols', None),
('cross_times', None),
('order', []),
('disp_ops', None),
('events', None),
('add_gids', []),
('fail_gids', []),
('timestamps', []),
('durstamps', []),
('trigstamps', [])])
- DEFAULTS['events'] = dict([('blk_on', False),
+ DEFAULTS['events'] = dict([('ord_id', None),
+ ('blk_on', False),
('blk_off', False),
('track_on', False),
('track_off', False),
('fix_on', False),
('fix_off', False),
('grp_on', False),
('grp_off', False),
('sids', set())])
def __init__(self, **keywords):
"""Creates the RunState."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
def start(self):
"""Initialize all subsystems and start the run."""
if self.disp_ops == None:
msg = "RunState lacks display options"
raise ValueError(msg)
if min(self.res, self.fps, self.bg,
self.cross_cols, self.cross_times) == None:
msg = "RunState intialized with insufficent project information"
raise ValueError(msg)
self._count = 0
# Create fixation crosses
self.fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if self.disp_ops['phototest']:
self.test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Initialize ports
if self.disp_ops['trigser']:
if not trigger.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trigpar']:
if not trigger.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
trigger.init(self.disp_ops['trigser'], self.disp_ops['trigpar'])
# Initialize eyetracking
if self.disp_ops['eyetrack']:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trybreak'] == None:
self.disp_ops['trybreak'] = len(self.order)
self.fixated = False
self.old_fixated = False
self.tracked = False
self.old_tracked = False
self.fix_fail = False
self.true_fail = False
eyetracking.select_source(self.disp_ops['etuser'],
self.disp_ops['etvideo'])
eyetracking.start()
# Stretch to fit screen only if project res does not equal screen res
self.scaling = False
if self.disp_ops['fullscreen']:
self.window = pyglet.window.Window(fullscreen=True, visible=False)
if (self.window.width, self.window.height) != self.res:
self.scaling = True
else:
self.window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
self.keystates = pyglet.window.key.KeyStateHandler()
self.window.push_handlers(self.keystates)
# Clear window and make visible
self.window.switch_to()
graphics.set_clear_color(self.bg)
self.window.clear()
self.window.set_visible()
# Create framebuffer object for drawing unscaled scene
if self.scaling:
self.canvas = pyglet.image.Texture.create(*self.res)
self.fbo = graphics.Framebuffer(self.canvas)
self.fbo.start_render()
graphics.set_clear_color(self.bg)
self.fbo.clear()
# Set process priority
if self.disp_ops['priority'] != None:
if not priority.available[sys.platform]:
msg = "setting priority not available on {0}".\
format(sys.platform)
raise NotImplementedError(msg)
else:
if self.disp_ops['priority'].isdigit():
self.disp_ops['priority'] = int(self.disp_ops['priority'])
priority.set(self.disp_ops['priority'])
# Start timers
if self.disp_ops['logtime']:
self.timer = Timer()
self.timer.start()
if self.disp_ops['logdur']:
self.dur = Timer()
self.dur.start()
def update(self):
"""Update the RunState."""
# Check for tracking and fixation
if self.disp_ops['eyetrack']:
self.old_tracked = self.tracked
self.tracked = eyetracking.is_tracked()
self.old_fixated = self.fixated
self.fixated = eyetracking.is_fixated(FIX_POS, FIX_RANGE, FIX_PER)
if self.fixated:
# Draw normal cross color if fixating
self.fix_crosses[0].draw()
else:
# Draw alternative cross color if not fixating
self.fix_crosses[1].draw()
# Update eyetracking events
if self.tracked != self.old_tracked:
if self.tracked:
self.events['track_on'] = True
else:
self.events['track_off'] = True
if self.fixated != self.old_fixated:
if self.fixated:
self.events['fix_on'] = True
else:
self.events['fix_off'] = True
# Check for failure of trial
if self.tracked and not self.fixated:
self.fix_fail = True
else:
# Change cross color based on time
if (self._count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
self.fix_crosses[0].draw()
else:
self.fix_crosses[1].draw()
# Blit canvas to screen if necessary
if self.scaling:
self.fbo.end_render()
self.canvas.blit(0, 0)
self.window.switch_to()
self.window.dispatch_events()
self.window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to lists
if self.disp_ops['logtime']:
self.timestamps.append(self.timer.elapsed())
elif self.disp_ops['logdur']:
self.timestamps.append('')
if self.disp_ops['logdur']:
self.durstamps.append(self.dur.restart())
elif self.disp_ops['logtime']:
self.durstamps.append('')
# Send trigger ASAP after flip
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
- trigger.send(trigser, trigpar, self.encode_events())
+ if self.encode_events() > 0:
+ trigger.send(trigser, trigpar, self.encode_events())
# Log when triggers are sent
- if (self.disp_ops['logtime'] and
- (self.disp_ops['trigser'] or self.disp_ops['trigpar']) and
- self.encode_events() != None):
+ if self.disp_ops['logtime'] and self.encode_events() > 0:
self.trigstamps.append(self.encode_events())
else:
self.trigstamps.append('')
# Clear canvas, events, prepare for next frame
if self.scaling:
self.fbo.start_render()
self.fbo.clear()
else:
self.window.clear()
self.events = self.__class__.DEFAULTS['events']
self._count += 1
def stop(self):
"""Clean up RunState."""
if self.disp_ops['eyetrack']:
eyetracking.stop()
if self.scaling:
self.fbo.delete()
del self.canvas
self.window.close()
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
trigger.quit(trigser, trigpar)
if self.disp_ops['priority'] != None:
priority.set('normal')
+ def encode_events(self):
+ """Hard code specific trigger values for events."""
+ code = 0
+ if self.events['ord_id'] != None:
+ code = self.events['ord_id'] + 1
+ elif self.events['blk_on']:
+ code = 128
+ elif self.events['blk_off']:
+ code = 127
+ else:
+ mult = 0
+ if self.events['fix_on']:
+ mult = 4
+ elif self.events['track_on']:
+ mult = 3
+ if self.events['track_off']:
+ mult = 1
+ elif self.events['fix_off']:
+ mult = 2
+ if self.events['grp_on']:
+ code = 100 + mult
+ elif self.events['grp_off']:
+ code = 90 + mult
+ elif len(self.events['sids']) > 0:
+ code = ((0 in self.events['sids'])*2**0 +
+ (1 in self.events['sids'])*2**1 +
+ (2 in self.events['sids'])*2**2 +
+ (3 in self.events['sids'])*2**3)
+ code = mult * 16 + (code + 1)
+ else:
+ code = 110 + mult
+ return code
+
def log(self, path=None):
"""Write a log file for the experimental run in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, LOG_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(LOG_FMT):
path = '{0}.{1}'.format(path, LOG_FMT)
with open(path, 'wb') as logfile:
writer = csv.writer(logfile, dialect='excel-tab')
writer.writerow(['checkergen log file'])
writer.writerow(['display options:'])
writer.writerow(self.disp_ops.keys())
writer.writerow(self.disp_ops.values())
writer.writerow(['order:'] + self.order)
if self.disp_ops['eyetrack']:
write.writerow(['groups added'])
for blk in grouper(self.add_gids,
self.disp_ops['trybreak'], ''):
write.writerow(blk)
write.writerow(['groups failed'])
for blk in grouper(self.fail_gids,
self.disp_ops['trybreak'], ''):
write.writerow(blk)
if self.disp_ops['logtime'] or self.disp_ops['logdur']:
stamps = [self.timestamps, self.durstamps, self.trigstamps]
writer.writerow(['timestamps', 'durations', 'triggers'])
for stamp in zip(*stamps):
writer.writerow(list(stamp))
class CkgDisplayGroup:
DEFAULTS = OrderedDict([('pre', 0), ('disp', 'Infinity'), ('post', 0)])
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets counts and all contained shapes."""
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, runstate):
"""Draws all contained shapes during the appropriate interval."""
for shape in self.shapes:
shape.draw(photoburst=runstate.disp_ops['photoburst'])
def update(self, runstate):
"""Updates contained shapes, sets event triggers."""
# Set events to be sent
if runstate.disp_ops['fpst'] > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= fpst:
runstate.events['sids'].add(n)
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(runstate.fps)
def display(self, runstate):
"""Display the group in the context described by supplied runstate."""
self.reset()
for count in range(self.pre * runstate.fps):
if runstate.window.has_exit:
break
runstate.update()
runstate.events['blk_on'] = True
if runstate.disp_ops['eyetrack']:
runstate.fix_fail = False
renstate.true_fail = False
for count in range(self.disp * runstate.fps):
if runstate.window.has_exit:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
runstate.events['blk_off'] = True
if runstate.disp_ops['eyetrack']:
if runstate.fix_fail:
runstate.true_fail = True
for count in range(self.post * runstate.fps):
if runstate.window.has_exit:
break
runstate.update()
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.steps_done = 0
def draw(self, runstate):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, runstate):
"""Checks for keypress, sends trigger upon end."""
if max([runstate.keystates[key] for
key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
def display(self, runstate):
"""Displays waitscreen in context described by supplied runstate."""
while self.steps_done < self.num_steps:
if runstate.window.has_exit:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = OrderedDict([('dims', (5, 5)),
('init_unit', (30, 30)),
('end_unit', (50, 50)),
('position', (0, 0)),
('anchor', 'bottomleft'),
('cols', ((0, 0, 0), (255, 255, 255))),
('freq', 1),
('phase', 0)])
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
if INT_HALF_PERIODS:
frames_per_half_period = round(fps / (self.freq * 2))
degs_per_frame = 180 / to_decimal(frames_per_half_period)
else:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
anchor=self.anchor)
cur_unit_rect.col = self.cols[(i + j) % 2]
cur_unit_rect.add_to_batch(self._batches[0])
cur_unit_rect.col = self.cols[(i + j + 1) % 2]
cur_unit_rect.add_to_batch(self._batches[1])
# Increase x values
cur_unit_pos[0] += \
graphics.locations[self.anchor][0] * cur_unit[0]
cur_unit[0] += unit_grad[0]
# Reset x values
cur_unit_pos[0] = init_pos[0]
cur_unit[0] = init_unit[0]
# Increase y values
cur_unit_pos[1] += \
graphics.locations[self.anchor][1] * cur_unit[1]
cur_unit[1] += unit_grad[1]
self._computed = True
def draw(self, photoburst=False, always_compute=False):
"""Draws appropriate batch depending on current phase.
photoburst -- draw first color for only one frame for testing purposes
always_compute -- recompute what the checkerboard should look like
every frame
"""
if not self._computed or always_compute:
self.compute()
self._cur_phase %= 360
n = int(self._cur_phase // 180)
if photoburst and n == 0 and not self.flipped:
n = 1
self._batches[n].draw()
def lazydraw(self):
"""Only draws on color reversal."""
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if (cur_n != prev_n) or self._first_draw:
self.draw()
if self._first_draw:
self._first_draw = False
diff --git a/src/trigger.py b/src/trigger.py
index b0d7540..b8bd243 100644
--- a/src/trigger.py
+++ b/src/trigger.py
@@ -1,109 +1,79 @@
"""Module for sending triggers upon various events through the serial or
parallel ports."""
-NULL_STATE = {'block': 0, 'tracking': 0, 'fixation': 0,
- 'group': 0, 'shape': 0, 'gid': 0, 'sid': 0,
- 'event': 0}
-CUR_STATE = dict(NULL_STATE)
-PREV_STATE = dict(NULL_STATE)
-
SERPORT = None
PARPORT = None
available = {'serial': False, 'parallel': False}
try:
import serial
try:
test_port = serial.Serial(0)
test_port.close()
del test_port
available['serial'] = True
except serial.serialutil.SerialException:
pass
except ImportError:
pass
try:
import parallel
try:
test_port = parallel.Parallel()
del test_port
available['parallel'] = True
except:
pass
except ImportError:
pass
if available['serial']:
def ser_init():
global SERPORT
SERPORT = serial.Serial(0)
- def ser_send(statebyte):
+ def ser_send(code):
global SERPORT
- SERPORT.write(statebyte)
+ SERPORT.write(code)
def ser_quit():
global SERPORT
SERPORT.close()
SERPORT = None
if available['parallel']:
def par_init():
global PARPORT
PARPORT = parallel.Parallel()
PARPORT.setData(0)
- def par_send(statebyte):
+ def par_send(code):
global PARPORT
- PARPORT.setData(statebyte)
+ PARPORT.setData(code)
def par_quit():
global PARPORT
PARPORT.setData(0)
PARPORT = None
def init(trigser, trigpar):
- global CUR_STATE
- global PREV_STATE
- CUR_STATE = NULL_STATE
- PREV_STATE = NULL_STATE
if trigser:
ser_init()
if trigpar:
par_init()
-def set_state(fieldname, value):
- global CUR_STATE
- global PREV_STATE
- PREV_STATE = CUR_STATE
- CUR_STATE[fieldname] = value
- CUR_STATE['event'] = 1
-
-def set_null():
- set_state(NULL_STATE)
-
-def send(trigser, trigpar):
- statebyte = ''.join([str(CUR_STATE[name]) for
- name in ['block', 'tracking', 'fixation',
- 'group', 'shape']]).ljust(8,'0')
- statebyte = int(statebyte, 2)
- # Preferentially send group id over shape id
- if CUR_STATE['group'] != PREV_STATE['group']:
- statebyte += CUR_STATE['gid'] + 1
- elif CUR_STATE['shape'] > PREV_STATE['shape']:
- statebyte += CUR_STATE['sid']
- if CUR_STATE != PREV_STATE:
- if trigser:
- ser_send(statebyte)
- if trigpar:
- par_send(statebyte)
+def send(trigser, trigpar, code):
+ if trigser:
+ ser_send(code)
+ if trigpar:
+ par_send(code)
def quit(trigser, trigpar):
- set_null()
+ send(trigser, trigpar, 0)
if trigser:
ser_quit()
if trigpar:
par_quit()
|
ztangent/checkergen
|
ee58d7bccf229d9240423b5565cf81f889127e66
|
Remove prerender to texture functionality.
|
diff --git a/src/core.py b/src/core.py
index cb32f06..6d6d518 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,554 +1,553 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import random
import itertools
from datetime import datetime
from xml.dom import minidom
import pyglet
import graphics
import priority
import trigger
import eyetracking
from utils import *
# Use OrderedDict substitute if we don't have Python 2.7
if sys.version_info < (2, 7):
from odict import OrderedDict
else:
from collections import OrderedDict
CKG_FMT = 'ckg'
LOG_FMT = 'csv'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
MAX_EXPORT_FRAMES = 100000
-PRERENDER_TO_TEXTURE = False
INT_HALF_PERIODS = True
EXPORT_FMTS = ['png']
EXPORT_DIR_SUFFIX = '-anim'
FIX_POS = (0, 0)
FIX_RANGE = (20, 20)
FIX_PER = 350
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = OrderedDict([('name', 'untitled'),
('fps', 60),
('res', (800, 600)),
('bg', (127, 127, 127)),
('export_fmt', 'png'),
('pre', 0),
('post', 0),
('cross_cols', ((0, 0, 0), (255, 0, 0))),
('cross_times', ('Infinity', 1)),
('orders', []),
('disp_ops', None)])
DEFAULTS['disp_ops'] = OrderedDict([('repeats', 1),
('waitless', False),
('fullscreen', False),
('priority', None),
('logtime', False),
('logdur', False),
('trigser', False),
('trigpar', False),
('fpst', 0),
('phototest', False),
('photoburst', False),
('eyetrack', False),
('etuser', False),
('etvideo', None),
('tryagain', 0),
('trybreak', None),
('nolog', False)])
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
export_fmt -- image format for animation to be exported as
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'export_fmt':
if value not in EXPORT_FMTS:
msg = 'image format not recognized or supported'
raise FileFormatError(msg)
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
# Vars that are dicts
dicts_to_load = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_load = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
for d_name in dicts_to_load:
d = self.__class__.DEFAULTS[d_name]
try:
d_el = [node for node in project.childNodes if
node.localName == d_name and
node.namespaceURI == XML_NAMESPACE][0]
for var in d.keys():
try:
d[var] = eval(xml_get(d_el, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}' in '{1}'".\
format(var, d_name)
print "using default value '{0}' instead...".\
format(d[var])
except IndexError:
print "warning: missing attribute set '{0}'".format(d_name)
print "using default values instead..."
setattr(self, d_name, d)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
# Vars that are dicts
dicts_to_save = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_save = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for d_name in dicts_to_save:
d_el = doc.createElement(d_name)
project.appendChild(d_el)
d = getattr(self, d_name)
for k, v in d.iteritems():
xml_set(doc, d_el, k, repr(v))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, **keywords):
"""Displays the project animation on the screen.
name -- name that logfile will be saved with
repeats -- number of times specified order of display groups should
be repeated
waitless -- if true, no waitscreens will appear at the start of each
repeat
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
priority -- priority level to which process should be raised
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
trigser -- send triggers through serial port when each group is shown
trigpar -- send triggers through parallel port when each group is shown
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- append a wait screen to the group queue every time
after this many groups have been appended to the queue
order -- order in which groups (specified by id) will be displayed
"""
# Create RunState
disp_ops = self.disp_ops
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'name' in keywords.keys() and keywords['name'] != None:
name = keywords['name']
else:
timestr = datetime.today().strftime('_%Y-%m-%d_%H-%M-%S')
name = self.name + timestr
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
waitscreen = CkgWaitScreen()
# Count through pre
for count in range(self.pre * self.fps):
if runstate.window.has_exit:
break
runstate.update()
# Loop through repeats
for i in range(runstate.disp_ops['repeats']):
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
# Loop through display groups
runstate.events['blk_on'] = True
for gid in runstate.order:
if gid == -1:
waitscreen.reset()
waitscreen.display(runstate)
else:
self.groups[gid].display(runstate)
# Append failed groups
if runstate.disp_ops['eyetrack'] and runstate.truefail:
if len(runstate.add_gids) < runstate.disp_ops['tryagain']:
runstate.add_gids.append(gid)
else:
runstate.fail_gids.append(gid)
runstate.events['blk_off'] = True
# Loop through added groups
if runstate.disp_ops['eyetrack']:
for blk in grouper(runstate.add_gids,
runstate.disp_ops['trybreak']):
# Show waitscreen
if not runstate.disp_ops['waitless']:
waitscreen.reset()
waitscreen.display(runstate)
runstate.events['blk_on'] = True
# Loop through display groups
for gid in blk:
if gid != None:
self.groups[gid].display(runstate)
runstate.events['blk_on'] = True
# Count through post
for count in range(self.post * self.fps):
if runstate.window.has_exit:
break
runstate.update()
# Stop and output log
runstate.stop()
if not runstate.disp_ops['nolog']:
runstate.log()
def export(self, export_dir, export_duration, groupq=[],
export_fmt=None, folder=True, force=False):
if not os.path.isdir(export_dir):
msg = 'export path is not a directory'
raise IOError(msg)
if export_fmt == None:
export_fmt = self.export_fmt
# Set-up groups and variables that control their display
if groupq == []:
groupq = list(self.groups)
n = -1
groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Limit export duration to display duration
frames = export_duration * self.fps
frames = min(frames, disp_end)
# Warn user if a lot of frames will be exported
if frames > MAX_EXPORT_FRAMES and not force:
msg = 'very large number ({0}) of frames to be exported'.\
format(frames)
raise FrameOverflowError(msg)
# Create folder to store images if necessary
if folder:
export_dir = os.path.join(export_dir,
self.name + EXPORT_DIR_SUFFIX)
if not os.path.isdir(export_dir):
os.mkdir(export_dir)
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Set up canvas and framebuffer object
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
# Main loop
while count < frames:
fbo.clear()
if groups_visible:
# Get next group from queue
if n < 0 or groupq[n].over:
n += 1
if n >= len(groupq):
groups_visible = False
else:
groupq[n].reset()
# Draw and then update group
if n >= 0:
groupq[n].draw()
groupq[n].update(fps=self.fps, fpst=0)
# Draw fixation cross based on current count
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Save current frame to file
savepath = \
os.path.join(export_dir,
'{0}{2}.{1}'.
format(self.name, export_fmt,
repr(count).zfill(numdigits(frames-1))))
canvas.save(savepath)
# Increment count and set whether groups should be shown
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
fbo.delete()
class CkgRunState:
"""Contains information about the state of a checkergen project
when it is being displayed or exported."""
DEFAULTS = dict([('name', 'untitled'),
('res', None),
('fps', None),
('bg', None),
@@ -605,597 +604,569 @@ class CkgRunState:
self.test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Initialize ports
if self.disp_ops['trigser']:
if not trigger.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trigpar']:
if not trigger.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
trigger.init(self.disp_ops['trigser'], self.disp_ops['trigpar'])
# Initialize eyetracking
if self.disp_ops['eyetrack']:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trybreak'] == None:
self.disp_ops['trybreak'] = len(self.order)
self.fixated = False
self.old_fixated = False
self.tracked = False
self.old_tracked = False
self.fix_fail = False
self.true_fail = False
eyetracking.select_source(self.disp_ops['etuser'],
self.disp_ops['etvideo'])
eyetracking.start()
# Stretch to fit screen only if project res does not equal screen res
self.scaling = False
if self.disp_ops['fullscreen']:
self.window = pyglet.window.Window(fullscreen=True, visible=False)
if (self.window.width, self.window.height) != self.res:
self.scaling = True
else:
self.window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
self.keystates = pyglet.window.key.KeyStateHandler()
self.window.push_handlers(self.keystates)
# Clear window and make visible
self.window.switch_to()
graphics.set_clear_color(self.bg)
self.window.clear()
self.window.set_visible()
# Create framebuffer object for drawing unscaled scene
if self.scaling:
self.canvas = pyglet.image.Texture.create(*self.res)
self.fbo = graphics.Framebuffer(self.canvas)
self.fbo.start_render()
graphics.set_clear_color(self.bg)
self.fbo.clear()
# Set process priority
if self.disp_ops['priority'] != None:
if not priority.available[sys.platform]:
msg = "setting priority not available on {0}".\
format(sys.platform)
raise NotImplementedError(msg)
else:
if self.disp_ops['priority'].isdigit():
self.disp_ops['priority'] = int(self.disp_ops['priority'])
priority.set(self.disp_ops['priority'])
# Start timers
if self.disp_ops['logtime']:
self.timer = Timer()
self.timer.start()
if self.disp_ops['logdur']:
self.dur = Timer()
self.dur.start()
def update(self):
"""Update the RunState."""
# Check for tracking and fixation
if self.disp_ops['eyetrack']:
self.old_tracked = self.tracked
self.tracked = eyetracking.is_tracked()
self.old_fixated = self.fixated
self.fixated = eyetracking.is_fixated(FIX_POS, FIX_RANGE, FIX_PER)
if self.fixated:
# Draw normal cross color if fixating
self.fix_crosses[0].draw()
else:
# Draw alternative cross color if not fixating
self.fix_crosses[1].draw()
# Update eyetracking events
if self.tracked != self.old_tracked:
if self.tracked:
self.events['track_on'] = True
else:
self.events['track_off'] = True
if self.fixated != self.old_fixated:
if self.fixated:
self.events['fix_on'] = True
else:
self.events['fix_off'] = True
# Check for failure of trial
if self.tracked and not self.fixated:
self.fix_fail = True
else:
# Change cross color based on time
if (self._count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
self.fix_crosses[0].draw()
else:
self.fix_crosses[1].draw()
# Blit canvas to screen if necessary
if self.scaling:
self.fbo.end_render()
self.canvas.blit(0, 0)
self.window.switch_to()
self.window.dispatch_events()
self.window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to lists
if self.disp_ops['logtime']:
self.timestamps.append(self.timer.elapsed())
elif self.disp_ops['logdur']:
self.timestamps.append('')
if self.disp_ops['logdur']:
self.durstamps.append(self.dur.restart())
elif self.disp_ops['logtime']:
self.durstamps.append('')
# Send trigger ASAP after flip
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
trigger.send(trigser, trigpar, self.encode_events())
# Log when triggers are sent
if (self.disp_ops['logtime'] and
(self.disp_ops['trigser'] or self.disp_ops['trigpar']) and
self.encode_events() != None):
self.trigstamps.append(self.encode_events())
else:
self.trigstamps.append('')
# Clear canvas, events, prepare for next frame
if self.scaling:
self.fbo.start_render()
self.fbo.clear()
else:
self.window.clear()
self.events = self.__class__.DEFAULTS['events']
self._count += 1
def stop(self):
"""Clean up RunState."""
if self.disp_ops['eyetrack']:
eyetracking.stop()
if self.scaling:
self.fbo.delete()
del self.canvas
self.window.close()
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
trigger.quit(trigser, trigpar)
if self.disp_ops['priority'] != None:
priority.set('normal')
def log(self, path=None):
"""Write a log file for the experimental run in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, LOG_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(LOG_FMT):
path = '{0}.{1}'.format(path, LOG_FMT)
with open(path, 'wb') as logfile:
writer = csv.writer(logfile, dialect='excel-tab')
writer.writerow(['checkergen log file'])
writer.writerow(['display options:'])
writer.writerow(self.disp_ops.keys())
writer.writerow(self.disp_ops.values())
writer.writerow(['order:'] + self.order)
if self.disp_ops['eyetrack']:
write.writerow(['groups added'])
for blk in grouper(self.add_gids,
self.disp_ops['trybreak'], ''):
write.writerow(blk)
write.writerow(['groups failed'])
for blk in grouper(self.fail_gids,
self.disp_ops['trybreak'], ''):
write.writerow(blk)
if self.disp_ops['logtime'] or self.disp_ops['logdur']:
stamps = [self.timestamps, self.durstamps, self.trigstamps]
writer.writerow(['timestamps', 'durations', 'triggers'])
for stamp in zip(*stamps):
writer.writerow(list(stamp))
class CkgDisplayGroup:
DEFAULTS = OrderedDict([('pre', 0), ('disp', 'Infinity'), ('post', 0)])
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets counts and all contained shapes."""
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, runstate):
"""Draws all contained shapes during the appropriate interval."""
for shape in self.shapes:
shape.draw(photoburst=runstate.disp_ops['photoburst'])
def update(self, runstate):
"""Updates contained shapes, sets event triggers."""
# Set events to be sent
if runstate.disp_ops['fpst'] > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= fpst:
runstate.events['sids'].add(n)
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(runstate.fps)
def display(self, runstate):
"""Display the group in the context described by supplied runstate."""
self.reset()
for count in range(self.pre * runstate.fps):
if runstate.window.has_exit:
break
runstate.update()
runstate.events['blk_on'] = True
if runstate.disp_ops['eyetrack']:
runstate.fix_fail = False
renstate.true_fail = False
for count in range(self.disp * runstate.fps):
if runstate.window.has_exit:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
runstate.events['blk_off'] = True
if runstate.disp_ops['eyetrack']:
if runstate.fix_fail:
runstate.true_fail = True
for count in range(self.post * runstate.fps):
if runstate.window.has_exit:
break
runstate.update()
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.steps_done = 0
def draw(self, runstate):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, runstate):
"""Checks for keypress, sends trigger upon end."""
if max([runstate.keystates[key] for
key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
def display(self, runstate):
"""Displays waitscreen in context described by supplied runstate."""
while self.steps_done < self.num_steps:
if runstate.window.has_exit:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = OrderedDict([('dims', (5, 5)),
('init_unit', (30, 30)),
('end_unit', (50, 50)),
('position', (0, 0)),
('anchor', 'bottomleft'),
('cols', ((0, 0, 0), (255, 255, 255))),
('freq', 1),
('phase', 0)])
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
if INT_HALF_PERIODS:
frames_per_half_period = round(fps / (self.freq * 2))
degs_per_frame = 180 / to_decimal(frames_per_half_period)
else:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
- if PRERENDER_TO_TEXTURE:
- init_pos = [(1 - a)* s/to_decimal(2) for s, a in
- zip(self._size, graphics.locations[self.anchor])]
- else:
- init_pos = list(self.position)
+ init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
anchor=self.anchor)
cur_unit_rect.col = self.cols[(i + j) % 2]
cur_unit_rect.add_to_batch(self._batches[0])
cur_unit_rect.col = self.cols[(i + j + 1) % 2]
cur_unit_rect.add_to_batch(self._batches[1])
# Increase x values
cur_unit_pos[0] += \
graphics.locations[self.anchor][0] * cur_unit[0]
cur_unit[0] += unit_grad[0]
# Reset x values
cur_unit_pos[0] = init_pos[0]
cur_unit[0] = init_unit[0]
# Increase y values
cur_unit_pos[1] += \
graphics.locations[self.anchor][1] * cur_unit[1]
cur_unit[1] += unit_grad[1]
- if PRERENDER_TO_TEXTURE:
- # Create textures
- int_size = [int(round(s)) for s in self._size]
- self._prerenders =\
- [pyglet.image.Texture.create(*int_size) for n in range(2)]
- # Set up framebuffer
- fbo = graphics.Framebuffer()
- for n in range(2):
- fbo.attach_texture(self._prerenders[n])
- # Draw batch to texture
- fbo.start_render()
- self._batches[n].draw()
- fbo.end_render()
- # Anchor textures for correct blitting later
- self._prerenders[n].anchor_x, self._prerenders[n].anchor_y =\
- [int(round((1 - a)* s/to_decimal(2))) for s, a in
- zip(self._size, graphics.locations[self.anchor])]
- fbo.delete()
- # Delete batches since they won't be used
- del self._batches
-
self._computed = True
def draw(self, photoburst=False, always_compute=False):
- """Draws appropriate prerender depending on current phase.
+ """Draws appropriate batch depending on current phase.
photoburst -- draw first color for only one frame for testing purposes
always_compute -- recompute what the checkerboard should look like
every frame
"""
if not self._computed or always_compute:
self.compute()
self._cur_phase %= 360
n = int(self._cur_phase // 180)
if photoburst and n == 0 and not self.flipped:
n = 1
- if PRERENDER_TO_TEXTURE:
- self._prerenders[n].blit(*self.position)
- else:
- self._batches[n].draw()
+ self._batches[n].draw()
def lazydraw(self):
"""Only draws on color reversal."""
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if (cur_n != prev_n) or self._first_draw:
self.draw()
if self._first_draw:
self._first_draw = False
|
ztangent/checkergen
|
e38ab9b2e8607f5e3fd784ac98f70a67fa69a4bc
|
waitless, nolog and name options working for do_display.
|
diff --git a/example.ckg b/example.ckg
index afa344b..d366c5e 100644
--- a/example.ckg
+++ b/example.ckg
@@ -1,74 +1,76 @@
<?xml version="1.0" ?>
<project xmlns="http://github.com/ZOMGxuan/checkergen">
<fps>Decimal('60')</fps>
<res>(800, 600)</res>
<bg>(127, 127, 127)</bg>
<export_fmt>'png'</export_fmt>
<pre>Decimal('0')</pre>
<post>Decimal('0')</post>
<cross_cols>((0, 0, 0), (255, 0, 0))</cross_cols>
<cross_times>(Decimal('Infinity'), Decimal('1'))</cross_times>
<orders>[]</orders>
<disp_ops>
+ <repeats>1</repeats>
+ <waitless>False</waitless>
<fullscreen>False</fullscreen>
<priority>None</priority>
<logtime>False</logtime>
<logdur>False</logdur>
<trigser>False</trigser>
<trigpar>False</trigpar>
<fpst>0</fpst>
<phototest>False</phototest>
<photoburst>False</photoburst>
<eyetrack>False</eyetrack>
<etuser>False</etuser>
<etvideo>None</etvideo>
<tryagain>0</tryagain>
<trybreak>None</trybreak>
- <repeats>1</repeats>
+ <nolog>False</nolog>
</disp_ops>
<group>
<pre>Decimal('2')</pre>
<disp>Decimal('10')</disp>
<post>Decimal('2')</post>
<shape type="board">
<dims>(5, 5)</dims>
<init_unit>(Decimal('40'), Decimal('40'))</init_unit>
<end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<position>(Decimal('420'), Decimal('320'))</position>
<anchor>'bottomleft'</anchor>
<cols>((0, 0, 0), (255, 255, 255))</cols>
<freq>Decimal('1')</freq>
<phase>Decimal('0')</phase>
</shape>
<shape type="board">
<dims>(5, 5)</dims>
<init_unit>(Decimal('40'), Decimal('40'))</init_unit>
<end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<position>(Decimal('380'), Decimal('320'))</position>
<anchor>'bottomright'</anchor>
<cols>((0, 0, 0), (255, 255, 255))</cols>
<freq>Decimal('2')</freq>
<phase>Decimal('90')</phase>
</shape>
<shape type="board">
<dims>(5, 5)</dims>
<init_unit>(Decimal('40'), Decimal('40'))</init_unit>
<end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<position>(Decimal('420'), Decimal('280'))</position>
<anchor>'topleft'</anchor>
<cols>((0, 0, 0), (255, 255, 255))</cols>
<freq>Decimal('3')</freq>
<phase>Decimal('180')</phase>
</shape>
<shape type="board">
<dims>(5, 5)</dims>
<init_unit>(Decimal('40'), Decimal('40'))</init_unit>
<end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<position>(Decimal('380'), Decimal('280'))</position>
<anchor>'topright'</anchor>
<cols>((0, 0, 0), (255, 255, 255))</cols>
<freq>Decimal('4')</freq>
<phase>Decimal('270')</phase>
</shape>
</group>
</project>
diff --git a/src/cli.py b/src/cli.py
index bb103b0..9a4f5a1 100644
--- a/src/cli.py
+++ b/src/cli.py
@@ -235,821 +235,830 @@ class CkgCmd(cmd.Cmd):
set_parser.add_argument('--cross_times', metavar='TIME1,TIME2',
action=store_tuple(2, ',', to_decimal),
help='''time in seconds each cross color
will be displayed''')
def help_set(self):
self.__class__.set_parser.print_help()
def do_set(self, line):
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
try:
args = self.__class__.set_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.set_parser.print_usage()
return
names = public_dir(args)
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
setattr(self.cur_proj, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.set_parser.print_usage()
mkgrp_parser = CmdParser(add_help=False, prog='mkgrp',
formatter_class=
argparse.ArgumentDefaultsHelpFormatter,
description='''Makes a new display group
with the given parameters.''')
mkgrp_parser.add_argument('pre', type=to_decimal, default=0, nargs='?',
help='''time in seconds a blank screen will
be shown before shapes are displayed''')
mkgrp_parser.add_argument('disp', type=to_decimal,
nargs='?', default='Infinity',
help='''time in seconds shapes will be
displayed''')
mkgrp_parser.add_argument('post', type=to_decimal, default=0, nargs='?',
help='''time in seconds a blank screen will
be shown after shapes are displayed''')
def help_mkgrp(self):
self.__class__.mkgrp_parser.print_help()
def do_mkgrp(self, line):
"""Makes a display group with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
try:
args = self.__class__.mkgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mkgrp_parser.print_usage()
return
group_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_group = core.CkgDisplayGroup(**group_dict)
new_id = self.cur_proj.add_group(new_group)
print "display group", new_id, "added"
self.cur_group = new_group
print "group", new_id, "is now the current display group"
edgrp_parser = CmdParser(add_help=False, prog='edgrp',
description='''Edits attributes of display groups
specified by ids.''')
edgrp_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='ids of display groups to be edited')
edgrp_parser.add_argument('--pre', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown before shapes are displayed''')
edgrp_parser.add_argument('--disp', type=to_decimal, metavar='SECONDS',
help='''time in seconds shapes will be
displayed''')
edgrp_parser.add_argument('--post', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown after shapes are displayed''')
def help_edgrp(self):
self.__class__.edgrp_parser.print_help()
def do_edgrp(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.edgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.edgrp_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_proj.groups) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_group_attr(x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.edgrp_parser.print_usage()
rmgrp_parser = CmdParser(add_help=False, prog='rmgrp',
description='''Removes display groups specified
by ids.''')
rmgrp_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='ids of display groups to be removed')
rmgrp_parser.add_argument('-a', '--all', action='store_true',
help='remove all groups from the project')
def help_rmgrp(self):
self.__class__.rmgrp_parser.print_help()
def do_rmgrp(self, line):
"""Removes display groups specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups to remove'
return
try:
args = self.__class__.rmgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rmgrp_parser.print_usage()
return
rmlist = []
if args.all:
for group in self.cur_proj.groups[:]:
self.cur_proj.del_group(group)
print "all display groups removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_proj.groups) or x < 0:
print "display group", x, "does not exist"
continue
rmlist.append(self.cur_proj.groups[x])
print "display group", x, "removed"
for group in rmlist:
self.cur_proj.del_group(group)
# Remember to point self.cur_group somewhere sane
if self.cur_group not in self.cur_proj.groups:
if len(self.cur_proj.groups) == 0:
self.cur_group = None
else:
self.cur_group = self.cur_proj.groups[0]
print "group 0 is now the current display group"
chgrp_parser = CmdParser(add_help=False, prog='chgrp',
description='''Changes display group that is
currently active for editing.
Prints current group id if
no group id is specified''')
chgrp_parser.add_argument('gid', metavar='id', type=int, nargs='?',
help='id of display group to be made active')
def help_chgrp(self):
self.__class__.chgrp_parser.print_help()
def do_chgrp(self, line):
"""Changes group that is currently active for editing."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups that can be made active'
return
try:
args = self.__class__.chgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.chgrp_parser.print_usage()
return
if args.gid == None:
print "group",\
self.cur_proj.groups.index(self.cur_group),\
"is the current display group"
elif args.gid >= len(self.cur_proj.groups) or args.gid < 0:
print "group", args.gid, "does not exist"
else:
self.cur_group = self.cur_proj.groups[args.gid]
print "group", args.gid, "is now the current display group"
mk_parser = CmdParser(add_help=False, prog='mk',
description='''Makes a new checkerboard in the
current group with the given
parameters.''')
mk_parser.add_argument('dims', action=store_tuple(2, ',', to_decimal),
help='''width,height of checkerboard in no. of
unit cells''')
mk_parser.add_argument('init_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of initial unit cell in pixels')
mk_parser.add_argument('end_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of final unit cell in pixels')
mk_parser.add_argument('position', action=store_tuple(2, ',', to_decimal),
help='x,y position of checkerboard in pixels')
mk_parser.add_argument('anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='anchor')
mk_parser.add_argument('cols', action=store_tuple(2, ',', to_color, [';']),
help='''color1,color2 of the checkerboard
(color format: R;G;B,
component range from 0-255)''')
mk_parser.add_argument('freq', type=to_decimal,
help='frequency of color reversal in Hz')
mk_parser.add_argument('phase', type=to_decimal, nargs='?', default='0',
help='initial phase of animation in degrees')
def help_mk(self):
self.__class__.mk_parser.print_help()
def do_mk(self, line):
"""Makes a checkerboard with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
if self.cur_group == None:
print 'automatically adding display group...'
self.do_mkgrp('')
try:
args = self.__class__.mk_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mk_parser.print_usage()
return
shape_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_shape = core.CheckerBoard(**shape_dict)
new_id = self.cur_proj.add_shape_to_group(self.cur_group, new_shape)
print "checkerboard", new_id, "added"
ed_parser = CmdParser(add_help=False, prog='ed',
description='''Edits attributes of checkerboards
specified by ids.''')
ed_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='''ids of checkerboards in the current
group to be edited''')
ed_parser.add_argument('--dims', action=store_tuple(2, ',', to_decimal),
help='checkerboard dimensions in unit cells',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--init_unit',
action=store_tuple(2, ',', to_decimal),
help='initial unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--end_unit',
action=store_tuple(2, ',', to_decimal),
help='final unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--position',
action=store_tuple(2, ',', to_decimal),
help='position of checkerboard in pixels',
metavar='X,Y')
ed_parser.add_argument('--anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='LOCATION')
ed_parser.add_argument('--cols', metavar='COLOR1,COLOR2',
action=store_tuple(2, ',', to_color, [';']),
help='''checkerboard colors (color format:
R;G;B, component range
from 0-255)''')
ed_parser.add_argument('--freq', type=to_decimal,
help='frequency of color reversal in Hz')
ed_parser.add_argument('--phase', type=to_decimal,
help='initial phase of animation in degrees')
def help_ed(self):
self.__class__.ed_parser.print_help()
def do_ed(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, please create one first'
return
try:
args = self.__class__.ed_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ed_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_group.shapes) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_shape_attr(self.cur_group, x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.ed_parser.print_usage()
rm_parser = CmdParser(add_help=False, prog='rm',
description='''Removes checkerboards specified
by ids.''')
rm_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''ids of checkerboards in the current group
to be removed''')
rm_parser.add_argument('-a', '--all', action='store_true',
help='''remove all checkerboards in the
current group''')
def help_rm(self):
self.__class__.rm_parser.print_help()
def do_rm(self, line):
"""Removes checkerboards specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, no boards to remove'
return
try:
args = self.__class__.rm_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rm_parser.print_usage()
return
rmlist = []
if args.all:
for shape in self.cur_group.shapes:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
print "all checkerboards removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_group.shapes) or x < 0:
print "checkerboard", x, "does not exist"
continue
rmlist.append(self.cur_group.shapes[x])
print "checkerboard", x, "removed"
for shape in rmlist:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
ls_parser = CmdParser(add_help=False, prog='ls',
description='''Lists project, display group and
checkerboard settings. If no group ids
are specified, all display groups
are listed.''')
ls_parser.add_argument('gidlist', nargs='*', metavar='gid', type=int,
help='''ids of the display groups to be listed''')
ls_group = ls_parser.add_mutually_exclusive_group()
ls_group.add_argument('-s', '--settings', action='store_true',
help='list only project settings')
ls_group.add_argument('-g', '--groups', action='store_true',
help='list only display groups')
def help_ls(self):
self.__class__.ls_parser.print_help()
def do_ls(self, line):
"""Lists project, display group and checkerboard settings."""
def ls_str(s, seps=[',',';']):
"""Special space-saving output formatter."""
if type(s) in [tuple, list]:
if len(seps) > 1:
newseps = seps[1:]
else:
newseps = seps
return seps[0].join([ls_str(i, newseps) for i in s])
else:
return str(s)
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.ls_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ls_parser.print_usage()
return
# Remove duplicates and ascending sort
args.gidlist = sorted(set(args.gidlist))
if len(self.cur_proj.groups) == 0:
if len(args.gidlist) > 0:
print 'this project has no display groups that can be listed'
args.settings = True
else:
for gid in args.gidlist[:]:
if gid >= len(self.cur_proj.groups) or gid < 0:
args.gidlist.remove(gid)
print 'display group', gid, 'does not exist'
if args.gidlist == []:
args.gidlist = range(len(self.cur_proj.groups))
else:
# If any (valid) groups are specified
# don't show project settings
args.groups = True
if not args.groups:
print 'PROJECT SETTINGS'.center(70,'*')
print \
'name'.rjust(16),\
'fps'.rjust(7),\
'resolution'.rjust(14),\
'bg color'.rjust(18)
# 'format'.rjust(7)
print \
ls_str(self.cur_proj.name).rjust(16),\
ls_str(self.cur_proj.fps).rjust(7),\
ls_str(self.cur_proj.res).rjust(14),\
ls_str(self.cur_proj.bg).rjust(18)
# ls_str(self.cur_proj.export_fmt).rjust(7)
print \
'pre-display'.rjust(26),\
'post-display'.rjust(26)
print \
ls_str(self.cur_proj.pre).rjust(26),\
ls_str(self.cur_proj.post).rjust(26)
print \
'cross colors'.rjust(26),\
'cross times'.rjust(26)
print \
ls_str(self.cur_proj.cross_cols).rjust(26),\
ls_str(self.cur_proj.cross_times).rjust(26)
if not args.settings and not args.groups:
# Insert empty line if both groups and project
# settings are listed
print ''
if not args.settings:
for i, n in enumerate(args.gidlist):
if i != 0:
# Print newline seperator between each group
print ''
group = self.cur_proj.groups[n]
print 'GROUP {n}'.format(n=n).center(70,'*')
print \
'pre-display'.rjust(20),\
'display'.rjust(20),\
'post-display'.rjust(20)
print \
ls_str(group.pre).rjust(20),\
ls_str(group.disp).rjust(20),\
ls_str(group.post).rjust(20)
if len(group.shapes) > 0:
print \
''.rjust(2),\
'shape id'.rjust(8),\
'dims'.rjust(10),\
'init_unit'.rjust(14),\
'end_unit'.rjust(14),\
'position'.rjust(14)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.dims).rjust(10),\
ls_str(shape.init_unit).rjust(14),\
ls_str(shape.end_unit).rjust(14),\
ls_str(shape.position).rjust(14)
print '\n',\
''.rjust(2),\
'shape id'.rjust(8),\
'colors'.rjust(27),\
'anchor'.rjust(12),\
'freq'.rjust(6),\
'phase'.rjust(7)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.cols).rjust(27),\
ls_str(shape.anchor).rjust(12),\
ls_str(shape.freq).rjust(6),\
ls_str(shape.phase).rjust(7)
display_parser = CmdParser(add_help=False, prog='display',
description='''Displays the animation in a
window or in fullscreen.''')
+ display_parser.add_argument('-n', '--name', metavar='FOOBAR',
+ help='''name of log file to be written''')
+ display_parser.add_argument('-r', '--repeats', metavar='N', type=int,
+ help='''repeatedly display specified display
+ groups N number of times''')
+ display_parser.add_argument('-wl', '--waitless', action='store_true',
+ help='''do not add waitscreens before the
+ start of each repeat''')
display_parser.add_argument('-f', '--fullscreen', action='store_true',
help='sets fullscreen mode, ESC to quit')
display_parser.add_argument('-p', '--priority', metavar='LEVEL',
help='''set priority while displaying,
higher priority results in
less dropped frames (choices:
0-3, low, normal, high,
realtime)''')
- display_parser.add_argument('-r', '--repeats', metavar='N', type=int,
- help='''repeatedly display specified display
- groups N number of times''')
display_parser.add_argument('-pt', '--phototest', action='store_true',
help='''draw white test rectangle in topleft
corner of screen when groups become
visible for a photodiode to detect''')
display_parser.add_argument('-pb', '--photoburst', action='store_true',
help='''make checkerboards only draw first
color for one frame to facilitate
testing with a photodiode''')
display_parser.add_argument('-lt', '--logtime', action='store_true',
help='output frame timestamps to a log file')
display_parser.add_argument('-ld', '--logdur', action='store_true',
help='output frame durations to a log file')
display_parser.add_argument('-ss', '--trigser', action='store_true',
help='''send triggers through the serial port
when shapes are being displayed''')
display_parser.add_argument('-sp', '--trigpar', action='store_true',
help='''send triggers through the parallel port
when shapes are being displayed''')
display_parser.add_argument('-fpst', metavar='M', type=int,
help='''unique trigger corresponding to a
checkerboard is sent after the shape
undergoes M color flips (default:
disabled, M=0)''')
display_parser.add_argument('-et', '--eyetrack', action='store_true',
help='''use eyetracking to ensure that subject
fixates on the cross in the center''')
display_parser.add_argument('-eu', '--etuser', action='store_true',
help='''allow user to select eyetracking video
source from a dialog''')
display_parser.add_argument('-ev', '--etvideo', metavar='path',
help='''path (with no spaces) to eyetracking
video file to be used as the source''')
display_parser.add_argument('-ta', '--tryagain', metavar='I',
type=int, default=0,
help='''append groups during which subject
failed to fixate up to I times to the
list of groups to be displayed
(default: disabled, I=0)''')
display_parser.add_argument('-tb', '--trybreak', metavar='J', type=int,
help='''used with --tryagain, append a wait
screen to the list of groups to be
displayed after every J groups have
been appended to the list (default:
J=total number of groups)''')
+ display_parser.add_argument('-nl', '--nolog', action='store_true',
+ help='''do not write a log file''')
display_parser.add_argument('order', nargs='*', metavar='id', type=int,
help='''order in which groups should be
displayed (default: random order
from list of orders if specified
in project, ascending otherwise)''')
def help_display(self):
self.__class__.display_parser.print_help()
def do_display(self, line):
"""Displays the animation in a window or in fullscreen"""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.display_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
if len(args.order) > 0:
for i in set(args.order):
if i >= len(self.cur_proj.groups) or i < -1:
print 'error: group', i, 'does not exist'
return
if args.eyetrack and eyetracking.available:
if not eyetracking.is_calibrated():
try:
self.do_calibrate('',query=True)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
return
print "displaying...",
try:
- self.cur_proj.display(fullscreen=args.fullscreen,
- priority=args.priority,
+ self.cur_proj.display(name=args.name,
repeats=args.repeats,
+ waitless=args.waitless,
+ fullscreen=args.fullscreen,
+ priority=args.priority,
logtime=args.logtime,
logdur=args.logdur,
trigser=args.trigser,
trigpar=args.trigpar,
fpst=args.fpst,
phototest=args.phototest,
photoburst=args.photoburst,
eyetrack=args.eyetrack,
etuser=args.etuser,
etvideo=args.etvideo,
tryagain=args.tryagain,
trybreak=args.trybreak,
+ nolog=args.nolog,
order=args.order)
except (IOError, NotImplementedError, eyetracking.EyetrackingError):
print ''
print "error:", str(sys.exc_value)
if args.priority != None:
try:
priority.set('normal')
except:
pass
return
print "done"
- print "log file written"
export_parser = CmdParser(add_help=False, prog='export',
description='''Exports animation as an image
sequence (in a folder) to the
specified directory.''')
# export_parser.add_argument('--fmt', dest='export_fmt',
# choices=core.EXPORT_FMTS,
# help='image format for export')
export_parser.add_argument('-n','--nofolder',
dest='folder', action='store_false',
help='''force images not to exported in
a containing folder''')
export_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly export specified display
groups N number of times''')
export_parser.add_argument('duration', nargs='?',
type=to_decimal, default='Infinity',
help='''number of seconds of the animation
that should be exported (default:
as long as the entire animation)''')
export_parser.add_argument('dir', nargs='?', default=os.getcwd(),
help='''destination directory for export
(default: current working directory)''')
export_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be exported
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_export(self):
self.__class__.export_parser.print_help()
def do_export(self, line):
"""Exports animation an image sequence to the specified directory."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.export_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.export_parser.print_usage()
return
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < 0:
print 'error: group', i, 'does not exist'
return
groupq = [self.cur_proj.groups[i] for i in args.idlist]
else:
groupq = list(self.cur_proj.groups)
if args.repeat != None:
groupq = list(groupq * args.repeat)
try:
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
folder=args.folder)
except IOError:
print "error:", str(sys.exc_value)
return
except core.FrameOverflowError:
print "warning:", str(sys.exc_value)
print "Are you sure you want to continue?"
while True:
try:
if self.__class__.yn_parse(raw_input()):
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
export_fmt=None,
folder=args.folder,
force=True)
break
else:
return
except TypeError:
print str(sys.exc_value)
except EOFError:
return
print "Export done."
def do_calibrate(self, line, query=False):
"""Calibrate subject for eyetracking, or load a calibration file."""
if not eyetracking.available:
print "error: eyetracking functionality not available"
return
if query:
print "path to calibration file (leave empty for GUI tool):"
try:
path = raw_input().strip().strip('"\'')
except EOFError:
msg = "calibration cancelled"
raise eyetracking.EyetrackingError(msg)
else:
path = line.strip().strip('"\'')
if len(path) == 0:
path = None
if not eyetracking.is_source_ready():
# Select default source if none has been selected
eyetracking.select_source()
try:
eyetracking.calibrate(path)
except eyetracking.EyetrackingError:
if query:
raise
else:
print "error:", str(sys.exc_value)
return
if len(path) > 0:
print "calibration file successfully loaded"
etsetup_parser = CmdParser(add_help=False, prog='etsetup',
description='''Set various eyetracking
parameters.''')
etsetup_parser.add_argument('-fp', '--fixperiod', type=int, metavar='MS',
help='''time in milliseconds subject
has to stare at the same spot
for fixation to be detected''')
etsetup_parser.add_argument('-fr', '--fixrange', type=float, metavar='MM',
help='''distance in mm beyond which the
eye position cannot change for
a fixation to be detected''')
etsetup_parser.add_argument('-s', '--size', metavar='WIDTH,HEIGHT',
action=store_tuple(2, ',', float),
help='physical screen dimensions in mm')
etsetup_parser.add_argument('-vd', '--viewdist', type=int, metavar='MM',
help='''viewing distance between subject's
eyes and the screen''')
def help_etsetup(self):
self.__class__.etsetup_parser.print_help()
def do_etsetup(self, line):
try:
args = self.__class__.etsetup_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.etsetup_parser.print_usage()
return
try:
eyetracking.setup(viewing_distance=args.viewdist,
screen_dims=args.size,
fixation_period=args.fixperiod,
fixation_range=args.fixrange)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
def do_pwd(self, line):
"""Prints the current working directory."""
print os.getcwd()
def do_cd(self, line):
"""Change working directory to specified path."""
path = line.strip().strip('"\'')
if not os.path.isdir(path):
print "error: specified path is not a directory"
return
os.chdir(path)
def do_quit(self, line):
"""Quits the program."""
if self.save_check():
return
return True
def help_EOF(self):
print "Typing {0} issues this command, which quits the program."\
.format(CMD_EOF_STRING)
def do_EOF(self, line):
"""Typing Ctrl-D issues this command, which quits the program."""
print '\r'
if self.save_check():
return
return True
def help_help(self):
print 'Prints a list of commands.'
print "Type 'help <topic>' for more details on each command."
def default(self, line):
command = line.split()[0]
print \
"'{0}' is not a checkergen command.".format(command),\
"Type 'help' for a list of commands"
diff --git a/src/core.py b/src/core.py
index 5c38885..cb32f06 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,957 +1,965 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import random
import itertools
from datetime import datetime
from xml.dom import minidom
import pyglet
import graphics
import priority
import trigger
import eyetracking
from utils import *
# Use OrderedDict substitute if we don't have Python 2.7
if sys.version_info < (2, 7):
from odict import OrderedDict
else:
from collections import OrderedDict
CKG_FMT = 'ckg'
LOG_FMT = 'csv'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
MAX_EXPORT_FRAMES = 100000
PRERENDER_TO_TEXTURE = False
INT_HALF_PERIODS = True
EXPORT_FMTS = ['png']
EXPORT_DIR_SUFFIX = '-anim'
FIX_POS = (0, 0)
FIX_RANGE = (20, 20)
FIX_PER = 350
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = OrderedDict([('name', 'untitled'),
('fps', 60),
('res', (800, 600)),
('bg', (127, 127, 127)),
('export_fmt', 'png'),
('pre', 0),
('post', 0),
('cross_cols', ((0, 0, 0), (255, 0, 0))),
('cross_times', ('Infinity', 1)),
('orders', []),
('disp_ops', None)])
- DEFAULTS['disp_ops'] = OrderedDict([('fullscreen', False),
+ DEFAULTS['disp_ops'] = OrderedDict([('repeats', 1),
+ ('waitless', False),
+ ('fullscreen', False),
('priority', None),
('logtime', False),
('logdur', False),
('trigser', False),
('trigpar', False),
('fpst', 0),
('phototest', False),
('photoburst', False),
('eyetrack', False),
('etuser', False),
('etvideo', None),
('tryagain', 0),
('trybreak', None),
- ('repeats', 1)])
+ ('nolog', False)])
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
export_fmt -- image format for animation to be exported as
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'export_fmt':
if value not in EXPORT_FMTS:
msg = 'image format not recognized or supported'
raise FileFormatError(msg)
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
# Vars that are dicts
dicts_to_load = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_load = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
for d_name in dicts_to_load:
d = self.__class__.DEFAULTS[d_name]
try:
d_el = [node for node in project.childNodes if
node.localName == d_name and
node.namespaceURI == XML_NAMESPACE][0]
for var in d.keys():
try:
d[var] = eval(xml_get(d_el, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}' in '{1}'".\
format(var, d_name)
print "using default value '{0}' instead...".\
format(d[var])
except IndexError:
print "warning: missing attribute set '{0}'".format(d_name)
print "using default values instead..."
setattr(self, d_name, d)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
# Vars that are dicts
dicts_to_save = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_save = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for d_name in dicts_to_save:
d_el = doc.createElement(d_name)
project.appendChild(d_el)
d = getattr(self, d_name)
for k, v in d.iteritems():
xml_set(doc, d_el, k, repr(v))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, **keywords):
"""Displays the project animation on the screen.
name -- name that logfile will be saved with
+ repeats -- number of times specified order of display groups should
+ be repeated
+
+ waitless -- if true, no waitscreens will appear at the start of each
+ repeat
+
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
priority -- priority level to which process should be raised
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
trigser -- send triggers through serial port when each group is shown
trigpar -- send triggers through parallel port when each group is shown
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- append a wait screen to the group queue every time
after this many groups have been appended to the queue
- repeats -- number of times specified order of display groups should
- be repeated
-
order -- order in which groups (specified by id) will be displayed
"""
# Create RunState
disp_ops = self.disp_ops
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'name' in keywords.keys() and keywords['name'] != None:
name = keywords['name']
else:
timestr = datetime.today().strftime('_%Y-%m-%d_%H-%M-%S')
name = self.name + timestr
if 'order' in keywords.keys() and len(keywords['order']) > 0:
order = keywords['order']
elif len(self.orders) > 0:
order = random.choice(self.orders)
else:
order = range(len(self.groups))
runstate = CkgRunState(name=name,
res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
waitscreen = CkgWaitScreen()
# Count through pre
for count in range(self.pre * self.fps):
if runstate.window.has_exit:
break
runstate.update()
# Loop through repeats
for i in range(runstate.disp_ops['repeats']):
# Show waitscreen
- waitscreen.reset()
- waitscreen.display(runstate)
+ if not runstate.disp_ops['waitless']:
+ waitscreen.reset()
+ waitscreen.display(runstate)
# Loop through display groups
runstate.events['blk_on'] = True
for gid in runstate.order:
if gid == -1:
waitscreen.reset()
waitscreen.display(runstate)
else:
self.groups[gid].display(runstate)
# Append failed groups
if runstate.disp_ops['eyetrack'] and runstate.truefail:
if len(runstate.add_gids) < runstate.disp_ops['tryagain']:
runstate.add_gids.append(gid)
else:
runstate.fail_gids.append(gid)
runstate.events['blk_off'] = True
# Loop through added groups
if runstate.disp_ops['eyetrack']:
for blk in grouper(runstate.add_gids,
runstate.disp_ops['trybreak']):
# Show waitscreen
- waitscreen.reset()
- waitscreen.display(runstate)
+ if not runstate.disp_ops['waitless']:
+ waitscreen.reset()
+ waitscreen.display(runstate)
runstate.events['blk_on'] = True
# Loop through display groups
for gid in blk:
if gid != None:
self.groups[gid].display(runstate)
runstate.events['blk_on'] = True
# Count through post
for count in range(self.post * self.fps):
if runstate.window.has_exit:
break
runstate.update()
# Stop and output log
runstate.stop()
- runstate.log()
+ if not runstate.disp_ops['nolog']:
+ runstate.log()
def export(self, export_dir, export_duration, groupq=[],
export_fmt=None, folder=True, force=False):
if not os.path.isdir(export_dir):
msg = 'export path is not a directory'
raise IOError(msg)
if export_fmt == None:
export_fmt = self.export_fmt
# Set-up groups and variables that control their display
if groupq == []:
groupq = list(self.groups)
n = -1
groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Limit export duration to display duration
frames = export_duration * self.fps
frames = min(frames, disp_end)
# Warn user if a lot of frames will be exported
if frames > MAX_EXPORT_FRAMES and not force:
msg = 'very large number ({0}) of frames to be exported'.\
format(frames)
raise FrameOverflowError(msg)
# Create folder to store images if necessary
if folder:
export_dir = os.path.join(export_dir,
self.name + EXPORT_DIR_SUFFIX)
if not os.path.isdir(export_dir):
os.mkdir(export_dir)
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Set up canvas and framebuffer object
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
# Main loop
while count < frames:
fbo.clear()
if groups_visible:
# Get next group from queue
if n < 0 or groupq[n].over:
n += 1
if n >= len(groupq):
groups_visible = False
else:
groupq[n].reset()
# Draw and then update group
if n >= 0:
groupq[n].draw()
groupq[n].update(fps=self.fps, fpst=0)
# Draw fixation cross based on current count
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Save current frame to file
savepath = \
os.path.join(export_dir,
'{0}{2}.{1}'.
format(self.name, export_fmt,
repr(count).zfill(numdigits(frames-1))))
canvas.save(savepath)
# Increment count and set whether groups should be shown
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
fbo.delete()
class CkgRunState:
"""Contains information about the state of a checkergen project
when it is being displayed or exported."""
DEFAULTS = dict([('name', 'untitled'),
('res', None),
('fps', None),
('bg', None),
('cross_cols', None),
('cross_times', None),
('order', []),
('disp_ops', None),
('events', None),
('add_gids', []),
('fail_gids', []),
('timestamps', []),
('durstamps', []),
('trigstamps', [])])
DEFAULTS['events'] = dict([('blk_on', False),
('blk_off', False),
('track_on', False),
('track_off', False),
('fix_on', False),
('fix_off', False),
('grp_on', False),
('grp_off', False),
('sids', set())])
def __init__(self, **keywords):
"""Creates the RunState."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
def start(self):
"""Initialize all subsystems and start the run."""
if self.disp_ops == None:
msg = "RunState lacks display options"
raise ValueError(msg)
if min(self.res, self.fps, self.bg,
self.cross_cols, self.cross_times) == None:
msg = "RunState intialized with insufficent project information"
raise ValueError(msg)
self._count = 0
# Create fixation crosses
self.fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if self.disp_ops['phototest']:
self.test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Initialize ports
if self.disp_ops['trigser']:
if not trigger.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trigpar']:
if not trigger.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
trigger.init(self.disp_ops['trigser'], self.disp_ops['trigpar'])
# Initialize eyetracking
if self.disp_ops['eyetrack']:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trybreak'] == None:
self.disp_ops['trybreak'] = len(self.order)
self.fixated = False
self.old_fixated = False
self.tracked = False
self.old_tracked = False
self.fix_fail = False
self.true_fail = False
eyetracking.select_source(self.disp_ops['etuser'],
self.disp_ops['etvideo'])
eyetracking.start()
# Stretch to fit screen only if project res does not equal screen res
self.scaling = False
if self.disp_ops['fullscreen']:
self.window = pyglet.window.Window(fullscreen=True, visible=False)
if (self.window.width, self.window.height) != self.res:
self.scaling = True
else:
self.window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
self.keystates = pyglet.window.key.KeyStateHandler()
self.window.push_handlers(self.keystates)
# Clear window and make visible
self.window.switch_to()
graphics.set_clear_color(self.bg)
self.window.clear()
self.window.set_visible()
# Create framebuffer object for drawing unscaled scene
if self.scaling:
self.canvas = pyglet.image.Texture.create(*self.res)
self.fbo = graphics.Framebuffer(self.canvas)
self.fbo.start_render()
graphics.set_clear_color(self.bg)
self.fbo.clear()
# Set process priority
if self.disp_ops['priority'] != None:
if not priority.available[sys.platform]:
msg = "setting priority not available on {0}".\
format(sys.platform)
raise NotImplementedError(msg)
else:
if self.disp_ops['priority'].isdigit():
self.disp_ops['priority'] = int(self.disp_ops['priority'])
priority.set(self.disp_ops['priority'])
# Start timers
if self.disp_ops['logtime']:
self.timer = Timer()
self.timer.start()
if self.disp_ops['logdur']:
self.dur = Timer()
self.dur.start()
def update(self):
"""Update the RunState."""
# Check for tracking and fixation
if self.disp_ops['eyetrack']:
self.old_tracked = self.tracked
self.tracked = eyetracking.is_tracked()
self.old_fixated = self.fixated
self.fixated = eyetracking.is_fixated(FIX_POS, FIX_RANGE, FIX_PER)
if self.fixated:
# Draw normal cross color if fixating
self.fix_crosses[0].draw()
else:
# Draw alternative cross color if not fixating
self.fix_crosses[1].draw()
# Update eyetracking events
if self.tracked != self.old_tracked:
if self.tracked:
self.events['track_on'] = True
else:
self.events['track_off'] = True
if self.fixated != self.old_fixated:
if self.fixated:
self.events['fix_on'] = True
else:
self.events['fix_off'] = True
# Check for failure of trial
if self.tracked and not self.fixated:
self.fix_fail = True
else:
# Change cross color based on time
if (self._count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
self.fix_crosses[0].draw()
else:
self.fix_crosses[1].draw()
# Blit canvas to screen if necessary
if self.scaling:
self.fbo.end_render()
self.canvas.blit(0, 0)
self.window.switch_to()
self.window.dispatch_events()
self.window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to lists
if self.disp_ops['logtime']:
self.timestamps.append(self.timer.elapsed())
elif self.disp_ops['logdur']:
self.timestamps.append('')
if self.disp_ops['logdur']:
self.durstamps.append(self.dur.restart())
elif self.disp_ops['logtime']:
self.durstamps.append('')
# Send trigger ASAP after flip
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
trigger.send(trigser, trigpar, self.encode_events())
# Log when triggers are sent
if (self.disp_ops['logtime'] and
(self.disp_ops['trigser'] or self.disp_ops['trigpar']) and
self.encode_events() != None):
self.trigstamps.append(self.encode_events())
else:
self.trigstamps.append('')
# Clear canvas, events, prepare for next frame
if self.scaling:
self.fbo.start_render()
self.fbo.clear()
else:
self.window.clear()
self.events = self.__class__.DEFAULTS['events']
self._count += 1
def stop(self):
"""Clean up RunState."""
if self.disp_ops['eyetrack']:
eyetracking.stop()
if self.scaling:
self.fbo.delete()
del self.canvas
self.window.close()
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
trigger.quit(trigser, trigpar)
if self.disp_ops['priority'] != None:
priority.set('normal')
def log(self, path=None):
"""Write a log file for the experimental run in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, LOG_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(LOG_FMT):
path = '{0}.{1}'.format(path, LOG_FMT)
with open(path, 'wb') as logfile:
writer = csv.writer(logfile, dialect='excel-tab')
writer.writerow(['checkergen log file'])
writer.writerow(['display options:'])
writer.writerow(self.disp_ops.keys())
writer.writerow(self.disp_ops.values())
writer.writerow(['order:'] + self.order)
if self.disp_ops['eyetrack']:
write.writerow(['groups added'])
for blk in grouper(self.add_gids,
self.disp_ops['trybreak'], ''):
write.writerow(blk)
write.writerow(['groups failed'])
for blk in grouper(self.fail_gids,
self.disp_ops['trybreak'], ''):
write.writerow(blk)
if self.disp_ops['logtime'] or self.disp_ops['logdur']:
stamps = [self.timestamps, self.durstamps, self.trigstamps]
writer.writerow(['timestamps', 'durations', 'triggers'])
for stamp in zip(*stamps):
writer.writerow(list(stamp))
class CkgDisplayGroup:
DEFAULTS = OrderedDict([('pre', 0), ('disp', 'Infinity'), ('post', 0)])
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets counts and all contained shapes."""
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, runstate):
"""Draws all contained shapes during the appropriate interval."""
for shape in self.shapes:
shape.draw(photoburst=runstate.disp_ops['photoburst'])
def update(self, runstate):
"""Updates contained shapes, sets event triggers."""
# Set events to be sent
if runstate.disp_ops['fpst'] > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= fpst:
runstate.events['sids'].add(n)
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(runstate.fps)
def display(self, runstate):
"""Display the group in the context described by supplied runstate."""
self.reset()
for count in range(self.pre * runstate.fps):
if runstate.window.has_exit:
break
runstate.update()
runstate.events['blk_on'] = True
if runstate.disp_ops['eyetrack']:
runstate.fix_fail = False
renstate.true_fail = False
for count in range(self.disp * runstate.fps):
if runstate.window.has_exit:
break
self.draw(runstate)
self.update(runstate)
runstate.update()
runstate.events['blk_off'] = True
if runstate.disp_ops['eyetrack']:
if runstate.fix_fail:
runstate.true_fail = True
for count in range(self.post * runstate.fps):
if runstate.window.has_exit:
break
runstate.update()
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
|
ztangent/checkergen
|
eea6a519553cd0dcc442377c595a84b5143ea36b
|
Display tested, debugged and working so far.
|
diff --git a/example.ckg b/example.ckg
index a2bfe9d..afa344b 100644
--- a/example.ckg
+++ b/example.ckg
@@ -1,73 +1,74 @@
<?xml version="1.0" ?>
<project xmlns="http://github.com/ZOMGxuan/checkergen">
<fps>Decimal('60')</fps>
<res>(800, 600)</res>
<bg>(127, 127, 127)</bg>
<export_fmt>'png'</export_fmt>
<pre>Decimal('0')</pre>
<post>Decimal('0')</post>
<cross_cols>((0, 0, 0), (255, 0, 0))</cross_cols>
<cross_times>(Decimal('Infinity'), Decimal('1'))</cross_times>
<orders>[]</orders>
<disp_ops>
<fullscreen>False</fullscreen>
- <priority>0</priority>
+ <priority>None</priority>
<logtime>False</logtime>
<logdur>False</logdur>
<trigser>False</trigser>
<trigpar>False</trigpar>
<fpst>0</fpst>
<phototest>False</phototest>
<photoburst>False</photoburst>
<eyetrack>False</eyetrack>
<etuser>False</etuser>
<etvideo>None</etvideo>
<tryagain>0</tryagain>
<trybreak>None</trybreak>
+ <repeats>1</repeats>
</disp_ops>
<group>
<pre>Decimal('2')</pre>
<disp>Decimal('10')</disp>
<post>Decimal('2')</post>
<shape type="board">
<dims>(5, 5)</dims>
<init_unit>(Decimal('40'), Decimal('40'))</init_unit>
<end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<position>(Decimal('420'), Decimal('320'))</position>
<anchor>'bottomleft'</anchor>
<cols>((0, 0, 0), (255, 255, 255))</cols>
<freq>Decimal('1')</freq>
<phase>Decimal('0')</phase>
</shape>
<shape type="board">
<dims>(5, 5)</dims>
<init_unit>(Decimal('40'), Decimal('40'))</init_unit>
<end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<position>(Decimal('380'), Decimal('320'))</position>
<anchor>'bottomright'</anchor>
<cols>((0, 0, 0), (255, 255, 255))</cols>
<freq>Decimal('2')</freq>
<phase>Decimal('90')</phase>
</shape>
<shape type="board">
<dims>(5, 5)</dims>
<init_unit>(Decimal('40'), Decimal('40'))</init_unit>
<end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<position>(Decimal('420'), Decimal('280'))</position>
<anchor>'topleft'</anchor>
<cols>((0, 0, 0), (255, 255, 255))</cols>
<freq>Decimal('3')</freq>
<phase>Decimal('180')</phase>
</shape>
<shape type="board">
<dims>(5, 5)</dims>
<init_unit>(Decimal('40'), Decimal('40'))</init_unit>
<end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<position>(Decimal('380'), Decimal('280'))</position>
<anchor>'topright'</anchor>
<cols>((0, 0, 0), (255, 255, 255))</cols>
<freq>Decimal('4')</freq>
<phase>Decimal('270')</phase>
</shape>
</group>
</project>
diff --git a/src/cli.py b/src/cli.py
index 9fb2462..bb103b0 100644
--- a/src/cli.py
+++ b/src/cli.py
@@ -235,969 +235,821 @@ class CkgCmd(cmd.Cmd):
set_parser.add_argument('--cross_times', metavar='TIME1,TIME2',
action=store_tuple(2, ',', to_decimal),
help='''time in seconds each cross color
will be displayed''')
def help_set(self):
self.__class__.set_parser.print_help()
def do_set(self, line):
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
try:
args = self.__class__.set_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.set_parser.print_usage()
return
names = public_dir(args)
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
setattr(self.cur_proj, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.set_parser.print_usage()
mkgrp_parser = CmdParser(add_help=False, prog='mkgrp',
formatter_class=
argparse.ArgumentDefaultsHelpFormatter,
description='''Makes a new display group
with the given parameters.''')
mkgrp_parser.add_argument('pre', type=to_decimal, default=0, nargs='?',
help='''time in seconds a blank screen will
be shown before shapes are displayed''')
mkgrp_parser.add_argument('disp', type=to_decimal,
nargs='?', default='Infinity',
help='''time in seconds shapes will be
displayed''')
mkgrp_parser.add_argument('post', type=to_decimal, default=0, nargs='?',
help='''time in seconds a blank screen will
be shown after shapes are displayed''')
def help_mkgrp(self):
self.__class__.mkgrp_parser.print_help()
def do_mkgrp(self, line):
"""Makes a display group with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
try:
args = self.__class__.mkgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mkgrp_parser.print_usage()
return
group_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_group = core.CkgDisplayGroup(**group_dict)
new_id = self.cur_proj.add_group(new_group)
print "display group", new_id, "added"
self.cur_group = new_group
print "group", new_id, "is now the current display group"
edgrp_parser = CmdParser(add_help=False, prog='edgrp',
description='''Edits attributes of display groups
specified by ids.''')
edgrp_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='ids of display groups to be edited')
edgrp_parser.add_argument('--pre', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown before shapes are displayed''')
edgrp_parser.add_argument('--disp', type=to_decimal, metavar='SECONDS',
help='''time in seconds shapes will be
displayed''')
edgrp_parser.add_argument('--post', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown after shapes are displayed''')
def help_edgrp(self):
self.__class__.edgrp_parser.print_help()
def do_edgrp(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.edgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.edgrp_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_proj.groups) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_group_attr(x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.edgrp_parser.print_usage()
rmgrp_parser = CmdParser(add_help=False, prog='rmgrp',
description='''Removes display groups specified
by ids.''')
rmgrp_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='ids of display groups to be removed')
rmgrp_parser.add_argument('-a', '--all', action='store_true',
help='remove all groups from the project')
def help_rmgrp(self):
self.__class__.rmgrp_parser.print_help()
def do_rmgrp(self, line):
"""Removes display groups specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups to remove'
return
try:
args = self.__class__.rmgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rmgrp_parser.print_usage()
return
rmlist = []
if args.all:
for group in self.cur_proj.groups[:]:
self.cur_proj.del_group(group)
print "all display groups removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_proj.groups) or x < 0:
print "display group", x, "does not exist"
continue
rmlist.append(self.cur_proj.groups[x])
print "display group", x, "removed"
for group in rmlist:
self.cur_proj.del_group(group)
# Remember to point self.cur_group somewhere sane
if self.cur_group not in self.cur_proj.groups:
if len(self.cur_proj.groups) == 0:
self.cur_group = None
else:
self.cur_group = self.cur_proj.groups[0]
print "group 0 is now the current display group"
chgrp_parser = CmdParser(add_help=False, prog='chgrp',
description='''Changes display group that is
currently active for editing.
Prints current group id if
no group id is specified''')
chgrp_parser.add_argument('gid', metavar='id', type=int, nargs='?',
help='id of display group to be made active')
def help_chgrp(self):
self.__class__.chgrp_parser.print_help()
def do_chgrp(self, line):
"""Changes group that is currently active for editing."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups that can be made active'
return
try:
args = self.__class__.chgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.chgrp_parser.print_usage()
return
if args.gid == None:
print "group",\
self.cur_proj.groups.index(self.cur_group),\
"is the current display group"
elif args.gid >= len(self.cur_proj.groups) or args.gid < 0:
print "group", args.gid, "does not exist"
else:
self.cur_group = self.cur_proj.groups[args.gid]
print "group", args.gid, "is now the current display group"
mk_parser = CmdParser(add_help=False, prog='mk',
description='''Makes a new checkerboard in the
current group with the given
parameters.''')
mk_parser.add_argument('dims', action=store_tuple(2, ',', to_decimal),
help='''width,height of checkerboard in no. of
unit cells''')
mk_parser.add_argument('init_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of initial unit cell in pixels')
mk_parser.add_argument('end_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of final unit cell in pixels')
mk_parser.add_argument('position', action=store_tuple(2, ',', to_decimal),
help='x,y position of checkerboard in pixels')
mk_parser.add_argument('anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='anchor')
mk_parser.add_argument('cols', action=store_tuple(2, ',', to_color, [';']),
help='''color1,color2 of the checkerboard
(color format: R;G;B,
component range from 0-255)''')
mk_parser.add_argument('freq', type=to_decimal,
help='frequency of color reversal in Hz')
mk_parser.add_argument('phase', type=to_decimal, nargs='?', default='0',
help='initial phase of animation in degrees')
def help_mk(self):
self.__class__.mk_parser.print_help()
def do_mk(self, line):
"""Makes a checkerboard with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
if self.cur_group == None:
print 'automatically adding display group...'
self.do_mkgrp('')
try:
args = self.__class__.mk_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mk_parser.print_usage()
return
shape_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_shape = core.CheckerBoard(**shape_dict)
new_id = self.cur_proj.add_shape_to_group(self.cur_group, new_shape)
print "checkerboard", new_id, "added"
ed_parser = CmdParser(add_help=False, prog='ed',
description='''Edits attributes of checkerboards
specified by ids.''')
ed_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='''ids of checkerboards in the current
group to be edited''')
ed_parser.add_argument('--dims', action=store_tuple(2, ',', to_decimal),
help='checkerboard dimensions in unit cells',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--init_unit',
action=store_tuple(2, ',', to_decimal),
help='initial unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--end_unit',
action=store_tuple(2, ',', to_decimal),
help='final unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--position',
action=store_tuple(2, ',', to_decimal),
help='position of checkerboard in pixels',
metavar='X,Y')
ed_parser.add_argument('--anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='LOCATION')
ed_parser.add_argument('--cols', metavar='COLOR1,COLOR2',
action=store_tuple(2, ',', to_color, [';']),
help='''checkerboard colors (color format:
R;G;B, component range
from 0-255)''')
ed_parser.add_argument('--freq', type=to_decimal,
help='frequency of color reversal in Hz')
ed_parser.add_argument('--phase', type=to_decimal,
help='initial phase of animation in degrees')
def help_ed(self):
self.__class__.ed_parser.print_help()
def do_ed(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, please create one first'
return
try:
args = self.__class__.ed_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ed_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_group.shapes) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_shape_attr(self.cur_group, x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.ed_parser.print_usage()
rm_parser = CmdParser(add_help=False, prog='rm',
description='''Removes checkerboards specified
by ids.''')
rm_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''ids of checkerboards in the current group
to be removed''')
rm_parser.add_argument('-a', '--all', action='store_true',
help='''remove all checkerboards in the
current group''')
def help_rm(self):
self.__class__.rm_parser.print_help()
def do_rm(self, line):
"""Removes checkerboards specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, no boards to remove'
return
try:
args = self.__class__.rm_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rm_parser.print_usage()
return
rmlist = []
if args.all:
for shape in self.cur_group.shapes:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
print "all checkerboards removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_group.shapes) or x < 0:
print "checkerboard", x, "does not exist"
continue
rmlist.append(self.cur_group.shapes[x])
print "checkerboard", x, "removed"
for shape in rmlist:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
ls_parser = CmdParser(add_help=False, prog='ls',
description='''Lists project, display group and
checkerboard settings. If no group ids
are specified, all display groups
are listed.''')
ls_parser.add_argument('gidlist', nargs='*', metavar='gid', type=int,
help='''ids of the display groups to be listed''')
ls_group = ls_parser.add_mutually_exclusive_group()
ls_group.add_argument('-s', '--settings', action='store_true',
help='list only project settings')
ls_group.add_argument('-g', '--groups', action='store_true',
help='list only display groups')
def help_ls(self):
self.__class__.ls_parser.print_help()
def do_ls(self, line):
"""Lists project, display group and checkerboard settings."""
def ls_str(s, seps=[',',';']):
"""Special space-saving output formatter."""
if type(s) in [tuple, list]:
if len(seps) > 1:
newseps = seps[1:]
else:
newseps = seps
return seps[0].join([ls_str(i, newseps) for i in s])
else:
return str(s)
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.ls_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ls_parser.print_usage()
return
# Remove duplicates and ascending sort
args.gidlist = sorted(set(args.gidlist))
if len(self.cur_proj.groups) == 0:
if len(args.gidlist) > 0:
print 'this project has no display groups that can be listed'
args.settings = True
else:
for gid in args.gidlist[:]:
if gid >= len(self.cur_proj.groups) or gid < 0:
args.gidlist.remove(gid)
print 'display group', gid, 'does not exist'
if args.gidlist == []:
args.gidlist = range(len(self.cur_proj.groups))
else:
# If any (valid) groups are specified
# don't show project settings
args.groups = True
if not args.groups:
print 'PROJECT SETTINGS'.center(70,'*')
print \
'name'.rjust(16),\
'fps'.rjust(7),\
'resolution'.rjust(14),\
'bg color'.rjust(18)
# 'format'.rjust(7)
print \
ls_str(self.cur_proj.name).rjust(16),\
ls_str(self.cur_proj.fps).rjust(7),\
ls_str(self.cur_proj.res).rjust(14),\
ls_str(self.cur_proj.bg).rjust(18)
# ls_str(self.cur_proj.export_fmt).rjust(7)
print \
'pre-display'.rjust(26),\
'post-display'.rjust(26)
print \
ls_str(self.cur_proj.pre).rjust(26),\
ls_str(self.cur_proj.post).rjust(26)
print \
'cross colors'.rjust(26),\
'cross times'.rjust(26)
print \
ls_str(self.cur_proj.cross_cols).rjust(26),\
ls_str(self.cur_proj.cross_times).rjust(26)
if not args.settings and not args.groups:
# Insert empty line if both groups and project
# settings are listed
print ''
if not args.settings:
for i, n in enumerate(args.gidlist):
if i != 0:
# Print newline seperator between each group
print ''
group = self.cur_proj.groups[n]
print 'GROUP {n}'.format(n=n).center(70,'*')
print \
'pre-display'.rjust(20),\
'display'.rjust(20),\
'post-display'.rjust(20)
print \
ls_str(group.pre).rjust(20),\
ls_str(group.disp).rjust(20),\
ls_str(group.post).rjust(20)
if len(group.shapes) > 0:
print \
''.rjust(2),\
'shape id'.rjust(8),\
'dims'.rjust(10),\
'init_unit'.rjust(14),\
'end_unit'.rjust(14),\
'position'.rjust(14)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.dims).rjust(10),\
ls_str(shape.init_unit).rjust(14),\
ls_str(shape.end_unit).rjust(14),\
ls_str(shape.position).rjust(14)
print '\n',\
''.rjust(2),\
'shape id'.rjust(8),\
'colors'.rjust(27),\
'anchor'.rjust(12),\
'freq'.rjust(6),\
'phase'.rjust(7)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.cols).rjust(27),\
ls_str(shape.anchor).rjust(12),\
ls_str(shape.freq).rjust(6),\
ls_str(shape.phase).rjust(7)
display_parser = CmdParser(add_help=False, prog='display',
description='''Displays the animation in a
window or in fullscreen.''')
- display_parser.add_argument('-e', '--expfile', metavar='PATH',
- help='''run experiment as described in
- specified file, ignore other flags''')
display_parser.add_argument('-f', '--fullscreen', action='store_true',
help='sets fullscreen mode, ESC to quit')
display_parser.add_argument('-p', '--priority', metavar='LEVEL',
help='''set priority while displaying,
higher priority results in
less dropped frames (choices:
0-3, low, normal, high,
realtime)''')
display_parser.add_argument('-r', '--repeats', metavar='N', type=int,
help='''repeatedly display specified display
groups N number of times''')
display_parser.add_argument('-pt', '--phototest', action='store_true',
help='''draw white test rectangle in topleft
corner of screen when groups become
visible for a photodiode to detect''')
display_parser.add_argument('-pb', '--photoburst', action='store_true',
help='''make checkerboards only draw first
color for one frame to facilitate
testing with a photodiode''')
display_parser.add_argument('-lt', '--logtime', action='store_true',
help='output frame timestamps to a log file')
display_parser.add_argument('-ld', '--logdur', action='store_true',
help='output frame durations to a log file')
display_parser.add_argument('-ss', '--trigser', action='store_true',
help='''send triggers through the serial port
when shapes are being displayed''')
display_parser.add_argument('-sp', '--trigpar', action='store_true',
help='''send triggers through the parallel port
when shapes are being displayed''')
- display_parser.add_argument('-fpst', metavar='M', type=int, default=0,
+ display_parser.add_argument('-fpst', metavar='M', type=int,
help='''unique trigger corresponding to a
checkerboard is sent after the shape
undergoes M color flips (default:
disabled, M=0)''')
display_parser.add_argument('-et', '--eyetrack', action='store_true',
help='''use eyetracking to ensure that subject
fixates on the cross in the center''')
display_parser.add_argument('-eu', '--etuser', action='store_true',
help='''allow user to select eyetracking video
source from a dialog''')
display_parser.add_argument('-ev', '--etvideo', metavar='path',
help='''path (with no spaces) to eyetracking
video file to be used as the source''')
display_parser.add_argument('-ta', '--tryagain', metavar='I',
type=int, default=0,
help='''append groups during which subject
failed to fixate up to I times to the
list of groups to be displayed
(default: disabled, I=0)''')
display_parser.add_argument('-tb', '--trybreak', metavar='J', type=int,
help='''used with --tryagain, append a wait
screen to the list of groups to be
displayed after every J groups have
been appended to the list (default:
J=total number of groups)''')
- display_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
- help='''list of display groups to be displayed
- in the specified order (default: order
- by id, i.e. group 0 is first)''')
-
+ display_parser.add_argument('order', nargs='*', metavar='id', type=int,
+ help='''order in which groups should be
+ displayed (default: random order
+ from list of orders if specified
+ in project, ascending otherwise)''')
+
def help_display(self):
self.__class__.display_parser.print_help()
def do_display(self, line):
"""Displays the animation in a window or in fullscreen"""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.display_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
- if args.expfile != None:
- try:
- exp = core.CkgExp(path=args.expfile)
- except IOError:
- print "error:", str(sys.exc_value)
- return
- try:
- args = self.__class__.\
- display_parser.parse_args(shlex.split(exp.flags))
- except (CmdParserError, ValueError):
- print 'error: invalid flags stored in run file'
- return
- try:
- print """name of log file (default: experiment name):"""
- runname = raw_input().strip().strip('"\'')
- except EOFError:
- return
- if runname == '':
- runname == exp.name
- run = exp.random_run(runname)
- args.idlist = run.idlist()
- else:
- run = core.CkgRun(name=self.cur_proj.name,
- blocks=None,
- flags=line,
- sequence=[])
-
- groupq = []
- if len(args.idlist) > 0:
- for i in set(args.idlist):
+ if len(args.order) > 0:
+ for i in set(args.order):
if i >= len(self.cur_proj.groups) or i < -1:
print 'error: group', i, 'does not exist'
return
- for i in args.idlist:
- if i == -1:
- groupq.append(core.CkgWaitScreen(res=self.cur_proj.res))
- else:
- groupq.append(self.cur_proj.groups[i])
- else:
- groupq = list(self.cur_proj.groups)
- if args.repeat != None:
- groupq = list(groupq * args.repeat)
if args.eyetrack and eyetracking.available:
if not eyetracking.is_calibrated():
try:
- self.do_calibrate('',True)
+ self.do_calibrate('',query=True)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
return
- if args.priority != None:
- if not priority.available[sys.platform]:
- print "error: setting priority not available on", sys.platform
- print "continuing..."
- else:
- if args.priority.isdigit():
- args.priority = int(args.priority)
- try:
- priority.set(args.priority)
- except ValueError:
- print "error:", str(sys.exc_value)
- print "continuing..."
-
- print "displaying..."
+ print "displaying...",
try:
self.cur_proj.display(fullscreen=args.fullscreen,
+ priority=args.priority,
+ repeats=args.repeats,
logtime=args.logtime,
logdur=args.logdur,
trigser=args.trigser,
trigpar=args.trigpar,
fpst=args.fpst,
phototest=args.phototest,
photoburst=args.photoburst,
eyetrack=args.eyetrack,
etuser=args.etuser,
etvideo=args.etvideo,
tryagain=args.tryagain,
trybreak=args.trybreak,
- groupq=groupq,
- run=run)
+ order=args.order)
except (IOError, NotImplementedError, eyetracking.EyetrackingError):
+ print ''
print "error:", str(sys.exc_value)
if args.priority != None:
try:
priority.set('normal')
except:
pass
return
-
- if args.priority != None:
- try:
- priority.set('normal')
- except:
- pass
-
- try:
- run.write_log()
- except IOError:
- print "error:", str(sys.exc_value)
- return
+ print "done"
print "log file written"
export_parser = CmdParser(add_help=False, prog='export',
description='''Exports animation as an image
sequence (in a folder) to the
specified directory.''')
# export_parser.add_argument('--fmt', dest='export_fmt',
# choices=core.EXPORT_FMTS,
# help='image format for export')
export_parser.add_argument('-n','--nofolder',
dest='folder', action='store_false',
help='''force images not to exported in
a containing folder''')
export_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly export specified display
groups N number of times''')
export_parser.add_argument('duration', nargs='?',
type=to_decimal, default='Infinity',
help='''number of seconds of the animation
that should be exported (default:
as long as the entire animation)''')
export_parser.add_argument('dir', nargs='?', default=os.getcwd(),
help='''destination directory for export
(default: current working directory)''')
export_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be exported
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_export(self):
self.__class__.export_parser.print_help()
def do_export(self, line):
"""Exports animation an image sequence to the specified directory."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.export_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.export_parser.print_usage()
return
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < 0:
print 'error: group', i, 'does not exist'
return
groupq = [self.cur_proj.groups[i] for i in args.idlist]
else:
groupq = list(self.cur_proj.groups)
if args.repeat != None:
groupq = list(groupq * args.repeat)
try:
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
folder=args.folder)
except IOError:
print "error:", str(sys.exc_value)
return
except core.FrameOverflowError:
print "warning:", str(sys.exc_value)
print "Are you sure you want to continue?"
while True:
try:
if self.__class__.yn_parse(raw_input()):
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
export_fmt=None,
folder=args.folder,
force=True)
break
else:
return
except TypeError:
print str(sys.exc_value)
except EOFError:
return
print "Export done."
- mkexp_parser = CmdParser(add_help=False, prog='mkexp',
- description='''Create checkergen experiment file
- which describes how the project
- is to be displayed.''')
- mkexp_parser.add_argument('-n', '--name',
- help='''name of the experiment (default: same
- name as current project)''')
- mkexp_parser.add_argument('-b', '--blocks', type=int, metavar='N',
- help='''N blocks displayed in a run, i.e.
- the same sequence will be displayed
- N times in that run, with waitscreens
- in between''')
- mkexp_parser.add_argument('-f', '--flags',
- help='''flags passed to the display command
- that should be used when the run
- file is run (enclose in quotes and use
- '+' or '++' in place of '-' or '--')''')
-
- def help_mkexp(self):
- self.__class__.mkexp_parser.print_help()
-
- def do_mkexp(self, line):
- """Creates checkergen experiment file."""
- if self.cur_proj == None:
- print 'please create or open a project first'
- return
-
- try:
- args = self.__class__.mkexp_parser.parse_args(shlex.split(line))
- except (CmdParserError, ValueError):
- print "error:", str(sys.exc_value)
- self.__class__.mkexp_parser.print_usage()
- return
-
- if args.blocks == None:
- print "number of blocks:"
- try:
- args.blocks = int(raw_input().strip())
- except EOFError:
- return
- except ValueError:
- print "error:", str(sys.exc_value)
- return
-
- if args.flags != None:
- args.flags = args.flags.replace('+','-')
- else:
- print "flags used with display command (leave blank if none):"
- try:
- args.flags = raw_input().strip().strip('"\'')
- except EOFError:
- return
-
- try:
- disp_args = self.__class__.display_parser.\
- parse_args(shlex.split(args.flags))
- except (CmdParserError, ValueError):
- print "error: invalid flags to display command"
- print str(sys.exc_value)
- self.__class__.display_parser.print_usage()
- return
-
- print "list of sequences to choose from in the format",\
- "'id1,id2,id3;seq2;seq3;seq4':"
- print "(default: reduced latin square)"
- try:
- seqs_str = raw_input().strip()
- if seqs_str == '':
- args.sequences = None
- else:
- args.sequences = [[int(i) for i in seq_str.split(',')]
- for seq_str in seqs_str.split(';')]
- except EOFError:
- return
-
- try:
- new_exp = core.CkgExp(name=args.name, proj=self.cur_proj,
- blocks=args.blocks,
- sequences=args.sequences,
- flags=args.flags)
- new_exp.save()
- except IOError:
- print "error:", str(sys.exc_value)
- return
-
- print "Experiment file created."
-
def do_calibrate(self, line, query=False):
"""Calibrate subject for eyetracking, or load a calibration file."""
if not eyetracking.available:
print "error: eyetracking functionality not available"
return
if query:
print "path to calibration file (leave empty for GUI tool):"
try:
path = raw_input().strip().strip('"\'')
except EOFError:
msg = "calibration cancelled"
raise eyetracking.EyetrackingError(msg)
else:
path = line.strip().strip('"\'')
if len(path) == 0:
path = None
if not eyetracking.is_source_ready():
# Select default source if none has been selected
eyetracking.select_source()
try:
eyetracking.calibrate(path)
except eyetracking.EyetrackingError:
if query:
raise
else:
print "error:", str(sys.exc_value)
return
if len(path) > 0:
print "calibration file successfully loaded"
etsetup_parser = CmdParser(add_help=False, prog='etsetup',
description='''Set various eyetracking
parameters.''')
etsetup_parser.add_argument('-fp', '--fixperiod', type=int, metavar='MS',
help='''time in milliseconds subject
has to stare at the same spot
for fixation to be detected''')
etsetup_parser.add_argument('-fr', '--fixrange', type=float, metavar='MM',
help='''distance in mm beyond which the
eye position cannot change for
a fixation to be detected''')
etsetup_parser.add_argument('-s', '--size', metavar='WIDTH,HEIGHT',
action=store_tuple(2, ',', float),
help='physical screen dimensions in mm')
etsetup_parser.add_argument('-vd', '--viewdist', type=int, metavar='MM',
help='''viewing distance between subject's
eyes and the screen''')
def help_etsetup(self):
self.__class__.etsetup_parser.print_help()
def do_etsetup(self, line):
try:
args = self.__class__.etsetup_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.etsetup_parser.print_usage()
return
try:
eyetracking.setup(viewing_distance=args.viewdist,
screen_dims=args.size,
fixation_period=args.fixperiod,
fixation_range=args.fixrange)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
def do_pwd(self, line):
"""Prints the current working directory."""
print os.getcwd()
def do_cd(self, line):
"""Change working directory to specified path."""
path = line.strip().strip('"\'')
if not os.path.isdir(path):
print "error: specified path is not a directory"
return
os.chdir(path)
def do_quit(self, line):
"""Quits the program."""
if self.save_check():
return
return True
def help_EOF(self):
print "Typing {0} issues this command, which quits the program."\
.format(CMD_EOF_STRING)
def do_EOF(self, line):
"""Typing Ctrl-D issues this command, which quits the program."""
print '\r'
if self.save_check():
return
return True
def help_help(self):
print 'Prints a list of commands.'
print "Type 'help <topic>' for more details on each command."
def default(self, line):
command = line.split()[0]
print \
"'{0}' is not a checkergen command.".format(command),\
"Type 'help' for a list of commands"
diff --git a/src/core.py b/src/core.py
index aec930b..5c38885 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,1134 +1,1193 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import random
import itertools
+from datetime import datetime
from xml.dom import minidom
import pyglet
import graphics
import priority
import trigger
import eyetracking
from utils import *
# Use OrderedDict substitute if we don't have Python 2.7
if sys.version_info < (2, 7):
from odict import OrderedDict
else:
from collections import OrderedDict
CKG_FMT = 'ckg'
-EXP_FMT = 'ckx'
-LOG_FMT = 'log'
+LOG_FMT = 'csv'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
MAX_EXPORT_FRAMES = 100000
PRERENDER_TO_TEXTURE = False
INT_HALF_PERIODS = True
EXPORT_FMTS = ['png']
EXPORT_DIR_SUFFIX = '-anim'
FIX_POS = (0, 0)
FIX_RANGE = (20, 20)
FIX_PER = 350
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = OrderedDict([('name', 'untitled'),
('fps', 60),
('res', (800, 600)),
('bg', (127, 127, 127)),
('export_fmt', 'png'),
('pre', 0),
('post', 0),
('cross_cols', ((0, 0, 0), (255, 0, 0))),
('cross_times', ('Infinity', 1)),
('orders', []),
('disp_ops', None)])
DEFAULTS['disp_ops'] = OrderedDict([('fullscreen', False),
('priority', None),
('logtime', False),
('logdur', False),
('trigser', False),
('trigpar', False),
('fpst', 0),
('phototest', False),
('photoburst', False),
('eyetrack', False),
('etuser', False),
('etvideo', None),
('tryagain', 0),
('trybreak', None),
('repeats', 1)])
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
export_fmt -- image format for animation to be exported as
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'export_fmt':
if value not in EXPORT_FMTS:
msg = 'image format not recognized or supported'
raise FileFormatError(msg)
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
# Vars that are dicts
dicts_to_load = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_load = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
for d_name in dicts_to_load:
d = self.__class__.DEFAULTS[d_name]
try:
d_el = [node for node in project.childNodes if
node.localName == d_name and
node.namespaceURI == XML_NAMESPACE][0]
for var in d.keys():
try:
d[var] = eval(xml_get(d_el, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}' in '{1}'".\
format(var, d_name)
print "using default value '{0}' instead...".\
format(d[var])
except IndexError:
print "warning: missing attribute set '{0}'".format(d_name)
print "using default values instead..."
setattr(self, d_name, d)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
# Vars that are dicts
dicts_to_save = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_save = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for d_name in dicts_to_save:
d_el = doc.createElement(d_name)
project.appendChild(d_el)
d = getattr(self, d_name)
for k, v in d.iteritems():
xml_set(doc, d_el, k, repr(v))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, **keywords):
"""Displays the project animation on the screen.
+ name -- name that logfile will be saved with
+
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
priority -- priority level to which process should be raised
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
trigser -- send triggers through serial port when each group is shown
trigpar -- send triggers through parallel port when each group is shown
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- append a wait screen to the group queue every time
after this many groups have been appended to the queue
repeats -- number of times specified order of display groups should
be repeated
order -- order in which groups (specified by id) will be displayed
"""
# Create RunState
- disp_ops = self.__class___.DEFAULTS['disp_ops']
+ disp_ops = self.disp_ops
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
- if 'order' in keywords.keys():
- order = keywords['order']
+ if 'name' in keywords.keys() and keywords['name'] != None:
+ name = keywords['name']
else:
+ timestr = datetime.today().strftime('_%Y-%m-%d_%H-%M-%S')
+ name = self.name + timestr
+ if 'order' in keywords.keys() and len(keywords['order']) > 0:
+ order = keywords['order']
+ elif len(self.orders) > 0:
order = random.choice(self.orders)
- runstate = CkgRunState(res=self.res, fps=self.fps, bg=self.bg,
+ else:
+ order = range(len(self.groups))
+ runstate = CkgRunState(name=name,
+ res=self.res, fps=self.fps, bg=self.bg,
cross_cols=self.cross_cols,
+ cross_times=self.cross_times,
disp_ops=disp_ops, order=order)
runstate.start()
+ waitscreen = CkgWaitScreen()
# Count through pre
for count in range(self.pre * self.fps):
+ if runstate.window.has_exit:
+ break
runstate.update()
# Loop through repeats
for i in range(runstate.disp_ops['repeats']):
# Show waitscreen
- waitscreen = CkgWaitscreen()
+ waitscreen.reset()
waitscreen.display(runstate)
# Loop through display groups
runstate.events['blk_on'] = True
for gid in runstate.order:
- self.groups[gid].display(runstate)
+ if gid == -1:
+ waitscreen.reset()
+ waitscreen.display(runstate)
+ else:
+ self.groups[gid].display(runstate)
+ # Append failed groups
+ if runstate.disp_ops['eyetrack'] and runstate.truefail:
+ if len(runstate.add_gids) < runstate.disp_ops['tryagain']:
+ runstate.add_gids.append(gid)
+ else:
+ runstate.fail_gids.append(gid)
runstate.events['blk_off'] = True
+ # Loop through added groups
+ if runstate.disp_ops['eyetrack']:
+ for blk in grouper(runstate.add_gids,
+ runstate.disp_ops['trybreak']):
+ # Show waitscreen
+ waitscreen.reset()
+ waitscreen.display(runstate)
+ runstate.events['blk_on'] = True
+ # Loop through display groups
+ for gid in blk:
+ if gid != None:
+ self.groups[gid].display(runstate)
+ runstate.events['blk_on'] = True
# Count through post
for count in range(self.post * self.fps):
+ if runstate.window.has_exit:
+ break
runstate.update()
# Stop and output log
runstate.stop()
runstate.log()
def export(self, export_dir, export_duration, groupq=[],
export_fmt=None, folder=True, force=False):
if not os.path.isdir(export_dir):
msg = 'export path is not a directory'
raise IOError(msg)
if export_fmt == None:
export_fmt = self.export_fmt
# Set-up groups and variables that control their display
if groupq == []:
groupq = list(self.groups)
n = -1
groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Limit export duration to display duration
frames = export_duration * self.fps
frames = min(frames, disp_end)
# Warn user if a lot of frames will be exported
if frames > MAX_EXPORT_FRAMES and not force:
msg = 'very large number ({0}) of frames to be exported'.\
format(frames)
raise FrameOverflowError(msg)
# Create folder to store images if necessary
if folder:
export_dir = os.path.join(export_dir,
self.name + EXPORT_DIR_SUFFIX)
if not os.path.isdir(export_dir):
os.mkdir(export_dir)
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Set up canvas and framebuffer object
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
# Main loop
while count < frames:
fbo.clear()
if groups_visible:
# Get next group from queue
if n < 0 or groupq[n].over:
n += 1
if n >= len(groupq):
groups_visible = False
else:
groupq[n].reset()
# Draw and then update group
if n >= 0:
groupq[n].draw()
groupq[n].update(fps=self.fps, fpst=0)
# Draw fixation cross based on current count
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Save current frame to file
savepath = \
os.path.join(export_dir,
'{0}{2}.{1}'.
format(self.name, export_fmt,
repr(count).zfill(numdigits(frames-1))))
canvas.save(savepath)
# Increment count and set whether groups should be shown
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
fbo.delete()
class CkgRunState:
"""Contains information about the state of a checkergen project
when it is being displayed or exported."""
- DEFAULTS = dict([('res', None),
+ DEFAULTS = dict([('name', 'untitled'),
+ ('res', None),
('fps', None),
('bg', None),
('cross_cols', None),
+ ('cross_times', None),
('order', []),
('disp_ops', None),
('events', None),
('add_gids', []),
('fail_gids', []),
('timestamps', []),
('durstamps', []),
('trigstamps', [])])
DEFAULTS['events'] = dict([('blk_on', False),
('blk_off', False),
('track_on', False),
('track_off', False),
('fix_on', False),
('fix_off', False),
('grp_on', False),
('grp_off', False),
('sids', set())])
def __init__(self, **keywords):
"""Creates the RunState."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
def start(self):
"""Initialize all subsystems and start the run."""
if self.disp_ops == None:
msg = "RunState lacks display options"
raise ValueError(msg)
- if min(self.res, self.fps, self.bg, self.cross_cols) == None:
+ if min(self.res, self.fps, self.bg,
+ self.cross_cols, self.cross_times) == None:
msg = "RunState intialized with insufficent project information"
raise ValueError(msg)
- self.count = 0
- self.trycount = self.disp_ops['tryagain']
+ self._count = 0
# Create fixation crosses
self.fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if self.disp_ops['phototest']:
self.test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Initialize ports
if self.disp_ops['trigser']:
if not trigger.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trigpar']:
if not trigger.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
- trigger.init(trigser, trigpar)
+ trigger.init(self.disp_ops['trigser'], self.disp_ops['trigpar'])
# Initialize eyetracking
if self.disp_ops['eyetrack']:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trybreak'] == None:
self.disp_ops['trybreak'] = len(self.order)
self.fixated = False
self.old_fixated = False
self.tracked = False
self.old_tracked = False
+ self.fix_fail = False
+ self.true_fail = False
eyetracking.select_source(self.disp_ops['etuser'],
self.disp_ops['etvideo'])
eyetracking.start()
# Stretch to fit screen only if project res does not equal screen res
self.scaling = False
if self.disp_ops['fullscreen']:
self.window = pyglet.window.Window(fullscreen=True, visible=False)
if (self.window.width, self.window.height) != self.res:
self.scaling = True
else:
self.window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
self.keystates = pyglet.window.key.KeyStateHandler()
- self.window.push_handlers(keystates)
+ self.window.push_handlers(self.keystates)
# Clear window and make visible
self.window.switch_to()
graphics.set_clear_color(self.bg)
self.window.clear()
self.window.set_visible()
# Create framebuffer object for drawing unscaled scene
if self.scaling:
self.canvas = pyglet.image.Texture.create(*self.res)
- self.fbo = graphics.Framebuffer(canvas)
+ self.fbo = graphics.Framebuffer(self.canvas)
self.fbo.start_render()
graphics.set_clear_color(self.bg)
self.fbo.clear()
# Set process priority
if self.disp_ops['priority'] != None:
if not priority.available[sys.platform]:
msg = "setting priority not available on {0}".\
format(sys.platform)
raise NotImplementedError(msg)
else:
if self.disp_ops['priority'].isdigit():
self.disp_ops['priority'] = int(self.disp_ops['priority'])
priority.set(self.disp_ops['priority'])
# Start timers
if self.disp_ops['logtime']:
self.timer = Timer()
self.timer.start()
if self.disp_ops['logdur']:
self.dur = Timer()
self.dur.start()
def update(self):
"""Update the RunState."""
# Check for tracking and fixation
if self.disp_ops['eyetrack']:
self.old_tracked = self.tracked
self.tracked = eyetracking.is_tracked()
self.old_fixated = self.fixated
self.fixated = eyetracking.is_fixated(FIX_POS, FIX_RANGE, FIX_PER)
- if fixated:
+ if self.fixated:
# Draw normal cross color if fixating
- fix_crosses[0].draw()
+ self.fix_crosses[0].draw()
else:
# Draw alternative cross color if not fixating
- fix_crosses[1].draw()
+ self.fix_crosses[1].draw()
# Update eyetracking events
if self.tracked != self.old_tracked:
if self.tracked:
self.events['track_on'] = True
else:
self.events['track_off'] = True
if self.fixated != self.old_fixated:
if self.fixated:
self.events['fix_on'] = True
else:
self.events['fix_off'] = True
+ # Check for failure of trial
+ if self.tracked and not self.fixated:
+ self.fix_fail = True
else:
# Change cross color based on time
- if (self.count % (sum(self.cross_times) * self.fps)
+ if (self._count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
- fix_crosses[0].draw()
+ self.fix_crosses[0].draw()
else:
- fix_crosses[1].draw()
+ self.fix_crosses[1].draw()
# Blit canvas to screen if necessary
if self.scaling:
self.fbo.end_render()
- self.window.switch_to()
self.canvas.blit(0, 0)
+ self.window.switch_to()
self.window.dispatch_events()
self.window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to lists
if self.disp_ops['logtime']:
self.timestamps.append(self.timer.elapsed())
elif self.disp_ops['logdur']:
self.timestamps.append('')
if self.disp_ops['logdur']:
self.durstamps.append(self.dur.restart())
elif self.disp_ops['logtime']:
self.durstamps.append('')
# Send trigger ASAP after flip
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
trigger.send(trigser, trigpar, self.encode_events())
# Log when triggers are sent
- if self.disp_ops['logtime']:
- if self.encode_events() != None:
- trigstamps.append(self.encode_events())
- else:
- trigstamps.append('')
+ if (self.disp_ops['logtime'] and
+ (self.disp_ops['trigser'] or self.disp_ops['trigpar']) and
+ self.encode_events() != None):
+ self.trigstamps.append(self.encode_events())
+ else:
+ self.trigstamps.append('')
# Clear canvas, events, prepare for next frame
if self.scaling:
self.fbo.start_render()
self.fbo.clear()
else:
self.window.clear()
self.events = self.__class__.DEFAULTS['events']
- self.count += 1
+ self._count += 1
def stop(self):
"""Clean up RunState."""
if self.disp_ops['eyetrack']:
eyetracking.stop()
- self.window.close()
if self.scaling:
self.fbo.delete()
del self.canvas
+ self.window.close()
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
trigger.quit(trigser, trigpar)
if self.disp_ops['priority'] != None:
priority.set('normal')
def log(self, path=None):
"""Write a log file for the experimental run in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, LOG_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(LOG_FMT):
path = '{0}.{1}'.format(path, LOG_FMT)
- with open(path, 'wb') as runfile:
- writer = csv.writer(runfile, dialect='excel-tab')
+ with open(path, 'wb') as logfile:
+ writer = csv.writer(logfile, dialect='excel-tab')
writer.writerow(['checkergen log file'])
- writer.writerow(['flags:', self.flags])
- writer.writerow(['blocks:', self.blocks])
- writer.writerow(['sequence:'] + self.sequence)
- if self.add_idlist != None:
- writer.writerow(['groups appended:'])
- rowlist = grouper(len(self.sequence), self.add_idlist, '')
- for row in rowlist:
- writer.writerow(row)
- if self.fail_idlist != None:
- writer.writerow(['groups failed (not appended):'])
- rowlist = grouper(len(self.sequence), self.fail_idlist, '')
- for row in rowlist:
- writer.writerow(row)
- stamps = [self.timestamps, self.durstamps, self.trigstamps]
- if len(max(stamps)) > 0:
- for l in stamps:
- if len(l) == 0:
- l = [''] * len(max(stamps))
+ writer.writerow(['display options:'])
+ writer.writerow(self.disp_ops.keys())
+ writer.writerow(self.disp_ops.values())
+ writer.writerow(['order:'] + self.order)
+ if self.disp_ops['eyetrack']:
+ write.writerow(['groups added'])
+ for blk in grouper(self.add_gids,
+ self.disp_ops['trybreak'], ''):
+ write.writerow(blk)
+ write.writerow(['groups failed'])
+ for blk in grouper(self.fail_gids,
+ self.disp_ops['trybreak'], ''):
+ write.writerow(blk)
+ if self.disp_ops['logtime'] or self.disp_ops['logdur']:
+ stamps = [self.timestamps, self.durstamps, self.trigstamps]
writer.writerow(['timestamps', 'durations', 'triggers'])
- for row in zip(*stamps):
- writer.writerow(row)
+ for stamp in zip(*stamps):
+ writer.writerow(list(stamp))
class CkgDisplayGroup:
DEFAULTS = OrderedDict([('pre', 0), ('disp', 'Infinity'), ('post', 0)])
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets counts and all contained shapes."""
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, runstate):
"""Draws all contained shapes during the appropriate interval."""
for shape in self.shapes:
shape.draw(photoburst=runstate.disp_ops['photoburst'])
def update(self, runstate):
"""Updates contained shapes, sets event triggers."""
# Set events to be sent
if runstate.disp_ops['fpst'] > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= fpst:
runstate.events['sids'].add(n)
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(runstate.fps)
def display(self, runstate):
"""Display the group in the context described by supplied runstate."""
+ self.reset()
for count in range(self.pre * runstate.fps):
+ if runstate.window.has_exit:
+ break
runstate.update()
runstate.events['blk_on'] = True
+ if runstate.disp_ops['eyetrack']:
+ runstate.fix_fail = False
+ renstate.true_fail = False
for count in range(self.disp * runstate.fps):
+ if runstate.window.has_exit:
+ break
self.draw(runstate)
self.update(runstate)
runstate.update()
runstate.events['blk_off'] = True
+ if runstate.disp_ops['eyetrack']:
+ if runstate.fix_fail:
+ runstate.true_fail = True
for count in range(self.post * runstate.fps):
+ if runstate.window.has_exit:
+ break
runstate.update()
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.steps_done = 0
def draw(self, runstate):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, runstate):
"""Checks for keypress, sends trigger upon end."""
if max([runstate.keystates[key] for
key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
def display(self, runstate):
"""Displays waitscreen in context described by supplied runstate."""
while self.steps_done < self.num_steps:
+ if runstate.window.has_exit:
+ break
self.draw(runstate)
self.update(runstate)
runstate.update()
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = OrderedDict([('dims', (5, 5)),
('init_unit', (30, 30)),
('end_unit', (50, 50)),
('position', (0, 0)),
('anchor', 'bottomleft'),
('cols', ((0, 0, 0), (255, 255, 255))),
('freq', 1),
('phase', 0)])
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
if INT_HALF_PERIODS:
frames_per_half_period = round(fps / (self.freq * 2))
degs_per_frame = 180 / to_decimal(frames_per_half_period)
else:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
if PRERENDER_TO_TEXTURE:
init_pos = [(1 - a)* s/to_decimal(2) for s, a in
zip(self._size, graphics.locations[self.anchor])]
else:
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
anchor=self.anchor)
cur_unit_rect.col = self.cols[(i + j) % 2]
cur_unit_rect.add_to_batch(self._batches[0])
cur_unit_rect.col = self.cols[(i + j + 1) % 2]
cur_unit_rect.add_to_batch(self._batches[1])
# Increase x values
cur_unit_pos[0] += \
graphics.locations[self.anchor][0] * cur_unit[0]
cur_unit[0] += unit_grad[0]
# Reset x values
cur_unit_pos[0] = init_pos[0]
cur_unit[0] = init_unit[0]
# Increase y values
cur_unit_pos[1] += \
graphics.locations[self.anchor][1] * cur_unit[1]
cur_unit[1] += unit_grad[1]
if PRERENDER_TO_TEXTURE:
# Create textures
int_size = [int(round(s)) for s in self._size]
self._prerenders =\
[pyglet.image.Texture.create(*int_size) for n in range(2)]
# Set up framebuffer
fbo = graphics.Framebuffer()
for n in range(2):
fbo.attach_texture(self._prerenders[n])
# Draw batch to texture
fbo.start_render()
self._batches[n].draw()
fbo.end_render()
# Anchor textures for correct blitting later
self._prerenders[n].anchor_x, self._prerenders[n].anchor_y =\
[int(round((1 - a)* s/to_decimal(2))) for s, a in
zip(self._size, graphics.locations[self.anchor])]
fbo.delete()
# Delete batches since they won't be used
del self._batches
self._computed = True
def draw(self, photoburst=False, always_compute=False):
"""Draws appropriate prerender depending on current phase.
photoburst -- draw first color for only one frame for testing purposes
always_compute -- recompute what the checkerboard should look like
every frame
"""
if not self._computed or always_compute:
self.compute()
self._cur_phase %= 360
n = int(self._cur_phase // 180)
if photoburst and n == 0 and not self.flipped:
n = 1
if PRERENDER_TO_TEXTURE:
self._prerenders[n].blit(*self.position)
else:
self._batches[n].draw()
def lazydraw(self):
"""Only draws on color reversal."""
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if (cur_n != prev_n) or self._first_draw:
self.draw()
if self._first_draw:
self._first_draw = False
diff --git a/src/utils.py b/src/utils.py
index 69fdfde..2e2febd 100644
--- a/src/utils.py
+++ b/src/utils.py
@@ -1,95 +1,95 @@
"""Utility functions and classes."""
import os
import time
import math
from decimal import *
from itertools import *
def numdigits(x):
"""Returns number of digits in a decimal integer."""
if x == 0:
return 1
elif x < 0:
x = -x
return int(math.log(x, 10)) + 1
def public_dir(obj):
"""Returns all 'public' attributes of an object"""
names = dir(obj)
for name in names[:]:
if name[0] == '_' or name[-1] == '_':
names.remove(name)
return names
def to_decimal(s):
"""ValueError raising Decimal converter."""
try:
return Decimal(s)
except (InvalidOperation, TypeError):
try:
return Decimal(str(s))
except (InvalidOperation, TypeError):
raise ValueError
def to_color(s, sep=','):
"""Tries to cast a string to a color (3-tuple)."""
c = tuple([int(x) for x in s.split(sep)])
if len(c) != 3:
raise ValueError
return c
def cyclic_permute(self, sequence):
"""Return a list of all cyclic permutations of supplied sequence."""
return [[sequence[i - j] for i in range(n)] for j in range(n, 0, -1)]
# From itertools documentation
-def grouper(n, iterable, fillvalue=None):
- """grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"""
+def grouper(iterable, n, fillvalue=None):
+ """grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"""
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
class Timer:
"""High-res timer that should be cross-platform."""
def __init__(self):
# Assigns appropriate clock function based on OS
if os.name == 'nt':
self.clock = time.clock
self.clock()
elif os.name == 'posix':
self.clock = time.time
self.running = False
def start(self):
self.start_time = self.clock()
self.running = True
def stop(self):
if not self.running:
return None
self.stop_time = self.clock()
self.running = False
return self.stop_time - self.start_time
def elapsed(self):
if not self.running:
return None
cur_time = self.clock()
return cur_time - self.start_time
def restart(self):
old_start_time = self.start_time
self.start_time = self.clock()
self.running = True
return self.start_time - old_start_time
def tick(self, fps):
"""Limits loop to specified fps. To be placed at start of loop."""
fps = float(fps)
ret = self.elapsed()
if self.elapsed() != -1:
while self.elapsed() < (1.0 / fps):
pass
self.start()
if ret != -1:
return ret * 1000
|
ztangent/checkergen
|
5c410fe5f542d714698c33895ba4f82e70f3205d
|
Display rewrite theoretically complete.
|
diff --git a/src/core.py b/src/core.py
index ef0671e..aec930b 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,1155 +1,1134 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
-CkgExp -- A checkergen experiment, describes how a projet is displayed.
CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import random
import itertools
from xml.dom import minidom
import pyglet
import graphics
import priority
import trigger
import eyetracking
from utils import *
# Use OrderedDict substitute if we don't have Python 2.7
if sys.version_info < (2, 7):
from odict import OrderedDict
else:
from collections import OrderedDict
CKG_FMT = 'ckg'
EXP_FMT = 'ckx'
LOG_FMT = 'log'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
MAX_EXPORT_FRAMES = 100000
PRERENDER_TO_TEXTURE = False
INT_HALF_PERIODS = True
EXPORT_FMTS = ['png']
EXPORT_DIR_SUFFIX = '-anim'
FIX_POS = (0, 0)
FIX_RANGE = (20, 20)
FIX_PER = 350
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = OrderedDict([('name', 'untitled'),
('fps', 60),
('res', (800, 600)),
('bg', (127, 127, 127)),
('export_fmt', 'png'),
('pre', 0),
('post', 0),
('cross_cols', ((0, 0, 0), (255, 0, 0))),
('cross_times', ('Infinity', 1)),
('orders', []),
('disp_ops', None)])
DEFAULTS['disp_ops'] = OrderedDict([('fullscreen', False),
('priority', None),
('logtime', False),
('logdur', False),
('trigser', False),
('trigpar', False),
('fpst', 0),
('phototest', False),
('photoburst', False),
('eyetrack', False),
('etuser', False),
('etvideo', None),
('tryagain', 0),
('trybreak', None),
('repeats', 1)])
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
export_fmt -- image format for animation to be exported as
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'export_fmt':
if value not in EXPORT_FMTS:
msg = 'image format not recognized or supported'
raise FileFormatError(msg)
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
# Vars that are dicts
dicts_to_load = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_load = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
for d_name in dicts_to_load:
d = self.__class__.DEFAULTS[d_name]
try:
d_el = [node for node in project.childNodes if
node.localName == d_name and
node.namespaceURI == XML_NAMESPACE][0]
for var in d.keys():
try:
d[var] = eval(xml_get(d_el, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}' in '{1}'".\
format(var, d_name)
print "using default value '{0}' instead...".\
format(d[var])
except IndexError:
print "warning: missing attribute set '{0}'".format(d_name)
print "using default values instead..."
setattr(self, d_name, d)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
# Vars that are dicts
dicts_to_save = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_save = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for d_name in dicts_to_save:
d_el = doc.createElement(d_name)
project.appendChild(d_el)
d = getattr(self, d_name)
for k, v in d.iteritems():
xml_set(doc, d_el, k, repr(v))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, **keywords):
"""Displays the project animation on the screen.
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
priority -- priority level to which process should be raised
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
trigser -- send triggers through serial port when each group is shown
trigpar -- send triggers through parallel port when each group is shown
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- append a wait screen to the group queue every time
after this many groups have been appended to the queue
repeats -- number of times specified order of display groups should
be repeated
order -- order in which groups (specified by id) will be displayed
"""
# Create RunState
disp_ops = self.__class___.DEFAULTS['disp_ops']
for kw in keywords.keys():
if kw in disp_ops.keys() and keywords[kw] != None:
disp_ops[kw] = keywords[kw]
if 'order' in keywords.keys():
order = keywords['order']
else:
order = random.choice(self.orders)
- runstate = CkgRunState(proj=self, disp_ops=disp_ops, order=order)
-
+ runstate = CkgRunState(res=self.res, fps=self.fps, bg=self.bg,
+ cross_cols=self.cross_cols,
+ disp_ops=disp_ops, order=order)
runstate.start()
# Count through pre
for count in range(self.pre * self.fps):
runstate.update()
-
# Loop through repeats
for i in range(runstate.disp_ops['repeats']):
# Show waitscreen
waitscreen = CkgWaitscreen()
waitscreen.display(runstate)
# Loop through display groups
+ runstate.events['blk_on'] = True
for gid in runstate.order:
self.groups[gid].display(runstate)
-
+ runstate.events['blk_off'] = True
# Count through post
for count in range(self.post * self.fps):
runstate.update()
- count += 1
+ # Stop and output log
runstate.stop()
runstate.log()
def export(self, export_dir, export_duration, groupq=[],
export_fmt=None, folder=True, force=False):
if not os.path.isdir(export_dir):
msg = 'export path is not a directory'
raise IOError(msg)
if export_fmt == None:
export_fmt = self.export_fmt
# Set-up groups and variables that control their display
if groupq == []:
groupq = list(self.groups)
n = -1
groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Limit export duration to display duration
frames = export_duration * self.fps
frames = min(frames, disp_end)
# Warn user if a lot of frames will be exported
if frames > MAX_EXPORT_FRAMES and not force:
msg = 'very large number ({0}) of frames to be exported'.\
format(frames)
raise FrameOverflowError(msg)
# Create folder to store images if necessary
if folder:
export_dir = os.path.join(export_dir,
self.name + EXPORT_DIR_SUFFIX)
if not os.path.isdir(export_dir):
os.mkdir(export_dir)
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Set up canvas and framebuffer object
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
# Main loop
while count < frames:
fbo.clear()
if groups_visible:
# Get next group from queue
if n < 0 or groupq[n].over:
n += 1
if n >= len(groupq):
groups_visible = False
else:
groupq[n].reset()
# Draw and then update group
if n >= 0:
groupq[n].draw()
groupq[n].update(fps=self.fps, fpst=0)
# Draw fixation cross based on current count
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Save current frame to file
savepath = \
os.path.join(export_dir,
'{0}{2}.{1}'.
format(self.name, export_fmt,
repr(count).zfill(numdigits(frames-1))))
canvas.save(savepath)
# Increment count and set whether groups should be shown
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
fbo.delete()
class CkgRunState:
"""Contains information about the state of a checkergen project
when it is being displayed or exported."""
- DEFAULTS = dict([('proj', None),
+ DEFAULTS = dict([('res', None),
+ ('fps', None),
+ ('bg', None),
+ ('cross_cols', None),
('order', []),
('disp_ops', None),
('events', None),
('add_gids', []),
('fail_gids', []),
('timestamps', []),
('durstamps', []),
('trigstamps', [])])
DEFAULTS['events'] = dict([('blk_on', False),
('blk_off', False),
('track_on', False),
('track_off', False),
('fix_on', False),
('fix_off', False),
('grp_on', False),
('grp_off', False),
- ('sids', [])])
+ ('sids', set())])
def __init__(self, **keywords):
"""Creates the RunState."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
def start(self):
"""Initialize all subsystems and start the run."""
- if self.proj == None:
- msg = "RunState lacks associated project, run cannot begin"
+ if self.disp_ops == None:
+ msg = "RunState lacks display options"
+ raise ValueError(msg)
+
+ if min(self.res, self.fps, self.bg, self.cross_cols) == None:
+ msg = "RunState intialized with insufficent project information"
raise ValueError(msg)
self.count = 0
self.trycount = self.disp_ops['tryagain']
# Create fixation crosses
- self.fix_crosses = [graphics.Cross([r/2 for r in self.proj.res],
+ self.fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
- for cross_col in self.proj.cross_cols]
+ for cross_col in self.cross_cols]
# Create test rectangle
if self.disp_ops['phototest']:
self.test_rect = graphics.Rect((0, self.res[1]),
- [r/8 for r in self.proj.res],
+ [r/8 for r in self.res],
anchor='topleft')
# Initialize ports
if self.disp_ops['trigser']:
if not trigger.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trigpar']:
if not trigger.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
trigger.init(trigser, trigpar)
# Initialize eyetracking
if self.disp_ops['eyetrack']:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trybreak'] == None:
- self.disp_ops['trybreak'] = len(self.proj.groups)
+ self.disp_ops['trybreak'] = len(self.order)
self.fixated = False
self.old_fixated = False
self.tracked = False
self.old_tracked = False
eyetracking.select_source(self.disp_ops['etuser'],
self.disp_ops['etvideo'])
eyetracking.start()
# Stretch to fit screen only if project res does not equal screen res
self.scaling = False
if self.disp_ops['fullscreen']:
self.window = pyglet.window.Window(fullscreen=True, visible=False)
- if (self.window.width, self.window.height) != self.proj.res:
+ if (self.window.width, self.window.height) != self.res:
self.scaling = True
else:
- self.window = pyglet.window.Window(*self.proj.res, visible=False)
+ self.window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
self.keystates = pyglet.window.key.KeyStateHandler()
self.window.push_handlers(keystates)
# Clear window and make visible
self.window.switch_to()
- graphics.set_clear_color(self.proj.bg)
+ graphics.set_clear_color(self.bg)
self.window.clear()
self.window.set_visible()
# Create framebuffer object for drawing unscaled scene
if self.scaling:
- self.canvas = pyglet.image.Texture.create(*self.proj.res)
+ self.canvas = pyglet.image.Texture.create(*self.res)
self.fbo = graphics.Framebuffer(canvas)
self.fbo.start_render()
- graphics.set_clear_color(self.proj.bg)
+ graphics.set_clear_color(self.bg)
self.fbo.clear()
# Set process priority
if self.disp_ops['priority'] != None:
if not priority.available[sys.platform]:
msg = "setting priority not available on {0}".\
format(sys.platform)
raise NotImplementedError(msg)
else:
if self.disp_ops['priority'].isdigit():
self.disp_ops['priority'] = int(self.disp_ops['priority'])
priority.set(self.disp_ops['priority'])
# Start timers
if self.disp_ops['logtime']:
self.timer = Timer()
self.timer.start()
if self.disp_ops['logdur']:
self.dur = Timer()
self.dur.start()
def update(self):
"""Update the RunState."""
# Check for tracking and fixation
if self.disp_ops['eyetrack']:
self.old_tracked = self.tracked
self.tracked = eyetracking.is_tracked()
self.old_fixated = self.fixated
self.fixated = eyetracking.is_fixated(FIX_POS, FIX_RANGE, FIX_PER)
if fixated:
# Draw normal cross color if fixating
fix_crosses[0].draw()
else:
# Draw alternative cross color if not fixating
fix_crosses[1].draw()
# Update eyetracking events
if self.tracked != self.old_tracked:
if self.tracked:
self.events['track_on'] = True
else:
self.events['track_off'] = True
if self.fixated != self.old_fixated:
if self.fixated:
self.events['fix_on'] = True
else:
self.events['fix_off'] = True
else:
# Change cross color based on time
if (self.count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Blit canvas to screen if necessary
if self.scaling:
self.fbo.end_render()
self.window.switch_to()
self.canvas.blit(0, 0)
self.window.dispatch_events()
self.window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to lists
if self.disp_ops['logtime']:
self.timestamps.append(self.timer.elapsed())
elif self.disp_ops['logdur']:
self.timestamps.append('')
if self.disp_ops['logdur']:
self.durstamps.append(self.dur.restart())
elif self.disp_ops['logtime']:
self.durstamps.append('')
# Send trigger ASAP after flip
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
trigger.send(trigser, trigpar, self.encode_events())
# Log when triggers are sent
if self.disp_ops['logtime']:
if self.encode_events() != None:
trigstamps.append(self.encode_events())
else:
trigstamps.append('')
# Clear canvas, events, prepare for next frame
if self.scaling:
self.fbo.start_render()
self.fbo.clear()
else:
self.window.clear()
self.events = self.__class__.DEFAULTS['events']
self.count += 1
def stop(self):
"""Clean up RunState."""
if self.disp_ops['eyetrack']:
eyetracking.stop()
self.window.close()
if self.scaling:
self.fbo.delete()
del self.canvas
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
trigger.quit(trigser, trigpar)
if self.disp_ops['priority'] != None:
priority.set('normal')
def log(self, path=None):
"""Write a log file for the experimental run in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, LOG_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(LOG_FMT):
path = '{0}.{1}'.format(path, LOG_FMT)
with open(path, 'wb') as runfile:
writer = csv.writer(runfile, dialect='excel-tab')
writer.writerow(['checkergen log file'])
writer.writerow(['flags:', self.flags])
writer.writerow(['blocks:', self.blocks])
writer.writerow(['sequence:'] + self.sequence)
if self.add_idlist != None:
writer.writerow(['groups appended:'])
rowlist = grouper(len(self.sequence), self.add_idlist, '')
for row in rowlist:
writer.writerow(row)
if self.fail_idlist != None:
writer.writerow(['groups failed (not appended):'])
rowlist = grouper(len(self.sequence), self.fail_idlist, '')
for row in rowlist:
writer.writerow(row)
stamps = [self.timestamps, self.durstamps, self.trigstamps]
if len(max(stamps)) > 0:
for l in stamps:
if len(l) == 0:
l = [''] * len(max(stamps))
writer.writerow(['timestamps', 'durations', 'triggers'])
for row in zip(*stamps):
writer.writerow(row)
class CkgDisplayGroup:
DEFAULTS = OrderedDict([('pre', 0), ('disp', 'Infinity'), ('post', 0)])
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
- """Resets internal count and all contained shapes."""
- self._count = 0
- self._start = self.pre
- self._stop = self.pre + self.disp
- self._end = self.pre + self.disp + self.post
- self.over = False
- self.old_visible = False
- if self._start == 0 and self._stop > 0:
- self.visible = True
- else:
- self.visible = False
- if self._end == 0:
- self.over = True
+ """Resets counts and all contained shapes."""
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
- def draw(self, lazy=False, photoburst=False):
+ def draw(self, runstate):
"""Draws all contained shapes during the appropriate interval."""
- if self.visible:
- for shape in self.shapes:
- if lazy:
- shape.lazydraw()
- else:
- shape.draw(photoburst=photoburst)
-
- def update(self, **keywords):
- """Increments internal count, makes group visible when appropriate.
-
- fps -- refresh rate of the display in frames per second
-
- fpst -- flips per shape trigger, i.e. number of shape color reversals
- (flips) that occur for a unique trigger to be sent for that shape
-
- """
+ for shape in self.shapes:
+ shape.draw(photoburst=runstate.disp_ops['photoburst'])
+
+ def update(self, runstate):
+ """Updates contained shapes, sets event triggers."""
+ # Set events to be sent
+ if runstate.disp_ops['fpst'] > 0:
+ for n, shape in enumerate(self.shapes):
+ if shape.flipped:
+ self._flip_count[n] += 1
+ if self._flip_count[n] >= fpst:
+ runstate.events['sids'].add(n)
+ self._flip_count[n] = 0
+ # Update contained shapes
+ for shape in self.shapes:
+ shape.update(runstate.fps)
- fps = keywords['fps']
- fpst = keywords['fpst']
-
- if self.visible:
- # Set triggers to be sent
- if fpst > 0:
- for n, shape in enumerate(self.shapes):
- if shape.flipped:
- self._flip_count[n] += 1
- if self._flip_count[n] >= fpst:
- trigger.CUR_STATE['shape'] = 1
- trigger.CUR_STATE['sid'] = n
- self._flip_count[n] = 0
- # Update contained shapes
- for shape in self.shapes:
- shape.update(fps)
-
- # Increment count and set flags for the next frame
- self._count += 1
- self.old_visible = self.visible
- if (self._start * fps) <= self._count < (self._stop * fps):
- self.visible = True
- else:
- self.visible = False
- if self._count >= (self._end * fps):
- self.over = True
- else:
- self.over = False
+ def display(self, runstate):
+ """Display the group in the context described by supplied runstate."""
+ for count in range(self.pre * runstate.fps):
+ runstate.update()
+ runstate.events['blk_on'] = True
+ for count in range(self.disp * runstate.fps):
+ self.draw(runstate)
+ self.update(runstate)
+ runstate.update()
+ runstate.events['blk_off'] = True
+ for count in range(self.post * runstate.fps):
+ runstate.update()
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
- self.visible = False
- self.old_visible = False
self.steps_done = 0
- self.over = False
- def draw(self, **keywords):
+ def draw(self, runstate):
"""Draw informative text."""
self.labels[self.steps_done].draw()
- def update(self, **keywords):
+ def update(self, runstate):
"""Checks for keypress, sends trigger upon end."""
-
- keystates = keywords['keystates']
-
- if max([keystates[key] for key in self.cont_keys[self.steps_done]]):
+ if max([runstate.keystates[key] for
+ key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
- if self.steps_done == self.num_steps:
- self.over = True
+
+ def display(self, runstate):
+ """Displays waitscreen in context described by supplied runstate."""
+ while self.steps_done < self.num_steps:
+ self.draw(runstate)
+ self.update(runstate)
+ runstate.update()
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = OrderedDict([('dims', (5, 5)),
('init_unit', (30, 30)),
('end_unit', (50, 50)),
('position', (0, 0)),
('anchor', 'bottomleft'),
('cols', ((0, 0, 0), (255, 255, 255))),
('freq', 1),
('phase', 0)])
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
if INT_HALF_PERIODS:
frames_per_half_period = round(fps / (self.freq * 2))
degs_per_frame = 180 / to_decimal(frames_per_half_period)
else:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
if PRERENDER_TO_TEXTURE:
init_pos = [(1 - a)* s/to_decimal(2) for s, a in
zip(self._size, graphics.locations[self.anchor])]
else:
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
anchor=self.anchor)
cur_unit_rect.col = self.cols[(i + j) % 2]
cur_unit_rect.add_to_batch(self._batches[0])
cur_unit_rect.col = self.cols[(i + j + 1) % 2]
cur_unit_rect.add_to_batch(self._batches[1])
# Increase x values
cur_unit_pos[0] += \
graphics.locations[self.anchor][0] * cur_unit[0]
cur_unit[0] += unit_grad[0]
# Reset x values
cur_unit_pos[0] = init_pos[0]
cur_unit[0] = init_unit[0]
# Increase y values
cur_unit_pos[1] += \
graphics.locations[self.anchor][1] * cur_unit[1]
cur_unit[1] += unit_grad[1]
if PRERENDER_TO_TEXTURE:
# Create textures
int_size = [int(round(s)) for s in self._size]
self._prerenders =\
[pyglet.image.Texture.create(*int_size) for n in range(2)]
# Set up framebuffer
fbo = graphics.Framebuffer()
for n in range(2):
fbo.attach_texture(self._prerenders[n])
# Draw batch to texture
fbo.start_render()
self._batches[n].draw()
fbo.end_render()
# Anchor textures for correct blitting later
self._prerenders[n].anchor_x, self._prerenders[n].anchor_y =\
[int(round((1 - a)* s/to_decimal(2))) for s, a in
zip(self._size, graphics.locations[self.anchor])]
fbo.delete()
# Delete batches since they won't be used
del self._batches
self._computed = True
def draw(self, photoburst=False, always_compute=False):
"""Draws appropriate prerender depending on current phase.
photoburst -- draw first color for only one frame for testing purposes
always_compute -- recompute what the checkerboard should look like
every frame
"""
if not self._computed or always_compute:
self.compute()
self._cur_phase %= 360
n = int(self._cur_phase // 180)
if photoburst and n == 0 and not self.flipped:
n = 1
if PRERENDER_TO_TEXTURE:
self._prerenders[n].blit(*self.position)
else:
self._batches[n].draw()
def lazydraw(self):
"""Only draws on color reversal."""
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if (cur_n != prev_n) or self._first_draw:
self.draw()
if self._first_draw:
self._first_draw = False
|
ztangent/checkergen
|
3479f85fe237ca6012552b47244cf8f058d71150
|
Fleshed out display a little more.
|
diff --git a/src/core.py b/src/core.py
index aba40b3..ef0671e 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,1123 +1,1155 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgExp -- A checkergen experiment, describes how a projet is displayed.
CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import random
import itertools
from xml.dom import minidom
import pyglet
import graphics
+import priority
import trigger
import eyetracking
from utils import *
# Use OrderedDict substitute if we don't have Python 2.7
if sys.version_info < (2, 7):
from odict import OrderedDict
else:
from collections import OrderedDict
CKG_FMT = 'ckg'
EXP_FMT = 'ckx'
LOG_FMT = 'log'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
MAX_EXPORT_FRAMES = 100000
PRERENDER_TO_TEXTURE = False
INT_HALF_PERIODS = True
EXPORT_FMTS = ['png']
EXPORT_DIR_SUFFIX = '-anim'
FIX_POS = (0, 0)
FIX_RANGE = (20, 20)
FIX_PER = 350
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = OrderedDict([('name', 'untitled'),
('fps', 60),
('res', (800, 600)),
('bg', (127, 127, 127)),
('export_fmt', 'png'),
('pre', 0),
('post', 0),
('cross_cols', ((0, 0, 0), (255, 0, 0))),
('cross_times', ('Infinity', 1)),
('orders', []),
('disp_ops', None)])
DEFAULTS['disp_ops'] = OrderedDict([('fullscreen', False),
- ('priority', 0),
+ ('priority', None),
('logtime', False),
('logdur', False),
('trigser', False),
('trigpar', False),
('fpst', 0),
('phototest', False),
('photoburst', False),
('eyetrack', False),
('etuser', False),
('etvideo', None),
('tryagain', 0),
('trybreak', None),
('repeats', 1)])
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
export_fmt -- image format for animation to be exported as
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'export_fmt':
if value not in EXPORT_FMTS:
msg = 'image format not recognized or supported'
raise FileFormatError(msg)
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
# Vars that are dicts
dicts_to_load = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_load = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
for d_name in dicts_to_load:
d = self.__class__.DEFAULTS[d_name]
try:
d_el = [node for node in project.childNodes if
node.localName == d_name and
node.namespaceURI == XML_NAMESPACE][0]
for var in d.keys():
try:
d[var] = eval(xml_get(d_el, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}' in '{1}'".\
format(var, d_name)
print "using default value '{0}' instead...".\
format(d[var])
except IndexError:
print "warning: missing attribute set '{0}'".format(d_name)
print "using default values instead..."
setattr(self, d_name, d)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
# Vars that are dicts
dicts_to_save = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_save = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for d_name in dicts_to_save:
d_el = doc.createElement(d_name)
project.appendChild(d_el)
d = getattr(self, d_name)
for k, v in d.iteritems():
xml_set(doc, d_el, k, repr(v))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
- def display(self, fullscreen=False, logtime=False, logdur=False,
- trigser=False, trigpar=False, fpst=0,
- phototest=False, photoburst=False,
- eyetrack=False, etuser=False, etvideo=None,
- tryagain=0, trybreak=None, groupq=[], run=None):
+ def display(self, **keywords):
"""Displays the project animation on the screen.
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
+ priority -- priority level to which process should be raised
+
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
trigser -- send triggers through serial port when each group is shown
trigpar -- send triggers through parallel port when each group is shown
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
- tryagain -- Append groups during which subject failed to fixate up to
+ tryagain -- append groups during which subject failed to fixate up to
this number of times to the group queue
- trybreak -- Append a wait screen to the group queue every time
+ trybreak -- append a wait screen to the group queue every time
after this many groups have been appended to the queue
- groupq -- queue of groups to be displayed, defaults to order of
- groups in project (i.e. groups[0] first, etc.)
+ repeats -- number of times specified order of display groups should
+ be repeated
- run -- experimental run where logged variables are saved (i.e.
- fail_idlist and time information)
+ order -- order in which groups (specified by id) will be displayed
"""
# Create RunState
+ disp_ops = self.__class___.DEFAULTS['disp_ops']
+ for kw in keywords.keys():
+ if kw in disp_ops.keys() and keywords[kw] != None:
+ disp_ops[kw] = keywords[kw]
+ if 'order' in keywords.keys():
+ order = keywords['order']
+ else:
+ order = random.choice(self.orders)
+ runstate = CkgRunState(proj=self, disp_ops=disp_ops, order=order)
- # Start run
+ runstate.start()
# Count through pre
+ for count in range(self.pre * self.fps):
+ runstate.update()
# Loop through repeats
- # Loop through display groups
+ for i in range(runstate.disp_ops['repeats']):
+ # Show waitscreen
+ waitscreen = CkgWaitscreen()
+ waitscreen.display(runstate)
+ # Loop through display groups
+ for gid in runstate.order:
+ self.groups[gid].display(runstate)
# Count through post
+ for count in range(self.post * self.fps):
+ runstate.update()
+ count += 1
- # Write log
+ runstate.stop()
runstate.log()
def export(self, export_dir, export_duration, groupq=[],
export_fmt=None, folder=True, force=False):
if not os.path.isdir(export_dir):
msg = 'export path is not a directory'
raise IOError(msg)
if export_fmt == None:
export_fmt = self.export_fmt
# Set-up groups and variables that control their display
if groupq == []:
groupq = list(self.groups)
n = -1
groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Limit export duration to display duration
frames = export_duration * self.fps
frames = min(frames, disp_end)
# Warn user if a lot of frames will be exported
if frames > MAX_EXPORT_FRAMES and not force:
msg = 'very large number ({0}) of frames to be exported'.\
format(frames)
raise FrameOverflowError(msg)
# Create folder to store images if necessary
if folder:
export_dir = os.path.join(export_dir,
self.name + EXPORT_DIR_SUFFIX)
if not os.path.isdir(export_dir):
os.mkdir(export_dir)
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Set up canvas and framebuffer object
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
# Main loop
while count < frames:
fbo.clear()
if groups_visible:
# Get next group from queue
if n < 0 or groupq[n].over:
n += 1
if n >= len(groupq):
groups_visible = False
else:
groupq[n].reset()
# Draw and then update group
if n >= 0:
groupq[n].draw()
groupq[n].update(fps=self.fps, fpst=0)
# Draw fixation cross based on current count
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Save current frame to file
savepath = \
os.path.join(export_dir,
'{0}{2}.{1}'.
format(self.name, export_fmt,
repr(count).zfill(numdigits(frames-1))))
canvas.save(savepath)
# Increment count and set whether groups should be shown
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
fbo.delete()
class CkgRunState:
"""Contains information about the state of a checkergen project
when it is being displayed or exported."""
DEFAULTS = dict([('proj', None),
('order', []),
('disp_ops', None),
('events', None),
('add_gids', []),
('fail_gids', []),
('timestamps', []),
('durstamps', []),
('trigstamps', [])])
DEFAULTS['events'] = dict([('blk_on', False),
('blk_off', False),
('track_on', False),
('track_off', False),
('fix_on', False),
('fix_off', False),
('grp_on', False),
('grp_off', False),
('sids', [])])
def __init__(self, **keywords):
"""Creates the RunState."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
def start(self):
"""Initialize all subsystems and start the run."""
if self.proj == None:
msg = "RunState lacks associated project, run cannot begin"
raise ValueError(msg)
self.count = 0
self.trycount = self.disp_ops['tryagain']
# Create fixation crosses
self.fix_crosses = [graphics.Cross([r/2 for r in self.proj.res],
(20, 20), col = cross_col)
for cross_col in self.proj.cross_cols]
# Create test rectangle
if self.disp_ops['phototest']:
self.test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.proj.res],
anchor='topleft')
# Initialize ports
if self.disp_ops['trigser']:
if not trigger.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trigpar']:
if not trigger.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
trigger.init(trigser, trigpar)
# Initialize eyetracking
if self.disp_ops['eyetrack']:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trybreak'] == None:
self.disp_ops['trybreak'] = len(self.proj.groups)
self.fixated = False
self.old_fixated = False
self.tracked = False
self.old_tracked = False
eyetracking.select_source(self.disp_ops['etuser'],
self.disp_ops['etvideo'])
eyetracking.start()
# Stretch to fit screen only if project res does not equal screen res
self.scaling = False
if self.disp_ops['fullscreen']:
self.window = pyglet.window.Window(fullscreen=True, visible=False)
if (self.window.width, self.window.height) != self.proj.res:
self.scaling = True
else:
self.window = pyglet.window.Window(*self.proj.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
self.keystates = pyglet.window.key.KeyStateHandler()
self.window.push_handlers(keystates)
# Clear window and make visible
self.window.switch_to()
graphics.set_clear_color(self.proj.bg)
self.window.clear()
self.window.set_visible()
# Create framebuffer object for drawing unscaled scene
if self.scaling:
self.canvas = pyglet.image.Texture.create(*self.proj.res)
self.fbo = graphics.Framebuffer(canvas)
self.fbo.start_render()
graphics.set_clear_color(self.proj.bg)
self.fbo.clear()
+ # Set process priority
+ if self.disp_ops['priority'] != None:
+ if not priority.available[sys.platform]:
+ msg = "setting priority not available on {0}".\
+ format(sys.platform)
+ raise NotImplementedError(msg)
+ else:
+ if self.disp_ops['priority'].isdigit():
+ self.disp_ops['priority'] = int(self.disp_ops['priority'])
+ priority.set(self.disp_ops['priority'])
+
# Start timers
if self.disp_ops['logtime']:
self.timer = Timer()
self.timer.start()
if self.disp_ops['logdur']:
self.dur = Timer()
self.dur.start()
def update(self):
"""Update the RunState."""
# Check for tracking and fixation
if self.disp_ops['eyetrack']:
self.old_tracked = self.tracked
self.tracked = eyetracking.is_tracked()
self.old_fixated = self.fixated
self.fixated = eyetracking.is_fixated(FIX_POS, FIX_RANGE, FIX_PER)
if fixated:
# Draw normal cross color if fixating
fix_crosses[0].draw()
else:
# Draw alternative cross color if not fixating
fix_crosses[1].draw()
# Update eyetracking events
if self.tracked != self.old_tracked:
if self.tracked:
self.events['track_on'] = True
else:
self.events['track_off'] = True
if self.fixated != self.old_fixated:
if self.fixated:
self.events['fix_on'] = True
else:
self.events['fix_off'] = True
else:
# Change cross color based on time
if (self.count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Blit canvas to screen if necessary
if self.scaling:
self.fbo.end_render()
self.window.switch_to()
self.canvas.blit(0, 0)
self.window.dispatch_events()
self.window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to lists
if self.disp_ops['logtime']:
self.timestamps.append(self.timer.elapsed())
elif self.disp_ops['logdur']:
self.timestamps.append('')
if self.disp_ops['logdur']:
self.durstamps.append(self.dur.restart())
elif self.disp_ops['logtime']:
self.durstamps.append('')
# Send trigger ASAP after flip
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
trigger.send(trigser, trigpar, self.encode_events())
# Log when triggers are sent
if self.disp_ops['logtime']:
if self.encode_events() != None:
trigstamps.append(self.encode_events())
else:
trigstamps.append('')
# Clear canvas, events, prepare for next frame
if self.scaling:
self.fbo.start_render()
self.fbo.clear()
else:
self.window.clear()
+ self.events = self.__class__.DEFAULTS['events']
self.count += 1
def stop(self):
"""Clean up RunState."""
if self.disp_ops['eyetrack']:
eyetracking.stop()
self.window.close()
if self.scaling:
self.fbo.delete()
del self.canvas
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
trigger.quit(trigser, trigpar)
+ if self.disp_ops['priority'] != None:
+ priority.set('normal')
def log(self, path=None):
"""Write a log file for the experimental run in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, LOG_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(LOG_FMT):
path = '{0}.{1}'.format(path, LOG_FMT)
with open(path, 'wb') as runfile:
writer = csv.writer(runfile, dialect='excel-tab')
writer.writerow(['checkergen log file'])
writer.writerow(['flags:', self.flags])
writer.writerow(['blocks:', self.blocks])
writer.writerow(['sequence:'] + self.sequence)
if self.add_idlist != None:
writer.writerow(['groups appended:'])
rowlist = grouper(len(self.sequence), self.add_idlist, '')
for row in rowlist:
writer.writerow(row)
if self.fail_idlist != None:
writer.writerow(['groups failed (not appended):'])
rowlist = grouper(len(self.sequence), self.fail_idlist, '')
for row in rowlist:
writer.writerow(row)
stamps = [self.timestamps, self.durstamps, self.trigstamps]
if len(max(stamps)) > 0:
for l in stamps:
if len(l) == 0:
l = [''] * len(max(stamps))
writer.writerow(['timestamps', 'durations', 'triggers'])
for row in zip(*stamps):
writer.writerow(row)
class CkgDisplayGroup:
DEFAULTS = OrderedDict([('pre', 0), ('disp', 'Infinity'), ('post', 0)])
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets internal count and all contained shapes."""
self._count = 0
self._start = self.pre
self._stop = self.pre + self.disp
self._end = self.pre + self.disp + self.post
self.over = False
self.old_visible = False
if self._start == 0 and self._stop > 0:
self.visible = True
else:
self.visible = False
if self._end == 0:
self.over = True
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, lazy=False, photoburst=False):
"""Draws all contained shapes during the appropriate interval."""
if self.visible:
for shape in self.shapes:
if lazy:
shape.lazydraw()
else:
shape.draw(photoburst=photoburst)
def update(self, **keywords):
"""Increments internal count, makes group visible when appropriate.
fps -- refresh rate of the display in frames per second
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
"""
fps = keywords['fps']
fpst = keywords['fpst']
if self.visible:
# Set triggers to be sent
if fpst > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= fpst:
trigger.CUR_STATE['shape'] = 1
trigger.CUR_STATE['sid'] = n
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(fps)
# Increment count and set flags for the next frame
self._count += 1
self.old_visible = self.visible
if (self._start * fps) <= self._count < (self._stop * fps):
self.visible = True
else:
self.visible = False
if self._count >= (self._end * fps):
self.over = True
else:
self.over = False
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.visible = False
self.old_visible = False
self.steps_done = 0
self.over = False
def draw(self, **keywords):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, **keywords):
"""Checks for keypress, sends trigger upon end."""
keystates = keywords['keystates']
if max([keystates[key] for key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
if self.steps_done == self.num_steps:
self.over = True
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = OrderedDict([('dims', (5, 5)),
('init_unit', (30, 30)),
('end_unit', (50, 50)),
('position', (0, 0)),
('anchor', 'bottomleft'),
('cols', ((0, 0, 0), (255, 255, 255))),
('freq', 1),
('phase', 0)])
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
if INT_HALF_PERIODS:
frames_per_half_period = round(fps / (self.freq * 2))
degs_per_frame = 180 / to_decimal(frames_per_half_period)
else:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
if PRERENDER_TO_TEXTURE:
init_pos = [(1 - a)* s/to_decimal(2) for s, a in
zip(self._size, graphics.locations[self.anchor])]
else:
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
anchor=self.anchor)
cur_unit_rect.col = self.cols[(i + j) % 2]
cur_unit_rect.add_to_batch(self._batches[0])
cur_unit_rect.col = self.cols[(i + j + 1) % 2]
cur_unit_rect.add_to_batch(self._batches[1])
# Increase x values
cur_unit_pos[0] += \
graphics.locations[self.anchor][0] * cur_unit[0]
cur_unit[0] += unit_grad[0]
# Reset x values
cur_unit_pos[0] = init_pos[0]
cur_unit[0] = init_unit[0]
# Increase y values
cur_unit_pos[1] += \
graphics.locations[self.anchor][1] * cur_unit[1]
cur_unit[1] += unit_grad[1]
if PRERENDER_TO_TEXTURE:
# Create textures
int_size = [int(round(s)) for s in self._size]
self._prerenders =\
[pyglet.image.Texture.create(*int_size) for n in range(2)]
# Set up framebuffer
fbo = graphics.Framebuffer()
for n in range(2):
fbo.attach_texture(self._prerenders[n])
# Draw batch to texture
fbo.start_render()
self._batches[n].draw()
fbo.end_render()
# Anchor textures for correct blitting later
self._prerenders[n].anchor_x, self._prerenders[n].anchor_y =\
[int(round((1 - a)* s/to_decimal(2))) for s, a in
zip(self._size, graphics.locations[self.anchor])]
fbo.delete()
# Delete batches since they won't be used
del self._batches
self._computed = True
def draw(self, photoburst=False, always_compute=False):
"""Draws appropriate prerender depending on current phase.
photoburst -- draw first color for only one frame for testing purposes
always_compute -- recompute what the checkerboard should look like
every frame
"""
if not self._computed or always_compute:
self.compute()
self._cur_phase %= 360
n = int(self._cur_phase // 180)
if photoburst and n == 0 and not self.flipped:
n = 1
if PRERENDER_TO_TEXTURE:
self._prerenders[n].blit(*self.position)
else:
self._batches[n].draw()
def lazydraw(self):
"""Only draws on color reversal."""
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if (cur_n != prev_n) or self._first_draw:
self.draw()
if self._first_draw:
self._first_draw = False
diff --git a/src/priority.py b/src/priority.py
index 18be24a..4a31aca 100644
--- a/src/priority.py
+++ b/src/priority.py
@@ -1,70 +1,74 @@
"""Module for setting process priority. Currently only for Windows."""
import os
import sys
available = {'win32':False, 'cygwin':False,
'linux2':False, 'darwin':False}
if sys.platform in ['win32', 'cygwin']:
try:
import win32api
import win32process
import win32con
available[sys.platform] = True
except ImportError:
pass
if available[sys.platform]:
def set(level=1, pid=None):
"""Sets priority of specified process.
level -- Can be low, normal, high or realtime. Users should be wary
when using realtime and provide a reliable way to exit the process,
since it may cause input to be dropped and other programs to become
unresponsive.
pid -- Process id. If None, current process id is used.
"""
if level in [0,'low','idle']:
set_low(pid)
elif level in [1, 'normal']:
set_normal(pid)
elif level in [2, 'high']:
set_high(pid)
elif level in [3, 'realtime']:
set_realtime(pid)
else:
msg = '{0} is not a valid priority level'.format(level)
raise ValueError(msg)
if sys.platform in ['win32', 'cygwin']:
CUR_PID = win32api.GetCurrentProcessId()
def set_low(pid):
if pid == None:
pid = CUR_PID
- handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid)
+ handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS,
+ True, pid)
win32process.SetPriorityClass(handle,
win32process.IDLE_PRIORITY_CLASS)
def set_normal(pid):
if pid == None:
pid = CUR_PID
- handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid)
+ handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS,
+ True, pid)
win32process.SetPriorityClass(handle,
win32process.NORMAL_PRIORITY_CLASS)
def set_high(pid):
if pid == None:
pid = CUR_PID
- handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid)
+ handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS,
+ True, pid)
win32process.SetPriorityClass(handle,
win32process.HIGH_PRIORITY_CLASS)
def set_realtime(pid):
if pid == None:
pid = CUR_PID
- handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid)
+ handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS,
+ True, pid)
win32process.SetPriorityClass(handle,
win32process.REALTIME_PRIORITY_CLASS)
|
ztangent/checkergen
|
0b1991ac9a65eaa6335baa3bccfb6cb3b1da16ab
|
write_log -> log, runwriter -> writer rename.
|
diff --git a/src/core.py b/src/core.py
index a838da4..aba40b3 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,1123 +1,1123 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgExp -- A checkergen experiment, describes how a projet is displayed.
CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import random
import itertools
from xml.dom import minidom
import pyglet
import graphics
import trigger
import eyetracking
from utils import *
# Use OrderedDict substitute if we don't have Python 2.7
if sys.version_info < (2, 7):
from odict import OrderedDict
else:
from collections import OrderedDict
CKG_FMT = 'ckg'
EXP_FMT = 'ckx'
LOG_FMT = 'log'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
MAX_EXPORT_FRAMES = 100000
PRERENDER_TO_TEXTURE = False
INT_HALF_PERIODS = True
EXPORT_FMTS = ['png']
EXPORT_DIR_SUFFIX = '-anim'
FIX_POS = (0, 0)
FIX_RANGE = (20, 20)
FIX_PER = 350
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = OrderedDict([('name', 'untitled'),
('fps', 60),
('res', (800, 600)),
('bg', (127, 127, 127)),
('export_fmt', 'png'),
('pre', 0),
('post', 0),
('cross_cols', ((0, 0, 0), (255, 0, 0))),
('cross_times', ('Infinity', 1)),
('orders', []),
('disp_ops', None)])
DEFAULTS['disp_ops'] = OrderedDict([('fullscreen', False),
('priority', 0),
('logtime', False),
('logdur', False),
('trigser', False),
('trigpar', False),
('fpst', 0),
('phototest', False),
('photoburst', False),
('eyetrack', False),
('etuser', False),
('etvideo', None),
('tryagain', 0),
('trybreak', None),
('repeats', 1)])
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
export_fmt -- image format for animation to be exported as
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'export_fmt':
if value not in EXPORT_FMTS:
msg = 'image format not recognized or supported'
raise FileFormatError(msg)
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
# Vars that are dicts
dicts_to_load = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_load = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
for d_name in dicts_to_load:
d = self.__class__.DEFAULTS[d_name]
try:
d_el = [node for node in project.childNodes if
node.localName == d_name and
node.namespaceURI == XML_NAMESPACE][0]
for var in d.keys():
try:
d[var] = eval(xml_get(d_el, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}' in '{1}'".\
format(var, d_name)
print "using default value '{0}' instead...".\
format(d[var])
except IndexError:
print "warning: missing attribute set '{0}'".format(d_name)
print "using default values instead..."
setattr(self, d_name, d)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
# Vars that are dicts
dicts_to_save = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_save = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for d_name in dicts_to_save:
d_el = doc.createElement(d_name)
project.appendChild(d_el)
d = getattr(self, d_name)
for k, v in d.iteritems():
xml_set(doc, d_el, k, repr(v))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, fullscreen=False, logtime=False, logdur=False,
trigser=False, trigpar=False, fpst=0,
phototest=False, photoburst=False,
eyetrack=False, etuser=False, etvideo=None,
tryagain=0, trybreak=None, groupq=[], run=None):
"""Displays the project animation on the screen.
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
trigser -- send triggers through serial port when each group is shown
trigpar -- send triggers through parallel port when each group is shown
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- Append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- Append a wait screen to the group queue every time
after this many groups have been appended to the queue
groupq -- queue of groups to be displayed, defaults to order of
groups in project (i.e. groups[0] first, etc.)
run -- experimental run where logged variables are saved (i.e.
fail_idlist and time information)
"""
# Create RunState
# Start run
# Count through pre
# Loop through repeats
# Loop through display groups
# Count through post
# Write log
- runstate.write_log()
+ runstate.log()
def export(self, export_dir, export_duration, groupq=[],
export_fmt=None, folder=True, force=False):
if not os.path.isdir(export_dir):
msg = 'export path is not a directory'
raise IOError(msg)
if export_fmt == None:
export_fmt = self.export_fmt
# Set-up groups and variables that control their display
if groupq == []:
groupq = list(self.groups)
n = -1
groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Limit export duration to display duration
frames = export_duration * self.fps
frames = min(frames, disp_end)
# Warn user if a lot of frames will be exported
if frames > MAX_EXPORT_FRAMES and not force:
msg = 'very large number ({0}) of frames to be exported'.\
format(frames)
raise FrameOverflowError(msg)
# Create folder to store images if necessary
if folder:
export_dir = os.path.join(export_dir,
self.name + EXPORT_DIR_SUFFIX)
if not os.path.isdir(export_dir):
os.mkdir(export_dir)
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Set up canvas and framebuffer object
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
# Main loop
while count < frames:
fbo.clear()
if groups_visible:
# Get next group from queue
if n < 0 or groupq[n].over:
n += 1
if n >= len(groupq):
groups_visible = False
else:
groupq[n].reset()
# Draw and then update group
if n >= 0:
groupq[n].draw()
groupq[n].update(fps=self.fps, fpst=0)
# Draw fixation cross based on current count
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Save current frame to file
savepath = \
os.path.join(export_dir,
'{0}{2}.{1}'.
format(self.name, export_fmt,
repr(count).zfill(numdigits(frames-1))))
canvas.save(savepath)
# Increment count and set whether groups should be shown
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
fbo.delete()
class CkgRunState:
"""Contains information about the state of a checkergen project
when it is being displayed or exported."""
DEFAULTS = dict([('proj', None),
('order', []),
('disp_ops', None),
('events', None),
('add_gids', []),
('fail_gids', []),
('timestamps', []),
('durstamps', []),
('trigstamps', [])])
DEFAULTS['events'] = dict([('blk_on', False),
('blk_off', False),
('track_on', False),
('track_off', False),
('fix_on', False),
('fix_off', False),
('grp_on', False),
('grp_off', False),
('sids', [])])
def __init__(self, **keywords):
"""Creates the RunState."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
def start(self):
"""Initialize all subsystems and start the run."""
if self.proj == None:
msg = "RunState lacks associated project, run cannot begin"
raise ValueError(msg)
self.count = 0
self.trycount = self.disp_ops['tryagain']
# Create fixation crosses
self.fix_crosses = [graphics.Cross([r/2 for r in self.proj.res],
(20, 20), col = cross_col)
for cross_col in self.proj.cross_cols]
# Create test rectangle
if self.disp_ops['phototest']:
self.test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.proj.res],
anchor='topleft')
# Initialize ports
if self.disp_ops['trigser']:
if not trigger.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trigpar']:
if not trigger.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
trigger.init(trigser, trigpar)
# Initialize eyetracking
if self.disp_ops['eyetrack']:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trybreak'] == None:
self.disp_ops['trybreak'] = len(self.proj.groups)
self.fixated = False
self.old_fixated = False
self.tracked = False
self.old_tracked = False
eyetracking.select_source(self.disp_ops['etuser'],
self.disp_ops['etvideo'])
eyetracking.start()
# Stretch to fit screen only if project res does not equal screen res
self.scaling = False
if self.disp_ops['fullscreen']:
self.window = pyglet.window.Window(fullscreen=True, visible=False)
if (self.window.width, self.window.height) != self.proj.res:
self.scaling = True
else:
self.window = pyglet.window.Window(*self.proj.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
self.keystates = pyglet.window.key.KeyStateHandler()
self.window.push_handlers(keystates)
# Clear window and make visible
self.window.switch_to()
graphics.set_clear_color(self.proj.bg)
self.window.clear()
self.window.set_visible()
# Create framebuffer object for drawing unscaled scene
if self.scaling:
self.canvas = pyglet.image.Texture.create(*self.proj.res)
self.fbo = graphics.Framebuffer(canvas)
self.fbo.start_render()
graphics.set_clear_color(self.proj.bg)
self.fbo.clear()
# Start timers
if self.disp_ops['logtime']:
self.timer = Timer()
self.timer.start()
if self.disp_ops['logdur']:
self.dur = Timer()
self.dur.start()
def update(self):
"""Update the RunState."""
# Check for tracking and fixation
if self.disp_ops['eyetrack']:
self.old_tracked = self.tracked
self.tracked = eyetracking.is_tracked()
self.old_fixated = self.fixated
self.fixated = eyetracking.is_fixated(FIX_POS, FIX_RANGE, FIX_PER)
if fixated:
# Draw normal cross color if fixating
fix_crosses[0].draw()
else:
# Draw alternative cross color if not fixating
fix_crosses[1].draw()
# Update eyetracking events
if self.tracked != self.old_tracked:
if self.tracked:
self.events['track_on'] = True
else:
self.events['track_off'] = True
if self.fixated != self.old_fixated:
if self.fixated:
self.events['fix_on'] = True
else:
self.events['fix_off'] = True
else:
# Change cross color based on time
if (self.count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Blit canvas to screen if necessary
if self.scaling:
self.fbo.end_render()
self.window.switch_to()
self.canvas.blit(0, 0)
self.window.dispatch_events()
self.window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to lists
if self.disp_ops['logtime']:
self.timestamps.append(self.timer.elapsed())
elif self.disp_ops['logdur']:
self.timestamps.append('')
if self.disp_ops['logdur']:
self.durstamps.append(self.dur.restart())
elif self.disp_ops['logtime']:
self.durstamps.append('')
# Send trigger ASAP after flip
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
trigger.send(trigser, trigpar, self.encode_events())
# Log when triggers are sent
if self.disp_ops['logtime']:
if self.encode_events() != None:
trigstamps.append(self.encode_events())
else:
trigstamps.append('')
# Clear canvas, events, prepare for next frame
if self.scaling:
self.fbo.start_render()
self.fbo.clear()
else:
self.window.clear()
self.count += 1
def stop(self):
"""Clean up RunState."""
if self.disp_ops['eyetrack']:
eyetracking.stop()
self.window.close()
if self.scaling:
self.fbo.delete()
del self.canvas
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
trigger.quit(trigser, trigpar)
- def write_log(self, path=None):
+ def log(self, path=None):
"""Write a log file for the experimental run in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, LOG_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(LOG_FMT):
path = '{0}.{1}'.format(path, LOG_FMT)
with open(path, 'wb') as runfile:
- runwriter = csv.writer(runfile, dialect='excel-tab')
- runwriter.writerow(['checkergen log file'])
- runwriter.writerow(['flags:', self.flags])
- runwriter.writerow(['blocks:', self.blocks])
- runwriter.writerow(['sequence:'] + self.sequence)
+ writer = csv.writer(runfile, dialect='excel-tab')
+ writer.writerow(['checkergen log file'])
+ writer.writerow(['flags:', self.flags])
+ writer.writerow(['blocks:', self.blocks])
+ writer.writerow(['sequence:'] + self.sequence)
if self.add_idlist != None:
- runwriter.writerow(['groups appended:'])
+ writer.writerow(['groups appended:'])
rowlist = grouper(len(self.sequence), self.add_idlist, '')
for row in rowlist:
- runwriter.writerow(row)
+ writer.writerow(row)
if self.fail_idlist != None:
- runwriter.writerow(['groups failed (not appended):'])
+ writer.writerow(['groups failed (not appended):'])
rowlist = grouper(len(self.sequence), self.fail_idlist, '')
for row in rowlist:
- runwriter.writerow(row)
+ writer.writerow(row)
stamps = [self.timestamps, self.durstamps, self.trigstamps]
if len(max(stamps)) > 0:
for l in stamps:
if len(l) == 0:
l = [''] * len(max(stamps))
- runwriter.writerow(['timestamps', 'durations', 'triggers'])
+ writer.writerow(['timestamps', 'durations', 'triggers'])
for row in zip(*stamps):
- runwriter.writerow(row)
+ writer.writerow(row)
class CkgDisplayGroup:
DEFAULTS = OrderedDict([('pre', 0), ('disp', 'Infinity'), ('post', 0)])
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets internal count and all contained shapes."""
self._count = 0
self._start = self.pre
self._stop = self.pre + self.disp
self._end = self.pre + self.disp + self.post
self.over = False
self.old_visible = False
if self._start == 0 and self._stop > 0:
self.visible = True
else:
self.visible = False
if self._end == 0:
self.over = True
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, lazy=False, photoburst=False):
"""Draws all contained shapes during the appropriate interval."""
if self.visible:
for shape in self.shapes:
if lazy:
shape.lazydraw()
else:
shape.draw(photoburst=photoburst)
def update(self, **keywords):
"""Increments internal count, makes group visible when appropriate.
fps -- refresh rate of the display in frames per second
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
"""
fps = keywords['fps']
fpst = keywords['fpst']
if self.visible:
# Set triggers to be sent
if fpst > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= fpst:
trigger.CUR_STATE['shape'] = 1
trigger.CUR_STATE['sid'] = n
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(fps)
# Increment count and set flags for the next frame
self._count += 1
self.old_visible = self.visible
if (self._start * fps) <= self._count < (self._stop * fps):
self.visible = True
else:
self.visible = False
if self._count >= (self._end * fps):
self.over = True
else:
self.over = False
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.visible = False
self.old_visible = False
self.steps_done = 0
self.over = False
def draw(self, **keywords):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, **keywords):
"""Checks for keypress, sends trigger upon end."""
keystates = keywords['keystates']
if max([keystates[key] for key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
if self.steps_done == self.num_steps:
self.over = True
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = OrderedDict([('dims', (5, 5)),
('init_unit', (30, 30)),
('end_unit', (50, 50)),
('position', (0, 0)),
('anchor', 'bottomleft'),
('cols', ((0, 0, 0), (255, 255, 255))),
('freq', 1),
('phase', 0)])
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
if INT_HALF_PERIODS:
frames_per_half_period = round(fps / (self.freq * 2))
degs_per_frame = 180 / to_decimal(frames_per_half_period)
else:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
if PRERENDER_TO_TEXTURE:
init_pos = [(1 - a)* s/to_decimal(2) for s, a in
zip(self._size, graphics.locations[self.anchor])]
else:
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
anchor=self.anchor)
cur_unit_rect.col = self.cols[(i + j) % 2]
cur_unit_rect.add_to_batch(self._batches[0])
cur_unit_rect.col = self.cols[(i + j + 1) % 2]
cur_unit_rect.add_to_batch(self._batches[1])
# Increase x values
cur_unit_pos[0] += \
graphics.locations[self.anchor][0] * cur_unit[0]
cur_unit[0] += unit_grad[0]
# Reset x values
cur_unit_pos[0] = init_pos[0]
cur_unit[0] = init_unit[0]
# Increase y values
cur_unit_pos[1] += \
graphics.locations[self.anchor][1] * cur_unit[1]
cur_unit[1] += unit_grad[1]
if PRERENDER_TO_TEXTURE:
# Create textures
int_size = [int(round(s)) for s in self._size]
self._prerenders =\
[pyglet.image.Texture.create(*int_size) for n in range(2)]
# Set up framebuffer
fbo = graphics.Framebuffer()
for n in range(2):
fbo.attach_texture(self._prerenders[n])
# Draw batch to texture
fbo.start_render()
self._batches[n].draw()
fbo.end_render()
# Anchor textures for correct blitting later
self._prerenders[n].anchor_x, self._prerenders[n].anchor_y =\
[int(round((1 - a)* s/to_decimal(2))) for s, a in
zip(self._size, graphics.locations[self.anchor])]
fbo.delete()
# Delete batches since they won't be used
del self._batches
self._computed = True
def draw(self, photoburst=False, always_compute=False):
"""Draws appropriate prerender depending on current phase.
photoburst -- draw first color for only one frame for testing purposes
always_compute -- recompute what the checkerboard should look like
every frame
"""
if not self._computed or always_compute:
self.compute()
self._cur_phase %= 360
n = int(self._cur_phase // 180)
if photoburst and n == 0 and not self.flipped:
n = 1
if PRERENDER_TO_TEXTURE:
self._prerenders[n].blit(*self.position)
else:
self._batches[n].draw()
def lazydraw(self):
"""Only draws on color reversal."""
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if (cur_n != prev_n) or self._first_draw:
self.draw()
if self._first_draw:
self._first_draw = False
|
ztangent/checkergen
|
0f688618307ed9bba40f7227b638319ae57a31f5
|
Obliterated CkgExp and old display content, add framework for new display.
|
diff --git a/src/core.py b/src/core.py
index b0f4b25..a838da4 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,1346 +1,992 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgExp -- A checkergen experiment, describes how a projet is displayed.
CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import random
import itertools
from xml.dom import minidom
import pyglet
import graphics
import trigger
import eyetracking
from utils import *
# Use OrderedDict substitute if we don't have Python 2.7
if sys.version_info < (2, 7):
from odict import OrderedDict
else:
from collections import OrderedDict
CKG_FMT = 'ckg'
EXP_FMT = 'ckx'
LOG_FMT = 'log'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
MAX_EXPORT_FRAMES = 100000
PRERENDER_TO_TEXTURE = False
INT_HALF_PERIODS = True
EXPORT_FMTS = ['png']
EXPORT_DIR_SUFFIX = '-anim'
FIX_POS = (0, 0)
FIX_RANGE = (20, 20)
FIX_PER = 350
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = OrderedDict([('name', 'untitled'),
('fps', 60),
('res', (800, 600)),
('bg', (127, 127, 127)),
('export_fmt', 'png'),
('pre', 0),
('post', 0),
('cross_cols', ((0, 0, 0), (255, 0, 0))),
('cross_times', ('Infinity', 1)),
('orders', []),
('disp_ops', None)])
DEFAULTS['disp_ops'] = OrderedDict([('fullscreen', False),
('priority', 0),
('logtime', False),
('logdur', False),
('trigser', False),
('trigpar', False),
('fpst', 0),
('phototest', False),
('photoburst', False),
('eyetrack', False),
('etuser', False),
('etvideo', None),
('tryagain', 0),
('trybreak', None),
('repeats', 1)])
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
export_fmt -- image format for animation to be exported as
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'export_fmt':
if value not in EXPORT_FMTS:
msg = 'image format not recognized or supported'
raise FileFormatError(msg)
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
# Vars that are dicts
dicts_to_load = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_load = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
for d_name in dicts_to_load:
d = self.__class__.DEFAULTS[d_name]
try:
d_el = [node for node in project.childNodes if
node.localName == d_name and
node.namespaceURI == XML_NAMESPACE][0]
for var in d.keys():
try:
d[var] = eval(xml_get(d_el, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}' in '{1}'".\
format(var, d_name)
print "using default value '{0}' instead...".\
format(d[var])
except IndexError:
print "warning: missing attribute set '{0}'".format(d_name)
print "using default values instead..."
setattr(self, d_name, d)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
# Vars that are dicts
dicts_to_save = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_save = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for d_name in dicts_to_save:
d_el = doc.createElement(d_name)
project.appendChild(d_el)
d = getattr(self, d_name)
for k, v in d.iteritems():
xml_set(doc, d_el, k, repr(v))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, fullscreen=False, logtime=False, logdur=False,
trigser=False, trigpar=False, fpst=0,
phototest=False, photoburst=False,
eyetrack=False, etuser=False, etvideo=None,
tryagain=0, trybreak=None, groupq=[], run=None):
"""Displays the project animation on the screen.
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
trigser -- send triggers through serial port when each group is shown
trigpar -- send triggers through parallel port when each group is shown
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- Append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- Append a wait screen to the group queue every time
after this many groups have been appended to the queue
groupq -- queue of groups to be displayed, defaults to order of
groups in project (i.e. groups[0] first, etc.)
run -- experimental run where logged variables are saved (i.e.
fail_idlist and time information)
"""
- # Create fixation crosses
- fix_crosses = [graphics.Cross([r/2 for r in self.res],
- (20, 20), col = cross_col)
- for cross_col in self.cross_cols]
- # Create test rectangle
- if phototest:
- test_rect = graphics.Rect((0, self.res[1]),
- [r/8 for r in self.res],
- anchor='topleft')
+ # Create RunState
- # Set-up groups and variables that control their display
- if groupq == []:
- groupq = list(self.groups)
- n = -1
- flipped = 0
- flip_id = -1
- groups_duration = sum([group.duration() for group in groupq])
- groups_start = self.pre * self.fps
- groups_stop = (self.pre + groups_duration) * self.fps
- disp_end = (self.pre + groups_duration + self.post) * self.fps
- if groups_start == 0 and groups_stop > 0:
- groups_visible = True
- else:
- groups_visible = False
- count = 0
+ # Start run
- # Initialize ports
- if trigser:
- if not trigger.available['serial']:
- msg = 'serial port functionality not available'
- raise NotImplementedError(msg)
- if trigpar:
- if not trigger.available['parallel']:
- msg = 'parallel port functionality not available'
- raise NotImplementedError(msg)
- trigger.init(trigser, trigpar)
+ # Count through pre
- # Initialize eyetracking
- if eyetrack:
- if not eyetracking.available:
- msg = 'eyetracking functionality not available'
- raise NotImplementedError(msg)
- if trybreak == None:
- trybreak = len(self.groups)
- fixated = False
- old_fixated = False
- tracked = False
- old_tracked = False
- cur_fix_fail = False
- trycount = 0
- fail_idlist = []
- eyetracking.select_source(etuser, etvideo)
- eyetracking.start()
-
- # Stretch to fit screen only if project res does not equal screen res
- scaling = False
- if fullscreen:
- window = pyglet.window.Window(fullscreen=True, visible=False)
- if (window.width, window.height) != self.res:
- scaling = True
- else:
- window = pyglet.window.Window(*self.res, visible=False)
+ # Loop through repeats
+ # Loop through display groups
- # Set up KeyStateHandler to handle keyboard input
- keystates = pyglet.window.key.KeyStateHandler()
- window.push_handlers(keystates)
-
- # Create framebuffer object for drawing unscaled scene
- if scaling:
- canvas = pyglet.image.Texture.create(*self.res)
- fbo = graphics.Framebuffer(canvas)
- fbo.start_render()
- graphics.set_clear_color(self.bg)
- fbo.clear()
- fbo.end_render()
-
- # Clear window and make visible
- window.switch_to()
- graphics.set_clear_color(self.bg)
- window.clear()
- window.set_visible()
-
- # Initialize logging variables
- if logtime:
- timestamps = []
- trigstamps = []
- timer = Timer()
- timer.start()
- if logdur:
- durstamps = []
- dur = Timer()
- dur.start()
-
- # Main loop
- while not window.has_exit and count < disp_end:
- # Clear canvas
- if scaling:
- fbo.start_render()
- fbo.clear()
- else:
- window.clear()
+ # Count through post
- # Assume no change to group visibility
- flipped = 0
-
- # Manage groups when they are on_screen
- if groups_visible:
- # Check whether group changes in visibility
- if n >= 0 and groupq[n].visible != groupq[n].old_visible:
- flip_id = self.groups.index(groupq[n])
- if groupq[n].visible:
- flipped = 1
- elif groupq[n].old_visible:
- flipped = -1
- # Get next group from queue
- if n < 0 or groupq[n].over:
- # Send special trigger if waitscreen ends
- if isinstance(groupq[n], CkgWaitScreen):
- trigger.CUR_STATE['user'] = 1
- n += 1
- if n >= len(groupq):
- groups_visible = False
- trigger.CUR_STATE['user'] = 0
- else:
- groupq[n].reset()
- if eyetrack:
- cur_fix_fail = False
- if groupq[n].visible:
- flip_id = self.groups.index(groupq[n])
- flipped = 1
- # Send special trigger when waitscreen ends
- if isinstance(groupq[n], CkgWaitScreen):
- trigger.CUR_STATE['user'] = 0
- # Draw and then update group
- if n >= 0:
- groupq[n].draw(photoburst=photoburst)
- groupq[n].update(fps=self.fps,
- fpst=fpst,
- keystates=keystates)
-
- # Send triggers upon group visibility change
- if flipped == 1:
- trigger.CUR_STATE['group'] = 1
- # Draw test rectangle
- if phototest:
- test_rect.draw()
- elif flipped == -1:
- trigger.CUR_STATE['group'] = 0
-
- if eyetrack:
- # First check if eye is being tracked and send trigger
- old_tracked = tracked
- tracked = eyetracking.is_tracked()
- if tracked:
- if not old_tracked:
- # Send trigger if eye starts being tracked
- trigger.set_track_start()
- else:
- if old_tracked:
- # Send trigger if eye stops being tracked
- trigger.set_track_stop()
-
- # Next check for fixation
- old_fixated = fixated
- fixated = eyetracking.is_fixated(FIX_POS, FIX_RANGE, FIX_PER)
- if fixated:
- # Draw normal cross color if fixating
- fix_crosses[0].draw()
- if not old_fixated:
- # Send trigger if fixation starts
- trigger.set_fix_start()
- else:
- # Draw alternative cross color if not fixating
- fix_crosses[1].draw()
- if old_fixated:
- # Send trigger if fixation stops
- trigger.set_fix_stop()
-
- # Take note of which groups in which fixation failed
- if not cur_fix_fail and groupq[n].visible and\
- (tracked and not fixated):
- cur_fix_fail = True
- # Append failed group to group queue
- if trycount < tryagain:
- # Insert waitscreen every trybreak failed groups
- if trybreak > 0:
- if len(fail_idlist) % trybreak == 0:
- groupq.append(CkgWaitScreen())
- groupq.append(groupq[n])
- groups_stop += groupq[n].duration() * self.fps
- disp_end += groupq[n].duration() * self.fps
- trycount += 1
- # Maintain list of failed IDs
- fail_idlist.append(self.groups.index(groupq[n]))
-
- # Change cross color based on time if eyetracking is not enabled
- if not eyetrack:
- if (count % (sum(self.cross_times) * self.fps)
- < self.cross_times[0] * self.fps):
- fix_crosses[0].draw()
- else:
- fix_crosses[1].draw()
-
- # Increment count and set whether groups should be shown
- if not isinstance(groupq[n], CkgWaitScreen):
- count += 1
- if groups_start <= count < groups_stop:
- groups_visible = True
- else:
- groups_visible = False
-
- # Blit canvas to screen if necessary
- if scaling:
- fbo.end_render()
- window.switch_to()
- canvas.blit(0, 0)
- window.dispatch_events()
- window.flip()
- # Make sure everything has been drawn
- pyglet.gl.glFinish()
-
- # Append time information to lists
- if logtime:
- timestamps.append(timer.elapsed())
- if logdur:
- durstamps.append(dur.restart())
-
- # Send trigger ASAP after flip
- trigger.send(trigser, trigpar)
-
- # Log when trigger are sent
- if logtime:
- if flipped != 0 and (trigser or trigpar):
- trigstamps.append(trigger.STATE)
- else:
- trigstamps.append('')
-
- # Clean up
- if eyetrack:
- eyetracking.stop()
- window.close()
- if scaling:
- fbo.delete()
- del canvas
- trigger.quit(trigser, trigpar)
-
- # Store variables in run object
- if run != None:
- if logtime:
- run.timestamps = timestamps
- run.trigstamps = trigstamps
- if logdur:
- run.durstamps = durstamps
- if eyetrack and len(fail_idlist) > 0:
- run.add_idlist = fail_idlist[:tryagain]
- run.fail_idlist = fail_idlist[tryagain:]
+ # Write log
+ runstate.write_log()
def export(self, export_dir, export_duration, groupq=[],
export_fmt=None, folder=True, force=False):
if not os.path.isdir(export_dir):
msg = 'export path is not a directory'
raise IOError(msg)
if export_fmt == None:
export_fmt = self.export_fmt
# Set-up groups and variables that control their display
if groupq == []:
groupq = list(self.groups)
n = -1
groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Limit export duration to display duration
frames = export_duration * self.fps
frames = min(frames, disp_end)
# Warn user if a lot of frames will be exported
if frames > MAX_EXPORT_FRAMES and not force:
msg = 'very large number ({0}) of frames to be exported'.\
format(frames)
raise FrameOverflowError(msg)
# Create folder to store images if necessary
if folder:
export_dir = os.path.join(export_dir,
self.name + EXPORT_DIR_SUFFIX)
if not os.path.isdir(export_dir):
os.mkdir(export_dir)
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Set up canvas and framebuffer object
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
# Main loop
while count < frames:
fbo.clear()
if groups_visible:
# Get next group from queue
if n < 0 or groupq[n].over:
n += 1
if n >= len(groupq):
groups_visible = False
else:
groupq[n].reset()
# Draw and then update group
if n >= 0:
groupq[n].draw()
groupq[n].update(fps=self.fps, fpst=0)
# Draw fixation cross based on current count
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Save current frame to file
savepath = \
os.path.join(export_dir,
'{0}{2}.{1}'.
format(self.name, export_fmt,
repr(count).zfill(numdigits(frames-1))))
canvas.save(savepath)
# Increment count and set whether groups should be shown
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
fbo.delete()
-
-class CkgExp:
-
- DEFAULTS = {'name': None, 'proj' : None,
- 'blocks': 1, 'sequences': None,
- 'flags': '--fullscreen --logtime --logdur'}
-
- def __init__(self, **keywords):
- """Create a checkergen experiment, which specifies how a project
- is to be displayed.
-
- path -- if specified, ignore other arguments and load project
- from path
-
- name -- name of the experiment
-
- proj -- CkgProj that the experiment is to be created for
-
- blocks -- number of times the selected sequence of display groups
- will be shown in one run
-
- sequences -- list of possible display group id sequences, from which
- one sequence will be randomly selected for display in a run,
- defaults to reduced latin square with side length equal to the number
- of display groups in the supplied CkgProj
-
- flags -- string passed to the display command as flags
-
- """
- if 'path' in keywords.keys():
- self.load(keywords['path'])
- return
- for kw in self.__class__.DEFAULTS.keys():
- if kw in keywords.keys():
- setattr(self, kw, keywords[kw])
- else:
- setattr(self, kw, self.__class__.DEFAULTS[kw])
-
- if self.name == None and self.proj != None:
- self.name = self.proj.name
-
- if self.sequences == None:
- if self.proj == None:
- msg = "either project or sequences have to be specified"
- raise ValueError(msg)
- else:
- self.gen_latin_square(len(self.proj.groups))
-
- del self.proj
-
- def gen_latin_square(self, n):
- """Set experiment sequences as a cyclic reduced latin square."""
- sequence = range(n)
- self.sequences = [[sequence[i - j] for i in range(n)]
- for j in range(n, 0, -1)]
-
- def random_run(self, name):
- """Choose random sequence, create run from it and return."""
- sequence = random.choice(self.sequences)
- run = CkgRun(name=name,
- flags=self.flags,
- blocks=self.blocks,
- sequence=sequence)
- return run
-
- def save(self, path=None):
- """Saves experiment to specified path in the CSV format."""
-
- if path == None:
- path = os.path.join(os.getcwd(),
- '{0}.{1}'.format(self.name, EXP_FMT))
- else:
- self.name, ext = os.path.splitext(os.path.basename(path))
- if ext != '.{0}'.format(EXP_FMT):
- path = '{0}.{1}'.format(path, EXP_FMT)
-
- with open(path, 'wb') as expfile:
- expwriter = csv.writer(expfile, dialect='excel-tab')
- expwriter.writerow(['checkergen experiment file'])
- expwriter.writerow(['flags:', self.flags])
- expwriter.writerow(['blocks:', self.blocks])
- expwriter.writerow(['sequences:'])
- for sequence in self.sequences:
- expwriter.writerow(sequence)
-
- def load(self, path):
- """Loads experiment from specified path."""
-
- # Get project name from filename
- name, ext = os.path.splitext(os.path.basename(path))
- if len(ext) == 0:
- path = '{0}.{1}'.format(path, EXP_FMT)
- elif ext != '.{0}'.format(EXP_FMT):
- msg = "path lacks '.{0}' extension".format(EXP_FMT)
- raise FileFormatError(msg)
- if not os.path.isfile(path):
- msg = "specified file does not exist"
- raise IOError(msg)
- self.name = name
-
- self.sequences = []
- with open(path, 'rb') as expfile:
- expreader = csv.reader(expfile, dialect='excel-tab')
- for n, row in enumerate(expreader):
- if n == 1:
- self.flags = row[1]
- elif n == 2:
- self.blocks = int(row[1])
- elif n > 3:
- sequence = [int(i) for i in row]
- self.sequences.append(sequence)
class CkgRunState:
"""Contains information about the state of a checkergen project
when it is being displayed or exported."""
DEFAULTS = dict([('proj', None),
('order', []),
('disp_ops', None),
('events', None),
('add_gids', []),
('fail_gids', []),
('timestamps', []),
('durstamps', []),
('trigstamps', [])])
DEFAULTS['events'] = dict([('blk_on', False),
('blk_off', False),
('track_on', False),
('track_off', False),
('fix_on', False),
('fix_off', False),
('grp_on', False),
('grp_off', False),
('sids', [])])
def __init__(self, **keywords):
"""Creates the RunState."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
def start(self):
"""Initialize all subsystems and start the run."""
if self.proj == None:
msg = "RunState lacks associated project, run cannot begin"
raise ValueError(msg)
self.count = 0
self.trycount = self.disp_ops['tryagain']
# Create fixation crosses
self.fix_crosses = [graphics.Cross([r/2 for r in self.proj.res],
(20, 20), col = cross_col)
for cross_col in self.proj.cross_cols]
# Create test rectangle
if self.disp_ops['phototest']:
self.test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.proj.res],
anchor='topleft')
# Initialize ports
if self.disp_ops['trigser']:
if not trigger.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trigpar']:
if not trigger.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
trigger.init(trigser, trigpar)
# Initialize eyetracking
if self.disp_ops['eyetrack']:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if self.disp_ops['trybreak'] == None:
self.disp_ops['trybreak'] = len(self.proj.groups)
self.fixated = False
self.old_fixated = False
self.tracked = False
self.old_tracked = False
eyetracking.select_source(self.disp_ops['etuser'],
self.disp_ops['etvideo'])
eyetracking.start()
# Stretch to fit screen only if project res does not equal screen res
self.scaling = False
if self.disp_ops['fullscreen']:
self.window = pyglet.window.Window(fullscreen=True, visible=False)
if (self.window.width, self.window.height) != self.proj.res:
self.scaling = True
else:
self.window = pyglet.window.Window(*self.proj.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
self.keystates = pyglet.window.key.KeyStateHandler()
self.window.push_handlers(keystates)
# Clear window and make visible
self.window.switch_to()
graphics.set_clear_color(self.proj.bg)
self.window.clear()
self.window.set_visible()
# Create framebuffer object for drawing unscaled scene
if self.scaling:
self.canvas = pyglet.image.Texture.create(*self.proj.res)
self.fbo = graphics.Framebuffer(canvas)
self.fbo.start_render()
graphics.set_clear_color(self.proj.bg)
self.fbo.clear()
# Start timers
if self.disp_ops['logtime']:
self.timer = Timer()
self.timer.start()
if self.disp_ops['logdur']:
self.dur = Timer()
self.dur.start()
def update(self):
"""Update the RunState."""
# Check for tracking and fixation
if self.disp_ops['eyetrack']:
self.old_tracked = self.tracked
self.tracked = eyetracking.is_tracked()
self.old_fixated = self.fixated
self.fixated = eyetracking.is_fixated(FIX_POS, FIX_RANGE, FIX_PER)
if fixated:
# Draw normal cross color if fixating
fix_crosses[0].draw()
else:
# Draw alternative cross color if not fixating
fix_crosses[1].draw()
# Update eyetracking events
if self.tracked != self.old_tracked:
if self.tracked:
self.events['track_on'] = True
else:
self.events['track_off'] = True
if self.fixated != self.old_fixated:
if self.fixated:
self.events['fix_on'] = True
else:
self.events['fix_off'] = True
else:
# Change cross color based on time
if (self.count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Blit canvas to screen if necessary
if self.scaling:
self.fbo.end_render()
self.window.switch_to()
self.canvas.blit(0, 0)
self.window.dispatch_events()
self.window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to lists
if self.disp_ops['logtime']:
self.timestamps.append(self.timer.elapsed())
elif self.disp_ops['logdur']:
self.timestamps.append('')
if self.disp_ops['logdur']:
self.durstamps.append(self.dur.restart())
elif self.disp_ops['logtime']:
self.durstamps.append('')
# Send trigger ASAP after flip
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
trigger.send(trigser, trigpar, self.encode_events())
# Log when triggers are sent
if self.disp_ops['logtime']:
if self.encode_events() != None:
trigstamps.append(self.encode_events())
else:
trigstamps.append('')
# Clear canvas, events, prepare for next frame
if self.scaling:
self.fbo.start_render()
self.fbo.clear()
else:
self.window.clear()
self.count += 1
def stop(self):
"""Clean up RunState."""
if self.disp_ops['eyetrack']:
eyetracking.stop()
self.window.close()
if self.scaling:
self.fbo.delete()
del self.canvas
if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
trigger.quit(trigser, trigpar)
def write_log(self, path=None):
"""Write a log file for the experimental run in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, LOG_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(LOG_FMT):
path = '{0}.{1}'.format(path, LOG_FMT)
with open(path, 'wb') as runfile:
runwriter = csv.writer(runfile, dialect='excel-tab')
runwriter.writerow(['checkergen log file'])
runwriter.writerow(['flags:', self.flags])
runwriter.writerow(['blocks:', self.blocks])
runwriter.writerow(['sequence:'] + self.sequence)
if self.add_idlist != None:
runwriter.writerow(['groups appended:'])
rowlist = grouper(len(self.sequence), self.add_idlist, '')
for row in rowlist:
runwriter.writerow(row)
if self.fail_idlist != None:
runwriter.writerow(['groups failed (not appended):'])
rowlist = grouper(len(self.sequence), self.fail_idlist, '')
for row in rowlist:
runwriter.writerow(row)
stamps = [self.timestamps, self.durstamps, self.trigstamps]
if len(max(stamps)) > 0:
for l in stamps:
if len(l) == 0:
l = [''] * len(max(stamps))
runwriter.writerow(['timestamps', 'durations', 'triggers'])
for row in zip(*stamps):
runwriter.writerow(row)
class CkgDisplayGroup:
DEFAULTS = OrderedDict([('pre', 0), ('disp', 'Infinity'), ('post', 0)])
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets internal count and all contained shapes."""
self._count = 0
self._start = self.pre
self._stop = self.pre + self.disp
self._end = self.pre + self.disp + self.post
self.over = False
self.old_visible = False
if self._start == 0 and self._stop > 0:
self.visible = True
else:
self.visible = False
if self._end == 0:
self.over = True
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, lazy=False, photoburst=False):
"""Draws all contained shapes during the appropriate interval."""
if self.visible:
for shape in self.shapes:
if lazy:
shape.lazydraw()
else:
shape.draw(photoburst=photoburst)
def update(self, **keywords):
"""Increments internal count, makes group visible when appropriate.
fps -- refresh rate of the display in frames per second
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
"""
fps = keywords['fps']
fpst = keywords['fpst']
if self.visible:
# Set triggers to be sent
if fpst > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= fpst:
trigger.CUR_STATE['shape'] = 1
trigger.CUR_STATE['sid'] = n
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(fps)
# Increment count and set flags for the next frame
self._count += 1
self.old_visible = self.visible
if (self._start * fps) <= self._count < (self._stop * fps):
self.visible = True
else:
self.visible = False
if self._count >= (self._end * fps):
self.over = True
else:
self.over = False
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.visible = False
self.old_visible = False
self.steps_done = 0
self.over = False
def draw(self, **keywords):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, **keywords):
"""Checks for keypress, sends trigger upon end."""
keystates = keywords['keystates']
if max([keystates[key] for key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
if self.steps_done == self.num_steps:
self.over = True
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = OrderedDict([('dims', (5, 5)),
('init_unit', (30, 30)),
('end_unit', (50, 50)),
('position', (0, 0)),
('anchor', 'bottomleft'),
('cols', ((0, 0, 0), (255, 255, 255))),
('freq', 1),
('phase', 0)])
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
|
ztangent/checkergen
|
77128652d104d0e5df250dffd2d83e6c4cbd59e8
|
Begin display re-write, using CkgRun->CkgRunState.
|
diff --git a/src/cli.py b/src/cli.py
index b2aff28..9fb2462 100644
--- a/src/cli.py
+++ b/src/cli.py
@@ -246,958 +246,958 @@ class CkgCmd(cmd.Cmd):
self.do_new('')
try:
args = self.__class__.set_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.set_parser.print_usage()
return
names = public_dir(args)
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
setattr(self.cur_proj, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.set_parser.print_usage()
mkgrp_parser = CmdParser(add_help=False, prog='mkgrp',
formatter_class=
argparse.ArgumentDefaultsHelpFormatter,
description='''Makes a new display group
with the given parameters.''')
mkgrp_parser.add_argument('pre', type=to_decimal, default=0, nargs='?',
help='''time in seconds a blank screen will
be shown before shapes are displayed''')
mkgrp_parser.add_argument('disp', type=to_decimal,
nargs='?', default='Infinity',
help='''time in seconds shapes will be
displayed''')
mkgrp_parser.add_argument('post', type=to_decimal, default=0, nargs='?',
help='''time in seconds a blank screen will
be shown after shapes are displayed''')
def help_mkgrp(self):
self.__class__.mkgrp_parser.print_help()
def do_mkgrp(self, line):
"""Makes a display group with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
try:
args = self.__class__.mkgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mkgrp_parser.print_usage()
return
group_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_group = core.CkgDisplayGroup(**group_dict)
new_id = self.cur_proj.add_group(new_group)
print "display group", new_id, "added"
self.cur_group = new_group
print "group", new_id, "is now the current display group"
edgrp_parser = CmdParser(add_help=False, prog='edgrp',
description='''Edits attributes of display groups
specified by ids.''')
edgrp_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='ids of display groups to be edited')
edgrp_parser.add_argument('--pre', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown before shapes are displayed''')
edgrp_parser.add_argument('--disp', type=to_decimal, metavar='SECONDS',
help='''time in seconds shapes will be
displayed''')
edgrp_parser.add_argument('--post', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown after shapes are displayed''')
def help_edgrp(self):
self.__class__.edgrp_parser.print_help()
def do_edgrp(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.edgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.edgrp_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_proj.groups) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_group_attr(x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.edgrp_parser.print_usage()
rmgrp_parser = CmdParser(add_help=False, prog='rmgrp',
description='''Removes display groups specified
by ids.''')
rmgrp_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='ids of display groups to be removed')
rmgrp_parser.add_argument('-a', '--all', action='store_true',
help='remove all groups from the project')
def help_rmgrp(self):
self.__class__.rmgrp_parser.print_help()
def do_rmgrp(self, line):
"""Removes display groups specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups to remove'
return
try:
args = self.__class__.rmgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rmgrp_parser.print_usage()
return
rmlist = []
if args.all:
for group in self.cur_proj.groups[:]:
self.cur_proj.del_group(group)
print "all display groups removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_proj.groups) or x < 0:
print "display group", x, "does not exist"
continue
rmlist.append(self.cur_proj.groups[x])
print "display group", x, "removed"
for group in rmlist:
self.cur_proj.del_group(group)
# Remember to point self.cur_group somewhere sane
if self.cur_group not in self.cur_proj.groups:
if len(self.cur_proj.groups) == 0:
self.cur_group = None
else:
self.cur_group = self.cur_proj.groups[0]
print "group 0 is now the current display group"
chgrp_parser = CmdParser(add_help=False, prog='chgrp',
description='''Changes display group that is
currently active for editing.
Prints current group id if
no group id is specified''')
chgrp_parser.add_argument('gid', metavar='id', type=int, nargs='?',
help='id of display group to be made active')
def help_chgrp(self):
self.__class__.chgrp_parser.print_help()
def do_chgrp(self, line):
"""Changes group that is currently active for editing."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups that can be made active'
return
try:
args = self.__class__.chgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.chgrp_parser.print_usage()
return
if args.gid == None:
print "group",\
self.cur_proj.groups.index(self.cur_group),\
"is the current display group"
elif args.gid >= len(self.cur_proj.groups) or args.gid < 0:
print "group", args.gid, "does not exist"
else:
self.cur_group = self.cur_proj.groups[args.gid]
print "group", args.gid, "is now the current display group"
mk_parser = CmdParser(add_help=False, prog='mk',
description='''Makes a new checkerboard in the
current group with the given
parameters.''')
mk_parser.add_argument('dims', action=store_tuple(2, ',', to_decimal),
help='''width,height of checkerboard in no. of
unit cells''')
mk_parser.add_argument('init_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of initial unit cell in pixels')
mk_parser.add_argument('end_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of final unit cell in pixels')
mk_parser.add_argument('position', action=store_tuple(2, ',', to_decimal),
help='x,y position of checkerboard in pixels')
mk_parser.add_argument('anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='anchor')
mk_parser.add_argument('cols', action=store_tuple(2, ',', to_color, [';']),
help='''color1,color2 of the checkerboard
(color format: R;G;B,
component range from 0-255)''')
mk_parser.add_argument('freq', type=to_decimal,
help='frequency of color reversal in Hz')
mk_parser.add_argument('phase', type=to_decimal, nargs='?', default='0',
help='initial phase of animation in degrees')
def help_mk(self):
self.__class__.mk_parser.print_help()
def do_mk(self, line):
"""Makes a checkerboard with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
if self.cur_group == None:
print 'automatically adding display group...'
self.do_mkgrp('')
try:
args = self.__class__.mk_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mk_parser.print_usage()
return
shape_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_shape = core.CheckerBoard(**shape_dict)
new_id = self.cur_proj.add_shape_to_group(self.cur_group, new_shape)
print "checkerboard", new_id, "added"
ed_parser = CmdParser(add_help=False, prog='ed',
description='''Edits attributes of checkerboards
specified by ids.''')
ed_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='''ids of checkerboards in the current
group to be edited''')
ed_parser.add_argument('--dims', action=store_tuple(2, ',', to_decimal),
help='checkerboard dimensions in unit cells',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--init_unit',
action=store_tuple(2, ',', to_decimal),
help='initial unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--end_unit',
action=store_tuple(2, ',', to_decimal),
help='final unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--position',
action=store_tuple(2, ',', to_decimal),
help='position of checkerboard in pixels',
metavar='X,Y')
ed_parser.add_argument('--anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='LOCATION')
ed_parser.add_argument('--cols', metavar='COLOR1,COLOR2',
action=store_tuple(2, ',', to_color, [';']),
help='''checkerboard colors (color format:
R;G;B, component range
from 0-255)''')
ed_parser.add_argument('--freq', type=to_decimal,
help='frequency of color reversal in Hz')
ed_parser.add_argument('--phase', type=to_decimal,
help='initial phase of animation in degrees')
def help_ed(self):
self.__class__.ed_parser.print_help()
def do_ed(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, please create one first'
return
try:
args = self.__class__.ed_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ed_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_group.shapes) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_shape_attr(self.cur_group, x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.ed_parser.print_usage()
rm_parser = CmdParser(add_help=False, prog='rm',
description='''Removes checkerboards specified
by ids.''')
rm_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''ids of checkerboards in the current group
to be removed''')
rm_parser.add_argument('-a', '--all', action='store_true',
help='''remove all checkerboards in the
current group''')
def help_rm(self):
self.__class__.rm_parser.print_help()
def do_rm(self, line):
"""Removes checkerboards specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, no boards to remove'
return
try:
args = self.__class__.rm_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rm_parser.print_usage()
return
rmlist = []
if args.all:
for shape in self.cur_group.shapes:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
print "all checkerboards removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_group.shapes) or x < 0:
print "checkerboard", x, "does not exist"
continue
rmlist.append(self.cur_group.shapes[x])
print "checkerboard", x, "removed"
for shape in rmlist:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
ls_parser = CmdParser(add_help=False, prog='ls',
description='''Lists project, display group and
checkerboard settings. If no group ids
are specified, all display groups
are listed.''')
ls_parser.add_argument('gidlist', nargs='*', metavar='gid', type=int,
help='''ids of the display groups to be listed''')
ls_group = ls_parser.add_mutually_exclusive_group()
ls_group.add_argument('-s', '--settings', action='store_true',
help='list only project settings')
ls_group.add_argument('-g', '--groups', action='store_true',
help='list only display groups')
def help_ls(self):
self.__class__.ls_parser.print_help()
def do_ls(self, line):
"""Lists project, display group and checkerboard settings."""
def ls_str(s, seps=[',',';']):
"""Special space-saving output formatter."""
if type(s) in [tuple, list]:
if len(seps) > 1:
newseps = seps[1:]
else:
newseps = seps
return seps[0].join([ls_str(i, newseps) for i in s])
else:
return str(s)
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.ls_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ls_parser.print_usage()
return
# Remove duplicates and ascending sort
args.gidlist = sorted(set(args.gidlist))
if len(self.cur_proj.groups) == 0:
if len(args.gidlist) > 0:
print 'this project has no display groups that can be listed'
args.settings = True
else:
for gid in args.gidlist[:]:
if gid >= len(self.cur_proj.groups) or gid < 0:
args.gidlist.remove(gid)
print 'display group', gid, 'does not exist'
if args.gidlist == []:
args.gidlist = range(len(self.cur_proj.groups))
else:
# If any (valid) groups are specified
# don't show project settings
args.groups = True
if not args.groups:
print 'PROJECT SETTINGS'.center(70,'*')
print \
'name'.rjust(16),\
'fps'.rjust(7),\
'resolution'.rjust(14),\
'bg color'.rjust(18)
# 'format'.rjust(7)
print \
ls_str(self.cur_proj.name).rjust(16),\
ls_str(self.cur_proj.fps).rjust(7),\
ls_str(self.cur_proj.res).rjust(14),\
ls_str(self.cur_proj.bg).rjust(18)
# ls_str(self.cur_proj.export_fmt).rjust(7)
print \
'pre-display'.rjust(26),\
'post-display'.rjust(26)
print \
ls_str(self.cur_proj.pre).rjust(26),\
ls_str(self.cur_proj.post).rjust(26)
print \
'cross colors'.rjust(26),\
'cross times'.rjust(26)
print \
ls_str(self.cur_proj.cross_cols).rjust(26),\
ls_str(self.cur_proj.cross_times).rjust(26)
if not args.settings and not args.groups:
# Insert empty line if both groups and project
# settings are listed
print ''
if not args.settings:
for i, n in enumerate(args.gidlist):
if i != 0:
# Print newline seperator between each group
print ''
group = self.cur_proj.groups[n]
print 'GROUP {n}'.format(n=n).center(70,'*')
print \
'pre-display'.rjust(20),\
'display'.rjust(20),\
'post-display'.rjust(20)
print \
ls_str(group.pre).rjust(20),\
ls_str(group.disp).rjust(20),\
ls_str(group.post).rjust(20)
if len(group.shapes) > 0:
print \
''.rjust(2),\
'shape id'.rjust(8),\
'dims'.rjust(10),\
'init_unit'.rjust(14),\
'end_unit'.rjust(14),\
'position'.rjust(14)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.dims).rjust(10),\
ls_str(shape.init_unit).rjust(14),\
ls_str(shape.end_unit).rjust(14),\
ls_str(shape.position).rjust(14)
print '\n',\
''.rjust(2),\
'shape id'.rjust(8),\
'colors'.rjust(27),\
'anchor'.rjust(12),\
'freq'.rjust(6),\
'phase'.rjust(7)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.cols).rjust(27),\
ls_str(shape.anchor).rjust(12),\
ls_str(shape.freq).rjust(6),\
ls_str(shape.phase).rjust(7)
display_parser = CmdParser(add_help=False, prog='display',
description='''Displays the animation in a
window or in fullscreen.''')
display_parser.add_argument('-e', '--expfile', metavar='PATH',
help='''run experiment as described in
specified file, ignore other flags''')
display_parser.add_argument('-f', '--fullscreen', action='store_true',
help='sets fullscreen mode, ESC to quit')
display_parser.add_argument('-p', '--priority', metavar='LEVEL',
help='''set priority while displaying,
higher priority results in
less dropped frames (choices:
0-3, low, normal, high,
realtime)''')
- display_parser.add_argument('-r', '--repeat', metavar='N', type=int,
+ display_parser.add_argument('-r', '--repeats', metavar='N', type=int,
help='''repeatedly display specified display
groups N number of times''')
display_parser.add_argument('-pt', '--phototest', action='store_true',
help='''draw white test rectangle in topleft
corner of screen when groups become
visible for a photodiode to detect''')
display_parser.add_argument('-pb', '--photoburst', action='store_true',
help='''make checkerboards only draw first
color for one frame to facilitate
testing with a photodiode''')
display_parser.add_argument('-lt', '--logtime', action='store_true',
help='output frame timestamps to a log file')
display_parser.add_argument('-ld', '--logdur', action='store_true',
help='output frame durations to a log file')
display_parser.add_argument('-ss', '--trigser', action='store_true',
help='''send triggers through the serial port
when shapes are being displayed''')
display_parser.add_argument('-sp', '--trigpar', action='store_true',
help='''send triggers through the parallel port
when shapes are being displayed''')
display_parser.add_argument('-fpst', metavar='M', type=int, default=0,
help='''unique trigger corresponding to a
checkerboard is sent after the shape
undergoes M color flips (default:
disabled, M=0)''')
display_parser.add_argument('-et', '--eyetrack', action='store_true',
help='''use eyetracking to ensure that subject
fixates on the cross in the center''')
display_parser.add_argument('-eu', '--etuser', action='store_true',
help='''allow user to select eyetracking video
source from a dialog''')
display_parser.add_argument('-ev', '--etvideo', metavar='path',
help='''path (with no spaces) to eyetracking
video file to be used as the source''')
display_parser.add_argument('-ta', '--tryagain', metavar='I',
type=int, default=0,
help='''append groups during which subject
failed to fixate up to I times to the
list of groups to be displayed
(default: disabled, I=0)''')
display_parser.add_argument('-tb', '--trybreak', metavar='J', type=int,
help='''used with --tryagain, append a wait
screen to the list of groups to be
displayed after every J groups have
been appended to the list (default:
J=total number of groups)''')
display_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be displayed
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_display(self):
self.__class__.display_parser.print_help()
def do_display(self, line):
"""Displays the animation in a window or in fullscreen"""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.display_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
if args.expfile != None:
try:
exp = core.CkgExp(path=args.expfile)
except IOError:
print "error:", str(sys.exc_value)
return
try:
args = self.__class__.\
display_parser.parse_args(shlex.split(exp.flags))
except (CmdParserError, ValueError):
print 'error: invalid flags stored in run file'
return
try:
print """name of log file (default: experiment name):"""
runname = raw_input().strip().strip('"\'')
except EOFError:
return
if runname == '':
runname == exp.name
run = exp.random_run(runname)
args.idlist = run.idlist()
else:
run = core.CkgRun(name=self.cur_proj.name,
blocks=None,
flags=line,
sequence=[])
groupq = []
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < -1:
print 'error: group', i, 'does not exist'
return
for i in args.idlist:
if i == -1:
groupq.append(core.CkgWaitScreen(res=self.cur_proj.res))
else:
groupq.append(self.cur_proj.groups[i])
else:
groupq = list(self.cur_proj.groups)
if args.repeat != None:
groupq = list(groupq * args.repeat)
if args.eyetrack and eyetracking.available:
if not eyetracking.is_calibrated():
try:
self.do_calibrate('',True)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
return
if args.priority != None:
if not priority.available[sys.platform]:
print "error: setting priority not available on", sys.platform
print "continuing..."
else:
if args.priority.isdigit():
args.priority = int(args.priority)
try:
priority.set(args.priority)
except ValueError:
print "error:", str(sys.exc_value)
print "continuing..."
print "displaying..."
try:
self.cur_proj.display(fullscreen=args.fullscreen,
logtime=args.logtime,
logdur=args.logdur,
trigser=args.trigser,
trigpar=args.trigpar,
fpst=args.fpst,
phototest=args.phototest,
photoburst=args.photoburst,
eyetrack=args.eyetrack,
etuser=args.etuser,
etvideo=args.etvideo,
tryagain=args.tryagain,
trybreak=args.trybreak,
groupq=groupq,
run=run)
except (IOError, NotImplementedError, eyetracking.EyetrackingError):
print "error:", str(sys.exc_value)
if args.priority != None:
try:
priority.set('normal')
except:
pass
return
if args.priority != None:
try:
priority.set('normal')
except:
pass
try:
run.write_log()
except IOError:
print "error:", str(sys.exc_value)
return
print "log file written"
export_parser = CmdParser(add_help=False, prog='export',
description='''Exports animation as an image
sequence (in a folder) to the
specified directory.''')
# export_parser.add_argument('--fmt', dest='export_fmt',
# choices=core.EXPORT_FMTS,
# help='image format for export')
export_parser.add_argument('-n','--nofolder',
dest='folder', action='store_false',
help='''force images not to exported in
a containing folder''')
export_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly export specified display
groups N number of times''')
export_parser.add_argument('duration', nargs='?',
type=to_decimal, default='Infinity',
help='''number of seconds of the animation
that should be exported (default:
as long as the entire animation)''')
export_parser.add_argument('dir', nargs='?', default=os.getcwd(),
help='''destination directory for export
(default: current working directory)''')
export_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be exported
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_export(self):
self.__class__.export_parser.print_help()
def do_export(self, line):
"""Exports animation an image sequence to the specified directory."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.export_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.export_parser.print_usage()
return
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < 0:
print 'error: group', i, 'does not exist'
return
groupq = [self.cur_proj.groups[i] for i in args.idlist]
else:
groupq = list(self.cur_proj.groups)
if args.repeat != None:
groupq = list(groupq * args.repeat)
try:
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
folder=args.folder)
except IOError:
print "error:", str(sys.exc_value)
return
except core.FrameOverflowError:
print "warning:", str(sys.exc_value)
print "Are you sure you want to continue?"
while True:
try:
if self.__class__.yn_parse(raw_input()):
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
export_fmt=None,
folder=args.folder,
force=True)
break
else:
return
except TypeError:
print str(sys.exc_value)
except EOFError:
return
print "Export done."
mkexp_parser = CmdParser(add_help=False, prog='mkexp',
description='''Create checkergen experiment file
which describes how the project
is to be displayed.''')
mkexp_parser.add_argument('-n', '--name',
help='''name of the experiment (default: same
name as current project)''')
mkexp_parser.add_argument('-b', '--blocks', type=int, metavar='N',
help='''N blocks displayed in a run, i.e.
the same sequence will be displayed
N times in that run, with waitscreens
in between''')
mkexp_parser.add_argument('-f', '--flags',
help='''flags passed to the display command
that should be used when the run
file is run (enclose in quotes and use
'+' or '++' in place of '-' or '--')''')
def help_mkexp(self):
self.__class__.mkexp_parser.print_help()
def do_mkexp(self, line):
"""Creates checkergen experiment file."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.mkexp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mkexp_parser.print_usage()
return
if args.blocks == None:
print "number of blocks:"
try:
args.blocks = int(raw_input().strip())
except EOFError:
return
except ValueError:
print "error:", str(sys.exc_value)
return
if args.flags != None:
args.flags = args.flags.replace('+','-')
else:
print "flags used with display command (leave blank if none):"
try:
args.flags = raw_input().strip().strip('"\'')
except EOFError:
return
try:
disp_args = self.__class__.display_parser.\
parse_args(shlex.split(args.flags))
except (CmdParserError, ValueError):
print "error: invalid flags to display command"
print str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
print "list of sequences to choose from in the format",\
"'id1,id2,id3;seq2;seq3;seq4':"
print "(default: reduced latin square)"
try:
seqs_str = raw_input().strip()
if seqs_str == '':
args.sequences = None
else:
args.sequences = [[int(i) for i in seq_str.split(',')]
for seq_str in seqs_str.split(';')]
except EOFError:
return
try:
new_exp = core.CkgExp(name=args.name, proj=self.cur_proj,
blocks=args.blocks,
sequences=args.sequences,
flags=args.flags)
new_exp.save()
except IOError:
print "error:", str(sys.exc_value)
return
print "Experiment file created."
def do_calibrate(self, line, query=False):
"""Calibrate subject for eyetracking, or load a calibration file."""
if not eyetracking.available:
print "error: eyetracking functionality not available"
return
if query:
print "path to calibration file (leave empty for GUI tool):"
try:
path = raw_input().strip().strip('"\'')
except EOFError:
msg = "calibration cancelled"
raise eyetracking.EyetrackingError(msg)
else:
path = line.strip().strip('"\'')
if len(path) == 0:
path = None
if not eyetracking.is_source_ready():
# Select default source if none has been selected
eyetracking.select_source()
try:
eyetracking.calibrate(path)
except eyetracking.EyetrackingError:
if query:
raise
else:
print "error:", str(sys.exc_value)
return
if len(path) > 0:
print "calibration file successfully loaded"
etsetup_parser = CmdParser(add_help=False, prog='etsetup',
description='''Set various eyetracking
parameters.''')
etsetup_parser.add_argument('-fp', '--fixperiod', type=int, metavar='MS',
help='''time in milliseconds subject
has to stare at the same spot
for fixation to be detected''')
etsetup_parser.add_argument('-fr', '--fixrange', type=float, metavar='MM',
help='''distance in mm beyond which the
eye position cannot change for
a fixation to be detected''')
etsetup_parser.add_argument('-s', '--size', metavar='WIDTH,HEIGHT',
action=store_tuple(2, ',', float),
help='physical screen dimensions in mm')
etsetup_parser.add_argument('-vd', '--viewdist', type=int, metavar='MM',
help='''viewing distance between subject's
eyes and the screen''')
def help_etsetup(self):
self.__class__.etsetup_parser.print_help()
def do_etsetup(self, line):
try:
args = self.__class__.etsetup_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.etsetup_parser.print_usage()
return
try:
eyetracking.setup(viewing_distance=args.viewdist,
screen_dims=args.size,
fixation_period=args.fixperiod,
fixation_range=args.fixrange)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
def do_pwd(self, line):
"""Prints the current working directory."""
print os.getcwd()
def do_cd(self, line):
"""Change working directory to specified path."""
path = line.strip().strip('"\'')
if not os.path.isdir(path):
print "error: specified path is not a directory"
return
os.chdir(path)
def do_quit(self, line):
"""Quits the program."""
if self.save_check():
return
return True
def help_EOF(self):
print "Typing {0} issues this command, which quits the program."\
.format(CMD_EOF_STRING)
def do_EOF(self, line):
"""Typing Ctrl-D issues this command, which quits the program."""
print '\r'
if self.save_check():
return
return True
def help_help(self):
print 'Prints a list of commands.'
print "Type 'help <topic>' for more details on each command."
def default(self, line):
command = line.split()[0]
print \
"'{0}' is not a checkergen command.".format(command),\
"Type 'help' for a list of commands"
diff --git a/src/core.py b/src/core.py
index c76c183..b0f4b25 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,1293 +1,1477 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgExp -- A checkergen experiment, describes how a projet is displayed.
CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import random
import itertools
from xml.dom import minidom
import pyglet
import graphics
import trigger
import eyetracking
from utils import *
# Use OrderedDict substitute if we don't have Python 2.7
if sys.version_info < (2, 7):
from odict import OrderedDict
else:
from collections import OrderedDict
CKG_FMT = 'ckg'
EXP_FMT = 'ckx'
LOG_FMT = 'log'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
MAX_EXPORT_FRAMES = 100000
PRERENDER_TO_TEXTURE = False
INT_HALF_PERIODS = True
EXPORT_FMTS = ['png']
EXPORT_DIR_SUFFIX = '-anim'
FIX_POS = (0, 0)
FIX_RANGE = (20, 20)
FIX_PER = 350
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = OrderedDict([('name', 'untitled'),
('fps', 60),
('res', (800, 600)),
('bg', (127, 127, 127)),
('export_fmt', 'png'),
('pre', 0),
('post', 0),
('cross_cols', ((0, 0, 0), (255, 0, 0))),
('cross_times', ('Infinity', 1)),
('orders', []),
('disp_ops', None)])
DEFAULTS['disp_ops'] = OrderedDict([('fullscreen', False),
('priority', 0),
('logtime', False),
('logdur', False),
('trigser', False),
('trigpar', False),
('fpst', 0),
('phototest', False),
('photoburst', False),
('eyetrack', False),
('etuser', False),
('etvideo', None),
('tryagain', 0),
- ('trybreak', None)])
+ ('trybreak', None),
+ ('repeats', 1)])
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
export_fmt -- image format for animation to be exported as
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'export_fmt':
if value not in EXPORT_FMTS:
msg = 'image format not recognized or supported'
raise FileFormatError(msg)
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
# Vars that are dicts
dicts_to_load = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_load = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
for d_name in dicts_to_load:
d = self.__class__.DEFAULTS[d_name]
try:
d_el = [node for node in project.childNodes if
node.localName == d_name and
node.namespaceURI == XML_NAMESPACE][0]
for var in d.keys():
try:
d[var] = eval(xml_get(d_el, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}' in '{1}'".\
format(var, d_name)
print "using default value '{0}' instead...".\
format(d[var])
except IndexError:
print "warning: missing attribute set '{0}'".format(d_name)
print "using default values instead..."
setattr(self, d_name, d)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
# Vars that are dicts
dicts_to_save = [var for var in self.__class__.DEFAULTS.keys() if
isinstance(self.__class__.DEFAULTS[var], dict)]
# Vars that are not dicts
vars_to_save = [var for var in self.__class__.DEFAULTS.keys() if not
isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for d_name in dicts_to_save:
d_el = doc.createElement(d_name)
project.appendChild(d_el)
d = getattr(self, d_name)
for k, v in d.iteritems():
xml_set(doc, d_el, k, repr(v))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, fullscreen=False, logtime=False, logdur=False,
trigser=False, trigpar=False, fpst=0,
phototest=False, photoburst=False,
eyetrack=False, etuser=False, etvideo=None,
tryagain=0, trybreak=None, groupq=[], run=None):
"""Displays the project animation on the screen.
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
trigser -- send triggers through serial port when each group is shown
trigpar -- send triggers through parallel port when each group is shown
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- Append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- Append a wait screen to the group queue every time
after this many groups have been appended to the queue
groupq -- queue of groups to be displayed, defaults to order of
groups in project (i.e. groups[0] first, etc.)
run -- experimental run where logged variables are saved (i.e.
fail_idlist and time information)
"""
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if phototest:
test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Set-up groups and variables that control their display
if groupq == []:
groupq = list(self.groups)
n = -1
flipped = 0
flip_id = -1
groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Initialize ports
if trigser:
if not trigger.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if trigpar:
if not trigger.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
trigger.init(trigser, trigpar)
# Initialize eyetracking
if eyetrack:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if trybreak == None:
trybreak = len(self.groups)
fixated = False
old_fixated = False
tracked = False
old_tracked = False
cur_fix_fail = False
trycount = 0
fail_idlist = []
eyetracking.select_source(etuser, etvideo)
eyetracking.start()
# Stretch to fit screen only if project res does not equal screen res
scaling = False
if fullscreen:
window = pyglet.window.Window(fullscreen=True, visible=False)
if (window.width, window.height) != self.res:
scaling = True
else:
window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
keystates = pyglet.window.key.KeyStateHandler()
window.push_handlers(keystates)
# Create framebuffer object for drawing unscaled scene
if scaling:
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
fbo.end_render()
# Clear window and make visible
window.switch_to()
graphics.set_clear_color(self.bg)
window.clear()
window.set_visible()
# Initialize logging variables
if logtime:
timestamps = []
trigstamps = []
timer = Timer()
timer.start()
if logdur:
durstamps = []
dur = Timer()
dur.start()
# Main loop
while not window.has_exit and count < disp_end:
# Clear canvas
if scaling:
fbo.start_render()
fbo.clear()
else:
window.clear()
# Assume no change to group visibility
flipped = 0
# Manage groups when they are on_screen
if groups_visible:
# Check whether group changes in visibility
if n >= 0 and groupq[n].visible != groupq[n].old_visible:
flip_id = self.groups.index(groupq[n])
if groupq[n].visible:
flipped = 1
elif groupq[n].old_visible:
flipped = -1
# Get next group from queue
if n < 0 or groupq[n].over:
# Send special trigger if waitscreen ends
if isinstance(groupq[n], CkgWaitScreen):
trigger.CUR_STATE['user'] = 1
n += 1
if n >= len(groupq):
groups_visible = False
trigger.CUR_STATE['user'] = 0
else:
groupq[n].reset()
if eyetrack:
cur_fix_fail = False
if groupq[n].visible:
flip_id = self.groups.index(groupq[n])
flipped = 1
# Send special trigger when waitscreen ends
if isinstance(groupq[n], CkgWaitScreen):
trigger.CUR_STATE['user'] = 0
# Draw and then update group
if n >= 0:
groupq[n].draw(photoburst=photoburst)
groupq[n].update(fps=self.fps,
fpst=fpst,
keystates=keystates)
# Send triggers upon group visibility change
if flipped == 1:
trigger.CUR_STATE['group'] = 1
# Draw test rectangle
if phototest:
test_rect.draw()
elif flipped == -1:
trigger.CUR_STATE['group'] = 0
if eyetrack:
# First check if eye is being tracked and send trigger
old_tracked = tracked
tracked = eyetracking.is_tracked()
if tracked:
if not old_tracked:
# Send trigger if eye starts being tracked
trigger.set_track_start()
else:
if old_tracked:
# Send trigger if eye stops being tracked
trigger.set_track_stop()
# Next check for fixation
old_fixated = fixated
fixated = eyetracking.is_fixated(FIX_POS, FIX_RANGE, FIX_PER)
if fixated:
# Draw normal cross color if fixating
fix_crosses[0].draw()
if not old_fixated:
# Send trigger if fixation starts
trigger.set_fix_start()
else:
# Draw alternative cross color if not fixating
fix_crosses[1].draw()
if old_fixated:
# Send trigger if fixation stops
trigger.set_fix_stop()
# Take note of which groups in which fixation failed
if not cur_fix_fail and groupq[n].visible and\
(tracked and not fixated):
cur_fix_fail = True
# Append failed group to group queue
if trycount < tryagain:
# Insert waitscreen every trybreak failed groups
if trybreak > 0:
if len(fail_idlist) % trybreak == 0:
groupq.append(CkgWaitScreen())
groupq.append(groupq[n])
groups_stop += groupq[n].duration() * self.fps
disp_end += groupq[n].duration() * self.fps
trycount += 1
# Maintain list of failed IDs
fail_idlist.append(self.groups.index(groupq[n]))
# Change cross color based on time if eyetracking is not enabled
if not eyetrack:
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Increment count and set whether groups should be shown
if not isinstance(groupq[n], CkgWaitScreen):
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
# Blit canvas to screen if necessary
if scaling:
fbo.end_render()
window.switch_to()
canvas.blit(0, 0)
window.dispatch_events()
window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to lists
if logtime:
timestamps.append(timer.elapsed())
if logdur:
durstamps.append(dur.restart())
# Send trigger ASAP after flip
trigger.send(trigser, trigpar)
# Log when trigger are sent
if logtime:
if flipped != 0 and (trigser or trigpar):
trigstamps.append(trigger.STATE)
else:
trigstamps.append('')
# Clean up
if eyetrack:
eyetracking.stop()
window.close()
if scaling:
fbo.delete()
del canvas
trigger.quit(trigser, trigpar)
# Store variables in run object
if run != None:
if logtime:
run.timestamps = timestamps
run.trigstamps = trigstamps
if logdur:
run.durstamps = durstamps
if eyetrack and len(fail_idlist) > 0:
run.add_idlist = fail_idlist[:tryagain]
run.fail_idlist = fail_idlist[tryagain:]
def export(self, export_dir, export_duration, groupq=[],
export_fmt=None, folder=True, force=False):
if not os.path.isdir(export_dir):
msg = 'export path is not a directory'
raise IOError(msg)
if export_fmt == None:
export_fmt = self.export_fmt
# Set-up groups and variables that control their display
if groupq == []:
groupq = list(self.groups)
n = -1
groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Limit export duration to display duration
frames = export_duration * self.fps
frames = min(frames, disp_end)
# Warn user if a lot of frames will be exported
if frames > MAX_EXPORT_FRAMES and not force:
msg = 'very large number ({0}) of frames to be exported'.\
format(frames)
raise FrameOverflowError(msg)
# Create folder to store images if necessary
if folder:
export_dir = os.path.join(export_dir,
self.name + EXPORT_DIR_SUFFIX)
if not os.path.isdir(export_dir):
os.mkdir(export_dir)
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Set up canvas and framebuffer object
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
# Main loop
while count < frames:
fbo.clear()
if groups_visible:
# Get next group from queue
if n < 0 or groupq[n].over:
n += 1
if n >= len(groupq):
groups_visible = False
else:
groupq[n].reset()
# Draw and then update group
if n >= 0:
groupq[n].draw()
groupq[n].update(fps=self.fps, fpst=0)
# Draw fixation cross based on current count
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Save current frame to file
savepath = \
os.path.join(export_dir,
'{0}{2}.{1}'.
format(self.name, export_fmt,
repr(count).zfill(numdigits(frames-1))))
canvas.save(savepath)
# Increment count and set whether groups should be shown
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
fbo.delete()
class CkgExp:
DEFAULTS = {'name': None, 'proj' : None,
'blocks': 1, 'sequences': None,
'flags': '--fullscreen --logtime --logdur'}
def __init__(self, **keywords):
"""Create a checkergen experiment, which specifies how a project
is to be displayed.
path -- if specified, ignore other arguments and load project
from path
name -- name of the experiment
proj -- CkgProj that the experiment is to be created for
blocks -- number of times the selected sequence of display groups
will be shown in one run
sequences -- list of possible display group id sequences, from which
one sequence will be randomly selected for display in a run,
defaults to reduced latin square with side length equal to the number
of display groups in the supplied CkgProj
flags -- string passed to the display command as flags
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
if self.name == None and self.proj != None:
self.name = self.proj.name
if self.sequences == None:
if self.proj == None:
msg = "either project or sequences have to be specified"
raise ValueError(msg)
else:
self.gen_latin_square(len(self.proj.groups))
del self.proj
def gen_latin_square(self, n):
"""Set experiment sequences as a cyclic reduced latin square."""
sequence = range(n)
self.sequences = [[sequence[i - j] for i in range(n)]
for j in range(n, 0, -1)]
def random_run(self, name):
"""Choose random sequence, create run from it and return."""
sequence = random.choice(self.sequences)
run = CkgRun(name=name,
flags=self.flags,
blocks=self.blocks,
sequence=sequence)
return run
def save(self, path=None):
"""Saves experiment to specified path in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, EXP_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(EXP_FMT):
path = '{0}.{1}'.format(path, EXP_FMT)
with open(path, 'wb') as expfile:
expwriter = csv.writer(expfile, dialect='excel-tab')
expwriter.writerow(['checkergen experiment file'])
expwriter.writerow(['flags:', self.flags])
expwriter.writerow(['blocks:', self.blocks])
expwriter.writerow(['sequences:'])
for sequence in self.sequences:
expwriter.writerow(sequence)
def load(self, path):
"""Loads experiment from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, EXP_FMT)
elif ext != '.{0}'.format(EXP_FMT):
msg = "path lacks '.{0}' extension".format(EXP_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
self.sequences = []
with open(path, 'rb') as expfile:
expreader = csv.reader(expfile, dialect='excel-tab')
for n, row in enumerate(expreader):
if n == 1:
self.flags = row[1]
elif n == 2:
self.blocks = int(row[1])
elif n > 3:
sequence = [int(i) for i in row]
self.sequences.append(sequence)
-class CkgRun:
+class CkgRunState:
+ """Contains information about the state of a checkergen project
+ when it is being displayed or exported."""
+
+ DEFAULTS = dict([('proj', None),
+ ('order', []),
+ ('disp_ops', None),
+ ('events', None),
+ ('add_gids', []),
+ ('fail_gids', []),
+ ('timestamps', []),
+ ('durstamps', []),
+ ('trigstamps', [])])
+
+ DEFAULTS['events'] = dict([('blk_on', False),
+ ('blk_off', False),
+ ('track_on', False),
+ ('track_off', False),
+ ('fix_on', False),
+ ('fix_off', False),
+ ('grp_on', False),
+ ('grp_off', False),
+ ('sids', [])])
+
+ def __init__(self, **keywords):
+ """Creates the RunState."""
+ for kw in self.__class__.DEFAULTS.keys():
+ if kw in keywords.keys():
+ setattr(self, kw, keywords[kw])
+ else:
+ setattr(self, kw, self.__class__.DEFAULTS[kw])
- def __init__(self, name, flags, blocks, sequence):
- """Creates an experimental run."""
- self.name = name
- self.flags = flags
- self.blocks = blocks
- self.sequence = sequence
- self.add_idlist = None
- self.fail_idlist = None
- self.timestamps = []
- self.durstamps = []
- self.trigstamps = []
-
- def idlist(self):
- """Generate idlist from sequence and return it."""
- idlist = ([-1] + self.sequence) * self.blocks
- return idlist
+ def start(self):
+ """Initialize all subsystems and start the run."""
+
+ if self.proj == None:
+ msg = "RunState lacks associated project, run cannot begin"
+ raise ValueError(msg)
+
+ self.count = 0
+ self.trycount = self.disp_ops['tryagain']
+
+ # Create fixation crosses
+ self.fix_crosses = [graphics.Cross([r/2 for r in self.proj.res],
+ (20, 20), col = cross_col)
+ for cross_col in self.proj.cross_cols]
+
+ # Create test rectangle
+ if self.disp_ops['phototest']:
+ self.test_rect = graphics.Rect((0, self.res[1]),
+ [r/8 for r in self.proj.res],
+ anchor='topleft')
+
+ # Initialize ports
+ if self.disp_ops['trigser']:
+ if not trigger.available['serial']:
+ msg = 'serial port functionality not available'
+ raise NotImplementedError(msg)
+ if self.disp_ops['trigpar']:
+ if not trigger.available['parallel']:
+ msg = 'parallel port functionality not available'
+ raise NotImplementedError(msg)
+ trigger.init(trigser, trigpar)
+
+ # Initialize eyetracking
+ if self.disp_ops['eyetrack']:
+ if not eyetracking.available:
+ msg = 'eyetracking functionality not available'
+ raise NotImplementedError(msg)
+ if self.disp_ops['trybreak'] == None:
+ self.disp_ops['trybreak'] = len(self.proj.groups)
+ self.fixated = False
+ self.old_fixated = False
+ self.tracked = False
+ self.old_tracked = False
+ eyetracking.select_source(self.disp_ops['etuser'],
+ self.disp_ops['etvideo'])
+ eyetracking.start()
+
+ # Stretch to fit screen only if project res does not equal screen res
+ self.scaling = False
+ if self.disp_ops['fullscreen']:
+ self.window = pyglet.window.Window(fullscreen=True, visible=False)
+ if (self.window.width, self.window.height) != self.proj.res:
+ self.scaling = True
+ else:
+ self.window = pyglet.window.Window(*self.proj.res, visible=False)
+
+ # Set up KeyStateHandler to handle keyboard input
+ self.keystates = pyglet.window.key.KeyStateHandler()
+ self.window.push_handlers(keystates)
+
+ # Clear window and make visible
+ self.window.switch_to()
+ graphics.set_clear_color(self.proj.bg)
+ self.window.clear()
+ self.window.set_visible()
+
+ # Create framebuffer object for drawing unscaled scene
+ if self.scaling:
+ self.canvas = pyglet.image.Texture.create(*self.proj.res)
+ self.fbo = graphics.Framebuffer(canvas)
+ self.fbo.start_render()
+ graphics.set_clear_color(self.proj.bg)
+ self.fbo.clear()
+
+ # Start timers
+ if self.disp_ops['logtime']:
+ self.timer = Timer()
+ self.timer.start()
+ if self.disp_ops['logdur']:
+ self.dur = Timer()
+ self.dur.start()
+
+ def update(self):
+ """Update the RunState."""
+
+ # Check for tracking and fixation
+ if self.disp_ops['eyetrack']:
+ self.old_tracked = self.tracked
+ self.tracked = eyetracking.is_tracked()
+ self.old_fixated = self.fixated
+ self.fixated = eyetracking.is_fixated(FIX_POS, FIX_RANGE, FIX_PER)
+
+ if fixated:
+ # Draw normal cross color if fixating
+ fix_crosses[0].draw()
+ else:
+ # Draw alternative cross color if not fixating
+ fix_crosses[1].draw()
+
+ # Update eyetracking events
+ if self.tracked != self.old_tracked:
+ if self.tracked:
+ self.events['track_on'] = True
+ else:
+ self.events['track_off'] = True
+ if self.fixated != self.old_fixated:
+ if self.fixated:
+ self.events['fix_on'] = True
+ else:
+ self.events['fix_off'] = True
+
+ else:
+ # Change cross color based on time
+ if (self.count % (sum(self.cross_times) * self.fps)
+ < self.cross_times[0] * self.fps):
+ fix_crosses[0].draw()
+ else:
+ fix_crosses[1].draw()
+
+ # Blit canvas to screen if necessary
+ if self.scaling:
+ self.fbo.end_render()
+ self.window.switch_to()
+ self.canvas.blit(0, 0)
+ self.window.dispatch_events()
+ self.window.flip()
+ # Make sure everything has been drawn
+ pyglet.gl.glFinish()
+
+ # Append time information to lists
+ if self.disp_ops['logtime']:
+ self.timestamps.append(self.timer.elapsed())
+ elif self.disp_ops['logdur']:
+ self.timestamps.append('')
+ if self.disp_ops['logdur']:
+ self.durstamps.append(self.dur.restart())
+ elif self.disp_ops['logtime']:
+ self.durstamps.append('')
+
+ # Send trigger ASAP after flip
+ if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
+ trigger.send(trigser, trigpar, self.encode_events())
+
+ # Log when triggers are sent
+ if self.disp_ops['logtime']:
+ if self.encode_events() != None:
+ trigstamps.append(self.encode_events())
+ else:
+ trigstamps.append('')
+
+ # Clear canvas, events, prepare for next frame
+ if self.scaling:
+ self.fbo.start_render()
+ self.fbo.clear()
+ else:
+ self.window.clear()
+
+ self.count += 1
+
+ def stop(self):
+ """Clean up RunState."""
+ if self.disp_ops['eyetrack']:
+ eyetracking.stop()
+ self.window.close()
+ if self.scaling:
+ self.fbo.delete()
+ del self.canvas
+ if self.disp_ops['trigser'] or self.disp_ops['trigpar']:
+ trigger.quit(trigser, trigpar)
def write_log(self, path=None):
"""Write a log file for the experimental run in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, LOG_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(LOG_FMT):
path = '{0}.{1}'.format(path, LOG_FMT)
with open(path, 'wb') as runfile:
runwriter = csv.writer(runfile, dialect='excel-tab')
runwriter.writerow(['checkergen log file'])
runwriter.writerow(['flags:', self.flags])
runwriter.writerow(['blocks:', self.blocks])
runwriter.writerow(['sequence:'] + self.sequence)
if self.add_idlist != None:
runwriter.writerow(['groups appended:'])
rowlist = grouper(len(self.sequence), self.add_idlist, '')
for row in rowlist:
runwriter.writerow(row)
if self.fail_idlist != None:
runwriter.writerow(['groups failed (not appended):'])
rowlist = grouper(len(self.sequence), self.fail_idlist, '')
for row in rowlist:
runwriter.writerow(row)
stamps = [self.timestamps, self.durstamps, self.trigstamps]
if len(max(stamps)) > 0:
for l in stamps:
if len(l) == 0:
l = [''] * len(max(stamps))
runwriter.writerow(['timestamps', 'durations', 'triggers'])
for row in zip(*stamps):
runwriter.writerow(row)
class CkgDisplayGroup:
DEFAULTS = OrderedDict([('pre', 0), ('disp', 'Infinity'), ('post', 0)])
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets internal count and all contained shapes."""
self._count = 0
self._start = self.pre
self._stop = self.pre + self.disp
self._end = self.pre + self.disp + self.post
self.over = False
self.old_visible = False
if self._start == 0 and self._stop > 0:
self.visible = True
else:
self.visible = False
if self._end == 0:
self.over = True
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, lazy=False, photoburst=False):
"""Draws all contained shapes during the appropriate interval."""
if self.visible:
for shape in self.shapes:
if lazy:
shape.lazydraw()
else:
shape.draw(photoburst=photoburst)
def update(self, **keywords):
"""Increments internal count, makes group visible when appropriate.
fps -- refresh rate of the display in frames per second
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
"""
fps = keywords['fps']
fpst = keywords['fpst']
if self.visible:
# Set triggers to be sent
if fpst > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= fpst:
trigger.CUR_STATE['shape'] = 1
trigger.CUR_STATE['sid'] = n
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(fps)
# Increment count and set flags for the next frame
self._count += 1
self.old_visible = self.visible
if (self._start * fps) <= self._count < (self._stop * fps):
self.visible = True
else:
self.visible = False
if self._count >= (self._end * fps):
self.over = True
else:
self.over = False
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.visible = False
self.old_visible = False
self.steps_done = 0
self.over = False
def draw(self, **keywords):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, **keywords):
"""Checks for keypress, sends trigger upon end."""
keystates = keywords['keystates']
if max([keystates[key] for key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
if self.steps_done == self.num_steps:
self.over = True
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = OrderedDict([('dims', (5, 5)),
('init_unit', (30, 30)),
('end_unit', (50, 50)),
('position', (0, 0)),
('anchor', 'bottomleft'),
('cols', ((0, 0, 0), (255, 255, 255))),
('freq', 1),
('phase', 0)])
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
if INT_HALF_PERIODS:
frames_per_half_period = round(fps / (self.freq * 2))
degs_per_frame = 180 / to_decimal(frames_per_half_period)
else:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
if PRERENDER_TO_TEXTURE:
init_pos = [(1 - a)* s/to_decimal(2) for s, a in
zip(self._size, graphics.locations[self.anchor])]
else:
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
anchor=self.anchor)
cur_unit_rect.col = self.cols[(i + j) % 2]
cur_unit_rect.add_to_batch(self._batches[0])
cur_unit_rect.col = self.cols[(i + j + 1) % 2]
cur_unit_rect.add_to_batch(self._batches[1])
# Increase x values
cur_unit_pos[0] += \
graphics.locations[self.anchor][0] * cur_unit[0]
cur_unit[0] += unit_grad[0]
# Reset x values
cur_unit_pos[0] = init_pos[0]
cur_unit[0] = init_unit[0]
# Increase y values
cur_unit_pos[1] += \
graphics.locations[self.anchor][1] * cur_unit[1]
cur_unit[1] += unit_grad[1]
if PRERENDER_TO_TEXTURE:
# Create textures
int_size = [int(round(s)) for s in self._size]
self._prerenders =\
[pyglet.image.Texture.create(*int_size) for n in range(2)]
# Set up framebuffer
fbo = graphics.Framebuffer()
for n in range(2):
fbo.attach_texture(self._prerenders[n])
# Draw batch to texture
fbo.start_render()
self._batches[n].draw()
fbo.end_render()
# Anchor textures for correct blitting later
self._prerenders[n].anchor_x, self._prerenders[n].anchor_y =\
[int(round((1 - a)* s/to_decimal(2))) for s, a in
zip(self._size, graphics.locations[self.anchor])]
fbo.delete()
# Delete batches since they won't be used
del self._batches
self._computed = True
def draw(self, photoburst=False, always_compute=False):
"""Draws appropriate prerender depending on current phase.
photoburst -- draw first color for only one frame for testing purposes
always_compute -- recompute what the checkerboard should look like
every frame
"""
if not self._computed or always_compute:
self.compute()
self._cur_phase %= 360
n = int(self._cur_phase // 180)
if photoburst and n == 0 and not self.flipped:
n = 1
if PRERENDER_TO_TEXTURE:
self._prerenders[n].blit(*self.position)
else:
self._batches[n].draw()
def lazydraw(self):
"""Only draws on color reversal."""
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if (cur_n != prev_n) or self._first_draw:
self.draw()
if self._first_draw:
self._first_draw = False
|
ztangent/checkergen
|
be36454c2818daf5fc581645995c9ccc51b42566
|
Load and saving of disp_ops and other dicts implemented.
|
diff --git a/example.ckg b/example.ckg
index ee30221..a2bfe9d 100644
--- a/example.ckg
+++ b/example.ckg
@@ -1,56 +1,73 @@
<?xml version="1.0" ?>
<project xmlns="http://github.com/ZOMGxuan/checkergen">
<fps>Decimal('60')</fps>
<res>(800, 600)</res>
<bg>(127, 127, 127)</bg>
<export_fmt>'png'</export_fmt>
<pre>Decimal('0')</pre>
<post>Decimal('0')</post>
<cross_cols>((0, 0, 0), (255, 0, 0))</cross_cols>
<cross_times>(Decimal('Infinity'), Decimal('1'))</cross_times>
+ <orders>[]</orders>
+ <disp_ops>
+ <fullscreen>False</fullscreen>
+ <priority>0</priority>
+ <logtime>False</logtime>
+ <logdur>False</logdur>
+ <trigser>False</trigser>
+ <trigpar>False</trigpar>
+ <fpst>0</fpst>
+ <phototest>False</phototest>
+ <photoburst>False</photoburst>
+ <eyetrack>False</eyetrack>
+ <etuser>False</etuser>
+ <etvideo>None</etvideo>
+ <tryagain>0</tryagain>
+ <trybreak>None</trybreak>
+ </disp_ops>
<group>
<pre>Decimal('2')</pre>
<disp>Decimal('10')</disp>
<post>Decimal('2')</post>
<shape type="board">
<dims>(5, 5)</dims>
<init_unit>(Decimal('40'), Decimal('40'))</init_unit>
<end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<position>(Decimal('420'), Decimal('320'))</position>
<anchor>'bottomleft'</anchor>
<cols>((0, 0, 0), (255, 255, 255))</cols>
<freq>Decimal('1')</freq>
<phase>Decimal('0')</phase>
</shape>
<shape type="board">
<dims>(5, 5)</dims>
<init_unit>(Decimal('40'), Decimal('40'))</init_unit>
<end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<position>(Decimal('380'), Decimal('320'))</position>
<anchor>'bottomright'</anchor>
<cols>((0, 0, 0), (255, 255, 255))</cols>
<freq>Decimal('2')</freq>
<phase>Decimal('90')</phase>
</shape>
<shape type="board">
<dims>(5, 5)</dims>
<init_unit>(Decimal('40'), Decimal('40'))</init_unit>
<end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<position>(Decimal('420'), Decimal('280'))</position>
<anchor>'topleft'</anchor>
<cols>((0, 0, 0), (255, 255, 255))</cols>
<freq>Decimal('3')</freq>
<phase>Decimal('180')</phase>
</shape>
<shape type="board">
<dims>(5, 5)</dims>
<init_unit>(Decimal('40'), Decimal('40'))</init_unit>
<end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<position>(Decimal('380'), Decimal('280'))</position>
<anchor>'topright'</anchor>
<cols>((0, 0, 0), (255, 255, 255))</cols>
<freq>Decimal('4')</freq>
<phase>Decimal('270')</phase>
</shape>
</group>
</project>
diff --git a/src/core.py b/src/core.py
index 65250eb..c76c183 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,779 +1,830 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgExp -- A checkergen experiment, describes how a projet is displayed.
CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import random
import itertools
from xml.dom import minidom
import pyglet
import graphics
import trigger
import eyetracking
from utils import *
# Use OrderedDict substitute if we don't have Python 2.7
if sys.version_info < (2, 7):
from odict import OrderedDict
else:
from collections import OrderedDict
CKG_FMT = 'ckg'
EXP_FMT = 'ckx'
LOG_FMT = 'log'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
MAX_EXPORT_FRAMES = 100000
PRERENDER_TO_TEXTURE = False
INT_HALF_PERIODS = True
EXPORT_FMTS = ['png']
EXPORT_DIR_SUFFIX = '-anim'
FIX_POS = (0, 0)
FIX_RANGE = (20, 20)
FIX_PER = 350
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = OrderedDict([('name', 'untitled'),
('fps', 60),
('res', (800, 600)),
('bg', (127, 127, 127)),
('export_fmt', 'png'),
('pre', 0),
('post', 0),
('cross_cols', ((0, 0, 0), (255, 0, 0))),
- ('cross_times', ('Infinity', 1))])
+ ('cross_times', ('Infinity', 1)),
+ ('orders', []),
+ ('disp_ops', None)])
+
+ DEFAULTS['disp_ops'] = OrderedDict([('fullscreen', False),
+ ('priority', 0),
+ ('logtime', False),
+ ('logdur', False),
+ ('trigser', False),
+ ('trigpar', False),
+ ('fpst', 0),
+ ('phototest', False),
+ ('photoburst', False),
+ ('eyetrack', False),
+ ('etuser', False),
+ ('etvideo', None),
+ ('tryagain', 0),
+ ('trybreak', None)])
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
export_fmt -- image format for animation to be exported as
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'export_fmt':
if value not in EXPORT_FMTS:
msg = 'image format not recognized or supported'
raise FileFormatError(msg)
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
- vars_to_load = self.__class__.DEFAULTS.keys()
+ # Vars that are dicts
+ dicts_to_load = [var for var in self.__class__.DEFAULTS.keys() if
+ isinstance(self.__class__.DEFAULTS[var], dict)]
+ # Vars that are not dicts
+ vars_to_load = [var for var in self.__class__.DEFAULTS.keys() if not
+ isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
+ for d_name in dicts_to_load:
+ d = self.__class__.DEFAULTS[d_name]
+ try:
+ d_el = [node for node in project.childNodes if
+ node.localName == d_name and
+ node.namespaceURI == XML_NAMESPACE][0]
+ for var in d.keys():
+ try:
+ d[var] = eval(xml_get(d_el, XML_NAMESPACE, var))
+ except IndexError:
+ print "warning: missing attribute '{0}' in '{1}'".\
+ format(var, d_name)
+ print "using default value '{0}' instead...".\
+ format(d[var])
+ except IndexError:
+ print "warning: missing attribute set '{0}'".format(d_name)
+ print "using default values instead..."
+ setattr(self, d_name, d)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
- vars_to_save = self.__class__.DEFAULTS.keys()
+ # Vars that are dicts
+ dicts_to_save = [var for var in self.__class__.DEFAULTS.keys() if
+ isinstance(self.__class__.DEFAULTS[var], dict)]
+ # Vars that are not dicts
+ vars_to_save = [var for var in self.__class__.DEFAULTS.keys() if not
+ isinstance(self.__class__.DEFAULTS[var], dict)]
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
+ for d_name in dicts_to_save:
+ d_el = doc.createElement(d_name)
+ project.appendChild(d_el)
+ d = getattr(self, d_name)
+ for k, v in d.iteritems():
+ xml_set(doc, d_el, k, repr(v))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, fullscreen=False, logtime=False, logdur=False,
trigser=False, trigpar=False, fpst=0,
phototest=False, photoburst=False,
eyetrack=False, etuser=False, etvideo=None,
tryagain=0, trybreak=None, groupq=[], run=None):
"""Displays the project animation on the screen.
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
trigser -- send triggers through serial port when each group is shown
trigpar -- send triggers through parallel port when each group is shown
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- Append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- Append a wait screen to the group queue every time
after this many groups have been appended to the queue
groupq -- queue of groups to be displayed, defaults to order of
groups in project (i.e. groups[0] first, etc.)
run -- experimental run where logged variables are saved (i.e.
fail_idlist and time information)
"""
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if phototest:
test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Set-up groups and variables that control their display
if groupq == []:
groupq = list(self.groups)
n = -1
flipped = 0
flip_id = -1
groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Initialize ports
if trigser:
if not trigger.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if trigpar:
if not trigger.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
trigger.init(trigser, trigpar)
# Initialize eyetracking
if eyetrack:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if trybreak == None:
trybreak = len(self.groups)
fixated = False
old_fixated = False
tracked = False
old_tracked = False
cur_fix_fail = False
trycount = 0
fail_idlist = []
eyetracking.select_source(etuser, etvideo)
eyetracking.start()
# Stretch to fit screen only if project res does not equal screen res
scaling = False
if fullscreen:
window = pyglet.window.Window(fullscreen=True, visible=False)
if (window.width, window.height) != self.res:
scaling = True
else:
window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
keystates = pyglet.window.key.KeyStateHandler()
window.push_handlers(keystates)
# Create framebuffer object for drawing unscaled scene
if scaling:
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
fbo.end_render()
# Clear window and make visible
window.switch_to()
graphics.set_clear_color(self.bg)
window.clear()
window.set_visible()
# Initialize logging variables
if logtime:
timestamps = []
trigstamps = []
timer = Timer()
timer.start()
if logdur:
durstamps = []
dur = Timer()
dur.start()
# Main loop
while not window.has_exit and count < disp_end:
# Clear canvas
if scaling:
fbo.start_render()
fbo.clear()
else:
window.clear()
# Assume no change to group visibility
flipped = 0
# Manage groups when they are on_screen
if groups_visible:
# Check whether group changes in visibility
if n >= 0 and groupq[n].visible != groupq[n].old_visible:
flip_id = self.groups.index(groupq[n])
if groupq[n].visible:
flipped = 1
elif groupq[n].old_visible:
flipped = -1
# Get next group from queue
if n < 0 or groupq[n].over:
# Send special trigger if waitscreen ends
if isinstance(groupq[n], CkgWaitScreen):
trigger.CUR_STATE['user'] = 1
n += 1
if n >= len(groupq):
groups_visible = False
trigger.CUR_STATE['user'] = 0
else:
groupq[n].reset()
if eyetrack:
cur_fix_fail = False
if groupq[n].visible:
flip_id = self.groups.index(groupq[n])
flipped = 1
# Send special trigger when waitscreen ends
if isinstance(groupq[n], CkgWaitScreen):
trigger.CUR_STATE['user'] = 0
# Draw and then update group
if n >= 0:
groupq[n].draw(photoburst=photoburst)
groupq[n].update(fps=self.fps,
fpst=fpst,
keystates=keystates)
# Send triggers upon group visibility change
if flipped == 1:
trigger.CUR_STATE['group'] = 1
# Draw test rectangle
if phototest:
test_rect.draw()
elif flipped == -1:
trigger.CUR_STATE['group'] = 0
if eyetrack:
# First check if eye is being tracked and send trigger
old_tracked = tracked
tracked = eyetracking.is_tracked()
if tracked:
if not old_tracked:
# Send trigger if eye starts being tracked
trigger.set_track_start()
else:
if old_tracked:
# Send trigger if eye stops being tracked
trigger.set_track_stop()
# Next check for fixation
old_fixated = fixated
fixated = eyetracking.is_fixated(FIX_POS, FIX_RANGE, FIX_PER)
if fixated:
# Draw normal cross color if fixating
fix_crosses[0].draw()
if not old_fixated:
# Send trigger if fixation starts
trigger.set_fix_start()
else:
# Draw alternative cross color if not fixating
fix_crosses[1].draw()
if old_fixated:
# Send trigger if fixation stops
trigger.set_fix_stop()
# Take note of which groups in which fixation failed
if not cur_fix_fail and groupq[n].visible and\
(tracked and not fixated):
cur_fix_fail = True
# Append failed group to group queue
if trycount < tryagain:
# Insert waitscreen every trybreak failed groups
if trybreak > 0:
if len(fail_idlist) % trybreak == 0:
groupq.append(CkgWaitScreen())
groupq.append(groupq[n])
groups_stop += groupq[n].duration() * self.fps
disp_end += groupq[n].duration() * self.fps
trycount += 1
# Maintain list of failed IDs
fail_idlist.append(self.groups.index(groupq[n]))
# Change cross color based on time if eyetracking is not enabled
if not eyetrack:
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Increment count and set whether groups should be shown
if not isinstance(groupq[n], CkgWaitScreen):
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
# Blit canvas to screen if necessary
if scaling:
fbo.end_render()
window.switch_to()
canvas.blit(0, 0)
window.dispatch_events()
window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to lists
if logtime:
timestamps.append(timer.elapsed())
if logdur:
durstamps.append(dur.restart())
# Send trigger ASAP after flip
trigger.send(trigser, trigpar)
# Log when trigger are sent
if logtime:
if flipped != 0 and (trigser or trigpar):
trigstamps.append(trigger.STATE)
else:
trigstamps.append('')
# Clean up
if eyetrack:
eyetracking.stop()
window.close()
if scaling:
fbo.delete()
del canvas
trigger.quit(trigser, trigpar)
# Store variables in run object
if run != None:
if logtime:
run.timestamps = timestamps
run.trigstamps = trigstamps
if logdur:
run.durstamps = durstamps
if eyetrack and len(fail_idlist) > 0:
run.add_idlist = fail_idlist[:tryagain]
run.fail_idlist = fail_idlist[tryagain:]
def export(self, export_dir, export_duration, groupq=[],
export_fmt=None, folder=True, force=False):
if not os.path.isdir(export_dir):
msg = 'export path is not a directory'
raise IOError(msg)
if export_fmt == None:
export_fmt = self.export_fmt
# Set-up groups and variables that control their display
if groupq == []:
groupq = list(self.groups)
n = -1
groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Limit export duration to display duration
frames = export_duration * self.fps
frames = min(frames, disp_end)
# Warn user if a lot of frames will be exported
if frames > MAX_EXPORT_FRAMES and not force:
msg = 'very large number ({0}) of frames to be exported'.\
format(frames)
raise FrameOverflowError(msg)
# Create folder to store images if necessary
if folder:
export_dir = os.path.join(export_dir,
self.name + EXPORT_DIR_SUFFIX)
if not os.path.isdir(export_dir):
os.mkdir(export_dir)
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Set up canvas and framebuffer object
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
# Main loop
while count < frames:
fbo.clear()
if groups_visible:
# Get next group from queue
if n < 0 or groupq[n].over:
n += 1
if n >= len(groupq):
groups_visible = False
else:
groupq[n].reset()
# Draw and then update group
if n >= 0:
groupq[n].draw()
groupq[n].update(fps=self.fps, fpst=0)
# Draw fixation cross based on current count
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Save current frame to file
savepath = \
os.path.join(export_dir,
'{0}{2}.{1}'.
format(self.name, export_fmt,
repr(count).zfill(numdigits(frames-1))))
canvas.save(savepath)
# Increment count and set whether groups should be shown
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
fbo.delete()
class CkgExp:
DEFAULTS = {'name': None, 'proj' : None,
'blocks': 1, 'sequences': None,
'flags': '--fullscreen --logtime --logdur'}
def __init__(self, **keywords):
"""Create a checkergen experiment, which specifies how a project
is to be displayed.
path -- if specified, ignore other arguments and load project
from path
name -- name of the experiment
proj -- CkgProj that the experiment is to be created for
blocks -- number of times the selected sequence of display groups
will be shown in one run
sequences -- list of possible display group id sequences, from which
one sequence will be randomly selected for display in a run,
defaults to reduced latin square with side length equal to the number
of display groups in the supplied CkgProj
flags -- string passed to the display command as flags
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
if self.name == None and self.proj != None:
self.name = self.proj.name
if self.sequences == None:
if self.proj == None:
msg = "either project or sequences have to be specified"
raise ValueError(msg)
else:
self.gen_latin_square(len(self.proj.groups))
del self.proj
def gen_latin_square(self, n):
"""Set experiment sequences as a cyclic reduced latin square."""
sequence = range(n)
self.sequences = [[sequence[i - j] for i in range(n)]
for j in range(n, 0, -1)]
def random_run(self, name):
"""Choose random sequence, create run from it and return."""
sequence = random.choice(self.sequences)
run = CkgRun(name=name,
flags=self.flags,
blocks=self.blocks,
sequence=sequence)
return run
def save(self, path=None):
"""Saves experiment to specified path in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, EXP_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(EXP_FMT):
path = '{0}.{1}'.format(path, EXP_FMT)
with open(path, 'wb') as expfile:
expwriter = csv.writer(expfile, dialect='excel-tab')
expwriter.writerow(['checkergen experiment file'])
expwriter.writerow(['flags:', self.flags])
expwriter.writerow(['blocks:', self.blocks])
expwriter.writerow(['sequences:'])
for sequence in self.sequences:
expwriter.writerow(sequence)
def load(self, path):
"""Loads experiment from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, EXP_FMT)
elif ext != '.{0}'.format(EXP_FMT):
msg = "path lacks '.{0}' extension".format(EXP_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
self.sequences = []
with open(path, 'rb') as expfile:
expreader = csv.reader(expfile, dialect='excel-tab')
for n, row in enumerate(expreader):
if n == 1:
self.flags = row[1]
elif n == 2:
self.blocks = int(row[1])
diff --git a/src/utils.py b/src/utils.py
index 2ff717b..69fdfde 100644
--- a/src/utils.py
+++ b/src/utils.py
@@ -1,91 +1,95 @@
"""Utility functions and classes."""
import os
import time
import math
from decimal import *
from itertools import *
def numdigits(x):
"""Returns number of digits in a decimal integer."""
if x == 0:
return 1
elif x < 0:
x = -x
return int(math.log(x, 10)) + 1
def public_dir(obj):
"""Returns all 'public' attributes of an object"""
names = dir(obj)
for name in names[:]:
if name[0] == '_' or name[-1] == '_':
names.remove(name)
return names
def to_decimal(s):
"""ValueError raising Decimal converter."""
try:
return Decimal(s)
except (InvalidOperation, TypeError):
try:
return Decimal(str(s))
except (InvalidOperation, TypeError):
raise ValueError
def to_color(s, sep=','):
"""Tries to cast a string to a color (3-tuple)."""
c = tuple([int(x) for x in s.split(sep)])
if len(c) != 3:
raise ValueError
return c
+def cyclic_permute(self, sequence):
+ """Return a list of all cyclic permutations of supplied sequence."""
+ return [[sequence[i - j] for i in range(n)] for j in range(n, 0, -1)]
+
# From itertools documentation
def grouper(n, iterable, fillvalue=None):
"""grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"""
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
class Timer:
"""High-res timer that should be cross-platform."""
def __init__(self):
# Assigns appropriate clock function based on OS
if os.name == 'nt':
self.clock = time.clock
self.clock()
elif os.name == 'posix':
self.clock = time.time
self.running = False
def start(self):
self.start_time = self.clock()
self.running = True
def stop(self):
if not self.running:
return None
self.stop_time = self.clock()
self.running = False
return self.stop_time - self.start_time
def elapsed(self):
if not self.running:
return None
cur_time = self.clock()
return cur_time - self.start_time
def restart(self):
old_start_time = self.start_time
self.start_time = self.clock()
self.running = True
return self.start_time - old_start_time
def tick(self, fps):
"""Limits loop to specified fps. To be placed at start of loop."""
fps = float(fps)
ret = self.elapsed()
if self.elapsed() != -1:
while self.elapsed() < (1.0 / fps):
pass
self.start()
if ret != -1:
return ret * 1000
|
ztangent/checkergen
|
e85f82768f28d5ee441d034882c87f2a484b32d9
|
Use OrderedDict for ordered XML output.
|
diff --git a/example.ckg b/example.ckg
index cc77e03..ee30221 100644
--- a/example.ckg
+++ b/example.ckg
@@ -1,56 +1,56 @@
<?xml version="1.0" ?>
<project xmlns="http://github.com/ZOMGxuan/checkergen">
- <export_fmt>'png'</export_fmt>
- <pre>Decimal('0')</pre>
- <bg>(127, 127, 127)</bg>
<fps>Decimal('60')</fps>
- <cross_cols>((0, 0, 0), (255, 0, 0))</cross_cols>
<res>(800, 600)</res>
+ <bg>(127, 127, 127)</bg>
+ <export_fmt>'png'</export_fmt>
+ <pre>Decimal('0')</pre>
<post>Decimal('0')</post>
+ <cross_cols>((0, 0, 0), (255, 0, 0))</cross_cols>
<cross_times>(Decimal('Infinity'), Decimal('1'))</cross_times>
<group>
<pre>Decimal('2')</pre>
<disp>Decimal('10')</disp>
<post>Decimal('2')</post>
<shape type="board">
- <end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<dims>(5, 5)</dims>
- <phase>Decimal('0')</phase>
+ <init_unit>(Decimal('40'), Decimal('40'))</init_unit>
+ <end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<position>(Decimal('420'), Decimal('320'))</position>
- <freq>Decimal('1')</freq>
<anchor>'bottomleft'</anchor>
- <init_unit>(Decimal('40'), Decimal('40'))</init_unit>
<cols>((0, 0, 0), (255, 255, 255))</cols>
+ <freq>Decimal('1')</freq>
+ <phase>Decimal('0')</phase>
</shape>
<shape type="board">
- <end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<dims>(5, 5)</dims>
- <phase>Decimal('90')</phase>
+ <init_unit>(Decimal('40'), Decimal('40'))</init_unit>
+ <end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<position>(Decimal('380'), Decimal('320'))</position>
- <freq>Decimal('2')</freq>
<anchor>'bottomright'</anchor>
- <init_unit>(Decimal('40'), Decimal('40'))</init_unit>
<cols>((0, 0, 0), (255, 255, 255))</cols>
+ <freq>Decimal('2')</freq>
+ <phase>Decimal('90')</phase>
</shape>
<shape type="board">
- <end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<dims>(5, 5)</dims>
- <phase>Decimal('180')</phase>
+ <init_unit>(Decimal('40'), Decimal('40'))</init_unit>
+ <end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<position>(Decimal('420'), Decimal('280'))</position>
- <freq>Decimal('3')</freq>
<anchor>'topleft'</anchor>
- <init_unit>(Decimal('40'), Decimal('40'))</init_unit>
<cols>((0, 0, 0), (255, 255, 255))</cols>
+ <freq>Decimal('3')</freq>
+ <phase>Decimal('180')</phase>
</shape>
<shape type="board">
- <end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<dims>(5, 5)</dims>
- <phase>Decimal('270')</phase>
+ <init_unit>(Decimal('40'), Decimal('40'))</init_unit>
+ <end_unit>(Decimal('50'), Decimal('50'))</end_unit>
<position>(Decimal('380'), Decimal('280'))</position>
- <freq>Decimal('4')</freq>
<anchor>'topright'</anchor>
- <init_unit>(Decimal('40'), Decimal('40'))</init_unit>
<cols>((0, 0, 0), (255, 255, 255))</cols>
+ <freq>Decimal('4')</freq>
+ <phase>Decimal('270')</phase>
</shape>
</group>
</project>
diff --git a/src/core.py b/src/core.py
index 6b692ea..65250eb 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,1235 +1,1242 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgExp -- A checkergen experiment, describes how a projet is displayed.
CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
-# TODO: Use OrderedDicts with fallback for python 2.6
-
import os
import sys
import re
import csv
import random
import itertools
from xml.dom import minidom
import pyglet
import graphics
import trigger
import eyetracking
from utils import *
+# Use OrderedDict substitute if we don't have Python 2.7
+if sys.version_info < (2, 7):
+ from odict import OrderedDict
+else:
+ from collections import OrderedDict
+
CKG_FMT = 'ckg'
EXP_FMT = 'ckx'
LOG_FMT = 'log'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
MAX_EXPORT_FRAMES = 100000
PRERENDER_TO_TEXTURE = False
INT_HALF_PERIODS = True
EXPORT_FMTS = ['png']
EXPORT_DIR_SUFFIX = '-anim'
FIX_POS = (0, 0)
FIX_RANGE = (20, 20)
FIX_PER = 350
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
- DEFAULTS = {'name': 'untitled',
- 'fps': 60,
- 'res': (800, 600),
- 'bg': (127, 127, 127),
- 'export_fmt': 'png',
- 'pre': 0,
- 'post': 0,
- 'cross_cols': ((0, 0, 0), (255, 0, 0)),
- 'cross_times': ('Infinity', 1)}
+ DEFAULTS = OrderedDict([('name', 'untitled'),
+ ('fps', 60),
+ ('res', (800, 600)),
+ ('bg', (127, 127, 127)),
+ ('export_fmt', 'png'),
+ ('pre', 0),
+ ('post', 0),
+ ('cross_cols', ((0, 0, 0), (255, 0, 0))),
+ ('cross_times', ('Infinity', 1))])
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
export_fmt -- image format for animation to be exported as
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'export_fmt':
if value not in EXPORT_FMTS:
msg = 'image format not recognized or supported'
raise FileFormatError(msg)
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
vars_to_load = self.__class__.DEFAULTS.keys()
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
vars_to_save = self.__class__.DEFAULTS.keys()
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, fullscreen=False, logtime=False, logdur=False,
trigser=False, trigpar=False, fpst=0,
phototest=False, photoburst=False,
eyetrack=False, etuser=False, etvideo=None,
tryagain=0, trybreak=None, groupq=[], run=None):
"""Displays the project animation on the screen.
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
trigser -- send triggers through serial port when each group is shown
trigpar -- send triggers through parallel port when each group is shown
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- Append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- Append a wait screen to the group queue every time
after this many groups have been appended to the queue
groupq -- queue of groups to be displayed, defaults to order of
groups in project (i.e. groups[0] first, etc.)
run -- experimental run where logged variables are saved (i.e.
fail_idlist and time information)
"""
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if phototest:
test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Set-up groups and variables that control their display
if groupq == []:
groupq = list(self.groups)
n = -1
flipped = 0
flip_id = -1
groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Initialize ports
if trigser:
if not trigger.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if trigpar:
if not trigger.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
trigger.init(trigser, trigpar)
# Initialize eyetracking
if eyetrack:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if trybreak == None:
trybreak = len(self.groups)
fixated = False
old_fixated = False
tracked = False
old_tracked = False
cur_fix_fail = False
trycount = 0
fail_idlist = []
eyetracking.select_source(etuser, etvideo)
eyetracking.start()
# Stretch to fit screen only if project res does not equal screen res
scaling = False
if fullscreen:
window = pyglet.window.Window(fullscreen=True, visible=False)
if (window.width, window.height) != self.res:
scaling = True
else:
window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
keystates = pyglet.window.key.KeyStateHandler()
window.push_handlers(keystates)
# Create framebuffer object for drawing unscaled scene
if scaling:
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
fbo.end_render()
# Clear window and make visible
window.switch_to()
graphics.set_clear_color(self.bg)
window.clear()
window.set_visible()
# Initialize logging variables
if logtime:
timestamps = []
trigstamps = []
timer = Timer()
timer.start()
if logdur:
durstamps = []
dur = Timer()
dur.start()
# Main loop
while not window.has_exit and count < disp_end:
# Clear canvas
if scaling:
fbo.start_render()
fbo.clear()
else:
window.clear()
# Assume no change to group visibility
flipped = 0
# Manage groups when they are on_screen
if groups_visible:
# Check whether group changes in visibility
if n >= 0 and groupq[n].visible != groupq[n].old_visible:
flip_id = self.groups.index(groupq[n])
if groupq[n].visible:
flipped = 1
elif groupq[n].old_visible:
flipped = -1
# Get next group from queue
if n < 0 or groupq[n].over:
# Send special trigger if waitscreen ends
if isinstance(groupq[n], CkgWaitScreen):
trigger.CUR_STATE['user'] = 1
n += 1
if n >= len(groupq):
groups_visible = False
trigger.CUR_STATE['user'] = 0
else:
groupq[n].reset()
if eyetrack:
cur_fix_fail = False
if groupq[n].visible:
flip_id = self.groups.index(groupq[n])
flipped = 1
# Send special trigger when waitscreen ends
if isinstance(groupq[n], CkgWaitScreen):
trigger.CUR_STATE['user'] = 0
# Draw and then update group
if n >= 0:
groupq[n].draw(photoburst=photoburst)
groupq[n].update(fps=self.fps,
fpst=fpst,
keystates=keystates)
# Send triggers upon group visibility change
if flipped == 1:
trigger.CUR_STATE['group'] = 1
# Draw test rectangle
if phototest:
test_rect.draw()
elif flipped == -1:
trigger.CUR_STATE['group'] = 0
if eyetrack:
# First check if eye is being tracked and send trigger
old_tracked = tracked
tracked = eyetracking.is_tracked()
if tracked:
if not old_tracked:
# Send trigger if eye starts being tracked
trigger.set_track_start()
else:
if old_tracked:
# Send trigger if eye stops being tracked
trigger.set_track_stop()
# Next check for fixation
old_fixated = fixated
fixated = eyetracking.is_fixated(FIX_POS, FIX_RANGE, FIX_PER)
if fixated:
# Draw normal cross color if fixating
fix_crosses[0].draw()
if not old_fixated:
# Send trigger if fixation starts
trigger.set_fix_start()
else:
# Draw alternative cross color if not fixating
fix_crosses[1].draw()
if old_fixated:
# Send trigger if fixation stops
trigger.set_fix_stop()
# Take note of which groups in which fixation failed
if not cur_fix_fail and groupq[n].visible and\
(tracked and not fixated):
cur_fix_fail = True
# Append failed group to group queue
if trycount < tryagain:
# Insert waitscreen every trybreak failed groups
if trybreak > 0:
if len(fail_idlist) % trybreak == 0:
groupq.append(CkgWaitScreen())
groupq.append(groupq[n])
groups_stop += groupq[n].duration() * self.fps
disp_end += groupq[n].duration() * self.fps
trycount += 1
# Maintain list of failed IDs
fail_idlist.append(self.groups.index(groupq[n]))
# Change cross color based on time if eyetracking is not enabled
if not eyetrack:
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Increment count and set whether groups should be shown
if not isinstance(groupq[n], CkgWaitScreen):
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
# Blit canvas to screen if necessary
if scaling:
fbo.end_render()
window.switch_to()
canvas.blit(0, 0)
window.dispatch_events()
window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to lists
if logtime:
timestamps.append(timer.elapsed())
if logdur:
durstamps.append(dur.restart())
# Send trigger ASAP after flip
trigger.send(trigser, trigpar)
# Log when trigger are sent
if logtime:
if flipped != 0 and (trigser or trigpar):
trigstamps.append(trigger.STATE)
else:
trigstamps.append('')
# Clean up
if eyetrack:
eyetracking.stop()
window.close()
if scaling:
fbo.delete()
del canvas
trigger.quit(trigser, trigpar)
# Store variables in run object
if run != None:
if logtime:
run.timestamps = timestamps
run.trigstamps = trigstamps
if logdur:
run.durstamps = durstamps
if eyetrack and len(fail_idlist) > 0:
run.add_idlist = fail_idlist[:tryagain]
run.fail_idlist = fail_idlist[tryagain:]
def export(self, export_dir, export_duration, groupq=[],
export_fmt=None, folder=True, force=False):
if not os.path.isdir(export_dir):
msg = 'export path is not a directory'
raise IOError(msg)
if export_fmt == None:
export_fmt = self.export_fmt
# Set-up groups and variables that control their display
if groupq == []:
groupq = list(self.groups)
n = -1
groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Limit export duration to display duration
frames = export_duration * self.fps
frames = min(frames, disp_end)
# Warn user if a lot of frames will be exported
if frames > MAX_EXPORT_FRAMES and not force:
msg = 'very large number ({0}) of frames to be exported'.\
format(frames)
raise FrameOverflowError(msg)
# Create folder to store images if necessary
if folder:
export_dir = os.path.join(export_dir,
self.name + EXPORT_DIR_SUFFIX)
if not os.path.isdir(export_dir):
os.mkdir(export_dir)
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Set up canvas and framebuffer object
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
# Main loop
while count < frames:
fbo.clear()
if groups_visible:
# Get next group from queue
if n < 0 or groupq[n].over:
n += 1
if n >= len(groupq):
groups_visible = False
else:
groupq[n].reset()
# Draw and then update group
if n >= 0:
groupq[n].draw()
groupq[n].update(fps=self.fps, fpst=0)
# Draw fixation cross based on current count
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Save current frame to file
savepath = \
os.path.join(export_dir,
'{0}{2}.{1}'.
format(self.name, export_fmt,
repr(count).zfill(numdigits(frames-1))))
canvas.save(savepath)
# Increment count and set whether groups should be shown
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
fbo.delete()
class CkgExp:
DEFAULTS = {'name': None, 'proj' : None,
'blocks': 1, 'sequences': None,
'flags': '--fullscreen --logtime --logdur'}
def __init__(self, **keywords):
"""Create a checkergen experiment, which specifies how a project
is to be displayed.
path -- if specified, ignore other arguments and load project
from path
name -- name of the experiment
proj -- CkgProj that the experiment is to be created for
blocks -- number of times the selected sequence of display groups
will be shown in one run
sequences -- list of possible display group id sequences, from which
one sequence will be randomly selected for display in a run,
defaults to reduced latin square with side length equal to the number
of display groups in the supplied CkgProj
flags -- string passed to the display command as flags
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
if self.name == None and self.proj != None:
self.name = self.proj.name
if self.sequences == None:
if self.proj == None:
msg = "either project or sequences have to be specified"
raise ValueError(msg)
else:
self.gen_latin_square(len(self.proj.groups))
del self.proj
def gen_latin_square(self, n):
"""Set experiment sequences as a cyclic reduced latin square."""
sequence = range(n)
self.sequences = [[sequence[i - j] for i in range(n)]
for j in range(n, 0, -1)]
def random_run(self, name):
"""Choose random sequence, create run from it and return."""
sequence = random.choice(self.sequences)
run = CkgRun(name=name,
flags=self.flags,
blocks=self.blocks,
sequence=sequence)
return run
def save(self, path=None):
"""Saves experiment to specified path in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, EXP_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(EXP_FMT):
path = '{0}.{1}'.format(path, EXP_FMT)
with open(path, 'wb') as expfile:
expwriter = csv.writer(expfile, dialect='excel-tab')
expwriter.writerow(['checkergen experiment file'])
expwriter.writerow(['flags:', self.flags])
expwriter.writerow(['blocks:', self.blocks])
expwriter.writerow(['sequences:'])
for sequence in self.sequences:
expwriter.writerow(sequence)
def load(self, path):
"""Loads experiment from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, EXP_FMT)
elif ext != '.{0}'.format(EXP_FMT):
msg = "path lacks '.{0}' extension".format(EXP_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
self.sequences = []
with open(path, 'rb') as expfile:
expreader = csv.reader(expfile, dialect='excel-tab')
for n, row in enumerate(expreader):
if n == 1:
self.flags = row[1]
elif n == 2:
self.blocks = int(row[1])
elif n > 3:
sequence = [int(i) for i in row]
self.sequences.append(sequence)
class CkgRun:
def __init__(self, name, flags, blocks, sequence):
"""Creates an experimental run."""
self.name = name
self.flags = flags
self.blocks = blocks
self.sequence = sequence
self.add_idlist = None
self.fail_idlist = None
self.timestamps = []
self.durstamps = []
self.trigstamps = []
def idlist(self):
"""Generate idlist from sequence and return it."""
idlist = ([-1] + self.sequence) * self.blocks
return idlist
def write_log(self, path=None):
"""Write a log file for the experimental run in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, LOG_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(LOG_FMT):
path = '{0}.{1}'.format(path, LOG_FMT)
with open(path, 'wb') as runfile:
runwriter = csv.writer(runfile, dialect='excel-tab')
runwriter.writerow(['checkergen log file'])
runwriter.writerow(['flags:', self.flags])
runwriter.writerow(['blocks:', self.blocks])
runwriter.writerow(['sequence:'] + self.sequence)
if self.add_idlist != None:
runwriter.writerow(['groups appended:'])
rowlist = grouper(len(self.sequence), self.add_idlist, '')
for row in rowlist:
runwriter.writerow(row)
if self.fail_idlist != None:
runwriter.writerow(['groups failed (not appended):'])
rowlist = grouper(len(self.sequence), self.fail_idlist, '')
for row in rowlist:
runwriter.writerow(row)
stamps = [self.timestamps, self.durstamps, self.trigstamps]
if len(max(stamps)) > 0:
for l in stamps:
if len(l) == 0:
l = [''] * len(max(stamps))
runwriter.writerow(['timestamps', 'durations', 'triggers'])
for row in zip(*stamps):
runwriter.writerow(row)
class CkgDisplayGroup:
- DEFAULTS = {'pre': 0, 'disp': 'Infinity', 'post': 0}
+ DEFAULTS = OrderedDict([('pre', 0), ('disp', 'Infinity'), ('post', 0)])
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets internal count and all contained shapes."""
self._count = 0
self._start = self.pre
self._stop = self.pre + self.disp
self._end = self.pre + self.disp + self.post
self.over = False
self.old_visible = False
if self._start == 0 and self._stop > 0:
self.visible = True
else:
self.visible = False
if self._end == 0:
self.over = True
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, lazy=False, photoburst=False):
"""Draws all contained shapes during the appropriate interval."""
if self.visible:
for shape in self.shapes:
if lazy:
shape.lazydraw()
else:
shape.draw(photoburst=photoburst)
def update(self, **keywords):
"""Increments internal count, makes group visible when appropriate.
fps -- refresh rate of the display in frames per second
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
"""
fps = keywords['fps']
fpst = keywords['fpst']
if self.visible:
# Set triggers to be sent
if fpst > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= fpst:
trigger.CUR_STATE['shape'] = 1
trigger.CUR_STATE['sid'] = n
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(fps)
# Increment count and set flags for the next frame
self._count += 1
self.old_visible = self.visible
if (self._start * fps) <= self._count < (self._stop * fps):
self.visible = True
else:
self.visible = False
if self._count >= (self._end * fps):
self.over = True
else:
self.over = False
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.visible = False
self.old_visible = False
self.steps_done = 0
self.over = False
def draw(self, **keywords):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, **keywords):
"""Checks for keypress, sends trigger upon end."""
keystates = keywords['keystates']
if max([keystates[key] for key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
if self.steps_done == self.num_steps:
self.over = True
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
- DEFAULTS = {'dims': (5, 5),
- 'init_unit': (30, 30), 'end_unit': (50, 50),
- 'position': (0, 0), 'anchor': 'bottomleft',
- 'cols': ((0, 0, 0), (255, 255, 255)),
- 'freq': 1, 'phase': 0}
+ DEFAULTS = OrderedDict([('dims', (5, 5)),
+ ('init_unit', (30, 30)),
+ ('end_unit', (50, 50)),
+ ('position', (0, 0)),
+ ('anchor', 'bottomleft'),
+ ('cols', ((0, 0, 0), (255, 255, 255))),
+ ('freq', 1),
+ ('phase', 0)])
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
if INT_HALF_PERIODS:
frames_per_half_period = round(fps / (self.freq * 2))
degs_per_frame = 180 / to_decimal(frames_per_half_period)
else:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
if PRERENDER_TO_TEXTURE:
init_pos = [(1 - a)* s/to_decimal(2) for s, a in
zip(self._size, graphics.locations[self.anchor])]
else:
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
anchor=self.anchor)
cur_unit_rect.col = self.cols[(i + j) % 2]
cur_unit_rect.add_to_batch(self._batches[0])
cur_unit_rect.col = self.cols[(i + j + 1) % 2]
cur_unit_rect.add_to_batch(self._batches[1])
# Increase x values
cur_unit_pos[0] += \
graphics.locations[self.anchor][0] * cur_unit[0]
cur_unit[0] += unit_grad[0]
# Reset x values
cur_unit_pos[0] = init_pos[0]
cur_unit[0] = init_unit[0]
# Increase y values
cur_unit_pos[1] += \
graphics.locations[self.anchor][1] * cur_unit[1]
cur_unit[1] += unit_grad[1]
if PRERENDER_TO_TEXTURE:
# Create textures
int_size = [int(round(s)) for s in self._size]
self._prerenders =\
[pyglet.image.Texture.create(*int_size) for n in range(2)]
# Set up framebuffer
fbo = graphics.Framebuffer()
for n in range(2):
fbo.attach_texture(self._prerenders[n])
# Draw batch to texture
fbo.start_render()
self._batches[n].draw()
fbo.end_render()
# Anchor textures for correct blitting later
self._prerenders[n].anchor_x, self._prerenders[n].anchor_y =\
[int(round((1 - a)* s/to_decimal(2))) for s, a in
zip(self._size, graphics.locations[self.anchor])]
fbo.delete()
# Delete batches since they won't be used
del self._batches
self._computed = True
def draw(self, photoburst=False, always_compute=False):
"""Draws appropriate prerender depending on current phase.
photoburst -- draw first color for only one frame for testing purposes
always_compute -- recompute what the checkerboard should look like
every frame
"""
if not self._computed or always_compute:
self.compute()
self._cur_phase %= 360
n = int(self._cur_phase // 180)
if photoburst and n == 0 and not self.flipped:
n = 1
if PRERENDER_TO_TEXTURE:
self._prerenders[n].blit(*self.position)
else:
self._batches[n].draw()
def lazydraw(self):
"""Only draws on color reversal."""
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if (cur_n != prev_n) or self._first_draw:
self.draw()
if self._first_draw:
self._first_draw = False
diff --git a/src/odict.py b/src/odict.py
new file mode 100644
index 0000000..b444106
--- /dev/null
+++ b/src/odict.py
@@ -0,0 +1,103 @@
+# Drop-in substitute for Py2.7's new collections.OrderedDict.
+# From http://code.activestate.com/recipes/576693/ by Raymond Hettinger.
+
+from UserDict import DictMixin
+
+class OrderedDict(dict, DictMixin):
+
+ def __init__(self, *args, **kwds):
+ if len(args) > 1:
+ raise TypeError('expected at most 1 arguments, got %d' % len(args))
+ try:
+ self.__end
+ except AttributeError:
+ self.clear()
+ self.update(*args, **kwds)
+
+ def clear(self):
+ self.__end = end = []
+ end += [None, end, end] # sentinel node for doubly linked list
+ self.__map = {} # key --> [key, prev, next]
+ dict.clear(self)
+
+ def __setitem__(self, key, value):
+ if key not in self:
+ end = self.__end
+ curr = end[1]
+ curr[2] = end[1] = self.__map[key] = [key, curr, end]
+ dict.__setitem__(self, key, value)
+
+ def __delitem__(self, key):
+ dict.__delitem__(self, key)
+ key, prev, next = self.__map.pop(key)
+ prev[2] = next
+ next[1] = prev
+
+ def __iter__(self):
+ end = self.__end
+ curr = end[2]
+ while curr is not end:
+ yield curr[0]
+ curr = curr[2]
+
+ def __reversed__(self):
+ end = self.__end
+ curr = end[1]
+ while curr is not end:
+ yield curr[0]
+ curr = curr[1]
+
+ def popitem(self, last=True):
+ if not self:
+ raise KeyError('dictionary is empty')
+ if last:
+ key = reversed(self).next()
+ else:
+ key = iter(self).next()
+ value = self.pop(key)
+ return key, value
+
+ def __reduce__(self):
+ items = [[k, self[k]] for k in self]
+ tmp = self.__map, self.__end
+ del self.__map, self.__end
+ inst_dict = vars(self).copy()
+ self.__map, self.__end = tmp
+ if inst_dict:
+ return (self.__class__, (items,), inst_dict)
+ return self.__class__, (items,)
+
+ def keys(self):
+ return list(self)
+
+ setdefault = DictMixin.setdefault
+ update = DictMixin.update
+ pop = DictMixin.pop
+ values = DictMixin.values
+ items = DictMixin.items
+ iterkeys = DictMixin.iterkeys
+ itervalues = DictMixin.itervalues
+ iteritems = DictMixin.iteritems
+
+ def __repr__(self):
+ if not self:
+ return '%s()' % (self.__class__.__name__,)
+ return '%s(%r)' % (self.__class__.__name__, self.items())
+
+ def copy(self):
+ return self.__class__(self)
+
+ @classmethod
+ def fromkeys(cls, iterable, value=None):
+ d = cls()
+ for key in iterable:
+ d[key] = value
+ return d
+
+ def __eq__(self, other):
+ if isinstance(other, OrderedDict):
+ return len(self)==len(other) and self.items() == other.items()
+ return dict.__eq__(self, other)
+
+ def __ne__(self, other):
+ return not self == other
|
ztangent/checkergen
|
da7aaf79a9f7baa97f1c6a06435a74e7566e840a
|
renaming of terms (block->run, trial->block)
|
diff --git a/src/cli.py b/src/cli.py
index 33749b1..b2aff28 100644
--- a/src/cli.py
+++ b/src/cli.py
@@ -324,880 +324,880 @@ class CkgCmd(cmd.Cmd):
try:
args = self.__class__.edgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.edgrp_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_proj.groups) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_group_attr(x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.edgrp_parser.print_usage()
rmgrp_parser = CmdParser(add_help=False, prog='rmgrp',
description='''Removes display groups specified
by ids.''')
rmgrp_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='ids of display groups to be removed')
rmgrp_parser.add_argument('-a', '--all', action='store_true',
help='remove all groups from the project')
def help_rmgrp(self):
self.__class__.rmgrp_parser.print_help()
def do_rmgrp(self, line):
"""Removes display groups specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups to remove'
return
try:
args = self.__class__.rmgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rmgrp_parser.print_usage()
return
rmlist = []
if args.all:
for group in self.cur_proj.groups[:]:
self.cur_proj.del_group(group)
print "all display groups removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_proj.groups) or x < 0:
print "display group", x, "does not exist"
continue
rmlist.append(self.cur_proj.groups[x])
print "display group", x, "removed"
for group in rmlist:
self.cur_proj.del_group(group)
# Remember to point self.cur_group somewhere sane
if self.cur_group not in self.cur_proj.groups:
if len(self.cur_proj.groups) == 0:
self.cur_group = None
else:
self.cur_group = self.cur_proj.groups[0]
print "group 0 is now the current display group"
chgrp_parser = CmdParser(add_help=False, prog='chgrp',
description='''Changes display group that is
currently active for editing.
Prints current group id if
no group id is specified''')
chgrp_parser.add_argument('gid', metavar='id', type=int, nargs='?',
help='id of display group to be made active')
def help_chgrp(self):
self.__class__.chgrp_parser.print_help()
def do_chgrp(self, line):
"""Changes group that is currently active for editing."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups that can be made active'
return
try:
args = self.__class__.chgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.chgrp_parser.print_usage()
return
if args.gid == None:
print "group",\
self.cur_proj.groups.index(self.cur_group),\
"is the current display group"
elif args.gid >= len(self.cur_proj.groups) or args.gid < 0:
print "group", args.gid, "does not exist"
else:
self.cur_group = self.cur_proj.groups[args.gid]
print "group", args.gid, "is now the current display group"
mk_parser = CmdParser(add_help=False, prog='mk',
description='''Makes a new checkerboard in the
current group with the given
parameters.''')
mk_parser.add_argument('dims', action=store_tuple(2, ',', to_decimal),
help='''width,height of checkerboard in no. of
unit cells''')
mk_parser.add_argument('init_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of initial unit cell in pixels')
mk_parser.add_argument('end_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of final unit cell in pixels')
mk_parser.add_argument('position', action=store_tuple(2, ',', to_decimal),
help='x,y position of checkerboard in pixels')
mk_parser.add_argument('anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='anchor')
mk_parser.add_argument('cols', action=store_tuple(2, ',', to_color, [';']),
help='''color1,color2 of the checkerboard
(color format: R;G;B,
component range from 0-255)''')
mk_parser.add_argument('freq', type=to_decimal,
help='frequency of color reversal in Hz')
mk_parser.add_argument('phase', type=to_decimal, nargs='?', default='0',
help='initial phase of animation in degrees')
def help_mk(self):
self.__class__.mk_parser.print_help()
def do_mk(self, line):
"""Makes a checkerboard with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
if self.cur_group == None:
print 'automatically adding display group...'
self.do_mkgrp('')
try:
args = self.__class__.mk_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mk_parser.print_usage()
return
shape_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_shape = core.CheckerBoard(**shape_dict)
new_id = self.cur_proj.add_shape_to_group(self.cur_group, new_shape)
print "checkerboard", new_id, "added"
ed_parser = CmdParser(add_help=False, prog='ed',
description='''Edits attributes of checkerboards
specified by ids.''')
ed_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='''ids of checkerboards in the current
group to be edited''')
ed_parser.add_argument('--dims', action=store_tuple(2, ',', to_decimal),
help='checkerboard dimensions in unit cells',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--init_unit',
action=store_tuple(2, ',', to_decimal),
help='initial unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--end_unit',
action=store_tuple(2, ',', to_decimal),
help='final unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--position',
action=store_tuple(2, ',', to_decimal),
help='position of checkerboard in pixels',
metavar='X,Y')
ed_parser.add_argument('--anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='LOCATION')
ed_parser.add_argument('--cols', metavar='COLOR1,COLOR2',
action=store_tuple(2, ',', to_color, [';']),
help='''checkerboard colors (color format:
R;G;B, component range
from 0-255)''')
ed_parser.add_argument('--freq', type=to_decimal,
help='frequency of color reversal in Hz')
ed_parser.add_argument('--phase', type=to_decimal,
help='initial phase of animation in degrees')
def help_ed(self):
self.__class__.ed_parser.print_help()
def do_ed(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, please create one first'
return
try:
args = self.__class__.ed_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ed_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_group.shapes) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_shape_attr(self.cur_group, x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.ed_parser.print_usage()
rm_parser = CmdParser(add_help=False, prog='rm',
description='''Removes checkerboards specified
by ids.''')
rm_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''ids of checkerboards in the current group
to be removed''')
rm_parser.add_argument('-a', '--all', action='store_true',
help='''remove all checkerboards in the
current group''')
def help_rm(self):
self.__class__.rm_parser.print_help()
def do_rm(self, line):
"""Removes checkerboards specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, no boards to remove'
return
try:
args = self.__class__.rm_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rm_parser.print_usage()
return
rmlist = []
if args.all:
for shape in self.cur_group.shapes:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
print "all checkerboards removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_group.shapes) or x < 0:
print "checkerboard", x, "does not exist"
continue
rmlist.append(self.cur_group.shapes[x])
print "checkerboard", x, "removed"
for shape in rmlist:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
ls_parser = CmdParser(add_help=False, prog='ls',
description='''Lists project, display group and
checkerboard settings. If no group ids
are specified, all display groups
are listed.''')
ls_parser.add_argument('gidlist', nargs='*', metavar='gid', type=int,
help='''ids of the display groups to be listed''')
ls_group = ls_parser.add_mutually_exclusive_group()
ls_group.add_argument('-s', '--settings', action='store_true',
help='list only project settings')
ls_group.add_argument('-g', '--groups', action='store_true',
help='list only display groups')
def help_ls(self):
self.__class__.ls_parser.print_help()
def do_ls(self, line):
"""Lists project, display group and checkerboard settings."""
def ls_str(s, seps=[',',';']):
"""Special space-saving output formatter."""
if type(s) in [tuple, list]:
if len(seps) > 1:
newseps = seps[1:]
else:
newseps = seps
return seps[0].join([ls_str(i, newseps) for i in s])
else:
return str(s)
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.ls_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ls_parser.print_usage()
return
# Remove duplicates and ascending sort
args.gidlist = sorted(set(args.gidlist))
if len(self.cur_proj.groups) == 0:
if len(args.gidlist) > 0:
print 'this project has no display groups that can be listed'
args.settings = True
else:
for gid in args.gidlist[:]:
if gid >= len(self.cur_proj.groups) or gid < 0:
args.gidlist.remove(gid)
print 'display group', gid, 'does not exist'
if args.gidlist == []:
args.gidlist = range(len(self.cur_proj.groups))
else:
# If any (valid) groups are specified
# don't show project settings
args.groups = True
if not args.groups:
print 'PROJECT SETTINGS'.center(70,'*')
print \
'name'.rjust(16),\
'fps'.rjust(7),\
'resolution'.rjust(14),\
'bg color'.rjust(18)
# 'format'.rjust(7)
print \
ls_str(self.cur_proj.name).rjust(16),\
ls_str(self.cur_proj.fps).rjust(7),\
ls_str(self.cur_proj.res).rjust(14),\
ls_str(self.cur_proj.bg).rjust(18)
# ls_str(self.cur_proj.export_fmt).rjust(7)
print \
'pre-display'.rjust(26),\
'post-display'.rjust(26)
print \
ls_str(self.cur_proj.pre).rjust(26),\
ls_str(self.cur_proj.post).rjust(26)
print \
'cross colors'.rjust(26),\
'cross times'.rjust(26)
print \
ls_str(self.cur_proj.cross_cols).rjust(26),\
ls_str(self.cur_proj.cross_times).rjust(26)
if not args.settings and not args.groups:
# Insert empty line if both groups and project
# settings are listed
print ''
if not args.settings:
for i, n in enumerate(args.gidlist):
if i != 0:
# Print newline seperator between each group
print ''
group = self.cur_proj.groups[n]
print 'GROUP {n}'.format(n=n).center(70,'*')
print \
'pre-display'.rjust(20),\
'display'.rjust(20),\
'post-display'.rjust(20)
print \
ls_str(group.pre).rjust(20),\
ls_str(group.disp).rjust(20),\
ls_str(group.post).rjust(20)
if len(group.shapes) > 0:
print \
''.rjust(2),\
'shape id'.rjust(8),\
'dims'.rjust(10),\
'init_unit'.rjust(14),\
'end_unit'.rjust(14),\
'position'.rjust(14)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.dims).rjust(10),\
ls_str(shape.init_unit).rjust(14),\
ls_str(shape.end_unit).rjust(14),\
ls_str(shape.position).rjust(14)
print '\n',\
''.rjust(2),\
'shape id'.rjust(8),\
'colors'.rjust(27),\
'anchor'.rjust(12),\
'freq'.rjust(6),\
'phase'.rjust(7)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.cols).rjust(27),\
ls_str(shape.anchor).rjust(12),\
ls_str(shape.freq).rjust(6),\
ls_str(shape.phase).rjust(7)
display_parser = CmdParser(add_help=False, prog='display',
description='''Displays the animation in a
window or in fullscreen.''')
display_parser.add_argument('-e', '--expfile', metavar='PATH',
help='''run experiment as described in
specified file, ignore other flags''')
display_parser.add_argument('-f', '--fullscreen', action='store_true',
help='sets fullscreen mode, ESC to quit')
display_parser.add_argument('-p', '--priority', metavar='LEVEL',
help='''set priority while displaying,
higher priority results in
less dropped frames (choices:
0-3, low, normal, high,
realtime)''')
display_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly display specified display
groups N number of times''')
display_parser.add_argument('-pt', '--phototest', action='store_true',
help='''draw white test rectangle in topleft
corner of screen when groups become
visible for a photodiode to detect''')
display_parser.add_argument('-pb', '--photoburst', action='store_true',
help='''make checkerboards only draw first
color for one frame to facilitate
testing with a photodiode''')
display_parser.add_argument('-lt', '--logtime', action='store_true',
help='output frame timestamps to a log file')
display_parser.add_argument('-ld', '--logdur', action='store_true',
help='output frame durations to a log file')
display_parser.add_argument('-ss', '--trigser', action='store_true',
help='''send triggers through the serial port
when shapes are being displayed''')
display_parser.add_argument('-sp', '--trigpar', action='store_true',
help='''send triggers through the parallel port
when shapes are being displayed''')
display_parser.add_argument('-fpst', metavar='M', type=int, default=0,
help='''unique trigger corresponding to a
checkerboard is sent after the shape
undergoes M color flips (default:
disabled, M=0)''')
display_parser.add_argument('-et', '--eyetrack', action='store_true',
help='''use eyetracking to ensure that subject
fixates on the cross in the center''')
display_parser.add_argument('-eu', '--etuser', action='store_true',
help='''allow user to select eyetracking video
source from a dialog''')
display_parser.add_argument('-ev', '--etvideo', metavar='path',
help='''path (with no spaces) to eyetracking
video file to be used as the source''')
display_parser.add_argument('-ta', '--tryagain', metavar='I',
type=int, default=0,
help='''append groups during which subject
failed to fixate up to I times to the
list of groups to be displayed
(default: disabled, I=0)''')
display_parser.add_argument('-tb', '--trybreak', metavar='J', type=int,
help='''used with --tryagain, append a wait
screen to the list of groups to be
displayed after every J groups have
been appended to the list (default:
J=total number of groups)''')
display_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be displayed
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_display(self):
self.__class__.display_parser.print_help()
def do_display(self, line):
"""Displays the animation in a window or in fullscreen"""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.display_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
if args.expfile != None:
try:
exp = core.CkgExp(path=args.expfile)
except IOError:
print "error:", str(sys.exc_value)
return
try:
args = self.__class__.\
display_parser.parse_args(shlex.split(exp.flags))
except (CmdParserError, ValueError):
- print 'error: invalid flags stored in block file'
+ print 'error: invalid flags stored in run file'
return
try:
print """name of log file (default: experiment name):"""
- blkname = raw_input().strip().strip('"\'')
+ runname = raw_input().strip().strip('"\'')
except EOFError:
return
- if blkname == '':
- blkname == exp.name
- blk = exp.random_blk(blkname)
- args.idlist = blk.idlist()
+ if runname == '':
+ runname == exp.name
+ run = exp.random_run(runname)
+ args.idlist = run.idlist()
else:
- blk = core.CkgBlk(name=self.cur_proj.name,
- trials=None,
+ run = core.CkgRun(name=self.cur_proj.name,
+ blocks=None,
flags=line,
sequence=[])
groupq = []
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < -1:
print 'error: group', i, 'does not exist'
return
for i in args.idlist:
if i == -1:
groupq.append(core.CkgWaitScreen(res=self.cur_proj.res))
else:
groupq.append(self.cur_proj.groups[i])
else:
groupq = list(self.cur_proj.groups)
if args.repeat != None:
groupq = list(groupq * args.repeat)
if args.eyetrack and eyetracking.available:
if not eyetracking.is_calibrated():
try:
self.do_calibrate('',True)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
return
if args.priority != None:
if not priority.available[sys.platform]:
print "error: setting priority not available on", sys.platform
print "continuing..."
else:
if args.priority.isdigit():
args.priority = int(args.priority)
try:
priority.set(args.priority)
except ValueError:
print "error:", str(sys.exc_value)
print "continuing..."
print "displaying..."
try:
self.cur_proj.display(fullscreen=args.fullscreen,
logtime=args.logtime,
logdur=args.logdur,
trigser=args.trigser,
trigpar=args.trigpar,
fpst=args.fpst,
phototest=args.phototest,
photoburst=args.photoburst,
eyetrack=args.eyetrack,
etuser=args.etuser,
etvideo=args.etvideo,
tryagain=args.tryagain,
trybreak=args.trybreak,
groupq=groupq,
- blk=blk)
+ run=run)
except (IOError, NotImplementedError, eyetracking.EyetrackingError):
print "error:", str(sys.exc_value)
if args.priority != None:
try:
priority.set('normal')
except:
pass
return
if args.priority != None:
try:
priority.set('normal')
except:
pass
try:
- blk.write_log()
+ run.write_log()
except IOError:
print "error:", str(sys.exc_value)
return
print "log file written"
export_parser = CmdParser(add_help=False, prog='export',
description='''Exports animation as an image
sequence (in a folder) to the
specified directory.''')
# export_parser.add_argument('--fmt', dest='export_fmt',
# choices=core.EXPORT_FMTS,
# help='image format for export')
export_parser.add_argument('-n','--nofolder',
dest='folder', action='store_false',
help='''force images not to exported in
a containing folder''')
export_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly export specified display
groups N number of times''')
export_parser.add_argument('duration', nargs='?',
type=to_decimal, default='Infinity',
help='''number of seconds of the animation
that should be exported (default:
as long as the entire animation)''')
export_parser.add_argument('dir', nargs='?', default=os.getcwd(),
help='''destination directory for export
(default: current working directory)''')
export_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be exported
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_export(self):
self.__class__.export_parser.print_help()
def do_export(self, line):
"""Exports animation an image sequence to the specified directory."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.export_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.export_parser.print_usage()
return
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < 0:
print 'error: group', i, 'does not exist'
return
groupq = [self.cur_proj.groups[i] for i in args.idlist]
else:
groupq = list(self.cur_proj.groups)
if args.repeat != None:
groupq = list(groupq * args.repeat)
try:
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
folder=args.folder)
except IOError:
print "error:", str(sys.exc_value)
return
except core.FrameOverflowError:
print "warning:", str(sys.exc_value)
print "Are you sure you want to continue?"
while True:
try:
if self.__class__.yn_parse(raw_input()):
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
export_fmt=None,
folder=args.folder,
force=True)
break
else:
return
except TypeError:
print str(sys.exc_value)
except EOFError:
return
print "Export done."
mkexp_parser = CmdParser(add_help=False, prog='mkexp',
description='''Create checkergen experiment file
which describes how the project
is to be displayed.''')
mkexp_parser.add_argument('-n', '--name',
help='''name of the experiment (default: same
name as current project)''')
- mkexp_parser.add_argument('-t', '--trials', type=int, metavar='N',
- help='''N trials displayed in a block, i.e.
+ mkexp_parser.add_argument('-b', '--blocks', type=int, metavar='N',
+ help='''N blocks displayed in a run, i.e.
the same sequence will be displayed
- N times in that block, with waitscreens
+ N times in that run, with waitscreens
in between''')
mkexp_parser.add_argument('-f', '--flags',
help='''flags passed to the display command
- that should be used when the block
+ that should be used when the run
file is run (enclose in quotes and use
'+' or '++' in place of '-' or '--')''')
def help_mkexp(self):
self.__class__.mkexp_parser.print_help()
def do_mkexp(self, line):
"""Creates checkergen experiment file."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.mkexp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mkexp_parser.print_usage()
return
- if args.trials == None:
- print "number of trials:"
+ if args.blocks == None:
+ print "number of blocks:"
try:
- args.trials = int(raw_input().strip())
+ args.blocks = int(raw_input().strip())
except EOFError:
return
except ValueError:
print "error:", str(sys.exc_value)
return
if args.flags != None:
args.flags = args.flags.replace('+','-')
else:
print "flags used with display command (leave blank if none):"
try:
args.flags = raw_input().strip().strip('"\'')
except EOFError:
return
try:
disp_args = self.__class__.display_parser.\
parse_args(shlex.split(args.flags))
except (CmdParserError, ValueError):
print "error: invalid flags to display command"
print str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
print "list of sequences to choose from in the format",\
"'id1,id2,id3;seq2;seq3;seq4':"
print "(default: reduced latin square)"
try:
seqs_str = raw_input().strip()
if seqs_str == '':
args.sequences = None
else:
args.sequences = [[int(i) for i in seq_str.split(',')]
for seq_str in seqs_str.split(';')]
except EOFError:
return
try:
new_exp = core.CkgExp(name=args.name, proj=self.cur_proj,
- trials=args.trials,
+ blocks=args.blocks,
sequences=args.sequences,
flags=args.flags)
new_exp.save()
except IOError:
print "error:", str(sys.exc_value)
return
print "Experiment file created."
def do_calibrate(self, line, query=False):
"""Calibrate subject for eyetracking, or load a calibration file."""
if not eyetracking.available:
print "error: eyetracking functionality not available"
return
if query:
print "path to calibration file (leave empty for GUI tool):"
try:
path = raw_input().strip().strip('"\'')
except EOFError:
msg = "calibration cancelled"
raise eyetracking.EyetrackingError(msg)
else:
path = line.strip().strip('"\'')
if len(path) == 0:
path = None
if not eyetracking.is_source_ready():
# Select default source if none has been selected
eyetracking.select_source()
try:
eyetracking.calibrate(path)
except eyetracking.EyetrackingError:
if query:
raise
else:
print "error:", str(sys.exc_value)
return
if len(path) > 0:
print "calibration file successfully loaded"
etsetup_parser = CmdParser(add_help=False, prog='etsetup',
description='''Set various eyetracking
parameters.''')
etsetup_parser.add_argument('-fp', '--fixperiod', type=int, metavar='MS',
help='''time in milliseconds subject
has to stare at the same spot
for fixation to be detected''')
etsetup_parser.add_argument('-fr', '--fixrange', type=float, metavar='MM',
help='''distance in mm beyond which the
eye position cannot change for
a fixation to be detected''')
etsetup_parser.add_argument('-s', '--size', metavar='WIDTH,HEIGHT',
action=store_tuple(2, ',', float),
help='physical screen dimensions in mm')
etsetup_parser.add_argument('-vd', '--viewdist', type=int, metavar='MM',
help='''viewing distance between subject's
eyes and the screen''')
def help_etsetup(self):
self.__class__.etsetup_parser.print_help()
def do_etsetup(self, line):
try:
args = self.__class__.etsetup_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.etsetup_parser.print_usage()
return
try:
eyetracking.setup(viewing_distance=args.viewdist,
screen_dims=args.size,
fixation_period=args.fixperiod,
fixation_range=args.fixrange)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
def do_pwd(self, line):
"""Prints the current working directory."""
print os.getcwd()
def do_cd(self, line):
"""Change working directory to specified path."""
path = line.strip().strip('"\'')
if not os.path.isdir(path):
print "error: specified path is not a directory"
return
os.chdir(path)
def do_quit(self, line):
"""Quits the program."""
if self.save_check():
return
return True
def help_EOF(self):
print "Typing {0} issues this command, which quits the program."\
.format(CMD_EOF_STRING)
def do_EOF(self, line):
"""Typing Ctrl-D issues this command, which quits the program."""
print '\r'
if self.save_check():
return
return True
def help_help(self):
print 'Prints a list of commands.'
print "Type 'help <topic>' for more details on each command."
def default(self, line):
command = line.split()[0]
print \
"'{0}' is not a checkergen command.".format(command),\
"Type 'help' for a list of commands"
diff --git a/src/core.py b/src/core.py
index 17840d7..6b692ea 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,1234 +1,1235 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgExp -- A checkergen experiment, describes how a projet is displayed.
CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
+# TODO: Use OrderedDicts with fallback for python 2.6
+
import os
import sys
import re
import csv
import random
import itertools
from xml.dom import minidom
import pyglet
import graphics
import trigger
import eyetracking
from utils import *
CKG_FMT = 'ckg'
EXP_FMT = 'ckx'
LOG_FMT = 'log'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
MAX_EXPORT_FRAMES = 100000
PRERENDER_TO_TEXTURE = False
INT_HALF_PERIODS = True
EXPORT_FMTS = ['png']
EXPORT_DIR_SUFFIX = '-anim'
-BLOCK_DIR_SUFFIX = '-blks'
FIX_POS = (0, 0)
FIX_RANGE = (20, 20)
FIX_PER = 350
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = {'name': 'untitled',
'fps': 60,
'res': (800, 600),
'bg': (127, 127, 127),
'export_fmt': 'png',
'pre': 0,
'post': 0,
'cross_cols': ((0, 0, 0), (255, 0, 0)),
'cross_times': ('Infinity', 1)}
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
export_fmt -- image format for animation to be exported as
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'export_fmt':
if value not in EXPORT_FMTS:
msg = 'image format not recognized or supported'
raise FileFormatError(msg)
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
vars_to_load = self.__class__.DEFAULTS.keys()
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
vars_to_save = self.__class__.DEFAULTS.keys()
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, fullscreen=False, logtime=False, logdur=False,
trigser=False, trigpar=False, fpst=0,
phototest=False, photoburst=False,
eyetrack=False, etuser=False, etvideo=None,
- tryagain=0, trybreak=None, groupq=[], blk=None):
+ tryagain=0, trybreak=None, groupq=[], run=None):
"""Displays the project animation on the screen.
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
trigser -- send triggers through serial port when each group is shown
trigpar -- send triggers through parallel port when each group is shown
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- Append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- Append a wait screen to the group queue every time
after this many groups have been appended to the queue
groupq -- queue of groups to be displayed, defaults to order of
groups in project (i.e. groups[0] first, etc.)
- blk -- experimental block where logged variables are saved (i.e.
+ run -- experimental run where logged variables are saved (i.e.
fail_idlist and time information)
"""
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if phototest:
test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Set-up groups and variables that control their display
if groupq == []:
groupq = list(self.groups)
n = -1
flipped = 0
flip_id = -1
groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Initialize ports
if trigser:
if not trigger.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if trigpar:
if not trigger.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
trigger.init(trigser, trigpar)
# Initialize eyetracking
if eyetrack:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if trybreak == None:
trybreak = len(self.groups)
fixated = False
old_fixated = False
tracked = False
old_tracked = False
cur_fix_fail = False
trycount = 0
fail_idlist = []
eyetracking.select_source(etuser, etvideo)
eyetracking.start()
# Stretch to fit screen only if project res does not equal screen res
scaling = False
if fullscreen:
window = pyglet.window.Window(fullscreen=True, visible=False)
if (window.width, window.height) != self.res:
scaling = True
else:
window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
keystates = pyglet.window.key.KeyStateHandler()
window.push_handlers(keystates)
# Create framebuffer object for drawing unscaled scene
if scaling:
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
fbo.end_render()
# Clear window and make visible
window.switch_to()
graphics.set_clear_color(self.bg)
window.clear()
window.set_visible()
# Initialize logging variables
if logtime:
timestamps = []
trigstamps = []
timer = Timer()
timer.start()
if logdur:
durstamps = []
dur = Timer()
dur.start()
# Main loop
while not window.has_exit and count < disp_end:
# Clear canvas
if scaling:
fbo.start_render()
fbo.clear()
else:
window.clear()
# Assume no change to group visibility
flipped = 0
# Manage groups when they are on_screen
if groups_visible:
# Check whether group changes in visibility
if n >= 0 and groupq[n].visible != groupq[n].old_visible:
flip_id = self.groups.index(groupq[n])
if groupq[n].visible:
flipped = 1
elif groupq[n].old_visible:
flipped = -1
# Get next group from queue
if n < 0 or groupq[n].over:
# Send special trigger if waitscreen ends
if isinstance(groupq[n], CkgWaitScreen):
trigger.CUR_STATE['user'] = 1
n += 1
if n >= len(groupq):
groups_visible = False
trigger.CUR_STATE['user'] = 0
else:
groupq[n].reset()
if eyetrack:
cur_fix_fail = False
if groupq[n].visible:
flip_id = self.groups.index(groupq[n])
flipped = 1
# Send special trigger when waitscreen ends
if isinstance(groupq[n], CkgWaitScreen):
trigger.CUR_STATE['user'] = 0
# Draw and then update group
if n >= 0:
groupq[n].draw(photoburst=photoburst)
groupq[n].update(fps=self.fps,
fpst=fpst,
keystates=keystates)
# Send triggers upon group visibility change
if flipped == 1:
trigger.CUR_STATE['group'] = 1
# Draw test rectangle
if phototest:
test_rect.draw()
elif flipped == -1:
trigger.CUR_STATE['group'] = 0
if eyetrack:
# First check if eye is being tracked and send trigger
old_tracked = tracked
tracked = eyetracking.is_tracked()
if tracked:
if not old_tracked:
# Send trigger if eye starts being tracked
trigger.set_track_start()
else:
if old_tracked:
# Send trigger if eye stops being tracked
trigger.set_track_stop()
# Next check for fixation
old_fixated = fixated
fixated = eyetracking.is_fixated(FIX_POS, FIX_RANGE, FIX_PER)
if fixated:
# Draw normal cross color if fixating
fix_crosses[0].draw()
if not old_fixated:
# Send trigger if fixation starts
trigger.set_fix_start()
else:
# Draw alternative cross color if not fixating
fix_crosses[1].draw()
if old_fixated:
# Send trigger if fixation stops
trigger.set_fix_stop()
# Take note of which groups in which fixation failed
if not cur_fix_fail and groupq[n].visible and\
(tracked and not fixated):
cur_fix_fail = True
# Append failed group to group queue
if trycount < tryagain:
# Insert waitscreen every trybreak failed groups
if trybreak > 0:
if len(fail_idlist) % trybreak == 0:
groupq.append(CkgWaitScreen())
groupq.append(groupq[n])
groups_stop += groupq[n].duration() * self.fps
disp_end += groupq[n].duration() * self.fps
trycount += 1
# Maintain list of failed IDs
fail_idlist.append(self.groups.index(groupq[n]))
# Change cross color based on time if eyetracking is not enabled
if not eyetrack:
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Increment count and set whether groups should be shown
if not isinstance(groupq[n], CkgWaitScreen):
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
# Blit canvas to screen if necessary
if scaling:
fbo.end_render()
window.switch_to()
canvas.blit(0, 0)
window.dispatch_events()
window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to lists
if logtime:
timestamps.append(timer.elapsed())
if logdur:
durstamps.append(dur.restart())
# Send trigger ASAP after flip
trigger.send(trigser, trigpar)
# Log when trigger are sent
if logtime:
if flipped != 0 and (trigser or trigpar):
trigstamps.append(trigger.STATE)
else:
trigstamps.append('')
# Clean up
if eyetrack:
eyetracking.stop()
window.close()
if scaling:
fbo.delete()
del canvas
trigger.quit(trigser, trigpar)
- # Store variables in block object
- if blk != None:
+ # Store variables in run object
+ if run != None:
if logtime:
- blk.timestamps = timestamps
- blk.trigstamps = trigstamps
+ run.timestamps = timestamps
+ run.trigstamps = trigstamps
if logdur:
- blk.durstamps = durstamps
+ run.durstamps = durstamps
if eyetrack and len(fail_idlist) > 0:
- blk.add_idlist = fail_idlist[:tryagain]
- blk.fail_idlist = fail_idlist[tryagain:]
+ run.add_idlist = fail_idlist[:tryagain]
+ run.fail_idlist = fail_idlist[tryagain:]
def export(self, export_dir, export_duration, groupq=[],
export_fmt=None, folder=True, force=False):
if not os.path.isdir(export_dir):
msg = 'export path is not a directory'
raise IOError(msg)
if export_fmt == None:
export_fmt = self.export_fmt
# Set-up groups and variables that control their display
if groupq == []:
groupq = list(self.groups)
n = -1
groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Limit export duration to display duration
frames = export_duration * self.fps
frames = min(frames, disp_end)
# Warn user if a lot of frames will be exported
if frames > MAX_EXPORT_FRAMES and not force:
msg = 'very large number ({0}) of frames to be exported'.\
format(frames)
raise FrameOverflowError(msg)
# Create folder to store images if necessary
if folder:
export_dir = os.path.join(export_dir,
self.name + EXPORT_DIR_SUFFIX)
if not os.path.isdir(export_dir):
os.mkdir(export_dir)
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Set up canvas and framebuffer object
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
# Main loop
while count < frames:
fbo.clear()
if groups_visible:
# Get next group from queue
if n < 0 or groupq[n].over:
n += 1
if n >= len(groupq):
groups_visible = False
else:
groupq[n].reset()
# Draw and then update group
if n >= 0:
groupq[n].draw()
groupq[n].update(fps=self.fps, fpst=0)
# Draw fixation cross based on current count
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Save current frame to file
savepath = \
os.path.join(export_dir,
'{0}{2}.{1}'.
format(self.name, export_fmt,
repr(count).zfill(numdigits(frames-1))))
canvas.save(savepath)
# Increment count and set whether groups should be shown
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
fbo.delete()
class CkgExp:
DEFAULTS = {'name': None, 'proj' : None,
- 'trials': 1, 'sequences': None,
+ 'blocks': 1, 'sequences': None,
'flags': '--fullscreen --logtime --logdur'}
def __init__(self, **keywords):
"""Create a checkergen experiment, which specifies how a project
is to be displayed.
path -- if specified, ignore other arguments and load project
from path
name -- name of the experiment
proj -- CkgProj that the experiment is to be created for
- trials -- number of times the selected sequence of display groups
- will be shown in one block
+ blocks -- number of times the selected sequence of display groups
+ will be shown in one run
sequences -- list of possible display group id sequences, from which
- one sequence will be randomly selected for display in a block,
+ one sequence will be randomly selected for display in a run,
defaults to reduced latin square with side length equal to the number
of display groups in the supplied CkgProj
flags -- string passed to the display command as flags
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
if self.name == None and self.proj != None:
self.name = self.proj.name
if self.sequences == None:
if self.proj == None:
msg = "either project or sequences have to be specified"
raise ValueError(msg)
else:
self.gen_latin_square(len(self.proj.groups))
del self.proj
def gen_latin_square(self, n):
"""Set experiment sequences as a cyclic reduced latin square."""
sequence = range(n)
self.sequences = [[sequence[i - j] for i in range(n)]
for j in range(n, 0, -1)]
- def random_blk(self, name):
- """Choose random sequence, create block from it and return."""
+ def random_run(self, name):
+ """Choose random sequence, create run from it and return."""
sequence = random.choice(self.sequences)
- blk = CkgBlk(name=name,
+ run = CkgRun(name=name,
flags=self.flags,
- trials=self.trials,
+ blocks=self.blocks,
sequence=sequence)
- return blk
+ return run
def save(self, path=None):
"""Saves experiment to specified path in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, EXP_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(EXP_FMT):
path = '{0}.{1}'.format(path, EXP_FMT)
with open(path, 'wb') as expfile:
expwriter = csv.writer(expfile, dialect='excel-tab')
expwriter.writerow(['checkergen experiment file'])
expwriter.writerow(['flags:', self.flags])
- expwriter.writerow(['trials:', self.trials])
+ expwriter.writerow(['blocks:', self.blocks])
expwriter.writerow(['sequences:'])
for sequence in self.sequences:
expwriter.writerow(sequence)
def load(self, path):
"""Loads experiment from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, EXP_FMT)
elif ext != '.{0}'.format(EXP_FMT):
msg = "path lacks '.{0}' extension".format(EXP_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
self.sequences = []
with open(path, 'rb') as expfile:
expreader = csv.reader(expfile, dialect='excel-tab')
for n, row in enumerate(expreader):
if n == 1:
self.flags = row[1]
elif n == 2:
- self.trials = int(row[1])
+ self.blocks = int(row[1])
elif n > 3:
sequence = [int(i) for i in row]
self.sequences.append(sequence)
-class CkgBlk:
+class CkgRun:
- def __init__(self, name, flags, trials, sequence):
- """Creates an experimental block."""
+ def __init__(self, name, flags, blocks, sequence):
+ """Creates an experimental run."""
self.name = name
self.flags = flags
- self.trials = trials
+ self.blocks = blocks
self.sequence = sequence
self.add_idlist = None
self.fail_idlist = None
self.timestamps = []
self.durstamps = []
self.trigstamps = []
def idlist(self):
"""Generate idlist from sequence and return it."""
- idlist = ([-1] + self.sequence) * self.trials
+ idlist = ([-1] + self.sequence) * self.blocks
return idlist
def write_log(self, path=None):
- """Write a log file for the experimental block in the CSV format."""
+ """Write a log file for the experimental run in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, LOG_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(LOG_FMT):
path = '{0}.{1}'.format(path, LOG_FMT)
- with open(path, 'wb') as blkfile:
- blkwriter = csv.writer(blkfile, dialect='excel-tab')
- blkwriter.writerow(['checkergen log file'])
- blkwriter.writerow(['flags:', self.flags])
- blkwriter.writerow(['trials:', self.trials])
- blkwriter.writerow(['sequence:'] + self.sequence)
+ with open(path, 'wb') as runfile:
+ runwriter = csv.writer(runfile, dialect='excel-tab')
+ runwriter.writerow(['checkergen log file'])
+ runwriter.writerow(['flags:', self.flags])
+ runwriter.writerow(['blocks:', self.blocks])
+ runwriter.writerow(['sequence:'] + self.sequence)
if self.add_idlist != None:
- blkwriter.writerow(['groups appended:'])
+ runwriter.writerow(['groups appended:'])
rowlist = grouper(len(self.sequence), self.add_idlist, '')
for row in rowlist:
- blkwriter.writerow(row)
+ runwriter.writerow(row)
if self.fail_idlist != None:
- blkwriter.writerow(['groups failed (not appended):'])
+ runwriter.writerow(['groups failed (not appended):'])
rowlist = grouper(len(self.sequence), self.fail_idlist, '')
for row in rowlist:
- blkwriter.writerow(row)
+ runwriter.writerow(row)
stamps = [self.timestamps, self.durstamps, self.trigstamps]
if len(max(stamps)) > 0:
for l in stamps:
if len(l) == 0:
l = [''] * len(max(stamps))
- blkwriter.writerow(['timestamps', 'durations', 'triggers'])
+ runwriter.writerow(['timestamps', 'durations', 'triggers'])
for row in zip(*stamps):
- blkwriter.writerow(row)
+ runwriter.writerow(row)
class CkgDisplayGroup:
DEFAULTS = {'pre': 0, 'disp': 'Infinity', 'post': 0}
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets internal count and all contained shapes."""
self._count = 0
self._start = self.pre
self._stop = self.pre + self.disp
self._end = self.pre + self.disp + self.post
self.over = False
self.old_visible = False
if self._start == 0 and self._stop > 0:
self.visible = True
else:
self.visible = False
if self._end == 0:
self.over = True
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, lazy=False, photoburst=False):
"""Draws all contained shapes during the appropriate interval."""
if self.visible:
for shape in self.shapes:
if lazy:
shape.lazydraw()
else:
shape.draw(photoburst=photoburst)
def update(self, **keywords):
"""Increments internal count, makes group visible when appropriate.
fps -- refresh rate of the display in frames per second
fpst -- flips per shape trigger, i.e. number of shape color reversals
(flips) that occur for a unique trigger to be sent for that shape
"""
fps = keywords['fps']
fpst = keywords['fpst']
if self.visible:
# Set triggers to be sent
if fpst > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= fpst:
trigger.CUR_STATE['shape'] = 1
trigger.CUR_STATE['sid'] = n
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(fps)
# Increment count and set flags for the next frame
self._count += 1
self.old_visible = self.visible
if (self._start * fps) <= self._count < (self._stop * fps):
self.visible = True
else:
self.visible = False
if self._count >= (self._end * fps):
self.over = True
else:
self.over = False
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.visible = False
self.old_visible = False
self.steps_done = 0
self.over = False
def draw(self, **keywords):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, **keywords):
"""Checks for keypress, sends trigger upon end."""
keystates = keywords['keystates']
if max([keystates[key] for key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
if self.steps_done == self.num_steps:
self.over = True
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = {'dims': (5, 5),
'init_unit': (30, 30), 'end_unit': (50, 50),
'position': (0, 0), 'anchor': 'bottomleft',
'cols': ((0, 0, 0), (255, 255, 255)),
'freq': 1, 'phase': 0}
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
if INT_HALF_PERIODS:
frames_per_half_period = round(fps / (self.freq * 2))
degs_per_frame = 180 / to_decimal(frames_per_half_period)
else:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
if PRERENDER_TO_TEXTURE:
init_pos = [(1 - a)* s/to_decimal(2) for s, a in
zip(self._size, graphics.locations[self.anchor])]
else:
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
anchor=self.anchor)
cur_unit_rect.col = self.cols[(i + j) % 2]
cur_unit_rect.add_to_batch(self._batches[0])
cur_unit_rect.col = self.cols[(i + j + 1) % 2]
cur_unit_rect.add_to_batch(self._batches[1])
# Increase x values
cur_unit_pos[0] += \
graphics.locations[self.anchor][0] * cur_unit[0]
cur_unit[0] += unit_grad[0]
# Reset x values
cur_unit_pos[0] = init_pos[0]
cur_unit[0] = init_unit[0]
# Increase y values
cur_unit_pos[1] += \
graphics.locations[self.anchor][1] * cur_unit[1]
cur_unit[1] += unit_grad[1]
if PRERENDER_TO_TEXTURE:
# Create textures
int_size = [int(round(s)) for s in self._size]
self._prerenders =\
[pyglet.image.Texture.create(*int_size) for n in range(2)]
# Set up framebuffer
fbo = graphics.Framebuffer()
for n in range(2):
fbo.attach_texture(self._prerenders[n])
# Draw batch to texture
fbo.start_render()
self._batches[n].draw()
fbo.end_render()
# Anchor textures for correct blitting later
self._prerenders[n].anchor_x, self._prerenders[n].anchor_y =\
[int(round((1 - a)* s/to_decimal(2))) for s, a in
zip(self._size, graphics.locations[self.anchor])]
fbo.delete()
# Delete batches since they won't be used
del self._batches
self._computed = True
def draw(self, photoburst=False, always_compute=False):
"""Draws appropriate prerender depending on current phase.
photoburst -- draw first color for only one frame for testing purposes
always_compute -- recompute what the checkerboard should look like
every frame
"""
if not self._computed or always_compute:
self.compute()
self._cur_phase %= 360
n = int(self._cur_phase // 180)
if photoburst and n == 0 and not self.flipped:
n = 1
if PRERENDER_TO_TEXTURE:
self._prerenders[n].blit(*self.position)
else:
self._batches[n].draw()
def lazydraw(self):
"""Only draws on color reversal."""
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if (cur_n != prev_n) or self._first_draw:
self.draw()
if self._first_draw:
self._first_draw = False
diff --git a/src/trigger.py b/src/trigger.py
index e489603..b0d7540 100644
--- a/src/trigger.py
+++ b/src/trigger.py
@@ -1,105 +1,109 @@
"""Module for sending triggers upon various events through the serial or
parallel ports."""
-NULL_STATE = {'user': 0, 'tracking': 0, 'fixation': 0,
- 'group': 0, 'shape': 0, 'gid': 0, 'sid': 0}
+NULL_STATE = {'block': 0, 'tracking': 0, 'fixation': 0,
+ 'group': 0, 'shape': 0, 'gid': 0, 'sid': 0,
+ 'event': 0}
CUR_STATE = dict(NULL_STATE)
PREV_STATE = dict(NULL_STATE)
SERPORT = None
PARPORT = None
available = {'serial': False, 'parallel': False}
try:
import serial
try:
test_port = serial.Serial(0)
test_port.close()
del test_port
available['serial'] = True
except serial.serialutil.SerialException:
pass
except ImportError:
pass
try:
import parallel
try:
test_port = parallel.Parallel()
del test_port
available['parallel'] = True
except:
pass
except ImportError:
pass
if available['serial']:
def ser_init():
global SERPORT
SERPORT = serial.Serial(0)
def ser_send(statebyte):
global SERPORT
SERPORT.write(statebyte)
def ser_quit():
global SERPORT
SERPORT.close()
SERPORT = None
if available['parallel']:
def par_init():
global PARPORT
PARPORT = parallel.Parallel()
PARPORT.setData(0)
def par_send(statebyte):
global PARPORT
PARPORT.setData(statebyte)
def par_quit():
global PARPORT
PARPORT.setData(0)
PARPORT = None
def init(trigser, trigpar):
global CUR_STATE
global PREV_STATE
CUR_STATE = NULL_STATE
PREV_STATE = NULL_STATE
if trigser:
ser_init()
if trigpar:
par_init()
def set_state(fieldname, value):
global CUR_STATE
global PREV_STATE
PREV_STATE = CUR_STATE
CUR_STATE[fieldname] = value
+ CUR_STATE['event'] = 1
def set_null():
set_state(NULL_STATE)
def send(trigser, trigpar):
- statebyte = int(''.join([str(CUR_STATE[name]) for
- name in ['user', 'tracking',
- 'fixation', 'group', 'shape']]), 2)
+ statebyte = ''.join([str(CUR_STATE[name]) for
+ name in ['block', 'tracking', 'fixation',
+ 'group', 'shape']]).ljust(8,'0')
+ statebyte = int(statebyte, 2)
+ # Preferentially send group id over shape id
if CUR_STATE['group'] != PREV_STATE['group']:
- statebyte += CUR_STATE['gid']
+ statebyte += CUR_STATE['gid'] + 1
elif CUR_STATE['shape'] > PREV_STATE['shape']:
statebyte += CUR_STATE['sid']
- if trigser:
- ser_send(statebyte)
if CUR_STATE != PREV_STATE:
+ if trigser:
+ ser_send(statebyte)
if trigpar:
par_send(statebyte)
def quit(trigser, trigpar):
set_null()
if trigser:
ser_quit()
if trigpar:
par_quit()
|
ztangent/checkergen
|
bfb9acc9d010478fc4da1b256ca22612b314e492
|
fpbs -> fpst small fix
|
diff --git a/src/cli.py b/src/cli.py
index 20da64f..33749b1 100644
--- a/src/cli.py
+++ b/src/cli.py
@@ -267,937 +267,937 @@ class CkgCmd(cmd.Cmd):
description='''Makes a new display group
with the given parameters.''')
mkgrp_parser.add_argument('pre', type=to_decimal, default=0, nargs='?',
help='''time in seconds a blank screen will
be shown before shapes are displayed''')
mkgrp_parser.add_argument('disp', type=to_decimal,
nargs='?', default='Infinity',
help='''time in seconds shapes will be
displayed''')
mkgrp_parser.add_argument('post', type=to_decimal, default=0, nargs='?',
help='''time in seconds a blank screen will
be shown after shapes are displayed''')
def help_mkgrp(self):
self.__class__.mkgrp_parser.print_help()
def do_mkgrp(self, line):
"""Makes a display group with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
try:
args = self.__class__.mkgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mkgrp_parser.print_usage()
return
group_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_group = core.CkgDisplayGroup(**group_dict)
new_id = self.cur_proj.add_group(new_group)
print "display group", new_id, "added"
self.cur_group = new_group
print "group", new_id, "is now the current display group"
edgrp_parser = CmdParser(add_help=False, prog='edgrp',
description='''Edits attributes of display groups
specified by ids.''')
edgrp_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='ids of display groups to be edited')
edgrp_parser.add_argument('--pre', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown before shapes are displayed''')
edgrp_parser.add_argument('--disp', type=to_decimal, metavar='SECONDS',
help='''time in seconds shapes will be
displayed''')
edgrp_parser.add_argument('--post', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown after shapes are displayed''')
def help_edgrp(self):
self.__class__.edgrp_parser.print_help()
def do_edgrp(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.edgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.edgrp_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_proj.groups) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_group_attr(x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.edgrp_parser.print_usage()
rmgrp_parser = CmdParser(add_help=False, prog='rmgrp',
description='''Removes display groups specified
by ids.''')
rmgrp_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='ids of display groups to be removed')
rmgrp_parser.add_argument('-a', '--all', action='store_true',
help='remove all groups from the project')
def help_rmgrp(self):
self.__class__.rmgrp_parser.print_help()
def do_rmgrp(self, line):
"""Removes display groups specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups to remove'
return
try:
args = self.__class__.rmgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rmgrp_parser.print_usage()
return
rmlist = []
if args.all:
for group in self.cur_proj.groups[:]:
self.cur_proj.del_group(group)
print "all display groups removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_proj.groups) or x < 0:
print "display group", x, "does not exist"
continue
rmlist.append(self.cur_proj.groups[x])
print "display group", x, "removed"
for group in rmlist:
self.cur_proj.del_group(group)
# Remember to point self.cur_group somewhere sane
if self.cur_group not in self.cur_proj.groups:
if len(self.cur_proj.groups) == 0:
self.cur_group = None
else:
self.cur_group = self.cur_proj.groups[0]
print "group 0 is now the current display group"
chgrp_parser = CmdParser(add_help=False, prog='chgrp',
description='''Changes display group that is
currently active for editing.
Prints current group id if
no group id is specified''')
chgrp_parser.add_argument('gid', metavar='id', type=int, nargs='?',
help='id of display group to be made active')
def help_chgrp(self):
self.__class__.chgrp_parser.print_help()
def do_chgrp(self, line):
"""Changes group that is currently active for editing."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups that can be made active'
return
try:
args = self.__class__.chgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.chgrp_parser.print_usage()
return
if args.gid == None:
print "group",\
self.cur_proj.groups.index(self.cur_group),\
"is the current display group"
elif args.gid >= len(self.cur_proj.groups) or args.gid < 0:
print "group", args.gid, "does not exist"
else:
self.cur_group = self.cur_proj.groups[args.gid]
print "group", args.gid, "is now the current display group"
mk_parser = CmdParser(add_help=False, prog='mk',
description='''Makes a new checkerboard in the
current group with the given
parameters.''')
mk_parser.add_argument('dims', action=store_tuple(2, ',', to_decimal),
help='''width,height of checkerboard in no. of
unit cells''')
mk_parser.add_argument('init_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of initial unit cell in pixels')
mk_parser.add_argument('end_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of final unit cell in pixels')
mk_parser.add_argument('position', action=store_tuple(2, ',', to_decimal),
help='x,y position of checkerboard in pixels')
mk_parser.add_argument('anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='anchor')
mk_parser.add_argument('cols', action=store_tuple(2, ',', to_color, [';']),
help='''color1,color2 of the checkerboard
(color format: R;G;B,
component range from 0-255)''')
mk_parser.add_argument('freq', type=to_decimal,
help='frequency of color reversal in Hz')
mk_parser.add_argument('phase', type=to_decimal, nargs='?', default='0',
help='initial phase of animation in degrees')
def help_mk(self):
self.__class__.mk_parser.print_help()
def do_mk(self, line):
"""Makes a checkerboard with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
if self.cur_group == None:
print 'automatically adding display group...'
self.do_mkgrp('')
try:
args = self.__class__.mk_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mk_parser.print_usage()
return
shape_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_shape = core.CheckerBoard(**shape_dict)
new_id = self.cur_proj.add_shape_to_group(self.cur_group, new_shape)
print "checkerboard", new_id, "added"
ed_parser = CmdParser(add_help=False, prog='ed',
description='''Edits attributes of checkerboards
specified by ids.''')
ed_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='''ids of checkerboards in the current
group to be edited''')
ed_parser.add_argument('--dims', action=store_tuple(2, ',', to_decimal),
help='checkerboard dimensions in unit cells',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--init_unit',
action=store_tuple(2, ',', to_decimal),
help='initial unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--end_unit',
action=store_tuple(2, ',', to_decimal),
help='final unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--position',
action=store_tuple(2, ',', to_decimal),
help='position of checkerboard in pixels',
metavar='X,Y')
ed_parser.add_argument('--anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='LOCATION')
ed_parser.add_argument('--cols', metavar='COLOR1,COLOR2',
action=store_tuple(2, ',', to_color, [';']),
help='''checkerboard colors (color format:
R;G;B, component range
from 0-255)''')
ed_parser.add_argument('--freq', type=to_decimal,
help='frequency of color reversal in Hz')
ed_parser.add_argument('--phase', type=to_decimal,
help='initial phase of animation in degrees')
def help_ed(self):
self.__class__.ed_parser.print_help()
def do_ed(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, please create one first'
return
try:
args = self.__class__.ed_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ed_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_group.shapes) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_shape_attr(self.cur_group, x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.ed_parser.print_usage()
rm_parser = CmdParser(add_help=False, prog='rm',
description='''Removes checkerboards specified
by ids.''')
rm_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''ids of checkerboards in the current group
to be removed''')
rm_parser.add_argument('-a', '--all', action='store_true',
help='''remove all checkerboards in the
current group''')
def help_rm(self):
self.__class__.rm_parser.print_help()
def do_rm(self, line):
"""Removes checkerboards specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, no boards to remove'
return
try:
args = self.__class__.rm_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rm_parser.print_usage()
return
rmlist = []
if args.all:
for shape in self.cur_group.shapes:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
print "all checkerboards removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_group.shapes) or x < 0:
print "checkerboard", x, "does not exist"
continue
rmlist.append(self.cur_group.shapes[x])
print "checkerboard", x, "removed"
for shape in rmlist:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
ls_parser = CmdParser(add_help=False, prog='ls',
description='''Lists project, display group and
checkerboard settings. If no group ids
are specified, all display groups
are listed.''')
ls_parser.add_argument('gidlist', nargs='*', metavar='gid', type=int,
help='''ids of the display groups to be listed''')
ls_group = ls_parser.add_mutually_exclusive_group()
ls_group.add_argument('-s', '--settings', action='store_true',
help='list only project settings')
ls_group.add_argument('-g', '--groups', action='store_true',
help='list only display groups')
def help_ls(self):
self.__class__.ls_parser.print_help()
def do_ls(self, line):
"""Lists project, display group and checkerboard settings."""
def ls_str(s, seps=[',',';']):
"""Special space-saving output formatter."""
if type(s) in [tuple, list]:
if len(seps) > 1:
newseps = seps[1:]
else:
newseps = seps
return seps[0].join([ls_str(i, newseps) for i in s])
else:
return str(s)
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.ls_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ls_parser.print_usage()
return
# Remove duplicates and ascending sort
args.gidlist = sorted(set(args.gidlist))
if len(self.cur_proj.groups) == 0:
if len(args.gidlist) > 0:
print 'this project has no display groups that can be listed'
args.settings = True
else:
for gid in args.gidlist[:]:
if gid >= len(self.cur_proj.groups) or gid < 0:
args.gidlist.remove(gid)
print 'display group', gid, 'does not exist'
if args.gidlist == []:
args.gidlist = range(len(self.cur_proj.groups))
else:
# If any (valid) groups are specified
# don't show project settings
args.groups = True
if not args.groups:
print 'PROJECT SETTINGS'.center(70,'*')
print \
'name'.rjust(16),\
'fps'.rjust(7),\
'resolution'.rjust(14),\
'bg color'.rjust(18)
# 'format'.rjust(7)
print \
ls_str(self.cur_proj.name).rjust(16),\
ls_str(self.cur_proj.fps).rjust(7),\
ls_str(self.cur_proj.res).rjust(14),\
ls_str(self.cur_proj.bg).rjust(18)
# ls_str(self.cur_proj.export_fmt).rjust(7)
print \
'pre-display'.rjust(26),\
'post-display'.rjust(26)
print \
ls_str(self.cur_proj.pre).rjust(26),\
ls_str(self.cur_proj.post).rjust(26)
print \
'cross colors'.rjust(26),\
'cross times'.rjust(26)
print \
ls_str(self.cur_proj.cross_cols).rjust(26),\
ls_str(self.cur_proj.cross_times).rjust(26)
if not args.settings and not args.groups:
# Insert empty line if both groups and project
# settings are listed
print ''
if not args.settings:
for i, n in enumerate(args.gidlist):
if i != 0:
# Print newline seperator between each group
print ''
group = self.cur_proj.groups[n]
print 'GROUP {n}'.format(n=n).center(70,'*')
print \
'pre-display'.rjust(20),\
'display'.rjust(20),\
'post-display'.rjust(20)
print \
ls_str(group.pre).rjust(20),\
ls_str(group.disp).rjust(20),\
ls_str(group.post).rjust(20)
if len(group.shapes) > 0:
print \
''.rjust(2),\
'shape id'.rjust(8),\
'dims'.rjust(10),\
'init_unit'.rjust(14),\
'end_unit'.rjust(14),\
'position'.rjust(14)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.dims).rjust(10),\
ls_str(shape.init_unit).rjust(14),\
ls_str(shape.end_unit).rjust(14),\
ls_str(shape.position).rjust(14)
print '\n',\
''.rjust(2),\
'shape id'.rjust(8),\
'colors'.rjust(27),\
'anchor'.rjust(12),\
'freq'.rjust(6),\
'phase'.rjust(7)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.cols).rjust(27),\
ls_str(shape.anchor).rjust(12),\
ls_str(shape.freq).rjust(6),\
ls_str(shape.phase).rjust(7)
display_parser = CmdParser(add_help=False, prog='display',
description='''Displays the animation in a
window or in fullscreen.''')
display_parser.add_argument('-e', '--expfile', metavar='PATH',
help='''run experiment as described in
specified file, ignore other flags''')
display_parser.add_argument('-f', '--fullscreen', action='store_true',
help='sets fullscreen mode, ESC to quit')
display_parser.add_argument('-p', '--priority', metavar='LEVEL',
help='''set priority while displaying,
higher priority results in
less dropped frames (choices:
0-3, low, normal, high,
realtime)''')
display_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly display specified display
groups N number of times''')
display_parser.add_argument('-pt', '--phototest', action='store_true',
help='''draw white test rectangle in topleft
corner of screen when groups become
visible for a photodiode to detect''')
display_parser.add_argument('-pb', '--photoburst', action='store_true',
help='''make checkerboards only draw first
color for one frame to facilitate
testing with a photodiode''')
display_parser.add_argument('-lt', '--logtime', action='store_true',
help='output frame timestamps to a log file')
display_parser.add_argument('-ld', '--logdur', action='store_true',
help='output frame durations to a log file')
display_parser.add_argument('-ss', '--trigser', action='store_true',
help='''send triggers through the serial port
when shapes are being displayed''')
display_parser.add_argument('-sp', '--trigpar', action='store_true',
help='''send triggers through the parallel port
when shapes are being displayed''')
- display_parser.add_argument('-fpbs', metavar='M', type=int, default=0,
+ display_parser.add_argument('-fpst', metavar='M', type=int, default=0,
help='''unique trigger corresponding to a
- checkerboard is sent after the board
+ checkerboard is sent after the shape
undergoes M color flips (default:
disabled, M=0)''')
display_parser.add_argument('-et', '--eyetrack', action='store_true',
help='''use eyetracking to ensure that subject
fixates on the cross in the center''')
display_parser.add_argument('-eu', '--etuser', action='store_true',
help='''allow user to select eyetracking video
source from a dialog''')
display_parser.add_argument('-ev', '--etvideo', metavar='path',
help='''path (with no spaces) to eyetracking
video file to be used as the source''')
display_parser.add_argument('-ta', '--tryagain', metavar='I',
type=int, default=0,
help='''append groups during which subject
failed to fixate up to I times to the
list of groups to be displayed
(default: disabled, I=0)''')
display_parser.add_argument('-tb', '--trybreak', metavar='J', type=int,
help='''used with --tryagain, append a wait
screen to the list of groups to be
displayed after every J groups have
been appended to the list (default:
J=total number of groups)''')
display_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be displayed
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_display(self):
self.__class__.display_parser.print_help()
def do_display(self, line):
"""Displays the animation in a window or in fullscreen"""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.display_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
if args.expfile != None:
try:
exp = core.CkgExp(path=args.expfile)
except IOError:
print "error:", str(sys.exc_value)
return
try:
args = self.__class__.\
display_parser.parse_args(shlex.split(exp.flags))
except (CmdParserError, ValueError):
print 'error: invalid flags stored in block file'
return
try:
print """name of log file (default: experiment name):"""
blkname = raw_input().strip().strip('"\'')
except EOFError:
return
if blkname == '':
blkname == exp.name
blk = exp.random_blk(blkname)
args.idlist = blk.idlist()
else:
blk = core.CkgBlk(name=self.cur_proj.name,
trials=None,
flags=line,
sequence=[])
groupq = []
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < -1:
print 'error: group', i, 'does not exist'
return
for i in args.idlist:
if i == -1:
groupq.append(core.CkgWaitScreen(res=self.cur_proj.res))
else:
groupq.append(self.cur_proj.groups[i])
else:
groupq = list(self.cur_proj.groups)
if args.repeat != None:
groupq = list(groupq * args.repeat)
if args.eyetrack and eyetracking.available:
if not eyetracking.is_calibrated():
try:
self.do_calibrate('',True)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
return
if args.priority != None:
if not priority.available[sys.platform]:
print "error: setting priority not available on", sys.platform
print "continuing..."
else:
if args.priority.isdigit():
args.priority = int(args.priority)
try:
priority.set(args.priority)
except ValueError:
print "error:", str(sys.exc_value)
print "continuing..."
print "displaying..."
try:
self.cur_proj.display(fullscreen=args.fullscreen,
logtime=args.logtime,
logdur=args.logdur,
trigser=args.trigser,
trigpar=args.trigpar,
- fpbs=args.fpbs,
+ fpst=args.fpst,
phototest=args.phototest,
photoburst=args.photoburst,
eyetrack=args.eyetrack,
etuser=args.etuser,
etvideo=args.etvideo,
tryagain=args.tryagain,
trybreak=args.trybreak,
groupq=groupq,
blk=blk)
except (IOError, NotImplementedError, eyetracking.EyetrackingError):
print "error:", str(sys.exc_value)
if args.priority != None:
try:
priority.set('normal')
except:
pass
return
if args.priority != None:
try:
priority.set('normal')
except:
pass
try:
blk.write_log()
except IOError:
print "error:", str(sys.exc_value)
return
print "log file written"
export_parser = CmdParser(add_help=False, prog='export',
description='''Exports animation as an image
sequence (in a folder) to the
specified directory.''')
# export_parser.add_argument('--fmt', dest='export_fmt',
# choices=core.EXPORT_FMTS,
# help='image format for export')
export_parser.add_argument('-n','--nofolder',
dest='folder', action='store_false',
help='''force images not to exported in
a containing folder''')
export_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly export specified display
groups N number of times''')
export_parser.add_argument('duration', nargs='?',
type=to_decimal, default='Infinity',
help='''number of seconds of the animation
that should be exported (default:
as long as the entire animation)''')
export_parser.add_argument('dir', nargs='?', default=os.getcwd(),
help='''destination directory for export
(default: current working directory)''')
export_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be exported
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_export(self):
self.__class__.export_parser.print_help()
def do_export(self, line):
"""Exports animation an image sequence to the specified directory."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.export_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.export_parser.print_usage()
return
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < 0:
print 'error: group', i, 'does not exist'
return
groupq = [self.cur_proj.groups[i] for i in args.idlist]
else:
groupq = list(self.cur_proj.groups)
if args.repeat != None:
groupq = list(groupq * args.repeat)
try:
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
folder=args.folder)
except IOError:
print "error:", str(sys.exc_value)
return
except core.FrameOverflowError:
print "warning:", str(sys.exc_value)
print "Are you sure you want to continue?"
while True:
try:
if self.__class__.yn_parse(raw_input()):
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
export_fmt=None,
folder=args.folder,
force=True)
break
else:
return
except TypeError:
print str(sys.exc_value)
except EOFError:
return
print "Export done."
mkexp_parser = CmdParser(add_help=False, prog='mkexp',
description='''Create checkergen experiment file
which describes how the project
is to be displayed.''')
mkexp_parser.add_argument('-n', '--name',
help='''name of the experiment (default: same
name as current project)''')
mkexp_parser.add_argument('-t', '--trials', type=int, metavar='N',
help='''N trials displayed in a block, i.e.
the same sequence will be displayed
N times in that block, with waitscreens
in between''')
mkexp_parser.add_argument('-f', '--flags',
help='''flags passed to the display command
that should be used when the block
file is run (enclose in quotes and use
'+' or '++' in place of '-' or '--')''')
def help_mkexp(self):
self.__class__.mkexp_parser.print_help()
def do_mkexp(self, line):
"""Creates checkergen experiment file."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.mkexp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mkexp_parser.print_usage()
return
if args.trials == None:
print "number of trials:"
try:
args.trials = int(raw_input().strip())
except EOFError:
return
except ValueError:
print "error:", str(sys.exc_value)
return
if args.flags != None:
args.flags = args.flags.replace('+','-')
else:
print "flags used with display command (leave blank if none):"
try:
args.flags = raw_input().strip().strip('"\'')
except EOFError:
return
try:
disp_args = self.__class__.display_parser.\
parse_args(shlex.split(args.flags))
except (CmdParserError, ValueError):
print "error: invalid flags to display command"
print str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
print "list of sequences to choose from in the format",\
"'id1,id2,id3;seq2;seq3;seq4':"
print "(default: reduced latin square)"
try:
seqs_str = raw_input().strip()
if seqs_str == '':
args.sequences = None
else:
args.sequences = [[int(i) for i in seq_str.split(',')]
for seq_str in seqs_str.split(';')]
except EOFError:
return
try:
new_exp = core.CkgExp(name=args.name, proj=self.cur_proj,
trials=args.trials,
sequences=args.sequences,
flags=args.flags)
new_exp.save()
except IOError:
print "error:", str(sys.exc_value)
return
print "Experiment file created."
def do_calibrate(self, line, query=False):
"""Calibrate subject for eyetracking, or load a calibration file."""
if not eyetracking.available:
print "error: eyetracking functionality not available"
return
if query:
print "path to calibration file (leave empty for GUI tool):"
try:
path = raw_input().strip().strip('"\'')
except EOFError:
msg = "calibration cancelled"
raise eyetracking.EyetrackingError(msg)
else:
path = line.strip().strip('"\'')
if len(path) == 0:
path = None
if not eyetracking.is_source_ready():
# Select default source if none has been selected
eyetracking.select_source()
try:
eyetracking.calibrate(path)
except eyetracking.EyetrackingError:
if query:
raise
else:
print "error:", str(sys.exc_value)
return
if len(path) > 0:
print "calibration file successfully loaded"
etsetup_parser = CmdParser(add_help=False, prog='etsetup',
description='''Set various eyetracking
parameters.''')
etsetup_parser.add_argument('-fp', '--fixperiod', type=int, metavar='MS',
help='''time in milliseconds subject
has to stare at the same spot
for fixation to be detected''')
etsetup_parser.add_argument('-fr', '--fixrange', type=float, metavar='MM',
help='''distance in mm beyond which the
eye position cannot change for
a fixation to be detected''')
etsetup_parser.add_argument('-s', '--size', metavar='WIDTH,HEIGHT',
action=store_tuple(2, ',', float),
help='physical screen dimensions in mm')
etsetup_parser.add_argument('-vd', '--viewdist', type=int, metavar='MM',
help='''viewing distance between subject's
eyes and the screen''')
def help_etsetup(self):
self.__class__.etsetup_parser.print_help()
def do_etsetup(self, line):
try:
args = self.__class__.etsetup_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.etsetup_parser.print_usage()
return
try:
eyetracking.setup(viewing_distance=args.viewdist,
screen_dims=args.size,
fixation_period=args.fixperiod,
fixation_range=args.fixrange)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
def do_pwd(self, line):
"""Prints the current working directory."""
print os.getcwd()
def do_cd(self, line):
"""Change working directory to specified path."""
path = line.strip().strip('"\'')
if not os.path.isdir(path):
print "error: specified path is not a directory"
return
os.chdir(path)
def do_quit(self, line):
"""Quits the program."""
if self.save_check():
return
return True
def help_EOF(self):
print "Typing {0} issues this command, which quits the program."\
.format(CMD_EOF_STRING)
def do_EOF(self, line):
"""Typing Ctrl-D issues this command, which quits the program."""
print '\r'
if self.save_check():
return
return True
def help_help(self):
print 'Prints a list of commands.'
print "Type 'help <topic>' for more details on each command."
def default(self, line):
command = line.split()[0]
print \
"'{0}' is not a checkergen command.".format(command),\
"Type 'help' for a list of commands"
|
ztangent/checkergen
|
3e6ebd22e6330f29429689e1738cc9456d85eef4
|
Reformulating and renaming of trigger code.
|
diff --git a/src/cli.py b/src/cli.py
index 7fc0439..20da64f 100644
--- a/src/cli.py
+++ b/src/cli.py
@@ -261,943 +261,943 @@ class CkgCmd(cmd.Cmd):
print "no options specified, please specify at least one"
self.__class__.set_parser.print_usage()
mkgrp_parser = CmdParser(add_help=False, prog='mkgrp',
formatter_class=
argparse.ArgumentDefaultsHelpFormatter,
description='''Makes a new display group
with the given parameters.''')
mkgrp_parser.add_argument('pre', type=to_decimal, default=0, nargs='?',
help='''time in seconds a blank screen will
be shown before shapes are displayed''')
mkgrp_parser.add_argument('disp', type=to_decimal,
nargs='?', default='Infinity',
help='''time in seconds shapes will be
displayed''')
mkgrp_parser.add_argument('post', type=to_decimal, default=0, nargs='?',
help='''time in seconds a blank screen will
be shown after shapes are displayed''')
def help_mkgrp(self):
self.__class__.mkgrp_parser.print_help()
def do_mkgrp(self, line):
"""Makes a display group with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
try:
args = self.__class__.mkgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mkgrp_parser.print_usage()
return
group_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_group = core.CkgDisplayGroup(**group_dict)
new_id = self.cur_proj.add_group(new_group)
print "display group", new_id, "added"
self.cur_group = new_group
print "group", new_id, "is now the current display group"
edgrp_parser = CmdParser(add_help=False, prog='edgrp',
description='''Edits attributes of display groups
specified by ids.''')
edgrp_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='ids of display groups to be edited')
edgrp_parser.add_argument('--pre', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown before shapes are displayed''')
edgrp_parser.add_argument('--disp', type=to_decimal, metavar='SECONDS',
help='''time in seconds shapes will be
displayed''')
edgrp_parser.add_argument('--post', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown after shapes are displayed''')
def help_edgrp(self):
self.__class__.edgrp_parser.print_help()
def do_edgrp(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.edgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.edgrp_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_proj.groups) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_group_attr(x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.edgrp_parser.print_usage()
rmgrp_parser = CmdParser(add_help=False, prog='rmgrp',
description='''Removes display groups specified
by ids.''')
rmgrp_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='ids of display groups to be removed')
rmgrp_parser.add_argument('-a', '--all', action='store_true',
help='remove all groups from the project')
def help_rmgrp(self):
self.__class__.rmgrp_parser.print_help()
def do_rmgrp(self, line):
"""Removes display groups specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups to remove'
return
try:
args = self.__class__.rmgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rmgrp_parser.print_usage()
return
rmlist = []
if args.all:
for group in self.cur_proj.groups[:]:
self.cur_proj.del_group(group)
print "all display groups removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_proj.groups) or x < 0:
print "display group", x, "does not exist"
continue
rmlist.append(self.cur_proj.groups[x])
print "display group", x, "removed"
for group in rmlist:
self.cur_proj.del_group(group)
# Remember to point self.cur_group somewhere sane
if self.cur_group not in self.cur_proj.groups:
if len(self.cur_proj.groups) == 0:
self.cur_group = None
else:
self.cur_group = self.cur_proj.groups[0]
print "group 0 is now the current display group"
chgrp_parser = CmdParser(add_help=False, prog='chgrp',
description='''Changes display group that is
currently active for editing.
Prints current group id if
no group id is specified''')
chgrp_parser.add_argument('gid', metavar='id', type=int, nargs='?',
help='id of display group to be made active')
def help_chgrp(self):
self.__class__.chgrp_parser.print_help()
def do_chgrp(self, line):
"""Changes group that is currently active for editing."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups that can be made active'
return
try:
args = self.__class__.chgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.chgrp_parser.print_usage()
return
if args.gid == None:
print "group",\
self.cur_proj.groups.index(self.cur_group),\
"is the current display group"
elif args.gid >= len(self.cur_proj.groups) or args.gid < 0:
print "group", args.gid, "does not exist"
else:
self.cur_group = self.cur_proj.groups[args.gid]
print "group", args.gid, "is now the current display group"
mk_parser = CmdParser(add_help=False, prog='mk',
description='''Makes a new checkerboard in the
current group with the given
parameters.''')
mk_parser.add_argument('dims', action=store_tuple(2, ',', to_decimal),
help='''width,height of checkerboard in no. of
unit cells''')
mk_parser.add_argument('init_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of initial unit cell in pixels')
mk_parser.add_argument('end_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of final unit cell in pixels')
mk_parser.add_argument('position', action=store_tuple(2, ',', to_decimal),
help='x,y position of checkerboard in pixels')
mk_parser.add_argument('anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='anchor')
mk_parser.add_argument('cols', action=store_tuple(2, ',', to_color, [';']),
help='''color1,color2 of the checkerboard
(color format: R;G;B,
component range from 0-255)''')
mk_parser.add_argument('freq', type=to_decimal,
help='frequency of color reversal in Hz')
mk_parser.add_argument('phase', type=to_decimal, nargs='?', default='0',
help='initial phase of animation in degrees')
def help_mk(self):
self.__class__.mk_parser.print_help()
def do_mk(self, line):
"""Makes a checkerboard with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
if self.cur_group == None:
print 'automatically adding display group...'
self.do_mkgrp('')
try:
args = self.__class__.mk_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mk_parser.print_usage()
return
shape_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_shape = core.CheckerBoard(**shape_dict)
new_id = self.cur_proj.add_shape_to_group(self.cur_group, new_shape)
print "checkerboard", new_id, "added"
ed_parser = CmdParser(add_help=False, prog='ed',
description='''Edits attributes of checkerboards
specified by ids.''')
ed_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='''ids of checkerboards in the current
group to be edited''')
ed_parser.add_argument('--dims', action=store_tuple(2, ',', to_decimal),
help='checkerboard dimensions in unit cells',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--init_unit',
action=store_tuple(2, ',', to_decimal),
help='initial unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--end_unit',
action=store_tuple(2, ',', to_decimal),
help='final unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--position',
action=store_tuple(2, ',', to_decimal),
help='position of checkerboard in pixels',
metavar='X,Y')
ed_parser.add_argument('--anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='LOCATION')
ed_parser.add_argument('--cols', metavar='COLOR1,COLOR2',
action=store_tuple(2, ',', to_color, [';']),
help='''checkerboard colors (color format:
R;G;B, component range
from 0-255)''')
ed_parser.add_argument('--freq', type=to_decimal,
help='frequency of color reversal in Hz')
ed_parser.add_argument('--phase', type=to_decimal,
help='initial phase of animation in degrees')
def help_ed(self):
self.__class__.ed_parser.print_help()
def do_ed(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, please create one first'
return
try:
args = self.__class__.ed_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ed_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_group.shapes) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_shape_attr(self.cur_group, x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.ed_parser.print_usage()
rm_parser = CmdParser(add_help=False, prog='rm',
description='''Removes checkerboards specified
by ids.''')
rm_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''ids of checkerboards in the current group
to be removed''')
rm_parser.add_argument('-a', '--all', action='store_true',
help='''remove all checkerboards in the
current group''')
def help_rm(self):
self.__class__.rm_parser.print_help()
def do_rm(self, line):
"""Removes checkerboards specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, no boards to remove'
return
try:
args = self.__class__.rm_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rm_parser.print_usage()
return
rmlist = []
if args.all:
for shape in self.cur_group.shapes:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
print "all checkerboards removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_group.shapes) or x < 0:
print "checkerboard", x, "does not exist"
continue
rmlist.append(self.cur_group.shapes[x])
print "checkerboard", x, "removed"
for shape in rmlist:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
ls_parser = CmdParser(add_help=False, prog='ls',
description='''Lists project, display group and
checkerboard settings. If no group ids
are specified, all display groups
are listed.''')
ls_parser.add_argument('gidlist', nargs='*', metavar='gid', type=int,
help='''ids of the display groups to be listed''')
ls_group = ls_parser.add_mutually_exclusive_group()
ls_group.add_argument('-s', '--settings', action='store_true',
help='list only project settings')
ls_group.add_argument('-g', '--groups', action='store_true',
help='list only display groups')
def help_ls(self):
self.__class__.ls_parser.print_help()
def do_ls(self, line):
"""Lists project, display group and checkerboard settings."""
def ls_str(s, seps=[',',';']):
"""Special space-saving output formatter."""
if type(s) in [tuple, list]:
if len(seps) > 1:
newseps = seps[1:]
else:
newseps = seps
return seps[0].join([ls_str(i, newseps) for i in s])
else:
return str(s)
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.ls_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ls_parser.print_usage()
return
# Remove duplicates and ascending sort
args.gidlist = sorted(set(args.gidlist))
if len(self.cur_proj.groups) == 0:
if len(args.gidlist) > 0:
print 'this project has no display groups that can be listed'
args.settings = True
else:
for gid in args.gidlist[:]:
if gid >= len(self.cur_proj.groups) or gid < 0:
args.gidlist.remove(gid)
print 'display group', gid, 'does not exist'
if args.gidlist == []:
args.gidlist = range(len(self.cur_proj.groups))
else:
# If any (valid) groups are specified
# don't show project settings
args.groups = True
if not args.groups:
print 'PROJECT SETTINGS'.center(70,'*')
print \
'name'.rjust(16),\
'fps'.rjust(7),\
'resolution'.rjust(14),\
'bg color'.rjust(18)
# 'format'.rjust(7)
print \
ls_str(self.cur_proj.name).rjust(16),\
ls_str(self.cur_proj.fps).rjust(7),\
ls_str(self.cur_proj.res).rjust(14),\
ls_str(self.cur_proj.bg).rjust(18)
# ls_str(self.cur_proj.export_fmt).rjust(7)
print \
'pre-display'.rjust(26),\
'post-display'.rjust(26)
print \
ls_str(self.cur_proj.pre).rjust(26),\
ls_str(self.cur_proj.post).rjust(26)
print \
'cross colors'.rjust(26),\
'cross times'.rjust(26)
print \
ls_str(self.cur_proj.cross_cols).rjust(26),\
ls_str(self.cur_proj.cross_times).rjust(26)
if not args.settings and not args.groups:
# Insert empty line if both groups and project
# settings are listed
print ''
if not args.settings:
for i, n in enumerate(args.gidlist):
if i != 0:
# Print newline seperator between each group
print ''
group = self.cur_proj.groups[n]
print 'GROUP {n}'.format(n=n).center(70,'*')
print \
'pre-display'.rjust(20),\
'display'.rjust(20),\
'post-display'.rjust(20)
print \
ls_str(group.pre).rjust(20),\
ls_str(group.disp).rjust(20),\
ls_str(group.post).rjust(20)
if len(group.shapes) > 0:
print \
''.rjust(2),\
'shape id'.rjust(8),\
'dims'.rjust(10),\
'init_unit'.rjust(14),\
'end_unit'.rjust(14),\
'position'.rjust(14)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.dims).rjust(10),\
ls_str(shape.init_unit).rjust(14),\
ls_str(shape.end_unit).rjust(14),\
ls_str(shape.position).rjust(14)
print '\n',\
''.rjust(2),\
'shape id'.rjust(8),\
'colors'.rjust(27),\
'anchor'.rjust(12),\
'freq'.rjust(6),\
'phase'.rjust(7)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.cols).rjust(27),\
ls_str(shape.anchor).rjust(12),\
ls_str(shape.freq).rjust(6),\
ls_str(shape.phase).rjust(7)
display_parser = CmdParser(add_help=False, prog='display',
description='''Displays the animation in a
window or in fullscreen.''')
display_parser.add_argument('-e', '--expfile', metavar='PATH',
help='''run experiment as described in
specified file, ignore other flags''')
display_parser.add_argument('-f', '--fullscreen', action='store_true',
help='sets fullscreen mode, ESC to quit')
display_parser.add_argument('-p', '--priority', metavar='LEVEL',
help='''set priority while displaying,
higher priority results in
less dropped frames (choices:
0-3, low, normal, high,
realtime)''')
display_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly display specified display
groups N number of times''')
display_parser.add_argument('-pt', '--phototest', action='store_true',
help='''draw white test rectangle in topleft
corner of screen when groups become
visible for a photodiode to detect''')
display_parser.add_argument('-pb', '--photoburst', action='store_true',
help='''make checkerboards only draw first
color for one frame to facilitate
testing with a photodiode''')
display_parser.add_argument('-lt', '--logtime', action='store_true',
help='output frame timestamps to a log file')
display_parser.add_argument('-ld', '--logdur', action='store_true',
help='output frame durations to a log file')
- display_parser.add_argument('-ss', '--sigser', action='store_true',
- help='''send signals through the serial port
+ display_parser.add_argument('-ss', '--trigser', action='store_true',
+ help='''send triggers through the serial port
when shapes are being displayed''')
- display_parser.add_argument('-sp', '--sigpar', action='store_true',
- help='''send signals through the parallel port
+ display_parser.add_argument('-sp', '--trigpar', action='store_true',
+ help='''send triggers through the parallel port
when shapes are being displayed''')
display_parser.add_argument('-fpbs', metavar='M', type=int, default=0,
- help='''unique signal corresponding to a
+ help='''unique trigger corresponding to a
checkerboard is sent after the board
undergoes M color flips (default:
disabled, M=0)''')
display_parser.add_argument('-et', '--eyetrack', action='store_true',
help='''use eyetracking to ensure that subject
fixates on the cross in the center''')
display_parser.add_argument('-eu', '--etuser', action='store_true',
help='''allow user to select eyetracking video
source from a dialog''')
display_parser.add_argument('-ev', '--etvideo', metavar='path',
help='''path (with no spaces) to eyetracking
video file to be used as the source''')
display_parser.add_argument('-ta', '--tryagain', metavar='I',
type=int, default=0,
help='''append groups during which subject
failed to fixate up to I times to the
list of groups to be displayed
(default: disabled, I=0)''')
display_parser.add_argument('-tb', '--trybreak', metavar='J', type=int,
help='''used with --tryagain, append a wait
screen to the list of groups to be
displayed after every J groups have
been appended to the list (default:
J=total number of groups)''')
display_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be displayed
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_display(self):
self.__class__.display_parser.print_help()
def do_display(self, line):
"""Displays the animation in a window or in fullscreen"""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.display_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
if args.expfile != None:
try:
exp = core.CkgExp(path=args.expfile)
except IOError:
print "error:", str(sys.exc_value)
return
try:
args = self.__class__.\
display_parser.parse_args(shlex.split(exp.flags))
except (CmdParserError, ValueError):
print 'error: invalid flags stored in block file'
return
try:
print """name of log file (default: experiment name):"""
blkname = raw_input().strip().strip('"\'')
except EOFError:
return
if blkname == '':
blkname == exp.name
blk = exp.random_blk(blkname)
args.idlist = blk.idlist()
else:
blk = core.CkgBlk(name=self.cur_proj.name,
trials=None,
flags=line,
sequence=[])
groupq = []
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < -1:
print 'error: group', i, 'does not exist'
return
for i in args.idlist:
if i == -1:
groupq.append(core.CkgWaitScreen(res=self.cur_proj.res))
else:
groupq.append(self.cur_proj.groups[i])
else:
groupq = list(self.cur_proj.groups)
if args.repeat != None:
groupq = list(groupq * args.repeat)
if args.eyetrack and eyetracking.available:
if not eyetracking.is_calibrated():
try:
self.do_calibrate('',True)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
return
if args.priority != None:
if not priority.available[sys.platform]:
print "error: setting priority not available on", sys.platform
print "continuing..."
else:
if args.priority.isdigit():
args.priority = int(args.priority)
try:
priority.set(args.priority)
except ValueError:
print "error:", str(sys.exc_value)
print "continuing..."
print "displaying..."
try:
self.cur_proj.display(fullscreen=args.fullscreen,
logtime=args.logtime,
logdur=args.logdur,
- sigser=args.sigser,
- sigpar=args.sigpar,
+ trigser=args.trigser,
+ trigpar=args.trigpar,
fpbs=args.fpbs,
phototest=args.phototest,
photoburst=args.photoburst,
eyetrack=args.eyetrack,
etuser=args.etuser,
etvideo=args.etvideo,
tryagain=args.tryagain,
trybreak=args.trybreak,
groupq=groupq,
blk=blk)
except (IOError, NotImplementedError, eyetracking.EyetrackingError):
print "error:", str(sys.exc_value)
if args.priority != None:
try:
priority.set('normal')
except:
pass
return
if args.priority != None:
try:
priority.set('normal')
except:
pass
try:
blk.write_log()
except IOError:
print "error:", str(sys.exc_value)
return
print "log file written"
export_parser = CmdParser(add_help=False, prog='export',
description='''Exports animation as an image
sequence (in a folder) to the
specified directory.''')
# export_parser.add_argument('--fmt', dest='export_fmt',
# choices=core.EXPORT_FMTS,
# help='image format for export')
export_parser.add_argument('-n','--nofolder',
dest='folder', action='store_false',
help='''force images not to exported in
a containing folder''')
export_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly export specified display
groups N number of times''')
export_parser.add_argument('duration', nargs='?',
type=to_decimal, default='Infinity',
help='''number of seconds of the animation
that should be exported (default:
as long as the entire animation)''')
export_parser.add_argument('dir', nargs='?', default=os.getcwd(),
help='''destination directory for export
(default: current working directory)''')
export_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be exported
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_export(self):
self.__class__.export_parser.print_help()
def do_export(self, line):
"""Exports animation an image sequence to the specified directory."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.export_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.export_parser.print_usage()
return
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < 0:
print 'error: group', i, 'does not exist'
return
groupq = [self.cur_proj.groups[i] for i in args.idlist]
else:
groupq = list(self.cur_proj.groups)
if args.repeat != None:
groupq = list(groupq * args.repeat)
try:
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
folder=args.folder)
except IOError:
print "error:", str(sys.exc_value)
return
except core.FrameOverflowError:
print "warning:", str(sys.exc_value)
print "Are you sure you want to continue?"
while True:
try:
if self.__class__.yn_parse(raw_input()):
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
export_fmt=None,
folder=args.folder,
force=True)
break
else:
return
except TypeError:
print str(sys.exc_value)
except EOFError:
return
print "Export done."
mkexp_parser = CmdParser(add_help=False, prog='mkexp',
description='''Create checkergen experiment file
which describes how the project
is to be displayed.''')
mkexp_parser.add_argument('-n', '--name',
help='''name of the experiment (default: same
name as current project)''')
mkexp_parser.add_argument('-t', '--trials', type=int, metavar='N',
help='''N trials displayed in a block, i.e.
the same sequence will be displayed
N times in that block, with waitscreens
in between''')
mkexp_parser.add_argument('-f', '--flags',
help='''flags passed to the display command
that should be used when the block
file is run (enclose in quotes and use
'+' or '++' in place of '-' or '--')''')
def help_mkexp(self):
self.__class__.mkexp_parser.print_help()
def do_mkexp(self, line):
"""Creates checkergen experiment file."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.mkexp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mkexp_parser.print_usage()
return
if args.trials == None:
print "number of trials:"
try:
args.trials = int(raw_input().strip())
except EOFError:
return
except ValueError:
print "error:", str(sys.exc_value)
return
if args.flags != None:
args.flags = args.flags.replace('+','-')
else:
print "flags used with display command (leave blank if none):"
try:
args.flags = raw_input().strip().strip('"\'')
except EOFError:
return
try:
disp_args = self.__class__.display_parser.\
parse_args(shlex.split(args.flags))
except (CmdParserError, ValueError):
print "error: invalid flags to display command"
print str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
print "list of sequences to choose from in the format",\
"'id1,id2,id3;seq2;seq3;seq4':"
print "(default: reduced latin square)"
try:
seqs_str = raw_input().strip()
if seqs_str == '':
args.sequences = None
else:
args.sequences = [[int(i) for i in seq_str.split(',')]
for seq_str in seqs_str.split(';')]
except EOFError:
return
try:
new_exp = core.CkgExp(name=args.name, proj=self.cur_proj,
trials=args.trials,
sequences=args.sequences,
flags=args.flags)
new_exp.save()
except IOError:
print "error:", str(sys.exc_value)
return
print "Experiment file created."
def do_calibrate(self, line, query=False):
"""Calibrate subject for eyetracking, or load a calibration file."""
if not eyetracking.available:
print "error: eyetracking functionality not available"
return
if query:
print "path to calibration file (leave empty for GUI tool):"
try:
path = raw_input().strip().strip('"\'')
except EOFError:
msg = "calibration cancelled"
raise eyetracking.EyetrackingError(msg)
else:
path = line.strip().strip('"\'')
if len(path) == 0:
path = None
if not eyetracking.is_source_ready():
# Select default source if none has been selected
eyetracking.select_source()
try:
eyetracking.calibrate(path)
except eyetracking.EyetrackingError:
if query:
raise
else:
print "error:", str(sys.exc_value)
return
if len(path) > 0:
print "calibration file successfully loaded"
etsetup_parser = CmdParser(add_help=False, prog='etsetup',
description='''Set various eyetracking
parameters.''')
etsetup_parser.add_argument('-fp', '--fixperiod', type=int, metavar='MS',
help='''time in milliseconds subject
has to stare at the same spot
for fixation to be detected''')
etsetup_parser.add_argument('-fr', '--fixrange', type=float, metavar='MM',
help='''distance in mm beyond which the
eye position cannot change for
a fixation to be detected''')
etsetup_parser.add_argument('-s', '--size', metavar='WIDTH,HEIGHT',
action=store_tuple(2, ',', float),
help='physical screen dimensions in mm')
etsetup_parser.add_argument('-vd', '--viewdist', type=int, metavar='MM',
help='''viewing distance between subject's
eyes and the screen''')
def help_etsetup(self):
self.__class__.etsetup_parser.print_help()
def do_etsetup(self, line):
try:
args = self.__class__.etsetup_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.etsetup_parser.print_usage()
return
try:
eyetracking.setup(viewing_distance=args.viewdist,
screen_dims=args.size,
fixation_period=args.fixperiod,
fixation_range=args.fixrange)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
def do_pwd(self, line):
"""Prints the current working directory."""
print os.getcwd()
def do_cd(self, line):
"""Change working directory to specified path."""
path = line.strip().strip('"\'')
if not os.path.isdir(path):
print "error: specified path is not a directory"
return
os.chdir(path)
def do_quit(self, line):
"""Quits the program."""
if self.save_check():
return
return True
def help_EOF(self):
print "Typing {0} issues this command, which quits the program."\
.format(CMD_EOF_STRING)
def do_EOF(self, line):
"""Typing Ctrl-D issues this command, which quits the program."""
print '\r'
if self.save_check():
return
return True
def help_help(self):
print 'Prints a list of commands.'
print "Type 'help <topic>' for more details on each command."
def default(self, line):
command = line.split()[0]
print \
"'{0}' is not a checkergen command.".format(command),\
"Type 'help' for a list of commands"
diff --git a/src/core.py b/src/core.py
index 4f9f8e0..17840d7 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,1230 +1,1234 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgExp -- A checkergen experiment, describes how a projet is displayed.
CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import random
import itertools
from xml.dom import minidom
import pyglet
import graphics
-import signals
+import trigger
import eyetracking
from utils import *
CKG_FMT = 'ckg'
EXP_FMT = 'ckx'
LOG_FMT = 'log'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
MAX_EXPORT_FRAMES = 100000
PRERENDER_TO_TEXTURE = False
INT_HALF_PERIODS = True
EXPORT_FMTS = ['png']
EXPORT_DIR_SUFFIX = '-anim'
BLOCK_DIR_SUFFIX = '-blks'
FIX_POS = (0, 0)
FIX_RANGE = (20, 20)
FIX_PER = 350
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = {'name': 'untitled',
'fps': 60,
'res': (800, 600),
'bg': (127, 127, 127),
'export_fmt': 'png',
'pre': 0,
'post': 0,
'cross_cols': ((0, 0, 0), (255, 0, 0)),
'cross_times': ('Infinity', 1)}
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
export_fmt -- image format for animation to be exported as
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'export_fmt':
if value not in EXPORT_FMTS:
msg = 'image format not recognized or supported'
raise FileFormatError(msg)
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
vars_to_load = self.__class__.DEFAULTS.keys()
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
vars_to_save = self.__class__.DEFAULTS.keys()
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, fullscreen=False, logtime=False, logdur=False,
- sigser=False, sigpar=False, fpbs=0,
+ trigser=False, trigpar=False, fpst=0,
phototest=False, photoburst=False,
eyetrack=False, etuser=False, etvideo=None,
tryagain=0, trybreak=None, groupq=[], blk=None):
"""Displays the project animation on the screen.
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
- sigser -- send signals through serial port when each group is shown
+ trigser -- send triggers through serial port when each group is shown
- sigpar -- send signals through parallel port when each group is shown
+ trigpar -- send triggers through parallel port when each group is shown
- fpbs -- flips per board signal, i.e. number of shape color reversals
- (flips) that occur for a unique signal to be sent for that shape
+ fpst -- flips per shape trigger, i.e. number of shape color reversals
+ (flips) that occur for a unique trigger to be sent for that shape
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- Append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- Append a wait screen to the group queue every time
after this many groups have been appended to the queue
groupq -- queue of groups to be displayed, defaults to order of
groups in project (i.e. groups[0] first, etc.)
blk -- experimental block where logged variables are saved (i.e.
fail_idlist and time information)
"""
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if phototest:
test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Set-up groups and variables that control their display
if groupq == []:
groupq = list(self.groups)
n = -1
flipped = 0
flip_id = -1
groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Initialize ports
- if sigser:
- if not signals.available['serial']:
+ if trigser:
+ if not trigger.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
- if sigpar:
- if not signals.available['parallel']:
+ if trigpar:
+ if not trigger.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
- signals.init(sigser, sigpar)
+ trigger.init(trigser, trigpar)
# Initialize eyetracking
if eyetrack:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if trybreak == None:
trybreak = len(self.groups)
fixated = False
old_fixated = False
tracked = False
old_tracked = False
cur_fix_fail = False
trycount = 0
fail_idlist = []
eyetracking.select_source(etuser, etvideo)
eyetracking.start()
# Stretch to fit screen only if project res does not equal screen res
scaling = False
if fullscreen:
window = pyglet.window.Window(fullscreen=True, visible=False)
if (window.width, window.height) != self.res:
scaling = True
else:
window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
keystates = pyglet.window.key.KeyStateHandler()
window.push_handlers(keystates)
# Create framebuffer object for drawing unscaled scene
if scaling:
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
fbo.end_render()
# Clear window and make visible
window.switch_to()
graphics.set_clear_color(self.bg)
window.clear()
window.set_visible()
# Initialize logging variables
if logtime:
timestamps = []
- sigstamps = []
+ trigstamps = []
timer = Timer()
timer.start()
if logdur:
durstamps = []
dur = Timer()
dur.start()
# Main loop
while not window.has_exit and count < disp_end:
# Clear canvas
if scaling:
fbo.start_render()
fbo.clear()
else:
window.clear()
# Assume no change to group visibility
flipped = 0
- signals.set_null()
# Manage groups when they are on_screen
if groups_visible:
# Check whether group changes in visibility
if n >= 0 and groupq[n].visible != groupq[n].old_visible:
flip_id = self.groups.index(groupq[n])
if groupq[n].visible:
flipped = 1
elif groupq[n].old_visible:
flipped = -1
# Get next group from queue
if n < 0 or groupq[n].over:
- # Send special signal if waitscreen ends
+ # Send special trigger if waitscreen ends
if isinstance(groupq[n], CkgWaitScreen):
- signals.set_user_start()
+ trigger.CUR_STATE['user'] = 1
n += 1
if n >= len(groupq):
groups_visible = False
+ trigger.CUR_STATE['user'] = 0
else:
groupq[n].reset()
if eyetrack:
cur_fix_fail = False
if groupq[n].visible:
flip_id = self.groups.index(groupq[n])
flipped = 1
+ # Send special trigger when waitscreen ends
+ if isinstance(groupq[n], CkgWaitScreen):
+ trigger.CUR_STATE['user'] = 0
# Draw and then update group
if n >= 0:
groupq[n].draw(photoburst=photoburst)
groupq[n].update(fps=self.fps,
- fpbs=fpbs,
+ fpst=fpst,
keystates=keystates)
- # Send signals upon group visibility change
+ # Send triggers upon group visibility change
if flipped == 1:
- signals.set_group_start(flip_id)
+ trigger.CUR_STATE['group'] = 1
# Draw test rectangle
if phototest:
test_rect.draw()
elif flipped == -1:
- signals.set_group_stop(flip_id)
+ trigger.CUR_STATE['group'] = 0
if eyetrack:
- # First check if eye is being tracked and send signals
+ # First check if eye is being tracked and send trigger
old_tracked = tracked
tracked = eyetracking.is_tracked()
if tracked:
if not old_tracked:
- # Send signal if eye starts being tracked
- signals.set_track_start()
+ # Send trigger if eye starts being tracked
+ trigger.set_track_start()
else:
if old_tracked:
- # Send signal if eye stops being tracked
- signals.set_track_stop()
+ # Send trigger if eye stops being tracked
+ trigger.set_track_stop()
# Next check for fixation
old_fixated = fixated
fixated = eyetracking.is_fixated(FIX_POS, FIX_RANGE, FIX_PER)
if fixated:
# Draw normal cross color if fixating
fix_crosses[0].draw()
if not old_fixated:
- # Send signal if fixation starts
- signals.set_fix_start()
+ # Send trigger if fixation starts
+ trigger.set_fix_start()
else:
# Draw alternative cross color if not fixating
fix_crosses[1].draw()
if old_fixated:
- # Send signal if fixation stops
- signals.set_fix_stop()
+ # Send trigger if fixation stops
+ trigger.set_fix_stop()
# Take note of which groups in which fixation failed
if not cur_fix_fail and groupq[n].visible and\
(tracked and not fixated):
cur_fix_fail = True
# Append failed group to group queue
if trycount < tryagain:
# Insert waitscreen every trybreak failed groups
if trybreak > 0:
if len(fail_idlist) % trybreak == 0:
groupq.append(CkgWaitScreen())
groupq.append(groupq[n])
groups_stop += groupq[n].duration() * self.fps
disp_end += groupq[n].duration() * self.fps
trycount += 1
# Maintain list of failed IDs
fail_idlist.append(self.groups.index(groupq[n]))
# Change cross color based on time if eyetracking is not enabled
if not eyetrack:
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Increment count and set whether groups should be shown
if not isinstance(groupq[n], CkgWaitScreen):
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
# Blit canvas to screen if necessary
if scaling:
fbo.end_render()
window.switch_to()
canvas.blit(0, 0)
window.dispatch_events()
window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to lists
if logtime:
timestamps.append(timer.elapsed())
if logdur:
durstamps.append(dur.restart())
- # Send signals ASAP after flip
- signals.send(sigser, sigpar)
+ # Send trigger ASAP after flip
+ trigger.send(trigser, trigpar)
- # Log when signals are sent
+ # Log when trigger are sent
if logtime:
- if flipped != 0 and (sigser or sigpar):
- sigstamps.append(signals.STATE)
+ if flipped != 0 and (trigser or trigpar):
+ trigstamps.append(trigger.STATE)
else:
- sigstamps.append('')
+ trigstamps.append('')
# Clean up
if eyetrack:
eyetracking.stop()
window.close()
if scaling:
fbo.delete()
del canvas
- signals.quit(sigser, sigpar)
+ trigger.quit(trigser, trigpar)
# Store variables in block object
if blk != None:
if logtime:
blk.timestamps = timestamps
- blk.sigstamps = sigstamps
+ blk.trigstamps = trigstamps
if logdur:
blk.durstamps = durstamps
if eyetrack and len(fail_idlist) > 0:
blk.add_idlist = fail_idlist[:tryagain]
blk.fail_idlist = fail_idlist[tryagain:]
def export(self, export_dir, export_duration, groupq=[],
export_fmt=None, folder=True, force=False):
if not os.path.isdir(export_dir):
msg = 'export path is not a directory'
raise IOError(msg)
if export_fmt == None:
export_fmt = self.export_fmt
# Set-up groups and variables that control their display
if groupq == []:
groupq = list(self.groups)
n = -1
groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Limit export duration to display duration
frames = export_duration * self.fps
frames = min(frames, disp_end)
# Warn user if a lot of frames will be exported
if frames > MAX_EXPORT_FRAMES and not force:
msg = 'very large number ({0}) of frames to be exported'.\
format(frames)
raise FrameOverflowError(msg)
# Create folder to store images if necessary
if folder:
export_dir = os.path.join(export_dir,
self.name + EXPORT_DIR_SUFFIX)
if not os.path.isdir(export_dir):
os.mkdir(export_dir)
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Set up canvas and framebuffer object
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
# Main loop
while count < frames:
fbo.clear()
if groups_visible:
# Get next group from queue
if n < 0 or groupq[n].over:
n += 1
if n >= len(groupq):
groups_visible = False
else:
groupq[n].reset()
# Draw and then update group
if n >= 0:
groupq[n].draw()
- groupq[n].update(fps=self.fps, fpbs=0)
+ groupq[n].update(fps=self.fps, fpst=0)
# Draw fixation cross based on current count
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Save current frame to file
savepath = \
os.path.join(export_dir,
'{0}{2}.{1}'.
format(self.name, export_fmt,
repr(count).zfill(numdigits(frames-1))))
canvas.save(savepath)
# Increment count and set whether groups should be shown
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
fbo.delete()
class CkgExp:
DEFAULTS = {'name': None, 'proj' : None,
'trials': 1, 'sequences': None,
'flags': '--fullscreen --logtime --logdur'}
def __init__(self, **keywords):
"""Create a checkergen experiment, which specifies how a project
is to be displayed.
path -- if specified, ignore other arguments and load project
from path
name -- name of the experiment
proj -- CkgProj that the experiment is to be created for
trials -- number of times the selected sequence of display groups
will be shown in one block
sequences -- list of possible display group id sequences, from which
one sequence will be randomly selected for display in a block,
defaults to reduced latin square with side length equal to the number
of display groups in the supplied CkgProj
flags -- string passed to the display command as flags
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
if self.name == None and self.proj != None:
self.name = self.proj.name
if self.sequences == None:
if self.proj == None:
msg = "either project or sequences have to be specified"
raise ValueError(msg)
else:
self.gen_latin_square(len(self.proj.groups))
del self.proj
def gen_latin_square(self, n):
"""Set experiment sequences as a cyclic reduced latin square."""
sequence = range(n)
self.sequences = [[sequence[i - j] for i in range(n)]
for j in range(n, 0, -1)]
def random_blk(self, name):
"""Choose random sequence, create block from it and return."""
sequence = random.choice(self.sequences)
blk = CkgBlk(name=name,
flags=self.flags,
trials=self.trials,
sequence=sequence)
return blk
def save(self, path=None):
"""Saves experiment to specified path in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, EXP_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(EXP_FMT):
path = '{0}.{1}'.format(path, EXP_FMT)
with open(path, 'wb') as expfile:
expwriter = csv.writer(expfile, dialect='excel-tab')
expwriter.writerow(['checkergen experiment file'])
expwriter.writerow(['flags:', self.flags])
expwriter.writerow(['trials:', self.trials])
expwriter.writerow(['sequences:'])
for sequence in self.sequences:
expwriter.writerow(sequence)
def load(self, path):
"""Loads experiment from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, EXP_FMT)
elif ext != '.{0}'.format(EXP_FMT):
msg = "path lacks '.{0}' extension".format(EXP_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
self.sequences = []
with open(path, 'rb') as expfile:
expreader = csv.reader(expfile, dialect='excel-tab')
for n, row in enumerate(expreader):
if n == 1:
self.flags = row[1]
elif n == 2:
self.trials = int(row[1])
elif n > 3:
sequence = [int(i) for i in row]
self.sequences.append(sequence)
class CkgBlk:
def __init__(self, name, flags, trials, sequence):
"""Creates an experimental block."""
self.name = name
self.flags = flags
self.trials = trials
self.sequence = sequence
self.add_idlist = None
self.fail_idlist = None
self.timestamps = []
self.durstamps = []
- self.sigstamps = []
+ self.trigstamps = []
def idlist(self):
"""Generate idlist from sequence and return it."""
idlist = ([-1] + self.sequence) * self.trials
return idlist
def write_log(self, path=None):
"""Write a log file for the experimental block in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, LOG_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(LOG_FMT):
path = '{0}.{1}'.format(path, LOG_FMT)
with open(path, 'wb') as blkfile:
blkwriter = csv.writer(blkfile, dialect='excel-tab')
blkwriter.writerow(['checkergen log file'])
blkwriter.writerow(['flags:', self.flags])
blkwriter.writerow(['trials:', self.trials])
blkwriter.writerow(['sequence:'] + self.sequence)
if self.add_idlist != None:
blkwriter.writerow(['groups appended:'])
rowlist = grouper(len(self.sequence), self.add_idlist, '')
for row in rowlist:
blkwriter.writerow(row)
if self.fail_idlist != None:
blkwriter.writerow(['groups failed (not appended):'])
rowlist = grouper(len(self.sequence), self.fail_idlist, '')
for row in rowlist:
blkwriter.writerow(row)
- stamps = [self.timestamps, self.durstamps, self.sigstamps]
+ stamps = [self.timestamps, self.durstamps, self.trigstamps]
if len(max(stamps)) > 0:
for l in stamps:
if len(l) == 0:
l = [''] * len(max(stamps))
blkwriter.writerow(['timestamps', 'durations', 'triggers'])
for row in zip(*stamps):
blkwriter.writerow(row)
class CkgDisplayGroup:
DEFAULTS = {'pre': 0, 'disp': 'Infinity', 'post': 0}
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets internal count and all contained shapes."""
self._count = 0
self._start = self.pre
self._stop = self.pre + self.disp
self._end = self.pre + self.disp + self.post
self.over = False
self.old_visible = False
if self._start == 0 and self._stop > 0:
self.visible = True
else:
self.visible = False
if self._end == 0:
self.over = True
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, lazy=False, photoburst=False):
"""Draws all contained shapes during the appropriate interval."""
if self.visible:
for shape in self.shapes:
if lazy:
shape.lazydraw()
else:
shape.draw(photoburst=photoburst)
def update(self, **keywords):
"""Increments internal count, makes group visible when appropriate.
fps -- refresh rate of the display in frames per second
- fpbs -- flips per board signal, i.e. number of shape color reversals
- (flips) that occur for a unique signal to be sent for that shape
+ fpst -- flips per shape trigger, i.e. number of shape color reversals
+ (flips) that occur for a unique trigger to be sent for that shape
"""
fps = keywords['fps']
- fpbs = keywords['fpbs']
+ fpst = keywords['fpst']
if self.visible:
# Set triggers to be sent
- if fpbs > 0:
+ if fpst > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
- if self._flip_count[n] >= fpbs:
- signals.set_board_flip(n)
+ if self._flip_count[n] >= fpst:
+ trigger.CUR_STATE['shape'] = 1
+ trigger.CUR_STATE['sid'] = n
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(fps)
# Increment count and set flags for the next frame
self._count += 1
self.old_visible = self.visible
if (self._start * fps) <= self._count < (self._stop * fps):
self.visible = True
else:
self.visible = False
if self._count >= (self._end * fps):
self.over = True
else:
self.over = False
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.visible = False
self.old_visible = False
self.steps_done = 0
self.over = False
def draw(self, **keywords):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, **keywords):
- """Checks for keypress, sends signal upon end."""
+ """Checks for keypress, sends trigger upon end."""
keystates = keywords['keystates']
if max([keystates[key] for key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
if self.steps_done == self.num_steps:
self.over = True
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = {'dims': (5, 5),
'init_unit': (30, 30), 'end_unit': (50, 50),
'position': (0, 0), 'anchor': 'bottomleft',
'cols': ((0, 0, 0), (255, 255, 255)),
'freq': 1, 'phase': 0}
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
if INT_HALF_PERIODS:
frames_per_half_period = round(fps / (self.freq * 2))
degs_per_frame = 180 / to_decimal(frames_per_half_period)
else:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
if PRERENDER_TO_TEXTURE:
init_pos = [(1 - a)* s/to_decimal(2) for s, a in
zip(self._size, graphics.locations[self.anchor])]
else:
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
anchor=self.anchor)
cur_unit_rect.col = self.cols[(i + j) % 2]
cur_unit_rect.add_to_batch(self._batches[0])
cur_unit_rect.col = self.cols[(i + j + 1) % 2]
cur_unit_rect.add_to_batch(self._batches[1])
# Increase x values
cur_unit_pos[0] += \
graphics.locations[self.anchor][0] * cur_unit[0]
cur_unit[0] += unit_grad[0]
# Reset x values
cur_unit_pos[0] = init_pos[0]
cur_unit[0] = init_unit[0]
# Increase y values
cur_unit_pos[1] += \
graphics.locations[self.anchor][1] * cur_unit[1]
cur_unit[1] += unit_grad[1]
if PRERENDER_TO_TEXTURE:
# Create textures
int_size = [int(round(s)) for s in self._size]
self._prerenders =\
[pyglet.image.Texture.create(*int_size) for n in range(2)]
# Set up framebuffer
fbo = graphics.Framebuffer()
for n in range(2):
fbo.attach_texture(self._prerenders[n])
# Draw batch to texture
fbo.start_render()
self._batches[n].draw()
fbo.end_render()
# Anchor textures for correct blitting later
self._prerenders[n].anchor_x, self._prerenders[n].anchor_y =\
[int(round((1 - a)* s/to_decimal(2))) for s, a in
zip(self._size, graphics.locations[self.anchor])]
fbo.delete()
# Delete batches since they won't be used
del self._batches
self._computed = True
def draw(self, photoburst=False, always_compute=False):
"""Draws appropriate prerender depending on current phase.
photoburst -- draw first color for only one frame for testing purposes
always_compute -- recompute what the checkerboard should look like
every frame
"""
if not self._computed or always_compute:
self.compute()
self._cur_phase %= 360
n = int(self._cur_phase // 180)
if photoburst and n == 0 and not self.flipped:
n = 1
if PRERENDER_TO_TEXTURE:
self._prerenders[n].blit(*self.position)
else:
self._batches[n].draw()
def lazydraw(self):
"""Only draws on color reversal."""
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if (cur_n != prev_n) or self._first_draw:
self.draw()
if self._first_draw:
self._first_draw = False
diff --git a/src/signals.py b/src/signals.py
deleted file mode 100644
index c972759..0000000
--- a/src/signals.py
+++ /dev/null
@@ -1,138 +0,0 @@
-"""Module for signalling upon stimuli appearance using the serial or
-parallel ports."""
-
-SERPORT = None
-PARPORT = None
-
-STATE = None
-OLD_STATE = None
-
-# Arranged in order of decreasing priority
-USER_START = 128 # 0b10000000
-FIX_START = 99 # 0b01100011
-TRACK_START = 98 # 0b01100010
-TRACK_STOP = 89 # 0b01011001
-FIX_STOP = 88 # 0b01011000
-GROUP_START = 60 # 0b00111100
-GROUP_STOP = 40 # 0b00101000
-BOARD_FLIP = 10 # 0b00001010
-
-available = {'serial': False, 'parallel': False}
-
-try:
- import serial
-
- try:
- test_port = serial.Serial(0)
- test_port.close()
- del test_port
- available['serial'] = True
- except serial.serialutil.SerialException:
- pass
-except ImportError:
- pass
-
-try:
- import parallel
- try:
- test_port = parallel.Parallel()
- del test_port
- available['parallel'] = True
- except:
- pass
-except ImportError:
- pass
-
-if available['serial']:
- def ser_init():
- global SERPORT
- SERPORT = serial.Serial(0)
-
- def ser_send():
- global SERPORT
- global STATE
- if STATE != None:
- SERPORT.write(str(STATE))
-
- def ser_quit():
- global SERPORT
- SERPORT.close()
- SERPORT = None
-
-if available['parallel']:
- def par_init():
- global PARPORT
- PARPORT = parallel.Parallel()
- PARPORT.setData(0)
-
- def par_send():
- global PARPORT
- global STATE
- if STATE != None:
- PARPORT.setData(STATE)
- else:
- PARPORT.setData(0)
-
- def par_quit():
- global PARPORT
- PARPORT.setData(0)
- PARPORT = None
-
-def init(sigser, sigpar):
- global STATE
- global OLD_STATE
- STATE = None
- OLD_STATE = None
- if sigser:
- ser_init()
- if sigpar:
- par_init()
-
-def set_state(NEW_STATE):
- global STATE
- global OLD_STATE
- if NEW_STATE == None or NEW_STATE >= STATE:
- OLD_STATE = STATE
- STATE = NEW_STATE
-
-def set_board_flip(board_id):
- set_state(BOARD_FLIP + board_id)
-
-def set_group_start(group_id):
- set_state(GROUP_START + group_id)
-
-def set_group_stop(group_id):
- set_state(GROUP_STOP + group_id)
-
-def set_user_start():
- set_state(USER_START)
-
-def set_fix_start():
- set_state(FIX_START)
-
-def set_fix_stop():
- set_state(FIX_STOP)
-
-def set_track_start():
- set_state(TRACK_START)
-
-def set_track_stop():
- set_state(TRACK_STOP)
-
-def set_null():
- set_state(None)
-
-def send(sigser, sigpar):
- if sigser:
- ser_send()
- if STATE != OLD_STATE:
- if sigpar:
- par_send()
-
-def quit(sigser, sigpar):
- set_null()
- if sigser:
- ser_quit()
- if sigpar:
- par_quit()
-
diff --git a/src/trigger.py b/src/trigger.py
new file mode 100644
index 0000000..e489603
--- /dev/null
+++ b/src/trigger.py
@@ -0,0 +1,105 @@
+"""Module for sending triggers upon various events through the serial or
+parallel ports."""
+
+NULL_STATE = {'user': 0, 'tracking': 0, 'fixation': 0,
+ 'group': 0, 'shape': 0, 'gid': 0, 'sid': 0}
+CUR_STATE = dict(NULL_STATE)
+PREV_STATE = dict(NULL_STATE)
+
+SERPORT = None
+PARPORT = None
+
+available = {'serial': False, 'parallel': False}
+
+try:
+ import serial
+
+ try:
+ test_port = serial.Serial(0)
+ test_port.close()
+ del test_port
+ available['serial'] = True
+ except serial.serialutil.SerialException:
+ pass
+except ImportError:
+ pass
+
+try:
+ import parallel
+ try:
+ test_port = parallel.Parallel()
+ del test_port
+ available['parallel'] = True
+ except:
+ pass
+except ImportError:
+ pass
+
+if available['serial']:
+ def ser_init():
+ global SERPORT
+ SERPORT = serial.Serial(0)
+
+ def ser_send(statebyte):
+ global SERPORT
+ SERPORT.write(statebyte)
+
+ def ser_quit():
+ global SERPORT
+ SERPORT.close()
+ SERPORT = None
+
+if available['parallel']:
+ def par_init():
+ global PARPORT
+ PARPORT = parallel.Parallel()
+ PARPORT.setData(0)
+
+ def par_send(statebyte):
+ global PARPORT
+ PARPORT.setData(statebyte)
+
+ def par_quit():
+ global PARPORT
+ PARPORT.setData(0)
+ PARPORT = None
+
+def init(trigser, trigpar):
+ global CUR_STATE
+ global PREV_STATE
+ CUR_STATE = NULL_STATE
+ PREV_STATE = NULL_STATE
+ if trigser:
+ ser_init()
+ if trigpar:
+ par_init()
+
+def set_state(fieldname, value):
+ global CUR_STATE
+ global PREV_STATE
+ PREV_STATE = CUR_STATE
+ CUR_STATE[fieldname] = value
+
+def set_null():
+ set_state(NULL_STATE)
+
+def send(trigser, trigpar):
+ statebyte = int(''.join([str(CUR_STATE[name]) for
+ name in ['user', 'tracking',
+ 'fixation', 'group', 'shape']]), 2)
+ if CUR_STATE['group'] != PREV_STATE['group']:
+ statebyte += CUR_STATE['gid']
+ elif CUR_STATE['shape'] > PREV_STATE['shape']:
+ statebyte += CUR_STATE['sid']
+ if trigser:
+ ser_send(statebyte)
+ if CUR_STATE != PREV_STATE:
+ if trigpar:
+ par_send(statebyte)
+
+def quit(trigser, trigpar):
+ set_null()
+ if trigser:
+ ser_quit()
+ if trigpar:
+ par_quit()
|
ztangent/checkergen
|
e0d089d85da01c90fa197dcd5e5b770f1c5a1b35
|
Fixed order of waitscreen append, differentiate between failed groups and added groups.
|
diff --git a/src/core.py b/src/core.py
index 0042753..4f9f8e0 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,1223 +1,1230 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgExp -- A checkergen experiment, describes how a projet is displayed.
CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import random
import itertools
from xml.dom import minidom
import pyglet
import graphics
import signals
import eyetracking
from utils import *
CKG_FMT = 'ckg'
EXP_FMT = 'ckx'
LOG_FMT = 'log'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
MAX_EXPORT_FRAMES = 100000
PRERENDER_TO_TEXTURE = False
INT_HALF_PERIODS = True
EXPORT_FMTS = ['png']
EXPORT_DIR_SUFFIX = '-anim'
BLOCK_DIR_SUFFIX = '-blks'
FIX_POS = (0, 0)
FIX_RANGE = (20, 20)
FIX_PER = 350
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = {'name': 'untitled',
'fps': 60,
'res': (800, 600),
'bg': (127, 127, 127),
'export_fmt': 'png',
'pre': 0,
'post': 0,
'cross_cols': ((0, 0, 0), (255, 0, 0)),
'cross_times': ('Infinity', 1)}
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
export_fmt -- image format for animation to be exported as
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'export_fmt':
if value not in EXPORT_FMTS:
msg = 'image format not recognized or supported'
raise FileFormatError(msg)
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
vars_to_load = self.__class__.DEFAULTS.keys()
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
vars_to_save = self.__class__.DEFAULTS.keys()
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, fullscreen=False, logtime=False, logdur=False,
sigser=False, sigpar=False, fpbs=0,
phototest=False, photoburst=False,
eyetrack=False, etuser=False, etvideo=None,
tryagain=0, trybreak=None, groupq=[], blk=None):
"""Displays the project animation on the screen.
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
sigser -- send signals through serial port when each group is shown
sigpar -- send signals through parallel port when each group is shown
fpbs -- flips per board signal, i.e. number of shape color reversals
(flips) that occur for a unique signal to be sent for that shape
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- Append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- Append a wait screen to the group queue every time
after this many groups have been appended to the queue
groupq -- queue of groups to be displayed, defaults to order of
groups in project (i.e. groups[0] first, etc.)
blk -- experimental block where logged variables are saved (i.e.
fail_idlist and time information)
"""
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if phototest:
test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Set-up groups and variables that control their display
if groupq == []:
groupq = list(self.groups)
n = -1
flipped = 0
flip_id = -1
groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Initialize ports
if sigser:
if not signals.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if sigpar:
if not signals.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
signals.init(sigser, sigpar)
# Initialize eyetracking
if eyetrack:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if trybreak == None:
trybreak = len(self.groups)
fixated = False
old_fixated = False
tracked = False
old_tracked = False
cur_fix_fail = False
+ trycount = 0
fail_idlist = []
eyetracking.select_source(etuser, etvideo)
eyetracking.start()
# Stretch to fit screen only if project res does not equal screen res
scaling = False
if fullscreen:
window = pyglet.window.Window(fullscreen=True, visible=False)
if (window.width, window.height) != self.res:
scaling = True
else:
window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
keystates = pyglet.window.key.KeyStateHandler()
window.push_handlers(keystates)
# Create framebuffer object for drawing unscaled scene
if scaling:
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
fbo.end_render()
# Clear window and make visible
window.switch_to()
graphics.set_clear_color(self.bg)
window.clear()
window.set_visible()
# Initialize logging variables
if logtime:
timestamps = []
sigstamps = []
timer = Timer()
timer.start()
if logdur:
durstamps = []
dur = Timer()
dur.start()
# Main loop
while not window.has_exit and count < disp_end:
# Clear canvas
if scaling:
fbo.start_render()
fbo.clear()
else:
window.clear()
# Assume no change to group visibility
flipped = 0
signals.set_null()
# Manage groups when they are on_screen
if groups_visible:
# Check whether group changes in visibility
if n >= 0 and groupq[n].visible != groupq[n].old_visible:
flip_id = self.groups.index(groupq[n])
if groupq[n].visible:
flipped = 1
elif groupq[n].old_visible:
flipped = -1
# Get next group from queue
if n < 0 or groupq[n].over:
# Send special signal if waitscreen ends
if isinstance(groupq[n], CkgWaitScreen):
signals.set_user_start()
n += 1
if n >= len(groupq):
groups_visible = False
else:
groupq[n].reset()
if eyetrack:
cur_fix_fail = False
if groupq[n].visible:
flip_id = self.groups.index(groupq[n])
flipped = 1
# Draw and then update group
if n >= 0:
groupq[n].draw(photoburst=photoburst)
groupq[n].update(fps=self.fps,
fpbs=fpbs,
keystates=keystates)
# Send signals upon group visibility change
if flipped == 1:
signals.set_group_start(flip_id)
# Draw test rectangle
if phototest:
test_rect.draw()
elif flipped == -1:
signals.set_group_stop(flip_id)
if eyetrack:
# First check if eye is being tracked and send signals
old_tracked = tracked
tracked = eyetracking.is_tracked()
if tracked:
if not old_tracked:
# Send signal if eye starts being tracked
signals.set_track_start()
else:
if old_tracked:
# Send signal if eye stops being tracked
signals.set_track_stop()
# Next check for fixation
old_fixated = fixated
fixated = eyetracking.is_fixated(FIX_POS, FIX_RANGE, FIX_PER)
if fixated:
# Draw normal cross color if fixating
fix_crosses[0].draw()
if not old_fixated:
# Send signal if fixation starts
signals.set_fix_start()
else:
# Draw alternative cross color if not fixating
fix_crosses[1].draw()
if old_fixated:
# Send signal if fixation stops
signals.set_fix_stop()
# Take note of which groups in which fixation failed
if not cur_fix_fail and groupq[n].visible and\
(tracked and not fixated):
cur_fix_fail = True
- if len(fail_idlist) == 0 and trybreak > 0:
- groupq.append(CkgWaitScreen(res=self.res))
- fail_idlist.append(self.groups.index(groupq[n]))
# Append failed group to group queue
- if tryagain > 0:
- groupq.append(groupq[n])
- groups_stop += groupq[n].duration() * self.fps
- disp_end += groupq[n].duration() * self.fps
+ if trycount < tryagain:
# Insert waitscreen every trybreak failed groups
if trybreak > 0:
if len(fail_idlist) % trybreak == 0:
groupq.append(CkgWaitScreen())
- tryagain -= 1
+ groupq.append(groupq[n])
+ groups_stop += groupq[n].duration() * self.fps
+ disp_end += groupq[n].duration() * self.fps
+ trycount += 1
+ # Maintain list of failed IDs
+ fail_idlist.append(self.groups.index(groupq[n]))
# Change cross color based on time if eyetracking is not enabled
if not eyetrack:
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Increment count and set whether groups should be shown
if not isinstance(groupq[n], CkgWaitScreen):
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
# Blit canvas to screen if necessary
if scaling:
fbo.end_render()
window.switch_to()
canvas.blit(0, 0)
window.dispatch_events()
window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to lists
if logtime:
timestamps.append(timer.elapsed())
if logdur:
durstamps.append(dur.restart())
# Send signals ASAP after flip
signals.send(sigser, sigpar)
# Log when signals are sent
if logtime:
if flipped != 0 and (sigser or sigpar):
sigstamps.append(signals.STATE)
else:
sigstamps.append('')
# Clean up
if eyetrack:
eyetracking.stop()
window.close()
if scaling:
fbo.delete()
del canvas
signals.quit(sigser, sigpar)
# Store variables in block object
if blk != None:
if logtime:
blk.timestamps = timestamps
blk.sigstamps = sigstamps
if logdur:
blk.durstamps = durstamps
if eyetrack and len(fail_idlist) > 0:
- blk.fail_idlist = fail_idlist
+ blk.add_idlist = fail_idlist[:tryagain]
+ blk.fail_idlist = fail_idlist[tryagain:]
def export(self, export_dir, export_duration, groupq=[],
export_fmt=None, folder=True, force=False):
if not os.path.isdir(export_dir):
msg = 'export path is not a directory'
raise IOError(msg)
if export_fmt == None:
export_fmt = self.export_fmt
# Set-up groups and variables that control their display
if groupq == []:
groupq = list(self.groups)
n = -1
groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Limit export duration to display duration
frames = export_duration * self.fps
frames = min(frames, disp_end)
# Warn user if a lot of frames will be exported
if frames > MAX_EXPORT_FRAMES and not force:
msg = 'very large number ({0}) of frames to be exported'.\
format(frames)
raise FrameOverflowError(msg)
# Create folder to store images if necessary
if folder:
export_dir = os.path.join(export_dir,
self.name + EXPORT_DIR_SUFFIX)
if not os.path.isdir(export_dir):
os.mkdir(export_dir)
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Set up canvas and framebuffer object
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
# Main loop
while count < frames:
fbo.clear()
if groups_visible:
# Get next group from queue
if n < 0 or groupq[n].over:
n += 1
if n >= len(groupq):
groups_visible = False
else:
groupq[n].reset()
# Draw and then update group
if n >= 0:
groupq[n].draw()
groupq[n].update(fps=self.fps, fpbs=0)
# Draw fixation cross based on current count
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Save current frame to file
savepath = \
os.path.join(export_dir,
'{0}{2}.{1}'.
format(self.name, export_fmt,
repr(count).zfill(numdigits(frames-1))))
canvas.save(savepath)
# Increment count and set whether groups should be shown
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
fbo.delete()
class CkgExp:
DEFAULTS = {'name': None, 'proj' : None,
'trials': 1, 'sequences': None,
'flags': '--fullscreen --logtime --logdur'}
def __init__(self, **keywords):
"""Create a checkergen experiment, which specifies how a project
is to be displayed.
path -- if specified, ignore other arguments and load project
from path
name -- name of the experiment
proj -- CkgProj that the experiment is to be created for
trials -- number of times the selected sequence of display groups
will be shown in one block
sequences -- list of possible display group id sequences, from which
one sequence will be randomly selected for display in a block,
defaults to reduced latin square with side length equal to the number
of display groups in the supplied CkgProj
flags -- string passed to the display command as flags
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
if self.name == None and self.proj != None:
self.name = self.proj.name
if self.sequences == None:
if self.proj == None:
msg = "either project or sequences have to be specified"
raise ValueError(msg)
else:
self.gen_latin_square(len(self.proj.groups))
del self.proj
def gen_latin_square(self, n):
"""Set experiment sequences as a cyclic reduced latin square."""
sequence = range(n)
self.sequences = [[sequence[i - j] for i in range(n)]
for j in range(n, 0, -1)]
def random_blk(self, name):
"""Choose random sequence, create block from it and return."""
sequence = random.choice(self.sequences)
blk = CkgBlk(name=name,
flags=self.flags,
trials=self.trials,
sequence=sequence)
return blk
def save(self, path=None):
"""Saves experiment to specified path in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, EXP_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(EXP_FMT):
path = '{0}.{1}'.format(path, EXP_FMT)
with open(path, 'wb') as expfile:
expwriter = csv.writer(expfile, dialect='excel-tab')
expwriter.writerow(['checkergen experiment file'])
expwriter.writerow(['flags:', self.flags])
expwriter.writerow(['trials:', self.trials])
expwriter.writerow(['sequences:'])
for sequence in self.sequences:
expwriter.writerow(sequence)
def load(self, path):
"""Loads experiment from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, EXP_FMT)
elif ext != '.{0}'.format(EXP_FMT):
msg = "path lacks '.{0}' extension".format(EXP_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
self.sequences = []
with open(path, 'rb') as expfile:
expreader = csv.reader(expfile, dialect='excel-tab')
for n, row in enumerate(expreader):
if n == 1:
self.flags = row[1]
elif n == 2:
self.trials = int(row[1])
elif n > 3:
sequence = [int(i) for i in row]
self.sequences.append(sequence)
class CkgBlk:
def __init__(self, name, flags, trials, sequence):
"""Creates an experimental block."""
self.name = name
self.flags = flags
self.trials = trials
self.sequence = sequence
+ self.add_idlist = None
self.fail_idlist = None
self.timestamps = []
self.durstamps = []
self.sigstamps = []
def idlist(self):
"""Generate idlist from sequence and return it."""
idlist = ([-1] + self.sequence) * self.trials
return idlist
def write_log(self, path=None):
"""Write a log file for the experimental block in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, LOG_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(LOG_FMT):
path = '{0}.{1}'.format(path, LOG_FMT)
with open(path, 'wb') as blkfile:
blkwriter = csv.writer(blkfile, dialect='excel-tab')
blkwriter.writerow(['checkergen log file'])
blkwriter.writerow(['flags:', self.flags])
blkwriter.writerow(['trials:', self.trials])
blkwriter.writerow(['sequence:'] + self.sequence)
+ if self.add_idlist != None:
+ blkwriter.writerow(['groups appended:'])
+ rowlist = grouper(len(self.sequence), self.add_idlist, '')
+ for row in rowlist:
+ blkwriter.writerow(row)
if self.fail_idlist != None:
- blkwriter.writerow(['groups added:'])
+ blkwriter.writerow(['groups failed (not appended):'])
rowlist = grouper(len(self.sequence), self.fail_idlist, '')
for row in rowlist:
blkwriter.writerow(row)
stamps = [self.timestamps, self.durstamps, self.sigstamps]
if len(max(stamps)) > 0:
for l in stamps:
if len(l) == 0:
l = [''] * len(max(stamps))
blkwriter.writerow(['timestamps', 'durations', 'triggers'])
for row in zip(*stamps):
blkwriter.writerow(row)
class CkgDisplayGroup:
DEFAULTS = {'pre': 0, 'disp': 'Infinity', 'post': 0}
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets internal count and all contained shapes."""
self._count = 0
self._start = self.pre
self._stop = self.pre + self.disp
self._end = self.pre + self.disp + self.post
self.over = False
self.old_visible = False
if self._start == 0 and self._stop > 0:
self.visible = True
else:
self.visible = False
if self._end == 0:
self.over = True
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, lazy=False, photoburst=False):
"""Draws all contained shapes during the appropriate interval."""
if self.visible:
for shape in self.shapes:
if lazy:
shape.lazydraw()
else:
shape.draw(photoburst=photoburst)
def update(self, **keywords):
"""Increments internal count, makes group visible when appropriate.
fps -- refresh rate of the display in frames per second
fpbs -- flips per board signal, i.e. number of shape color reversals
(flips) that occur for a unique signal to be sent for that shape
"""
fps = keywords['fps']
fpbs = keywords['fpbs']
if self.visible:
# Set triggers to be sent
if fpbs > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= fpbs:
signals.set_board_flip(n)
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(fps)
# Increment count and set flags for the next frame
self._count += 1
self.old_visible = self.visible
if (self._start * fps) <= self._count < (self._stop * fps):
self.visible = True
else:
self.visible = False
if self._count >= (self._end * fps):
self.over = True
else:
self.over = False
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.visible = False
self.old_visible = False
self.steps_done = 0
self.over = False
def draw(self, **keywords):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, **keywords):
"""Checks for keypress, sends signal upon end."""
keystates = keywords['keystates']
if max([keystates[key] for key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
if self.steps_done == self.num_steps:
self.over = True
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = {'dims': (5, 5),
'init_unit': (30, 30), 'end_unit': (50, 50),
'position': (0, 0), 'anchor': 'bottomleft',
'cols': ((0, 0, 0), (255, 255, 255)),
'freq': 1, 'phase': 0}
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
if INT_HALF_PERIODS:
frames_per_half_period = round(fps / (self.freq * 2))
degs_per_frame = 180 / to_decimal(frames_per_half_period)
else:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
if PRERENDER_TO_TEXTURE:
init_pos = [(1 - a)* s/to_decimal(2) for s, a in
zip(self._size, graphics.locations[self.anchor])]
else:
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
anchor=self.anchor)
cur_unit_rect.col = self.cols[(i + j) % 2]
cur_unit_rect.add_to_batch(self._batches[0])
cur_unit_rect.col = self.cols[(i + j + 1) % 2]
cur_unit_rect.add_to_batch(self._batches[1])
# Increase x values
cur_unit_pos[0] += \
graphics.locations[self.anchor][0] * cur_unit[0]
cur_unit[0] += unit_grad[0]
# Reset x values
cur_unit_pos[0] = init_pos[0]
cur_unit[0] = init_unit[0]
# Increase y values
cur_unit_pos[1] += \
graphics.locations[self.anchor][1] * cur_unit[1]
cur_unit[1] += unit_grad[1]
if PRERENDER_TO_TEXTURE:
# Create textures
int_size = [int(round(s)) for s in self._size]
self._prerenders =\
[pyglet.image.Texture.create(*int_size) for n in range(2)]
# Set up framebuffer
fbo = graphics.Framebuffer()
for n in range(2):
fbo.attach_texture(self._prerenders[n])
# Draw batch to texture
fbo.start_render()
self._batches[n].draw()
fbo.end_render()
# Anchor textures for correct blitting later
self._prerenders[n].anchor_x, self._prerenders[n].anchor_y =\
[int(round((1 - a)* s/to_decimal(2))) for s, a in
zip(self._size, graphics.locations[self.anchor])]
fbo.delete()
# Delete batches since they won't be used
del self._batches
self._computed = True
def draw(self, photoburst=False, always_compute=False):
"""Draws appropriate prerender depending on current phase.
photoburst -- draw first color for only one frame for testing purposes
always_compute -- recompute what the checkerboard should look like
every frame
"""
if not self._computed or always_compute:
self.compute()
self._cur_phase %= 360
n = int(self._cur_phase // 180)
if photoburst and n == 0 and not self.flipped:
n = 1
if PRERENDER_TO_TEXTURE:
self._prerenders[n].blit(*self.position)
else:
self._batches[n].draw()
def lazydraw(self):
"""Only draws on color reversal."""
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if (cur_n != prev_n) or self._first_draw:
self.draw()
if self._first_draw:
self._first_draw = False
|
ztangent/checkergen
|
396eb13aa14ed5ca6f75922c0b749a50804e1949
|
Fixed calibrate function never actually calibrating.
|
diff --git a/src/eyetracking.py b/src/eyetracking.py
index 8449c8e..4d8b4a0 100644
--- a/src/eyetracking.py
+++ b/src/eyetracking.py
@@ -1,163 +1,164 @@
"""Provides support for CRS VideoEyetracker Toolbox."""
import os.path
try:
import win32com.client
available = True
except ImportError:
available = False
# COM ProgID of the Toolbox
ProgID = "crsVET.VideoEyeTracker"
RecordName = "etResultSet"
# VET application object
VET = None
class EyetrackingError(Exception):
"""Raised when something goes wrong with VET."""
pass
if available:
# Try dispatching object, else unavailable
try:
from win32com.client import gencache
# Ensure makepy module is generated
gencache.EnsureModule('{248DBF0C-A874-4032-82CE-DC5B307BB6E7}',
0, 3, 11)
VET = win32com.client.Dispatch(ProgID)
DummyResultSet = win32com.client.Record(RecordName, VET)
except:
available = False
if available:
# For easier access to constants and standardization with MATLAB interface
CRS = win32com.client.constants
lastgoodstamp = 0
def select_source(user_select = False, path = None):
if user_select:
if not VET.SelectVideoSource(CRS.vsUserSelect, ''):
msg = 'could not select video source'
raise EyetrackingError(msg)
elif path != None:
# Open from file
if not VET.SelectVideoSource(CRS.vsFile, path):
msg = 'could not use path as video source'
raise EyetrackingError(msg)
else:
# Default to 250 Hz High Speed Camera
if not VET.SelectVideoSource(CRS.vsHighSpeedCamera250, ''):
msg = 'could not select video source'
raise EyetrackingError(msg)
def is_source_ready():
"""Returns true if a video source has been selected."""
if VET.VideoSourceType == 0:
return False
else:
return True
def show_camera():
VET.CreateCameraScreen(0)
def quit_camera():
VET.DestroyCameraScreen()
def setup(viewing_distance=None, screen_dims=None,
fixation_period=None, fixation_range=None):
"""Calibrates the display and sets fixation properties."""
if viewing_distance != None and screen_dims != None:
if len(screen_dims) != 2:
msg = 'screen_dims must be a 2-tuple'
raise ValueError(msg)
VET.SetDeviceParameters(CRS.deUser, viewing_distance,
screen_dims[0], screen_dims[1])
if fixation_period != None:
VET.FixationPeriod = fixation_period
if fixation_range != None:
VET.FixationRange = fixation_range
def calibrate(path = None):
"""Calibrate the subject.
Optionally supply a path with no spaces to a
calibration file to load."""
if not is_source_ready():
select_source()
if not VET.Tracking:
- start()
+ VET.ClearDataBuffer()
+ VET.StartTracking()
if path == None:
if not VET.Calibrate():
msg = 'calibration failed'
raise EyetrackingError(msg)
else:
if not os.path.isfile(path):
msg = 'specified file does not exist'
raise EyetrackingError(msg)
if not VET.LoadCalibrationFile(path):
msg = 'file could not be loaded'
raise EyetrackingError(msg)
if not is_calibrated():
msg = 'calibration failed'
raise EyetrackingError(msg)
def is_calibrated():
if VET.CalibrationStatus()[0] != 0:
return True
else:
return False
def start():
"""Start tracking the eye."""
global lastgoodstamp
if not is_source_ready():
select_source()
if not is_calibrated():
msg = 'subject not yet calibrated'
raise EyetrackingError(msg)
lastgoodstamp = 0
VET.ClearDataBuffer()
VET.StartTracking()
def stop():
"""Stop tracking the eye."""
VET.StopTracking()
def is_tracked():
"""Returns true if the eye is being tracked."""
data = VET.GetLatestEyePosition(DummyResultSet)[1]
return data.Tracked
def is_fixated(fix_pos, fix_range, fix_period):
"""Checks whether subject is fixating on specificied location.
fix_pos -- (x, y) position of desired fixation location in mm
from center of screen
fix_range -- (width, height) of box surrounding fix_pos within
which fixation is allowed (in mm)
fix_period -- duration in milliseconds within which subject is
assumed to continue fixating after fixation is detected at a
specific time
"""
global lastgoodstamp
if VET.CalibrationStatus()[0] == 0:
msg = 'subject not yet calibrated'
raise EyetrackingError(msg)
data = VET.GetLatestEyePosition(DummyResultSet)[1]
pos = (data.ScreenPositionXmm, data.ScreenPositionYmm)
diff = [abs(p - fp) for p, fp in zip(pos, fix_pos)]
if data.Tracked == True:
if diff[0] < fix_range[0] and diff[1] < fix_range[1]:
lastgoodstamp = data.TimeStamp
return True
elif (data.Timestamp - lastgoodstamp) <= fix_period:
return True
elif (data.Timestamp - lastgoodstamp) <= fix_period:
return True
return False
|
ztangent/checkergen
|
7547fcea679d9c935bf2c47986acb30368f06b0d
|
Fixed priority availability checking in cli.
|
diff --git a/src/cli.py b/src/cli.py
index 3f9e64c..7fc0439 100644
--- a/src/cli.py
+++ b/src/cli.py
@@ -366,838 +366,838 @@ class CkgCmd(cmd.Cmd):
return
elif self.cur_group == None:
print 'current project has no groups to remove'
return
try:
args = self.__class__.rmgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rmgrp_parser.print_usage()
return
rmlist = []
if args.all:
for group in self.cur_proj.groups[:]:
self.cur_proj.del_group(group)
print "all display groups removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_proj.groups) or x < 0:
print "display group", x, "does not exist"
continue
rmlist.append(self.cur_proj.groups[x])
print "display group", x, "removed"
for group in rmlist:
self.cur_proj.del_group(group)
# Remember to point self.cur_group somewhere sane
if self.cur_group not in self.cur_proj.groups:
if len(self.cur_proj.groups) == 0:
self.cur_group = None
else:
self.cur_group = self.cur_proj.groups[0]
print "group 0 is now the current display group"
chgrp_parser = CmdParser(add_help=False, prog='chgrp',
description='''Changes display group that is
currently active for editing.
Prints current group id if
no group id is specified''')
chgrp_parser.add_argument('gid', metavar='id', type=int, nargs='?',
help='id of display group to be made active')
def help_chgrp(self):
self.__class__.chgrp_parser.print_help()
def do_chgrp(self, line):
"""Changes group that is currently active for editing."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups that can be made active'
return
try:
args = self.__class__.chgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.chgrp_parser.print_usage()
return
if args.gid == None:
print "group",\
self.cur_proj.groups.index(self.cur_group),\
"is the current display group"
elif args.gid >= len(self.cur_proj.groups) or args.gid < 0:
print "group", args.gid, "does not exist"
else:
self.cur_group = self.cur_proj.groups[args.gid]
print "group", args.gid, "is now the current display group"
mk_parser = CmdParser(add_help=False, prog='mk',
description='''Makes a new checkerboard in the
current group with the given
parameters.''')
mk_parser.add_argument('dims', action=store_tuple(2, ',', to_decimal),
help='''width,height of checkerboard in no. of
unit cells''')
mk_parser.add_argument('init_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of initial unit cell in pixels')
mk_parser.add_argument('end_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of final unit cell in pixels')
mk_parser.add_argument('position', action=store_tuple(2, ',', to_decimal),
help='x,y position of checkerboard in pixels')
mk_parser.add_argument('anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='anchor')
mk_parser.add_argument('cols', action=store_tuple(2, ',', to_color, [';']),
help='''color1,color2 of the checkerboard
(color format: R;G;B,
component range from 0-255)''')
mk_parser.add_argument('freq', type=to_decimal,
help='frequency of color reversal in Hz')
mk_parser.add_argument('phase', type=to_decimal, nargs='?', default='0',
help='initial phase of animation in degrees')
def help_mk(self):
self.__class__.mk_parser.print_help()
def do_mk(self, line):
"""Makes a checkerboard with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
if self.cur_group == None:
print 'automatically adding display group...'
self.do_mkgrp('')
try:
args = self.__class__.mk_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mk_parser.print_usage()
return
shape_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_shape = core.CheckerBoard(**shape_dict)
new_id = self.cur_proj.add_shape_to_group(self.cur_group, new_shape)
print "checkerboard", new_id, "added"
ed_parser = CmdParser(add_help=False, prog='ed',
description='''Edits attributes of checkerboards
specified by ids.''')
ed_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='''ids of checkerboards in the current
group to be edited''')
ed_parser.add_argument('--dims', action=store_tuple(2, ',', to_decimal),
help='checkerboard dimensions in unit cells',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--init_unit',
action=store_tuple(2, ',', to_decimal),
help='initial unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--end_unit',
action=store_tuple(2, ',', to_decimal),
help='final unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--position',
action=store_tuple(2, ',', to_decimal),
help='position of checkerboard in pixels',
metavar='X,Y')
ed_parser.add_argument('--anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='LOCATION')
ed_parser.add_argument('--cols', metavar='COLOR1,COLOR2',
action=store_tuple(2, ',', to_color, [';']),
help='''checkerboard colors (color format:
R;G;B, component range
from 0-255)''')
ed_parser.add_argument('--freq', type=to_decimal,
help='frequency of color reversal in Hz')
ed_parser.add_argument('--phase', type=to_decimal,
help='initial phase of animation in degrees')
def help_ed(self):
self.__class__.ed_parser.print_help()
def do_ed(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, please create one first'
return
try:
args = self.__class__.ed_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ed_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_group.shapes) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_shape_attr(self.cur_group, x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.ed_parser.print_usage()
rm_parser = CmdParser(add_help=False, prog='rm',
description='''Removes checkerboards specified
by ids.''')
rm_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''ids of checkerboards in the current group
to be removed''')
rm_parser.add_argument('-a', '--all', action='store_true',
help='''remove all checkerboards in the
current group''')
def help_rm(self):
self.__class__.rm_parser.print_help()
def do_rm(self, line):
"""Removes checkerboards specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, no boards to remove'
return
try:
args = self.__class__.rm_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rm_parser.print_usage()
return
rmlist = []
if args.all:
for shape in self.cur_group.shapes:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
print "all checkerboards removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_group.shapes) or x < 0:
print "checkerboard", x, "does not exist"
continue
rmlist.append(self.cur_group.shapes[x])
print "checkerboard", x, "removed"
for shape in rmlist:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
ls_parser = CmdParser(add_help=False, prog='ls',
description='''Lists project, display group and
checkerboard settings. If no group ids
are specified, all display groups
are listed.''')
ls_parser.add_argument('gidlist', nargs='*', metavar='gid', type=int,
help='''ids of the display groups to be listed''')
ls_group = ls_parser.add_mutually_exclusive_group()
ls_group.add_argument('-s', '--settings', action='store_true',
help='list only project settings')
ls_group.add_argument('-g', '--groups', action='store_true',
help='list only display groups')
def help_ls(self):
self.__class__.ls_parser.print_help()
def do_ls(self, line):
"""Lists project, display group and checkerboard settings."""
def ls_str(s, seps=[',',';']):
"""Special space-saving output formatter."""
if type(s) in [tuple, list]:
if len(seps) > 1:
newseps = seps[1:]
else:
newseps = seps
return seps[0].join([ls_str(i, newseps) for i in s])
else:
return str(s)
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.ls_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ls_parser.print_usage()
return
# Remove duplicates and ascending sort
args.gidlist = sorted(set(args.gidlist))
if len(self.cur_proj.groups) == 0:
if len(args.gidlist) > 0:
print 'this project has no display groups that can be listed'
args.settings = True
else:
for gid in args.gidlist[:]:
if gid >= len(self.cur_proj.groups) or gid < 0:
args.gidlist.remove(gid)
print 'display group', gid, 'does not exist'
if args.gidlist == []:
args.gidlist = range(len(self.cur_proj.groups))
else:
# If any (valid) groups are specified
# don't show project settings
args.groups = True
if not args.groups:
print 'PROJECT SETTINGS'.center(70,'*')
print \
'name'.rjust(16),\
'fps'.rjust(7),\
'resolution'.rjust(14),\
'bg color'.rjust(18)
# 'format'.rjust(7)
print \
ls_str(self.cur_proj.name).rjust(16),\
ls_str(self.cur_proj.fps).rjust(7),\
ls_str(self.cur_proj.res).rjust(14),\
ls_str(self.cur_proj.bg).rjust(18)
# ls_str(self.cur_proj.export_fmt).rjust(7)
print \
'pre-display'.rjust(26),\
'post-display'.rjust(26)
print \
ls_str(self.cur_proj.pre).rjust(26),\
ls_str(self.cur_proj.post).rjust(26)
print \
'cross colors'.rjust(26),\
'cross times'.rjust(26)
print \
ls_str(self.cur_proj.cross_cols).rjust(26),\
ls_str(self.cur_proj.cross_times).rjust(26)
if not args.settings and not args.groups:
# Insert empty line if both groups and project
# settings are listed
print ''
if not args.settings:
for i, n in enumerate(args.gidlist):
if i != 0:
# Print newline seperator between each group
print ''
group = self.cur_proj.groups[n]
print 'GROUP {n}'.format(n=n).center(70,'*')
print \
'pre-display'.rjust(20),\
'display'.rjust(20),\
'post-display'.rjust(20)
print \
ls_str(group.pre).rjust(20),\
ls_str(group.disp).rjust(20),\
ls_str(group.post).rjust(20)
if len(group.shapes) > 0:
print \
''.rjust(2),\
'shape id'.rjust(8),\
'dims'.rjust(10),\
'init_unit'.rjust(14),\
'end_unit'.rjust(14),\
'position'.rjust(14)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.dims).rjust(10),\
ls_str(shape.init_unit).rjust(14),\
ls_str(shape.end_unit).rjust(14),\
ls_str(shape.position).rjust(14)
print '\n',\
''.rjust(2),\
'shape id'.rjust(8),\
'colors'.rjust(27),\
'anchor'.rjust(12),\
'freq'.rjust(6),\
'phase'.rjust(7)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.cols).rjust(27),\
ls_str(shape.anchor).rjust(12),\
ls_str(shape.freq).rjust(6),\
ls_str(shape.phase).rjust(7)
display_parser = CmdParser(add_help=False, prog='display',
description='''Displays the animation in a
window or in fullscreen.''')
display_parser.add_argument('-e', '--expfile', metavar='PATH',
help='''run experiment as described in
specified file, ignore other flags''')
display_parser.add_argument('-f', '--fullscreen', action='store_true',
help='sets fullscreen mode, ESC to quit')
display_parser.add_argument('-p', '--priority', metavar='LEVEL',
help='''set priority while displaying,
higher priority results in
less dropped frames (choices:
0-3, low, normal, high,
realtime)''')
display_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly display specified display
groups N number of times''')
display_parser.add_argument('-pt', '--phototest', action='store_true',
help='''draw white test rectangle in topleft
corner of screen when groups become
visible for a photodiode to detect''')
display_parser.add_argument('-pb', '--photoburst', action='store_true',
help='''make checkerboards only draw first
color for one frame to facilitate
testing with a photodiode''')
display_parser.add_argument('-lt', '--logtime', action='store_true',
help='output frame timestamps to a log file')
display_parser.add_argument('-ld', '--logdur', action='store_true',
help='output frame durations to a log file')
display_parser.add_argument('-ss', '--sigser', action='store_true',
help='''send signals through the serial port
when shapes are being displayed''')
display_parser.add_argument('-sp', '--sigpar', action='store_true',
help='''send signals through the parallel port
when shapes are being displayed''')
display_parser.add_argument('-fpbs', metavar='M', type=int, default=0,
help='''unique signal corresponding to a
checkerboard is sent after the board
undergoes M color flips (default:
disabled, M=0)''')
display_parser.add_argument('-et', '--eyetrack', action='store_true',
help='''use eyetracking to ensure that subject
fixates on the cross in the center''')
display_parser.add_argument('-eu', '--etuser', action='store_true',
help='''allow user to select eyetracking video
source from a dialog''')
display_parser.add_argument('-ev', '--etvideo', metavar='path',
help='''path (with no spaces) to eyetracking
video file to be used as the source''')
display_parser.add_argument('-ta', '--tryagain', metavar='I',
type=int, default=0,
help='''append groups during which subject
failed to fixate up to I times to the
list of groups to be displayed
(default: disabled, I=0)''')
display_parser.add_argument('-tb', '--trybreak', metavar='J', type=int,
help='''used with --tryagain, append a wait
screen to the list of groups to be
displayed after every J groups have
been appended to the list (default:
J=total number of groups)''')
display_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be displayed
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_display(self):
self.__class__.display_parser.print_help()
def do_display(self, line):
"""Displays the animation in a window or in fullscreen"""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.display_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
if args.expfile != None:
try:
exp = core.CkgExp(path=args.expfile)
except IOError:
print "error:", str(sys.exc_value)
return
try:
args = self.__class__.\
display_parser.parse_args(shlex.split(exp.flags))
except (CmdParserError, ValueError):
print 'error: invalid flags stored in block file'
return
try:
print """name of log file (default: experiment name):"""
blkname = raw_input().strip().strip('"\'')
except EOFError:
return
if blkname == '':
blkname == exp.name
blk = exp.random_blk(blkname)
args.idlist = blk.idlist()
else:
blk = core.CkgBlk(name=self.cur_proj.name,
trials=None,
flags=line,
sequence=[])
groupq = []
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < -1:
print 'error: group', i, 'does not exist'
return
for i in args.idlist:
if i == -1:
groupq.append(core.CkgWaitScreen(res=self.cur_proj.res))
else:
groupq.append(self.cur_proj.groups[i])
else:
groupq = list(self.cur_proj.groups)
if args.repeat != None:
groupq = list(groupq * args.repeat)
if args.eyetrack and eyetracking.available:
if not eyetracking.is_calibrated():
try:
self.do_calibrate('',True)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
return
if args.priority != None:
- if not priority.available:
- print "error: setting priority not avaible on", sys.platform
+ if not priority.available[sys.platform]:
+ print "error: setting priority not available on", sys.platform
print "continuing..."
else:
if args.priority.isdigit():
args.priority = int(args.priority)
try:
priority.set(args.priority)
except ValueError:
print "error:", str(sys.exc_value)
print "continuing..."
print "displaying..."
try:
self.cur_proj.display(fullscreen=args.fullscreen,
logtime=args.logtime,
logdur=args.logdur,
sigser=args.sigser,
sigpar=args.sigpar,
fpbs=args.fpbs,
phototest=args.phototest,
photoburst=args.photoburst,
eyetrack=args.eyetrack,
etuser=args.etuser,
etvideo=args.etvideo,
tryagain=args.tryagain,
trybreak=args.trybreak,
groupq=groupq,
blk=blk)
except (IOError, NotImplementedError, eyetracking.EyetrackingError):
print "error:", str(sys.exc_value)
if args.priority != None:
try:
priority.set('normal')
except:
pass
return
if args.priority != None:
try:
priority.set('normal')
except:
pass
try:
blk.write_log()
except IOError:
print "error:", str(sys.exc_value)
return
print "log file written"
export_parser = CmdParser(add_help=False, prog='export',
description='''Exports animation as an image
sequence (in a folder) to the
specified directory.''')
# export_parser.add_argument('--fmt', dest='export_fmt',
# choices=core.EXPORT_FMTS,
# help='image format for export')
export_parser.add_argument('-n','--nofolder',
dest='folder', action='store_false',
help='''force images not to exported in
a containing folder''')
export_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly export specified display
groups N number of times''')
export_parser.add_argument('duration', nargs='?',
type=to_decimal, default='Infinity',
help='''number of seconds of the animation
that should be exported (default:
as long as the entire animation)''')
export_parser.add_argument('dir', nargs='?', default=os.getcwd(),
help='''destination directory for export
(default: current working directory)''')
export_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be exported
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_export(self):
self.__class__.export_parser.print_help()
def do_export(self, line):
"""Exports animation an image sequence to the specified directory."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.export_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.export_parser.print_usage()
return
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < 0:
print 'error: group', i, 'does not exist'
return
groupq = [self.cur_proj.groups[i] for i in args.idlist]
else:
groupq = list(self.cur_proj.groups)
if args.repeat != None:
groupq = list(groupq * args.repeat)
try:
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
folder=args.folder)
except IOError:
print "error:", str(sys.exc_value)
return
except core.FrameOverflowError:
print "warning:", str(sys.exc_value)
print "Are you sure you want to continue?"
while True:
try:
if self.__class__.yn_parse(raw_input()):
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
export_fmt=None,
folder=args.folder,
force=True)
break
else:
return
except TypeError:
print str(sys.exc_value)
except EOFError:
return
print "Export done."
mkexp_parser = CmdParser(add_help=False, prog='mkexp',
description='''Create checkergen experiment file
which describes how the project
is to be displayed.''')
mkexp_parser.add_argument('-n', '--name',
help='''name of the experiment (default: same
name as current project)''')
mkexp_parser.add_argument('-t', '--trials', type=int, metavar='N',
help='''N trials displayed in a block, i.e.
the same sequence will be displayed
N times in that block, with waitscreens
in between''')
mkexp_parser.add_argument('-f', '--flags',
help='''flags passed to the display command
that should be used when the block
file is run (enclose in quotes and use
'+' or '++' in place of '-' or '--')''')
def help_mkexp(self):
self.__class__.mkexp_parser.print_help()
def do_mkexp(self, line):
"""Creates checkergen experiment file."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.mkexp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mkexp_parser.print_usage()
return
if args.trials == None:
print "number of trials:"
try:
args.trials = int(raw_input().strip())
except EOFError:
return
except ValueError:
print "error:", str(sys.exc_value)
return
if args.flags != None:
args.flags = args.flags.replace('+','-')
else:
print "flags used with display command (leave blank if none):"
try:
args.flags = raw_input().strip().strip('"\'')
except EOFError:
return
try:
disp_args = self.__class__.display_parser.\
parse_args(shlex.split(args.flags))
except (CmdParserError, ValueError):
print "error: invalid flags to display command"
print str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
print "list of sequences to choose from in the format",\
"'id1,id2,id3;seq2;seq3;seq4':"
print "(default: reduced latin square)"
try:
seqs_str = raw_input().strip()
if seqs_str == '':
args.sequences = None
else:
args.sequences = [[int(i) for i in seq_str.split(',')]
for seq_str in seqs_str.split(';')]
except EOFError:
return
try:
new_exp = core.CkgExp(name=args.name, proj=self.cur_proj,
trials=args.trials,
sequences=args.sequences,
flags=args.flags)
new_exp.save()
except IOError:
print "error:", str(sys.exc_value)
return
print "Experiment file created."
def do_calibrate(self, line, query=False):
"""Calibrate subject for eyetracking, or load a calibration file."""
if not eyetracking.available:
print "error: eyetracking functionality not available"
return
if query:
print "path to calibration file (leave empty for GUI tool):"
try:
path = raw_input().strip().strip('"\'')
except EOFError:
msg = "calibration cancelled"
raise eyetracking.EyetrackingError(msg)
else:
path = line.strip().strip('"\'')
if len(path) == 0:
path = None
if not eyetracking.is_source_ready():
# Select default source if none has been selected
eyetracking.select_source()
try:
eyetracking.calibrate(path)
except eyetracking.EyetrackingError:
if query:
raise
else:
print "error:", str(sys.exc_value)
return
if len(path) > 0:
print "calibration file successfully loaded"
etsetup_parser = CmdParser(add_help=False, prog='etsetup',
description='''Set various eyetracking
parameters.''')
etsetup_parser.add_argument('-fp', '--fixperiod', type=int, metavar='MS',
help='''time in milliseconds subject
has to stare at the same spot
for fixation to be detected''')
etsetup_parser.add_argument('-fr', '--fixrange', type=float, metavar='MM',
help='''distance in mm beyond which the
eye position cannot change for
a fixation to be detected''')
etsetup_parser.add_argument('-s', '--size', metavar='WIDTH,HEIGHT',
action=store_tuple(2, ',', float),
help='physical screen dimensions in mm')
etsetup_parser.add_argument('-vd', '--viewdist', type=int, metavar='MM',
help='''viewing distance between subject's
eyes and the screen''')
def help_etsetup(self):
self.__class__.etsetup_parser.print_help()
def do_etsetup(self, line):
try:
args = self.__class__.etsetup_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.etsetup_parser.print_usage()
return
try:
eyetracking.setup(viewing_distance=args.viewdist,
screen_dims=args.size,
fixation_period=args.fixperiod,
fixation_range=args.fixrange)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
def do_pwd(self, line):
"""Prints the current working directory."""
print os.getcwd()
def do_cd(self, line):
"""Change working directory to specified path."""
path = line.strip().strip('"\'')
if not os.path.isdir(path):
print "error: specified path is not a directory"
return
os.chdir(path)
def do_quit(self, line):
"""Quits the program."""
if self.save_check():
return
return True
def help_EOF(self):
print "Typing {0} issues this command, which quits the program."\
.format(CMD_EOF_STRING)
def do_EOF(self, line):
"""Typing Ctrl-D issues this command, which quits the program."""
print '\r'
if self.save_check():
return
return True
def help_help(self):
print 'Prints a list of commands.'
print "Type 'help <topic>' for more details on each command."
def default(self, line):
command = line.split()[0]
print \
"'{0}' is not a checkergen command.".format(command),\
"Type 'help' for a list of commands"
|
ztangent/checkergen
|
67bd4c2f3e245dcd9d44725eb83be40b379996ee
|
Fixed int casting in mkexp command.
|
diff --git a/src/cli.py b/src/cli.py
index 2cd34c2..3f9e64c 100644
--- a/src/cli.py
+++ b/src/cli.py
@@ -541,660 +541,663 @@ class CkgCmd(cmd.Cmd):
if x >= len(self.cur_group.shapes) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_shape_attr(self.cur_group, x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.ed_parser.print_usage()
rm_parser = CmdParser(add_help=False, prog='rm',
description='''Removes checkerboards specified
by ids.''')
rm_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''ids of checkerboards in the current group
to be removed''')
rm_parser.add_argument('-a', '--all', action='store_true',
help='''remove all checkerboards in the
current group''')
def help_rm(self):
self.__class__.rm_parser.print_help()
def do_rm(self, line):
"""Removes checkerboards specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, no boards to remove'
return
try:
args = self.__class__.rm_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rm_parser.print_usage()
return
rmlist = []
if args.all:
for shape in self.cur_group.shapes:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
print "all checkerboards removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_group.shapes) or x < 0:
print "checkerboard", x, "does not exist"
continue
rmlist.append(self.cur_group.shapes[x])
print "checkerboard", x, "removed"
for shape in rmlist:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
ls_parser = CmdParser(add_help=False, prog='ls',
description='''Lists project, display group and
checkerboard settings. If no group ids
are specified, all display groups
are listed.''')
ls_parser.add_argument('gidlist', nargs='*', metavar='gid', type=int,
help='''ids of the display groups to be listed''')
ls_group = ls_parser.add_mutually_exclusive_group()
ls_group.add_argument('-s', '--settings', action='store_true',
help='list only project settings')
ls_group.add_argument('-g', '--groups', action='store_true',
help='list only display groups')
def help_ls(self):
self.__class__.ls_parser.print_help()
def do_ls(self, line):
"""Lists project, display group and checkerboard settings."""
def ls_str(s, seps=[',',';']):
"""Special space-saving output formatter."""
if type(s) in [tuple, list]:
if len(seps) > 1:
newseps = seps[1:]
else:
newseps = seps
return seps[0].join([ls_str(i, newseps) for i in s])
else:
return str(s)
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.ls_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ls_parser.print_usage()
return
# Remove duplicates and ascending sort
args.gidlist = sorted(set(args.gidlist))
if len(self.cur_proj.groups) == 0:
if len(args.gidlist) > 0:
print 'this project has no display groups that can be listed'
args.settings = True
else:
for gid in args.gidlist[:]:
if gid >= len(self.cur_proj.groups) or gid < 0:
args.gidlist.remove(gid)
print 'display group', gid, 'does not exist'
if args.gidlist == []:
args.gidlist = range(len(self.cur_proj.groups))
else:
# If any (valid) groups are specified
# don't show project settings
args.groups = True
if not args.groups:
print 'PROJECT SETTINGS'.center(70,'*')
print \
'name'.rjust(16),\
'fps'.rjust(7),\
'resolution'.rjust(14),\
'bg color'.rjust(18)
# 'format'.rjust(7)
print \
ls_str(self.cur_proj.name).rjust(16),\
ls_str(self.cur_proj.fps).rjust(7),\
ls_str(self.cur_proj.res).rjust(14),\
ls_str(self.cur_proj.bg).rjust(18)
# ls_str(self.cur_proj.export_fmt).rjust(7)
print \
'pre-display'.rjust(26),\
'post-display'.rjust(26)
print \
ls_str(self.cur_proj.pre).rjust(26),\
ls_str(self.cur_proj.post).rjust(26)
print \
'cross colors'.rjust(26),\
'cross times'.rjust(26)
print \
ls_str(self.cur_proj.cross_cols).rjust(26),\
ls_str(self.cur_proj.cross_times).rjust(26)
if not args.settings and not args.groups:
# Insert empty line if both groups and project
# settings are listed
print ''
if not args.settings:
for i, n in enumerate(args.gidlist):
if i != 0:
# Print newline seperator between each group
print ''
group = self.cur_proj.groups[n]
print 'GROUP {n}'.format(n=n).center(70,'*')
print \
'pre-display'.rjust(20),\
'display'.rjust(20),\
'post-display'.rjust(20)
print \
ls_str(group.pre).rjust(20),\
ls_str(group.disp).rjust(20),\
ls_str(group.post).rjust(20)
if len(group.shapes) > 0:
print \
''.rjust(2),\
'shape id'.rjust(8),\
'dims'.rjust(10),\
'init_unit'.rjust(14),\
'end_unit'.rjust(14),\
'position'.rjust(14)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.dims).rjust(10),\
ls_str(shape.init_unit).rjust(14),\
ls_str(shape.end_unit).rjust(14),\
ls_str(shape.position).rjust(14)
print '\n',\
''.rjust(2),\
'shape id'.rjust(8),\
'colors'.rjust(27),\
'anchor'.rjust(12),\
'freq'.rjust(6),\
'phase'.rjust(7)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.cols).rjust(27),\
ls_str(shape.anchor).rjust(12),\
ls_str(shape.freq).rjust(6),\
ls_str(shape.phase).rjust(7)
display_parser = CmdParser(add_help=False, prog='display',
description='''Displays the animation in a
window or in fullscreen.''')
display_parser.add_argument('-e', '--expfile', metavar='PATH',
help='''run experiment as described in
specified file, ignore other flags''')
display_parser.add_argument('-f', '--fullscreen', action='store_true',
help='sets fullscreen mode, ESC to quit')
display_parser.add_argument('-p', '--priority', metavar='LEVEL',
help='''set priority while displaying,
higher priority results in
less dropped frames (choices:
0-3, low, normal, high,
realtime)''')
display_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly display specified display
groups N number of times''')
display_parser.add_argument('-pt', '--phototest', action='store_true',
help='''draw white test rectangle in topleft
corner of screen when groups become
visible for a photodiode to detect''')
display_parser.add_argument('-pb', '--photoburst', action='store_true',
help='''make checkerboards only draw first
color for one frame to facilitate
testing with a photodiode''')
display_parser.add_argument('-lt', '--logtime', action='store_true',
help='output frame timestamps to a log file')
display_parser.add_argument('-ld', '--logdur', action='store_true',
help='output frame durations to a log file')
display_parser.add_argument('-ss', '--sigser', action='store_true',
help='''send signals through the serial port
when shapes are being displayed''')
display_parser.add_argument('-sp', '--sigpar', action='store_true',
help='''send signals through the parallel port
when shapes are being displayed''')
display_parser.add_argument('-fpbs', metavar='M', type=int, default=0,
help='''unique signal corresponding to a
checkerboard is sent after the board
undergoes M color flips (default:
disabled, M=0)''')
display_parser.add_argument('-et', '--eyetrack', action='store_true',
help='''use eyetracking to ensure that subject
fixates on the cross in the center''')
display_parser.add_argument('-eu', '--etuser', action='store_true',
help='''allow user to select eyetracking video
source from a dialog''')
display_parser.add_argument('-ev', '--etvideo', metavar='path',
help='''path (with no spaces) to eyetracking
video file to be used as the source''')
display_parser.add_argument('-ta', '--tryagain', metavar='I',
type=int, default=0,
help='''append groups during which subject
failed to fixate up to I times to the
list of groups to be displayed
(default: disabled, I=0)''')
display_parser.add_argument('-tb', '--trybreak', metavar='J', type=int,
help='''used with --tryagain, append a wait
screen to the list of groups to be
displayed after every J groups have
been appended to the list (default:
J=total number of groups)''')
display_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be displayed
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_display(self):
self.__class__.display_parser.print_help()
def do_display(self, line):
"""Displays the animation in a window or in fullscreen"""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.display_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
if args.expfile != None:
try:
exp = core.CkgExp(path=args.expfile)
except IOError:
print "error:", str(sys.exc_value)
return
try:
args = self.__class__.\
display_parser.parse_args(shlex.split(exp.flags))
except (CmdParserError, ValueError):
print 'error: invalid flags stored in block file'
return
try:
print """name of log file (default: experiment name):"""
blkname = raw_input().strip().strip('"\'')
except EOFError:
return
if blkname == '':
blkname == exp.name
blk = exp.random_blk(blkname)
args.idlist = blk.idlist()
else:
blk = core.CkgBlk(name=self.cur_proj.name,
trials=None,
flags=line,
sequence=[])
groupq = []
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < -1:
print 'error: group', i, 'does not exist'
return
for i in args.idlist:
if i == -1:
groupq.append(core.CkgWaitScreen(res=self.cur_proj.res))
else:
groupq.append(self.cur_proj.groups[i])
else:
groupq = list(self.cur_proj.groups)
if args.repeat != None:
groupq = list(groupq * args.repeat)
if args.eyetrack and eyetracking.available:
if not eyetracking.is_calibrated():
try:
self.do_calibrate('',True)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
return
if args.priority != None:
if not priority.available:
print "error: setting priority not avaible on", sys.platform
print "continuing..."
else:
if args.priority.isdigit():
args.priority = int(args.priority)
try:
priority.set(args.priority)
except ValueError:
print "error:", str(sys.exc_value)
print "continuing..."
print "displaying..."
try:
self.cur_proj.display(fullscreen=args.fullscreen,
logtime=args.logtime,
logdur=args.logdur,
sigser=args.sigser,
sigpar=args.sigpar,
fpbs=args.fpbs,
phototest=args.phototest,
photoburst=args.photoburst,
eyetrack=args.eyetrack,
etuser=args.etuser,
etvideo=args.etvideo,
tryagain=args.tryagain,
trybreak=args.trybreak,
groupq=groupq,
blk=blk)
except (IOError, NotImplementedError, eyetracking.EyetrackingError):
print "error:", str(sys.exc_value)
if args.priority != None:
try:
priority.set('normal')
except:
pass
return
if args.priority != None:
try:
priority.set('normal')
except:
pass
try:
blk.write_log()
except IOError:
print "error:", str(sys.exc_value)
return
print "log file written"
export_parser = CmdParser(add_help=False, prog='export',
description='''Exports animation as an image
sequence (in a folder) to the
specified directory.''')
# export_parser.add_argument('--fmt', dest='export_fmt',
# choices=core.EXPORT_FMTS,
# help='image format for export')
export_parser.add_argument('-n','--nofolder',
dest='folder', action='store_false',
help='''force images not to exported in
a containing folder''')
export_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly export specified display
groups N number of times''')
export_parser.add_argument('duration', nargs='?',
type=to_decimal, default='Infinity',
help='''number of seconds of the animation
that should be exported (default:
as long as the entire animation)''')
export_parser.add_argument('dir', nargs='?', default=os.getcwd(),
help='''destination directory for export
(default: current working directory)''')
export_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be exported
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_export(self):
self.__class__.export_parser.print_help()
def do_export(self, line):
"""Exports animation an image sequence to the specified directory."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.export_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.export_parser.print_usage()
return
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < 0:
print 'error: group', i, 'does not exist'
return
groupq = [self.cur_proj.groups[i] for i in args.idlist]
else:
groupq = list(self.cur_proj.groups)
if args.repeat != None:
groupq = list(groupq * args.repeat)
try:
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
folder=args.folder)
except IOError:
print "error:", str(sys.exc_value)
return
except core.FrameOverflowError:
print "warning:", str(sys.exc_value)
print "Are you sure you want to continue?"
while True:
try:
if self.__class__.yn_parse(raw_input()):
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
export_fmt=None,
folder=args.folder,
force=True)
break
else:
return
except TypeError:
print str(sys.exc_value)
except EOFError:
return
print "Export done."
mkexp_parser = CmdParser(add_help=False, prog='mkexp',
description='''Create checkergen experiment file
which describes how the project
is to be displayed.''')
mkexp_parser.add_argument('-n', '--name',
help='''name of the experiment (default: same
name as current project)''')
mkexp_parser.add_argument('-t', '--trials', type=int, metavar='N',
help='''N trials displayed in a block, i.e.
the same sequence will be displayed
N times in that block, with waitscreens
in between''')
mkexp_parser.add_argument('-f', '--flags',
help='''flags passed to the display command
that should be used when the block
file is run (enclose in quotes and use
'+' or '++' in place of '-' or '--')''')
def help_mkexp(self):
self.__class__.mkexp_parser.print_help()
def do_mkexp(self, line):
"""Creates checkergen experiment file."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.mkexp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mkexp_parser.print_usage()
return
if args.trials == None:
print "number of trials:"
try:
args.trials = int(raw_input().strip())
except EOFError:
return
+ except ValueError:
+ print "error:", str(sys.exc_value)
+ return
if args.flags != None:
args.flags = args.flags.replace('+','-')
else:
print "flags used with display command (leave blank if none):"
try:
args.flags = raw_input().strip().strip('"\'')
except EOFError:
return
try:
disp_args = self.__class__.display_parser.\
parse_args(shlex.split(args.flags))
except (CmdParserError, ValueError):
print "error: invalid flags to display command"
print str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
print "list of sequences to choose from in the format",\
"'id1,id2,id3;seq2;seq3;seq4':"
print "(default: reduced latin square)"
try:
seqs_str = raw_input().strip()
if seqs_str == '':
args.sequences = None
else:
args.sequences = [[int(i) for i in seq_str.split(',')]
for seq_str in seqs_str.split(';')]
except EOFError:
return
try:
new_exp = core.CkgExp(name=args.name, proj=self.cur_proj,
trials=args.trials,
sequences=args.sequences,
flags=args.flags)
new_exp.save()
except IOError:
print "error:", str(sys.exc_value)
return
print "Experiment file created."
def do_calibrate(self, line, query=False):
"""Calibrate subject for eyetracking, or load a calibration file."""
if not eyetracking.available:
print "error: eyetracking functionality not available"
return
if query:
print "path to calibration file (leave empty for GUI tool):"
try:
path = raw_input().strip().strip('"\'')
except EOFError:
msg = "calibration cancelled"
raise eyetracking.EyetrackingError(msg)
else:
path = line.strip().strip('"\'')
if len(path) == 0:
path = None
if not eyetracking.is_source_ready():
# Select default source if none has been selected
eyetracking.select_source()
try:
eyetracking.calibrate(path)
except eyetracking.EyetrackingError:
if query:
raise
else:
print "error:", str(sys.exc_value)
return
if len(path) > 0:
print "calibration file successfully loaded"
etsetup_parser = CmdParser(add_help=False, prog='etsetup',
description='''Set various eyetracking
parameters.''')
etsetup_parser.add_argument('-fp', '--fixperiod', type=int, metavar='MS',
help='''time in milliseconds subject
has to stare at the same spot
for fixation to be detected''')
etsetup_parser.add_argument('-fr', '--fixrange', type=float, metavar='MM',
help='''distance in mm beyond which the
eye position cannot change for
a fixation to be detected''')
etsetup_parser.add_argument('-s', '--size', metavar='WIDTH,HEIGHT',
action=store_tuple(2, ',', float),
help='physical screen dimensions in mm')
etsetup_parser.add_argument('-vd', '--viewdist', type=int, metavar='MM',
help='''viewing distance between subject's
eyes and the screen''')
def help_etsetup(self):
self.__class__.etsetup_parser.print_help()
def do_etsetup(self, line):
try:
args = self.__class__.etsetup_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.etsetup_parser.print_usage()
return
try:
eyetracking.setup(viewing_distance=args.viewdist,
screen_dims=args.size,
fixation_period=args.fixperiod,
fixation_range=args.fixrange)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
def do_pwd(self, line):
"""Prints the current working directory."""
print os.getcwd()
def do_cd(self, line):
"""Change working directory to specified path."""
path = line.strip().strip('"\'')
if not os.path.isdir(path):
print "error: specified path is not a directory"
return
os.chdir(path)
def do_quit(self, line):
"""Quits the program."""
if self.save_check():
return
return True
def help_EOF(self):
print "Typing {0} issues this command, which quits the program."\
.format(CMD_EOF_STRING)
def do_EOF(self, line):
"""Typing Ctrl-D issues this command, which quits the program."""
print '\r'
if self.save_check():
return
return True
def help_help(self):
print 'Prints a list of commands.'
print "Type 'help <topic>' for more details on each command."
def default(self, line):
command = line.split()[0]
print \
"'{0}' is not a checkergen command.".format(command),\
"Type 'help' for a list of commands"
|
ztangent/checkergen
|
726d60298526f5c74f45b9d76874e5ca7777598f
|
Consolidated logging through CkgBlk objects.
|
diff --git a/src/cli.py b/src/cli.py
index e700557..2cd34c2 100644
--- a/src/cli.py
+++ b/src/cli.py
@@ -314,885 +314,887 @@ class CkgCmd(cmd.Cmd):
help='''time in seconds a blank screen will
be shown after shapes are displayed''')
def help_edgrp(self):
self.__class__.edgrp_parser.print_help()
def do_edgrp(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.edgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.edgrp_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_proj.groups) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_group_attr(x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.edgrp_parser.print_usage()
rmgrp_parser = CmdParser(add_help=False, prog='rmgrp',
description='''Removes display groups specified
by ids.''')
rmgrp_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='ids of display groups to be removed')
rmgrp_parser.add_argument('-a', '--all', action='store_true',
help='remove all groups from the project')
def help_rmgrp(self):
self.__class__.rmgrp_parser.print_help()
def do_rmgrp(self, line):
"""Removes display groups specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups to remove'
return
try:
args = self.__class__.rmgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rmgrp_parser.print_usage()
return
rmlist = []
if args.all:
for group in self.cur_proj.groups[:]:
self.cur_proj.del_group(group)
print "all display groups removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_proj.groups) or x < 0:
print "display group", x, "does not exist"
continue
rmlist.append(self.cur_proj.groups[x])
print "display group", x, "removed"
for group in rmlist:
self.cur_proj.del_group(group)
# Remember to point self.cur_group somewhere sane
if self.cur_group not in self.cur_proj.groups:
if len(self.cur_proj.groups) == 0:
self.cur_group = None
else:
self.cur_group = self.cur_proj.groups[0]
print "group 0 is now the current display group"
chgrp_parser = CmdParser(add_help=False, prog='chgrp',
description='''Changes display group that is
currently active for editing.
Prints current group id if
no group id is specified''')
chgrp_parser.add_argument('gid', metavar='id', type=int, nargs='?',
help='id of display group to be made active')
def help_chgrp(self):
self.__class__.chgrp_parser.print_help()
def do_chgrp(self, line):
"""Changes group that is currently active for editing."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups that can be made active'
return
try:
args = self.__class__.chgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.chgrp_parser.print_usage()
return
if args.gid == None:
print "group",\
self.cur_proj.groups.index(self.cur_group),\
"is the current display group"
elif args.gid >= len(self.cur_proj.groups) or args.gid < 0:
print "group", args.gid, "does not exist"
else:
self.cur_group = self.cur_proj.groups[args.gid]
print "group", args.gid, "is now the current display group"
mk_parser = CmdParser(add_help=False, prog='mk',
description='''Makes a new checkerboard in the
current group with the given
parameters.''')
mk_parser.add_argument('dims', action=store_tuple(2, ',', to_decimal),
help='''width,height of checkerboard in no. of
unit cells''')
mk_parser.add_argument('init_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of initial unit cell in pixels')
mk_parser.add_argument('end_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of final unit cell in pixels')
mk_parser.add_argument('position', action=store_tuple(2, ',', to_decimal),
help='x,y position of checkerboard in pixels')
mk_parser.add_argument('anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='anchor')
mk_parser.add_argument('cols', action=store_tuple(2, ',', to_color, [';']),
help='''color1,color2 of the checkerboard
(color format: R;G;B,
component range from 0-255)''')
mk_parser.add_argument('freq', type=to_decimal,
help='frequency of color reversal in Hz')
mk_parser.add_argument('phase', type=to_decimal, nargs='?', default='0',
help='initial phase of animation in degrees')
def help_mk(self):
self.__class__.mk_parser.print_help()
def do_mk(self, line):
"""Makes a checkerboard with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
if self.cur_group == None:
print 'automatically adding display group...'
self.do_mkgrp('')
try:
args = self.__class__.mk_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mk_parser.print_usage()
return
shape_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_shape = core.CheckerBoard(**shape_dict)
new_id = self.cur_proj.add_shape_to_group(self.cur_group, new_shape)
print "checkerboard", new_id, "added"
ed_parser = CmdParser(add_help=False, prog='ed',
description='''Edits attributes of checkerboards
specified by ids.''')
ed_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='''ids of checkerboards in the current
group to be edited''')
ed_parser.add_argument('--dims', action=store_tuple(2, ',', to_decimal),
help='checkerboard dimensions in unit cells',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--init_unit',
action=store_tuple(2, ',', to_decimal),
help='initial unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--end_unit',
action=store_tuple(2, ',', to_decimal),
help='final unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--position',
action=store_tuple(2, ',', to_decimal),
help='position of checkerboard in pixels',
metavar='X,Y')
ed_parser.add_argument('--anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='LOCATION')
ed_parser.add_argument('--cols', metavar='COLOR1,COLOR2',
action=store_tuple(2, ',', to_color, [';']),
help='''checkerboard colors (color format:
R;G;B, component range
from 0-255)''')
ed_parser.add_argument('--freq', type=to_decimal,
help='frequency of color reversal in Hz')
ed_parser.add_argument('--phase', type=to_decimal,
help='initial phase of animation in degrees')
def help_ed(self):
self.__class__.ed_parser.print_help()
def do_ed(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, please create one first'
return
try:
args = self.__class__.ed_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ed_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_group.shapes) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_shape_attr(self.cur_group, x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.ed_parser.print_usage()
rm_parser = CmdParser(add_help=False, prog='rm',
description='''Removes checkerboards specified
by ids.''')
rm_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''ids of checkerboards in the current group
to be removed''')
rm_parser.add_argument('-a', '--all', action='store_true',
help='''remove all checkerboards in the
current group''')
def help_rm(self):
self.__class__.rm_parser.print_help()
def do_rm(self, line):
"""Removes checkerboards specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, no boards to remove'
return
try:
args = self.__class__.rm_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rm_parser.print_usage()
return
rmlist = []
if args.all:
for shape in self.cur_group.shapes:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
print "all checkerboards removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_group.shapes) or x < 0:
print "checkerboard", x, "does not exist"
continue
rmlist.append(self.cur_group.shapes[x])
print "checkerboard", x, "removed"
for shape in rmlist:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
ls_parser = CmdParser(add_help=False, prog='ls',
description='''Lists project, display group and
checkerboard settings. If no group ids
are specified, all display groups
are listed.''')
ls_parser.add_argument('gidlist', nargs='*', metavar='gid', type=int,
help='''ids of the display groups to be listed''')
ls_group = ls_parser.add_mutually_exclusive_group()
ls_group.add_argument('-s', '--settings', action='store_true',
help='list only project settings')
ls_group.add_argument('-g', '--groups', action='store_true',
help='list only display groups')
def help_ls(self):
self.__class__.ls_parser.print_help()
def do_ls(self, line):
"""Lists project, display group and checkerboard settings."""
def ls_str(s, seps=[',',';']):
"""Special space-saving output formatter."""
if type(s) in [tuple, list]:
if len(seps) > 1:
newseps = seps[1:]
else:
newseps = seps
return seps[0].join([ls_str(i, newseps) for i in s])
else:
return str(s)
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.ls_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ls_parser.print_usage()
return
# Remove duplicates and ascending sort
args.gidlist = sorted(set(args.gidlist))
if len(self.cur_proj.groups) == 0:
if len(args.gidlist) > 0:
print 'this project has no display groups that can be listed'
args.settings = True
else:
for gid in args.gidlist[:]:
if gid >= len(self.cur_proj.groups) or gid < 0:
args.gidlist.remove(gid)
print 'display group', gid, 'does not exist'
if args.gidlist == []:
args.gidlist = range(len(self.cur_proj.groups))
else:
# If any (valid) groups are specified
# don't show project settings
args.groups = True
if not args.groups:
print 'PROJECT SETTINGS'.center(70,'*')
print \
'name'.rjust(16),\
'fps'.rjust(7),\
'resolution'.rjust(14),\
'bg color'.rjust(18)
# 'format'.rjust(7)
print \
ls_str(self.cur_proj.name).rjust(16),\
ls_str(self.cur_proj.fps).rjust(7),\
ls_str(self.cur_proj.res).rjust(14),\
ls_str(self.cur_proj.bg).rjust(18)
# ls_str(self.cur_proj.export_fmt).rjust(7)
print \
'pre-display'.rjust(26),\
'post-display'.rjust(26)
print \
ls_str(self.cur_proj.pre).rjust(26),\
ls_str(self.cur_proj.post).rjust(26)
print \
'cross colors'.rjust(26),\
'cross times'.rjust(26)
print \
ls_str(self.cur_proj.cross_cols).rjust(26),\
ls_str(self.cur_proj.cross_times).rjust(26)
if not args.settings and not args.groups:
# Insert empty line if both groups and project
# settings are listed
print ''
if not args.settings:
for i, n in enumerate(args.gidlist):
if i != 0:
# Print newline seperator between each group
print ''
group = self.cur_proj.groups[n]
print 'GROUP {n}'.format(n=n).center(70,'*')
print \
'pre-display'.rjust(20),\
'display'.rjust(20),\
'post-display'.rjust(20)
print \
ls_str(group.pre).rjust(20),\
ls_str(group.disp).rjust(20),\
ls_str(group.post).rjust(20)
if len(group.shapes) > 0:
print \
''.rjust(2),\
'shape id'.rjust(8),\
'dims'.rjust(10),\
'init_unit'.rjust(14),\
'end_unit'.rjust(14),\
'position'.rjust(14)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.dims).rjust(10),\
ls_str(shape.init_unit).rjust(14),\
ls_str(shape.end_unit).rjust(14),\
ls_str(shape.position).rjust(14)
print '\n',\
''.rjust(2),\
'shape id'.rjust(8),\
'colors'.rjust(27),\
'anchor'.rjust(12),\
'freq'.rjust(6),\
'phase'.rjust(7)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.cols).rjust(27),\
ls_str(shape.anchor).rjust(12),\
ls_str(shape.freq).rjust(6),\
ls_str(shape.phase).rjust(7)
display_parser = CmdParser(add_help=False, prog='display',
description='''Displays the animation in a
window or in fullscreen.''')
display_parser.add_argument('-e', '--expfile', metavar='PATH',
help='''run experiment as described in
specified file, ignore other flags''')
display_parser.add_argument('-f', '--fullscreen', action='store_true',
help='sets fullscreen mode, ESC to quit')
display_parser.add_argument('-p', '--priority', metavar='LEVEL',
help='''set priority while displaying,
higher priority results in
less dropped frames (choices:
0-3, low, normal, high,
realtime)''')
display_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly display specified display
groups N number of times''')
display_parser.add_argument('-pt', '--phototest', action='store_true',
help='''draw white test rectangle in topleft
corner of screen when groups become
visible for a photodiode to detect''')
display_parser.add_argument('-pb', '--photoburst', action='store_true',
help='''make checkerboards only draw first
color for one frame to facilitate
testing with a photodiode''')
display_parser.add_argument('-lt', '--logtime', action='store_true',
help='output frame timestamps to a log file')
display_parser.add_argument('-ld', '--logdur', action='store_true',
help='output frame durations to a log file')
display_parser.add_argument('-ss', '--sigser', action='store_true',
help='''send signals through the serial port
when shapes are being displayed''')
display_parser.add_argument('-sp', '--sigpar', action='store_true',
help='''send signals through the parallel port
when shapes are being displayed''')
display_parser.add_argument('-fpbs', metavar='M', type=int, default=0,
help='''unique signal corresponding to a
checkerboard is sent after the board
undergoes M color flips (default:
disabled, M=0)''')
display_parser.add_argument('-et', '--eyetrack', action='store_true',
help='''use eyetracking to ensure that subject
fixates on the cross in the center''')
display_parser.add_argument('-eu', '--etuser', action='store_true',
help='''allow user to select eyetracking video
source from a dialog''')
display_parser.add_argument('-ev', '--etvideo', metavar='path',
help='''path (with no spaces) to eyetracking
video file to be used as the source''')
display_parser.add_argument('-ta', '--tryagain', metavar='I',
type=int, default=0,
help='''append groups during which subject
failed to fixate up to I times to the
list of groups to be displayed
(default: disabled, I=0)''')
display_parser.add_argument('-tb', '--trybreak', metavar='J', type=int,
help='''used with --tryagain, append a wait
screen to the list of groups to be
displayed after every J groups have
been appended to the list (default:
J=total number of groups)''')
display_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be displayed
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_display(self):
self.__class__.display_parser.print_help()
def do_display(self, line):
"""Displays the animation in a window or in fullscreen"""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.display_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
- blk = None
if args.expfile != None:
try:
exp = core.CkgExp(path=args.expfile)
except IOError:
print "error:", str(sys.exc_value)
return
try:
args = self.__class__.\
display_parser.parse_args(shlex.split(exp.flags))
except (CmdParserError, ValueError):
print 'error: invalid flags stored in block file'
return
try:
print """name of log file (default: experiment name):"""
blkname = raw_input().strip().strip('"\'')
except EOFError:
return
if blkname == '':
blkname == exp.name
blk = exp.random_blk(blkname)
args.idlist = blk.idlist()
+ else:
+ blk = core.CkgBlk(name=self.cur_proj.name,
+ trials=None,
+ flags=line,
+ sequence=[])
groupq = []
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < -1:
print 'error: group', i, 'does not exist'
return
for i in args.idlist:
if i == -1:
groupq.append(core.CkgWaitScreen(res=self.cur_proj.res))
else:
groupq.append(self.cur_proj.groups[i])
else:
groupq = list(self.cur_proj.groups)
if args.repeat != None:
groupq = list(groupq * args.repeat)
if args.eyetrack and eyetracking.available:
if not eyetracking.is_calibrated():
try:
self.do_calibrate('',True)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
return
if args.priority != None:
if not priority.available:
print "error: setting priority not avaible on", sys.platform
print "continuing..."
else:
if args.priority.isdigit():
args.priority = int(args.priority)
try:
priority.set(args.priority)
except ValueError:
print "error:", str(sys.exc_value)
print "continuing..."
print "displaying..."
try:
- fail_idlist = self.cur_proj.display(fullscreen=args.fullscreen,
- logtime=args.logtime,
- logdur=args.logdur,
- sigser=args.sigser,
- sigpar=args.sigpar,
- fpbs=args.fpbs,
- phototest=args.phototest,
- photoburst=args.photoburst,
- eyetrack=args.eyetrack,
- etuser=args.etuser,
- etvideo=args.etvideo,
- tryagain=args.tryagain,
- trybreak=args.trybreak,
- groupq=groupq)
+ self.cur_proj.display(fullscreen=args.fullscreen,
+ logtime=args.logtime,
+ logdur=args.logdur,
+ sigser=args.sigser,
+ sigpar=args.sigpar,
+ fpbs=args.fpbs,
+ phototest=args.phototest,
+ photoburst=args.photoburst,
+ eyetrack=args.eyetrack,
+ etuser=args.etuser,
+ etvideo=args.etvideo,
+ tryagain=args.tryagain,
+ trybreak=args.trybreak,
+ groupq=groupq,
+ blk=blk)
except (IOError, NotImplementedError, eyetracking.EyetrackingError):
print "error:", str(sys.exc_value)
if args.priority != None:
try:
priority.set('normal')
except:
pass
return
if args.priority != None:
try:
priority.set('normal')
except:
pass
- # Save log file
- if blk != None:
- blk.fail_idlist = fail_idlist
- try:
- blk.write_log()
- except IOError:
- print "error:", str(sys.exc_value)
- return
- print "log file written"
+ try:
+ blk.write_log()
+ except IOError:
+ print "error:", str(sys.exc_value)
+ return
+ print "log file written"
export_parser = CmdParser(add_help=False, prog='export',
description='''Exports animation as an image
sequence (in a folder) to the
specified directory.''')
# export_parser.add_argument('--fmt', dest='export_fmt',
# choices=core.EXPORT_FMTS,
# help='image format for export')
export_parser.add_argument('-n','--nofolder',
dest='folder', action='store_false',
help='''force images not to exported in
a containing folder''')
export_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly export specified display
groups N number of times''')
export_parser.add_argument('duration', nargs='?',
type=to_decimal, default='Infinity',
help='''number of seconds of the animation
that should be exported (default:
as long as the entire animation)''')
export_parser.add_argument('dir', nargs='?', default=os.getcwd(),
help='''destination directory for export
(default: current working directory)''')
export_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be exported
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_export(self):
self.__class__.export_parser.print_help()
def do_export(self, line):
"""Exports animation an image sequence to the specified directory."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.export_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.export_parser.print_usage()
return
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < 0:
print 'error: group', i, 'does not exist'
return
groupq = [self.cur_proj.groups[i] for i in args.idlist]
else:
groupq = list(self.cur_proj.groups)
if args.repeat != None:
groupq = list(groupq * args.repeat)
try:
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
folder=args.folder)
except IOError:
print "error:", str(sys.exc_value)
return
except core.FrameOverflowError:
print "warning:", str(sys.exc_value)
print "Are you sure you want to continue?"
while True:
try:
if self.__class__.yn_parse(raw_input()):
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
export_fmt=None,
folder=args.folder,
force=True)
break
else:
return
except TypeError:
print str(sys.exc_value)
except EOFError:
return
print "Export done."
mkexp_parser = CmdParser(add_help=False, prog='mkexp',
description='''Create checkergen experiment file
which describes how the project
is to be displayed.''')
mkexp_parser.add_argument('-n', '--name',
help='''name of the experiment (default: same
name as current project)''')
mkexp_parser.add_argument('-t', '--trials', type=int, metavar='N',
help='''N trials displayed in a block, i.e.
the same sequence will be displayed
N times in that block, with waitscreens
in between''')
mkexp_parser.add_argument('-f', '--flags',
help='''flags passed to the display command
that should be used when the block
file is run (enclose in quotes and use
'+' or '++' in place of '-' or '--')''')
def help_mkexp(self):
self.__class__.mkexp_parser.print_help()
def do_mkexp(self, line):
"""Creates checkergen experiment file."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.mkexp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mkexp_parser.print_usage()
return
if args.trials == None:
print "number of trials:"
try:
args.trials = int(raw_input().strip())
except EOFError:
return
if args.flags != None:
args.flags = args.flags.replace('+','-')
else:
print "flags used with display command (leave blank if none):"
try:
args.flags = raw_input().strip().strip('"\'')
except EOFError:
return
try:
disp_args = self.__class__.display_parser.\
parse_args(shlex.split(args.flags))
except (CmdParserError, ValueError):
print "error: invalid flags to display command"
print str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
print "list of sequences to choose from in the format",\
"'id1,id2,id3;seq2;seq3;seq4':"
print "(default: reduced latin square)"
try:
seqs_str = raw_input().strip()
if seqs_str == '':
args.sequences = None
else:
args.sequences = [[int(i) for i in seq_str.split(',')]
for seq_str in seqs_str.split(';')]
except EOFError:
return
try:
new_exp = core.CkgExp(name=args.name, proj=self.cur_proj,
trials=args.trials,
sequences=args.sequences,
flags=args.flags)
new_exp.save()
except IOError:
print "error:", str(sys.exc_value)
return
print "Experiment file created."
def do_calibrate(self, line, query=False):
"""Calibrate subject for eyetracking, or load a calibration file."""
if not eyetracking.available:
print "error: eyetracking functionality not available"
return
if query:
print "path to calibration file (leave empty for GUI tool):"
try:
path = raw_input().strip().strip('"\'')
except EOFError:
msg = "calibration cancelled"
raise eyetracking.EyetrackingError(msg)
else:
path = line.strip().strip('"\'')
if len(path) == 0:
path = None
if not eyetracking.is_source_ready():
# Select default source if none has been selected
eyetracking.select_source()
try:
eyetracking.calibrate(path)
except eyetracking.EyetrackingError:
if query:
raise
else:
print "error:", str(sys.exc_value)
return
if len(path) > 0:
print "calibration file successfully loaded"
etsetup_parser = CmdParser(add_help=False, prog='etsetup',
description='''Set various eyetracking
parameters.''')
etsetup_parser.add_argument('-fp', '--fixperiod', type=int, metavar='MS',
help='''time in milliseconds subject
has to stare at the same spot
for fixation to be detected''')
etsetup_parser.add_argument('-fr', '--fixrange', type=float, metavar='MM',
help='''distance in mm beyond which the
eye position cannot change for
a fixation to be detected''')
etsetup_parser.add_argument('-s', '--size', metavar='WIDTH,HEIGHT',
action=store_tuple(2, ',', float),
help='physical screen dimensions in mm')
etsetup_parser.add_argument('-vd', '--viewdist', type=int, metavar='MM',
help='''viewing distance between subject's
eyes and the screen''')
def help_etsetup(self):
self.__class__.etsetup_parser.print_help()
def do_etsetup(self, line):
try:
args = self.__class__.etsetup_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.etsetup_parser.print_usage()
return
try:
eyetracking.setup(viewing_distance=args.viewdist,
screen_dims=args.size,
fixation_period=args.fixperiod,
fixation_range=args.fixrange)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
def do_pwd(self, line):
"""Prints the current working directory."""
print os.getcwd()
def do_cd(self, line):
"""Change working directory to specified path."""
path = line.strip().strip('"\'')
if not os.path.isdir(path):
print "error: specified path is not a directory"
return
os.chdir(path)
def do_quit(self, line):
"""Quits the program."""
if self.save_check():
return
return True
def help_EOF(self):
print "Typing {0} issues this command, which quits the program."\
.format(CMD_EOF_STRING)
def do_EOF(self, line):
"""Typing Ctrl-D issues this command, which quits the program."""
print '\r'
if self.save_check():
return
return True
def help_help(self):
print 'Prints a list of commands.'
print "Type 'help <topic>' for more details on each command."
def default(self, line):
command = line.split()[0]
print \
"'{0}' is not a checkergen command.".format(command),\
"Type 'help' for a list of commands"
diff --git a/src/core.py b/src/core.py
index 3e7bd69..0042753 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,1215 +1,1223 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgExp -- A checkergen experiment, describes how a projet is displayed.
CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import random
import itertools
from xml.dom import minidom
import pyglet
import graphics
import signals
import eyetracking
from utils import *
CKG_FMT = 'ckg'
EXP_FMT = 'ckx'
LOG_FMT = 'log'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
MAX_EXPORT_FRAMES = 100000
PRERENDER_TO_TEXTURE = False
INT_HALF_PERIODS = True
EXPORT_FMTS = ['png']
EXPORT_DIR_SUFFIX = '-anim'
BLOCK_DIR_SUFFIX = '-blks'
FIX_POS = (0, 0)
FIX_RANGE = (20, 20)
FIX_PER = 350
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = {'name': 'untitled',
'fps': 60,
'res': (800, 600),
'bg': (127, 127, 127),
'export_fmt': 'png',
'pre': 0,
'post': 0,
'cross_cols': ((0, 0, 0), (255, 0, 0)),
'cross_times': ('Infinity', 1)}
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
export_fmt -- image format for animation to be exported as
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'export_fmt':
if value not in EXPORT_FMTS:
msg = 'image format not recognized or supported'
raise FileFormatError(msg)
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
vars_to_load = self.__class__.DEFAULTS.keys()
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
vars_to_save = self.__class__.DEFAULTS.keys()
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def display(self, fullscreen=False, logtime=False, logdur=False,
sigser=False, sigpar=False, fpbs=0,
phototest=False, photoburst=False,
eyetrack=False, etuser=False, etvideo=None,
- tryagain=0, trybreak=None, groupq=[]):
+ tryagain=0, trybreak=None, groupq=[], blk=None):
"""Displays the project animation on the screen.
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
sigser -- send signals through serial port when each group is shown
sigpar -- send signals through parallel port when each group is shown
fpbs -- flips per board signal, i.e. number of shape color reversals
(flips) that occur for a unique signal to be sent for that shape
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- Append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- Append a wait screen to the group queue every time
after this many groups have been appended to the queue
groupq -- queue of groups to be displayed, defaults to order of
groups in project (i.e. groups[0] first, etc.)
-
+
+ blk -- experimental block where logged variables are saved (i.e.
+ fail_idlist and time information)
+
"""
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if phototest:
test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Set-up groups and variables that control their display
if groupq == []:
groupq = list(self.groups)
n = -1
flipped = 0
flip_id = -1
groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Initialize ports
if sigser:
if not signals.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if sigpar:
if not signals.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
signals.init(sigser, sigpar)
# Initialize eyetracking
if eyetrack:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if trybreak == None:
trybreak = len(self.groups)
fixated = False
old_fixated = False
tracked = False
old_tracked = False
cur_fix_fail = False
fail_idlist = []
eyetracking.select_source(etuser, etvideo)
eyetracking.start()
# Stretch to fit screen only if project res does not equal screen res
scaling = False
if fullscreen:
window = pyglet.window.Window(fullscreen=True, visible=False)
if (window.width, window.height) != self.res:
scaling = True
else:
window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
keystates = pyglet.window.key.KeyStateHandler()
window.push_handlers(keystates)
# Create framebuffer object for drawing unscaled scene
if scaling:
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
fbo.end_render()
# Clear window and make visible
window.switch_to()
graphics.set_clear_color(self.bg)
window.clear()
window.set_visible()
# Initialize logging variables
- if logtime and logdur:
- logstring = ''
- stamp = Timer()
- dur = Timer()
- stamp.start()
- dur.start()
- elif logtime or logdur:
- logstring = ''
+ if logtime:
+ timestamps = []
+ sigstamps = []
timer = Timer()
timer.start()
+ if logdur:
+ durstamps = []
+ dur = Timer()
+ dur.start()
# Main loop
while not window.has_exit and count < disp_end:
# Clear canvas
if scaling:
fbo.start_render()
fbo.clear()
else:
window.clear()
# Assume no change to group visibility
flipped = 0
signals.set_null()
# Manage groups when they are on_screen
if groups_visible:
# Check whether group changes in visibility
if n >= 0 and groupq[n].visible != groupq[n].old_visible:
flip_id = self.groups.index(groupq[n])
if groupq[n].visible:
flipped = 1
elif groupq[n].old_visible:
flipped = -1
# Get next group from queue
if n < 0 or groupq[n].over:
# Send special signal if waitscreen ends
if isinstance(groupq[n], CkgWaitScreen):
signals.set_user_start()
n += 1
if n >= len(groupq):
groups_visible = False
else:
groupq[n].reset()
if eyetrack:
cur_fix_fail = False
if groupq[n].visible:
flip_id = self.groups.index(groupq[n])
flipped = 1
# Draw and then update group
if n >= 0:
groupq[n].draw(photoburst=photoburst)
groupq[n].update(fps=self.fps,
fpbs=fpbs,
keystates=keystates)
# Send signals upon group visibility change
if flipped == 1:
signals.set_group_start(flip_id)
# Draw test rectangle
if phototest:
test_rect.draw()
elif flipped == -1:
signals.set_group_stop(flip_id)
if eyetrack:
# First check if eye is being tracked and send signals
old_tracked = tracked
tracked = eyetracking.is_tracked()
if tracked:
if not old_tracked:
# Send signal if eye starts being tracked
signals.set_track_start()
else:
if old_tracked:
# Send signal if eye stops being tracked
signals.set_track_stop()
# Next check for fixation
old_fixated = fixated
fixated = eyetracking.is_fixated(FIX_POS, FIX_RANGE, FIX_PER)
if fixated:
# Draw normal cross color if fixating
fix_crosses[0].draw()
if not old_fixated:
# Send signal if fixation starts
signals.set_fix_start()
else:
# Draw alternative cross color if not fixating
fix_crosses[1].draw()
if old_fixated:
# Send signal if fixation stops
signals.set_fix_stop()
# Take note of which groups in which fixation failed
if not cur_fix_fail and groupq[n].visible and\
(tracked and not fixated):
cur_fix_fail = True
if len(fail_idlist) == 0 and trybreak > 0:
groupq.append(CkgWaitScreen(res=self.res))
fail_idlist.append(self.groups.index(groupq[n]))
# Append failed group to group queue
if tryagain > 0:
groupq.append(groupq[n])
groups_stop += groupq[n].duration() * self.fps
disp_end += groupq[n].duration() * self.fps
# Insert waitscreen every trybreak failed groups
if trybreak > 0:
if len(fail_idlist) % trybreak == 0:
groupq.append(CkgWaitScreen())
tryagain -= 1
# Change cross color based on time if eyetracking is not enabled
if not eyetrack:
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Increment count and set whether groups should be shown
if not isinstance(groupq[n], CkgWaitScreen):
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
# Blit canvas to screen if necessary
if scaling:
fbo.end_render()
window.switch_to()
canvas.blit(0, 0)
window.dispatch_events()
window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
- # Append time information to log string
- if logtime and logdur:
- logstring = '\n'.join([logstring, str(stamp.elapsed())])
- logstring = '\t'.join([logstring, str(dur.restart())])
- elif logtime:
- logstring = '\n'.join([logstring, str(timer.elapsed())])
- elif logdur:
- logstring = '\n'.join([logstring, str(timer.restart())])
+ # Append time information to lists
+ if logtime:
+ timestamps.append(timer.elapsed())
+ if logdur:
+ durstamps.append(dur.restart())
# Send signals ASAP after flip
signals.send(sigser, sigpar)
# Log when signals are sent
- if logtime or logdur:
+ if logtime:
if flipped != 0 and (sigser or sigpar):
- sigmsg = '{0} sent'.format(signals.STATE)
- logstring = '\t'.join([logstring, sigmsg])
+ sigstamps.append(signals.STATE)
+ else:
+ sigstamps.append('')
# Clean up
if eyetrack:
eyetracking.stop()
window.close()
if scaling:
fbo.delete()
del canvas
signals.quit(sigser, sigpar)
- # Write log string to file
- if logtime or logdur:
- filename = '{0}.log'.format(self.name)
- with open(filename, 'w') as logfile:
- logfile.write(logstring)
-
- # Return list of ids of failed groups
- if eyetrack and len(fail_idlist) > 0:
- return fail_idlist
+ # Store variables in block object
+ if blk != None:
+ if logtime:
+ blk.timestamps = timestamps
+ blk.sigstamps = sigstamps
+ if logdur:
+ blk.durstamps = durstamps
+ if eyetrack and len(fail_idlist) > 0:
+ blk.fail_idlist = fail_idlist
def export(self, export_dir, export_duration, groupq=[],
export_fmt=None, folder=True, force=False):
if not os.path.isdir(export_dir):
msg = 'export path is not a directory'
raise IOError(msg)
if export_fmt == None:
export_fmt = self.export_fmt
# Set-up groups and variables that control their display
if groupq == []:
groupq = list(self.groups)
n = -1
groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Limit export duration to display duration
frames = export_duration * self.fps
frames = min(frames, disp_end)
# Warn user if a lot of frames will be exported
if frames > MAX_EXPORT_FRAMES and not force:
msg = 'very large number ({0}) of frames to be exported'.\
format(frames)
raise FrameOverflowError(msg)
# Create folder to store images if necessary
if folder:
export_dir = os.path.join(export_dir,
self.name + EXPORT_DIR_SUFFIX)
if not os.path.isdir(export_dir):
os.mkdir(export_dir)
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Set up canvas and framebuffer object
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
# Main loop
while count < frames:
fbo.clear()
if groups_visible:
# Get next group from queue
if n < 0 or groupq[n].over:
n += 1
if n >= len(groupq):
groups_visible = False
else:
groupq[n].reset()
# Draw and then update group
if n >= 0:
groupq[n].draw()
groupq[n].update(fps=self.fps, fpbs=0)
# Draw fixation cross based on current count
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Save current frame to file
savepath = \
os.path.join(export_dir,
'{0}{2}.{1}'.
format(self.name, export_fmt,
repr(count).zfill(numdigits(frames-1))))
canvas.save(savepath)
# Increment count and set whether groups should be shown
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
fbo.delete()
class CkgExp:
DEFAULTS = {'name': None, 'proj' : None,
'trials': 1, 'sequences': None,
'flags': '--fullscreen --logtime --logdur'}
def __init__(self, **keywords):
"""Create a checkergen experiment, which specifies how a project
is to be displayed.
path -- if specified, ignore other arguments and load project
from path
name -- name of the experiment
proj -- CkgProj that the experiment is to be created for
trials -- number of times the selected sequence of display groups
will be shown in one block
sequences -- list of possible display group id sequences, from which
one sequence will be randomly selected for display in a block,
defaults to reduced latin square with side length equal to the number
of display groups in the supplied CkgProj
flags -- string passed to the display command as flags
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
if self.name == None and self.proj != None:
self.name = self.proj.name
if self.sequences == None:
if self.proj == None:
msg = "either project or sequences have to be specified"
raise ValueError(msg)
else:
self.gen_latin_square(len(self.proj.groups))
del self.proj
def gen_latin_square(self, n):
"""Set experiment sequences as a cyclic reduced latin square."""
sequence = range(n)
self.sequences = [[sequence[i - j] for i in range(n)]
for j in range(n, 0, -1)]
def random_blk(self, name):
"""Choose random sequence, create block from it and return."""
sequence = random.choice(self.sequences)
blk = CkgBlk(name=name,
flags=self.flags,
trials=self.trials,
sequence=sequence)
return blk
def save(self, path=None):
"""Saves experiment to specified path in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, EXP_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(EXP_FMT):
path = '{0}.{1}'.format(path, EXP_FMT)
with open(path, 'wb') as expfile:
expwriter = csv.writer(expfile, dialect='excel-tab')
expwriter.writerow(['checkergen experiment file'])
expwriter.writerow(['flags:', self.flags])
expwriter.writerow(['trials:', self.trials])
expwriter.writerow(['sequences:'])
for sequence in self.sequences:
expwriter.writerow(sequence)
def load(self, path):
"""Loads experiment from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, EXP_FMT)
elif ext != '.{0}'.format(EXP_FMT):
msg = "path lacks '.{0}' extension".format(EXP_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
self.sequences = []
with open(path, 'rb') as expfile:
expreader = csv.reader(expfile, dialect='excel-tab')
for n, row in enumerate(expreader):
if n == 1:
self.flags = row[1]
elif n == 2:
self.trials = int(row[1])
elif n > 3:
sequence = [int(i) for i in row]
self.sequences.append(sequence)
class CkgBlk:
def __init__(self, name, flags, trials, sequence):
"""Creates an experimental block."""
self.name = name
self.flags = flags
self.trials = trials
self.sequence = sequence
self.fail_idlist = None
- self.timelog = None
+ self.timestamps = []
+ self.durstamps = []
+ self.sigstamps = []
def idlist(self):
"""Generate idlist from sequence and return it."""
idlist = ([-1] + self.sequence) * self.trials
return idlist
def write_log(self, path=None):
"""Write a log file for the experimental block in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, LOG_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(LOG_FMT):
path = '{0}.{1}'.format(path, LOG_FMT)
with open(path, 'wb') as blkfile:
blkwriter = csv.writer(blkfile, dialect='excel-tab')
blkwriter.writerow(['checkergen log file'])
blkwriter.writerow(['flags:', self.flags])
blkwriter.writerow(['trials:', self.trials])
blkwriter.writerow(['sequence:'] + self.sequence)
if self.fail_idlist != None:
blkwriter.writerow(['groups added:'])
rowlist = grouper(len(self.sequence), self.fail_idlist, '')
for row in rowlist:
blkwriter.writerow(row)
- if self.timelog != None:
- pass
-
+ stamps = [self.timestamps, self.durstamps, self.sigstamps]
+ if len(max(stamps)) > 0:
+ for l in stamps:
+ if len(l) == 0:
+ l = [''] * len(max(stamps))
+ blkwriter.writerow(['timestamps', 'durations', 'triggers'])
+ for row in zip(*stamps):
+ blkwriter.writerow(row)
+
class CkgDisplayGroup:
DEFAULTS = {'pre': 0, 'disp': 'Infinity', 'post': 0}
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets internal count and all contained shapes."""
self._count = 0
self._start = self.pre
self._stop = self.pre + self.disp
self._end = self.pre + self.disp + self.post
self.over = False
self.old_visible = False
if self._start == 0 and self._stop > 0:
self.visible = True
else:
self.visible = False
if self._end == 0:
self.over = True
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, lazy=False, photoburst=False):
"""Draws all contained shapes during the appropriate interval."""
if self.visible:
for shape in self.shapes:
if lazy:
shape.lazydraw()
else:
shape.draw(photoburst=photoburst)
def update(self, **keywords):
"""Increments internal count, makes group visible when appropriate.
fps -- refresh rate of the display in frames per second
fpbs -- flips per board signal, i.e. number of shape color reversals
(flips) that occur for a unique signal to be sent for that shape
"""
fps = keywords['fps']
fpbs = keywords['fpbs']
if self.visible:
# Set triggers to be sent
if fpbs > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= fpbs:
signals.set_board_flip(n)
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(fps)
# Increment count and set flags for the next frame
self._count += 1
self.old_visible = self.visible
if (self._start * fps) <= self._count < (self._stop * fps):
self.visible = True
else:
self.visible = False
if self._count >= (self._end * fps):
self.over = True
else:
self.over = False
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.visible = False
self.old_visible = False
self.steps_done = 0
self.over = False
def draw(self, **keywords):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, **keywords):
"""Checks for keypress, sends signal upon end."""
keystates = keywords['keystates']
if max([keystates[key] for key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
if self.steps_done == self.num_steps:
self.over = True
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = {'dims': (5, 5),
'init_unit': (30, 30), 'end_unit': (50, 50),
'position': (0, 0), 'anchor': 'bottomleft',
'cols': ((0, 0, 0), (255, 255, 255)),
'freq': 1, 'phase': 0}
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
if INT_HALF_PERIODS:
frames_per_half_period = round(fps / (self.freq * 2))
degs_per_frame = 180 / to_decimal(frames_per_half_period)
else:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
if PRERENDER_TO_TEXTURE:
init_pos = [(1 - a)* s/to_decimal(2) for s, a in
zip(self._size, graphics.locations[self.anchor])]
else:
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
anchor=self.anchor)
cur_unit_rect.col = self.cols[(i + j) % 2]
cur_unit_rect.add_to_batch(self._batches[0])
cur_unit_rect.col = self.cols[(i + j + 1) % 2]
cur_unit_rect.add_to_batch(self._batches[1])
# Increase x values
cur_unit_pos[0] += \
graphics.locations[self.anchor][0] * cur_unit[0]
cur_unit[0] += unit_grad[0]
# Reset x values
cur_unit_pos[0] = init_pos[0]
cur_unit[0] = init_unit[0]
# Increase y values
cur_unit_pos[1] += \
graphics.locations[self.anchor][1] * cur_unit[1]
cur_unit[1] += unit_grad[1]
if PRERENDER_TO_TEXTURE:
# Create textures
int_size = [int(round(s)) for s in self._size]
self._prerenders =\
[pyglet.image.Texture.create(*int_size) for n in range(2)]
# Set up framebuffer
fbo = graphics.Framebuffer()
for n in range(2):
fbo.attach_texture(self._prerenders[n])
# Draw batch to texture
fbo.start_render()
self._batches[n].draw()
fbo.end_render()
# Anchor textures for correct blitting later
self._prerenders[n].anchor_x, self._prerenders[n].anchor_y =\
[int(round((1 - a)* s/to_decimal(2))) for s, a in
zip(self._size, graphics.locations[self.anchor])]
fbo.delete()
# Delete batches since they won't be used
del self._batches
self._computed = True
def draw(self, photoburst=False, always_compute=False):
"""Draws appropriate prerender depending on current phase.
photoburst -- draw first color for only one frame for testing purposes
always_compute -- recompute what the checkerboard should look like
every frame
"""
if not self._computed or always_compute:
self.compute()
self._cur_phase %= 360
n = int(self._cur_phase // 180)
if photoburst and n == 0 and not self.flipped:
n = 1
if PRERENDER_TO_TEXTURE:
self._prerenders[n].blit(*self.position)
else:
self._batches[n].draw()
def lazydraw(self):
"""Only draws on color reversal."""
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if (cur_n != prev_n) or self._first_draw:
self.draw()
if self._first_draw:
self._first_draw = False
|
ztangent/checkergen
|
1de7388595fe9db11095ed41e261c45bff092cba
|
Experiment functionality working, old blockwise method excised.
|
diff --git a/src/cli.py b/src/cli.py
index d216017..e700557 100644
--- a/src/cli.py
+++ b/src/cli.py
@@ -235,958 +235,964 @@ class CkgCmd(cmd.Cmd):
set_parser.add_argument('--cross_times', metavar='TIME1,TIME2',
action=store_tuple(2, ',', to_decimal),
help='''time in seconds each cross color
will be displayed''')
def help_set(self):
self.__class__.set_parser.print_help()
def do_set(self, line):
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
try:
args = self.__class__.set_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.set_parser.print_usage()
return
names = public_dir(args)
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
setattr(self.cur_proj, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.set_parser.print_usage()
mkgrp_parser = CmdParser(add_help=False, prog='mkgrp',
formatter_class=
argparse.ArgumentDefaultsHelpFormatter,
description='''Makes a new display group
with the given parameters.''')
mkgrp_parser.add_argument('pre', type=to_decimal, default=0, nargs='?',
help='''time in seconds a blank screen will
be shown before shapes are displayed''')
mkgrp_parser.add_argument('disp', type=to_decimal,
nargs='?', default='Infinity',
help='''time in seconds shapes will be
displayed''')
mkgrp_parser.add_argument('post', type=to_decimal, default=0, nargs='?',
help='''time in seconds a blank screen will
be shown after shapes are displayed''')
def help_mkgrp(self):
self.__class__.mkgrp_parser.print_help()
def do_mkgrp(self, line):
"""Makes a display group with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
try:
args = self.__class__.mkgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mkgrp_parser.print_usage()
return
group_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_group = core.CkgDisplayGroup(**group_dict)
new_id = self.cur_proj.add_group(new_group)
print "display group", new_id, "added"
self.cur_group = new_group
print "group", new_id, "is now the current display group"
edgrp_parser = CmdParser(add_help=False, prog='edgrp',
description='''Edits attributes of display groups
specified by ids.''')
edgrp_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='ids of display groups to be edited')
edgrp_parser.add_argument('--pre', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown before shapes are displayed''')
edgrp_parser.add_argument('--disp', type=to_decimal, metavar='SECONDS',
help='''time in seconds shapes will be
displayed''')
edgrp_parser.add_argument('--post', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown after shapes are displayed''')
def help_edgrp(self):
self.__class__.edgrp_parser.print_help()
def do_edgrp(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.edgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.edgrp_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_proj.groups) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_group_attr(x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.edgrp_parser.print_usage()
rmgrp_parser = CmdParser(add_help=False, prog='rmgrp',
description='''Removes display groups specified
by ids.''')
rmgrp_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='ids of display groups to be removed')
rmgrp_parser.add_argument('-a', '--all', action='store_true',
help='remove all groups from the project')
def help_rmgrp(self):
self.__class__.rmgrp_parser.print_help()
def do_rmgrp(self, line):
"""Removes display groups specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups to remove'
return
try:
args = self.__class__.rmgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rmgrp_parser.print_usage()
return
rmlist = []
if args.all:
for group in self.cur_proj.groups[:]:
self.cur_proj.del_group(group)
print "all display groups removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_proj.groups) or x < 0:
print "display group", x, "does not exist"
continue
rmlist.append(self.cur_proj.groups[x])
print "display group", x, "removed"
for group in rmlist:
self.cur_proj.del_group(group)
# Remember to point self.cur_group somewhere sane
if self.cur_group not in self.cur_proj.groups:
if len(self.cur_proj.groups) == 0:
self.cur_group = None
else:
self.cur_group = self.cur_proj.groups[0]
print "group 0 is now the current display group"
chgrp_parser = CmdParser(add_help=False, prog='chgrp',
description='''Changes display group that is
currently active for editing.
Prints current group id if
no group id is specified''')
chgrp_parser.add_argument('gid', metavar='id', type=int, nargs='?',
help='id of display group to be made active')
def help_chgrp(self):
self.__class__.chgrp_parser.print_help()
def do_chgrp(self, line):
"""Changes group that is currently active for editing."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups that can be made active'
return
try:
args = self.__class__.chgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.chgrp_parser.print_usage()
return
if args.gid == None:
print "group",\
self.cur_proj.groups.index(self.cur_group),\
"is the current display group"
elif args.gid >= len(self.cur_proj.groups) or args.gid < 0:
print "group", args.gid, "does not exist"
else:
self.cur_group = self.cur_proj.groups[args.gid]
print "group", args.gid, "is now the current display group"
mk_parser = CmdParser(add_help=False, prog='mk',
description='''Makes a new checkerboard in the
current group with the given
parameters.''')
mk_parser.add_argument('dims', action=store_tuple(2, ',', to_decimal),
help='''width,height of checkerboard in no. of
unit cells''')
mk_parser.add_argument('init_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of initial unit cell in pixels')
mk_parser.add_argument('end_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of final unit cell in pixels')
mk_parser.add_argument('position', action=store_tuple(2, ',', to_decimal),
help='x,y position of checkerboard in pixels')
mk_parser.add_argument('anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='anchor')
mk_parser.add_argument('cols', action=store_tuple(2, ',', to_color, [';']),
help='''color1,color2 of the checkerboard
(color format: R;G;B,
component range from 0-255)''')
mk_parser.add_argument('freq', type=to_decimal,
help='frequency of color reversal in Hz')
mk_parser.add_argument('phase', type=to_decimal, nargs='?', default='0',
help='initial phase of animation in degrees')
def help_mk(self):
self.__class__.mk_parser.print_help()
def do_mk(self, line):
"""Makes a checkerboard with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
if self.cur_group == None:
print 'automatically adding display group...'
self.do_mkgrp('')
try:
args = self.__class__.mk_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mk_parser.print_usage()
return
shape_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_shape = core.CheckerBoard(**shape_dict)
new_id = self.cur_proj.add_shape_to_group(self.cur_group, new_shape)
print "checkerboard", new_id, "added"
ed_parser = CmdParser(add_help=False, prog='ed',
description='''Edits attributes of checkerboards
specified by ids.''')
ed_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='''ids of checkerboards in the current
group to be edited''')
ed_parser.add_argument('--dims', action=store_tuple(2, ',', to_decimal),
help='checkerboard dimensions in unit cells',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--init_unit',
action=store_tuple(2, ',', to_decimal),
help='initial unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--end_unit',
action=store_tuple(2, ',', to_decimal),
help='final unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--position',
action=store_tuple(2, ',', to_decimal),
help='position of checkerboard in pixels',
metavar='X,Y')
ed_parser.add_argument('--anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='LOCATION')
ed_parser.add_argument('--cols', metavar='COLOR1,COLOR2',
action=store_tuple(2, ',', to_color, [';']),
help='''checkerboard colors (color format:
R;G;B, component range
from 0-255)''')
ed_parser.add_argument('--freq', type=to_decimal,
help='frequency of color reversal in Hz')
ed_parser.add_argument('--phase', type=to_decimal,
help='initial phase of animation in degrees')
def help_ed(self):
self.__class__.ed_parser.print_help()
def do_ed(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, please create one first'
return
try:
args = self.__class__.ed_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ed_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_group.shapes) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_shape_attr(self.cur_group, x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.ed_parser.print_usage()
rm_parser = CmdParser(add_help=False, prog='rm',
description='''Removes checkerboards specified
by ids.''')
rm_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''ids of checkerboards in the current group
to be removed''')
rm_parser.add_argument('-a', '--all', action='store_true',
help='''remove all checkerboards in the
current group''')
def help_rm(self):
self.__class__.rm_parser.print_help()
def do_rm(self, line):
"""Removes checkerboards specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, no boards to remove'
return
try:
args = self.__class__.rm_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rm_parser.print_usage()
return
rmlist = []
if args.all:
for shape in self.cur_group.shapes:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
print "all checkerboards removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_group.shapes) or x < 0:
print "checkerboard", x, "does not exist"
continue
rmlist.append(self.cur_group.shapes[x])
print "checkerboard", x, "removed"
for shape in rmlist:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
ls_parser = CmdParser(add_help=False, prog='ls',
description='''Lists project, display group and
checkerboard settings. If no group ids
are specified, all display groups
are listed.''')
ls_parser.add_argument('gidlist', nargs='*', metavar='gid', type=int,
help='''ids of the display groups to be listed''')
ls_group = ls_parser.add_mutually_exclusive_group()
ls_group.add_argument('-s', '--settings', action='store_true',
help='list only project settings')
ls_group.add_argument('-g', '--groups', action='store_true',
help='list only display groups')
def help_ls(self):
self.__class__.ls_parser.print_help()
def do_ls(self, line):
"""Lists project, display group and checkerboard settings."""
def ls_str(s, seps=[',',';']):
"""Special space-saving output formatter."""
if type(s) in [tuple, list]:
if len(seps) > 1:
newseps = seps[1:]
else:
newseps = seps
return seps[0].join([ls_str(i, newseps) for i in s])
else:
return str(s)
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.ls_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ls_parser.print_usage()
return
# Remove duplicates and ascending sort
args.gidlist = sorted(set(args.gidlist))
if len(self.cur_proj.groups) == 0:
if len(args.gidlist) > 0:
print 'this project has no display groups that can be listed'
args.settings = True
else:
for gid in args.gidlist[:]:
if gid >= len(self.cur_proj.groups) or gid < 0:
args.gidlist.remove(gid)
print 'display group', gid, 'does not exist'
if args.gidlist == []:
args.gidlist = range(len(self.cur_proj.groups))
else:
# If any (valid) groups are specified
# don't show project settings
args.groups = True
if not args.groups:
print 'PROJECT SETTINGS'.center(70,'*')
print \
'name'.rjust(16),\
'fps'.rjust(7),\
'resolution'.rjust(14),\
'bg color'.rjust(18)
# 'format'.rjust(7)
print \
ls_str(self.cur_proj.name).rjust(16),\
ls_str(self.cur_proj.fps).rjust(7),\
ls_str(self.cur_proj.res).rjust(14),\
ls_str(self.cur_proj.bg).rjust(18)
# ls_str(self.cur_proj.export_fmt).rjust(7)
print \
'pre-display'.rjust(26),\
'post-display'.rjust(26)
print \
ls_str(self.cur_proj.pre).rjust(26),\
ls_str(self.cur_proj.post).rjust(26)
print \
'cross colors'.rjust(26),\
'cross times'.rjust(26)
print \
ls_str(self.cur_proj.cross_cols).rjust(26),\
ls_str(self.cur_proj.cross_times).rjust(26)
if not args.settings and not args.groups:
# Insert empty line if both groups and project
# settings are listed
print ''
if not args.settings:
for i, n in enumerate(args.gidlist):
if i != 0:
# Print newline seperator between each group
print ''
group = self.cur_proj.groups[n]
print 'GROUP {n}'.format(n=n).center(70,'*')
print \
'pre-display'.rjust(20),\
'display'.rjust(20),\
'post-display'.rjust(20)
print \
ls_str(group.pre).rjust(20),\
ls_str(group.disp).rjust(20),\
ls_str(group.post).rjust(20)
if len(group.shapes) > 0:
print \
''.rjust(2),\
'shape id'.rjust(8),\
'dims'.rjust(10),\
'init_unit'.rjust(14),\
'end_unit'.rjust(14),\
'position'.rjust(14)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.dims).rjust(10),\
ls_str(shape.init_unit).rjust(14),\
ls_str(shape.end_unit).rjust(14),\
ls_str(shape.position).rjust(14)
print '\n',\
''.rjust(2),\
'shape id'.rjust(8),\
'colors'.rjust(27),\
'anchor'.rjust(12),\
'freq'.rjust(6),\
'phase'.rjust(7)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.cols).rjust(27),\
ls_str(shape.anchor).rjust(12),\
ls_str(shape.freq).rjust(6),\
ls_str(shape.phase).rjust(7)
display_parser = CmdParser(add_help=False, prog='display',
description='''Displays the animation in a
window or in fullscreen.''')
- display_parser.add_argument('-b', '--block', metavar='PATH',
- help='''read flags and dislay group order from
+ display_parser.add_argument('-e', '--expfile', metavar='PATH',
+ help='''run experiment as described in
specified file, ignore other flags''')
display_parser.add_argument('-f', '--fullscreen', action='store_true',
help='sets fullscreen mode, ESC to quit')
display_parser.add_argument('-p', '--priority', metavar='LEVEL',
help='''set priority while displaying,
higher priority results in
less dropped frames (choices:
0-3, low, normal, high,
realtime)''')
display_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly display specified display
groups N number of times''')
display_parser.add_argument('-pt', '--phototest', action='store_true',
help='''draw white test rectangle in topleft
corner of screen when groups become
visible for a photodiode to detect''')
display_parser.add_argument('-pb', '--photoburst', action='store_true',
help='''make checkerboards only draw first
color for one frame to facilitate
testing with a photodiode''')
display_parser.add_argument('-lt', '--logtime', action='store_true',
help='output frame timestamps to a log file')
display_parser.add_argument('-ld', '--logdur', action='store_true',
help='output frame durations to a log file')
display_parser.add_argument('-ss', '--sigser', action='store_true',
help='''send signals through the serial port
when shapes are being displayed''')
display_parser.add_argument('-sp', '--sigpar', action='store_true',
help='''send signals through the parallel port
when shapes are being displayed''')
display_parser.add_argument('-fpbs', metavar='M', type=int, default=0,
help='''unique signal corresponding to a
checkerboard is sent after the board
undergoes M color flips (default:
disabled, M=0)''')
display_parser.add_argument('-et', '--eyetrack', action='store_true',
help='''use eyetracking to ensure that subject
fixates on the cross in the center''')
display_parser.add_argument('-eu', '--etuser', action='store_true',
help='''allow user to select eyetracking video
source from a dialog''')
display_parser.add_argument('-ev', '--etvideo', metavar='path',
help='''path (with no spaces) to eyetracking
video file to be used as the source''')
display_parser.add_argument('-ta', '--tryagain', metavar='I',
type=int, default=0,
help='''append groups during which subject
failed to fixate up to I times to the
list of groups to be displayed
(default: disabled, I=0)''')
display_parser.add_argument('-tb', '--trybreak', metavar='J', type=int,
help='''used with --tryagain, append a wait
screen to the list of groups to be
displayed after every J groups have
been appended to the list (default:
J=total number of groups)''')
display_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be displayed
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_display(self):
self.__class__.display_parser.print_help()
def do_display(self, line):
"""Displays the animation in a window or in fullscreen"""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.display_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
- if args.block != None:
- blkpath = args.block
+ blk = None
+ if args.expfile != None:
try:
- blkdict = core.CkgProj.readblk(blkpath)
- flags = blkdict['flags']
- try:
- args = self.__class__.\
- display_parser.parse_args(shlex.split(flags))
- args.idlist = blkdict['idlist']
- except (CmdParserError, ValueError):
- print 'error: invalid flags stored in block file'
- return
+ exp = core.CkgExp(path=args.expfile)
except IOError:
print "error:", str(sys.exc_value)
return
- else:
- blkpath = None
+ try:
+ args = self.__class__.\
+ display_parser.parse_args(shlex.split(exp.flags))
+ except (CmdParserError, ValueError):
+ print 'error: invalid flags stored in block file'
+ return
+ try:
+ print """name of log file (default: experiment name):"""
+ blkname = raw_input().strip().strip('"\'')
+ except EOFError:
+ return
+ if blkname == '':
+ blkname == exp.name
+ blk = exp.random_blk(blkname)
+ args.idlist = blk.idlist()
groupq = []
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < -1:
print 'error: group', i, 'does not exist'
return
for i in args.idlist:
if i == -1:
- groupq.append(core.CkgWaitScreen(res=
- self.cur_proj.res))
+ groupq.append(core.CkgWaitScreen(res=self.cur_proj.res))
else:
groupq.append(self.cur_proj.groups[i])
else:
groupq = list(self.cur_proj.groups)
if args.repeat != None:
groupq = list(groupq * args.repeat)
if args.eyetrack and eyetracking.available:
if not eyetracking.is_calibrated():
try:
self.do_calibrate('',True)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
return
if args.priority != None:
if not priority.available:
print "error: setting priority not avaible on", sys.platform
print "continuing..."
else:
if args.priority.isdigit():
args.priority = int(args.priority)
try:
priority.set(args.priority)
except ValueError:
print "error:", str(sys.exc_value)
print "continuing..."
+ print "displaying..."
try:
fail_idlist = self.cur_proj.display(fullscreen=args.fullscreen,
logtime=args.logtime,
logdur=args.logdur,
sigser=args.sigser,
sigpar=args.sigpar,
fpbs=args.fpbs,
phototest=args.phototest,
photoburst=args.photoburst,
eyetrack=args.eyetrack,
etuser=args.etuser,
etvideo=args.etvideo,
tryagain=args.tryagain,
trybreak=args.trybreak,
groupq=groupq)
except (IOError, NotImplementedError, eyetracking.EyetrackingError):
print "error:", str(sys.exc_value)
if args.priority != None:
try:
priority.set('normal')
except:
pass
return
if args.priority != None:
try:
priority.set('normal')
except:
pass
- # Append list of ids of failed groups to block file
- if fail_idlist != None and blkpath != None:
+ # Save log file
+ if blk != None:
+ blk.fail_idlist = fail_idlist
try:
- core.CkgProj.addtoblk(blkpath, fail_idlist,
- len(self.cur_proj.groups))
+ blk.write_log()
except IOError:
print "error:", str(sys.exc_value)
return
+ print "log file written"
export_parser = CmdParser(add_help=False, prog='export',
description='''Exports animation as an image
sequence (in a folder) to the
specified directory.''')
# export_parser.add_argument('--fmt', dest='export_fmt',
# choices=core.EXPORT_FMTS,
# help='image format for export')
export_parser.add_argument('-n','--nofolder',
dest='folder', action='store_false',
help='''force images not to exported in
a containing folder''')
export_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly export specified display
groups N number of times''')
export_parser.add_argument('duration', nargs='?',
type=to_decimal, default='Infinity',
help='''number of seconds of the animation
that should be exported (default:
as long as the entire animation)''')
export_parser.add_argument('dir', nargs='?', default=os.getcwd(),
help='''destination directory for export
(default: current working directory)''')
export_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be exported
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_export(self):
self.__class__.export_parser.print_help()
def do_export(self, line):
"""Exports animation an image sequence to the specified directory."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.export_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.export_parser.print_usage()
return
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < 0:
print 'error: group', i, 'does not exist'
return
groupq = [self.cur_proj.groups[i] for i in args.idlist]
else:
groupq = list(self.cur_proj.groups)
if args.repeat != None:
groupq = list(groupq * args.repeat)
try:
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
folder=args.folder)
except IOError:
print "error:", str(sys.exc_value)
return
except core.FrameOverflowError:
print "warning:", str(sys.exc_value)
print "Are you sure you want to continue?"
while True:
try:
if self.__class__.yn_parse(raw_input()):
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
export_fmt=None,
folder=args.folder,
force=True)
break
else:
return
except TypeError:
print str(sys.exc_value)
except EOFError:
return
print "Export done."
mkexp_parser = CmdParser(add_help=False, prog='mkexp',
description='''Create checkergen experiment file
which describes how the project
is to be displayed.''')
mkexp_parser.add_argument('-n', '--name',
help='''name of the experiment (default: same
name as current project)''')
mkexp_parser.add_argument('-t', '--trials', type=int, metavar='N',
help='''N trials displayed in a block, i.e.
the same sequence will be displayed
N times in that block, with waitscreens
in between''')
mkexp_parser.add_argument('-f', '--flags',
help='''flags passed to the display command
that should be used when the block
file is run (enclose in quotes and use
'+' or '++' in place of '-' or '--')''')
def help_mkexp(self):
self.__class__.mkexp_parser.print_help()
def do_mkexp(self, line):
"""Creates checkergen experiment file."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.mkexp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mkexp_parser.print_usage()
return
if args.trials == None:
print "number of trials:"
try:
args.trials = int(raw_input().strip())
except EOFError:
return
if args.flags != None:
args.flags = args.flags.replace('+','-')
else:
print "flags used with display command (leave blank if none):"
try:
args.flags = raw_input().strip().strip('"\'')
except EOFError:
return
try:
disp_args = self.__class__.display_parser.\
parse_args(shlex.split(args.flags))
except (CmdParserError, ValueError):
print "error: invalid flags to display command"
print str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
print "list of sequences to choose from in the format",\
"'id1,id2,id3;seq2;seq3;seq4':"
print "(default: reduced latin square)"
try:
seqs_str = raw_input().strip()
if seqs_str == '':
args.sequences = None
else:
args.sequences = [[int(i) for i in seq_str.split(',')]
for seq_str in seqs_str.split(';')]
except EOFError:
return
try:
new_exp = core.CkgExp(name=args.name, proj=self.cur_proj,
trials=args.trials,
sequences=args.sequences,
flags=args.flags)
new_exp.save()
except IOError:
print "error:", str(sys.exc_value)
return
print "Experiment file created."
def do_calibrate(self, line, query=False):
"""Calibrate subject for eyetracking, or load a calibration file."""
if not eyetracking.available:
print "error: eyetracking functionality not available"
return
if query:
print "path to calibration file (leave empty for GUI tool):"
try:
path = raw_input().strip().strip('"\'')
except EOFError:
msg = "calibration cancelled"
raise eyetracking.EyetrackingError(msg)
else:
path = line.strip().strip('"\'')
if len(path) == 0:
path = None
if not eyetracking.is_source_ready():
# Select default source if none has been selected
eyetracking.select_source()
try:
eyetracking.calibrate(path)
except eyetracking.EyetrackingError:
if query:
raise
else:
print "error:", str(sys.exc_value)
return
if len(path) > 0:
print "calibration file successfully loaded"
etsetup_parser = CmdParser(add_help=False, prog='etsetup',
description='''Set various eyetracking
parameters.''')
etsetup_parser.add_argument('-fp', '--fixperiod', type=int, metavar='MS',
help='''time in milliseconds subject
has to stare at the same spot
for fixation to be detected''')
etsetup_parser.add_argument('-fr', '--fixrange', type=float, metavar='MM',
help='''distance in mm beyond which the
eye position cannot change for
a fixation to be detected''')
etsetup_parser.add_argument('-s', '--size', metavar='WIDTH,HEIGHT',
action=store_tuple(2, ',', float),
help='physical screen dimensions in mm')
etsetup_parser.add_argument('-vd', '--viewdist', type=int, metavar='MM',
help='''viewing distance between subject's
eyes and the screen''')
def help_etsetup(self):
self.__class__.etsetup_parser.print_help()
def do_etsetup(self, line):
try:
args = self.__class__.etsetup_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.etsetup_parser.print_usage()
return
try:
eyetracking.setup(viewing_distance=args.viewdist,
screen_dims=args.size,
fixation_period=args.fixperiod,
fixation_range=args.fixrange)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
def do_pwd(self, line):
"""Prints the current working directory."""
print os.getcwd()
def do_cd(self, line):
"""Change working directory to specified path."""
path = line.strip().strip('"\'')
if not os.path.isdir(path):
print "error: specified path is not a directory"
return
os.chdir(path)
def do_quit(self, line):
"""Quits the program."""
if self.save_check():
return
return True
def help_EOF(self):
print "Typing {0} issues this command, which quits the program."\
.format(CMD_EOF_STRING)
def do_EOF(self, line):
"""Typing Ctrl-D issues this command, which quits the program."""
print '\r'
if self.save_check():
return
return True
def help_help(self):
print 'Prints a list of commands.'
print "Type 'help <topic>' for more details on each command."
def default(self, line):
command = line.split()[0]
print \
"'{0}' is not a checkergen command.".format(command),\
"Type 'help' for a list of commands"
diff --git a/src/core.py b/src/core.py
index 09056f7..3e7bd69 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,1249 +1,1215 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgExp -- A checkergen experiment, describes how a projet is displayed.
CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import random
import itertools
from xml.dom import minidom
import pyglet
import graphics
import signals
import eyetracking
from utils import *
CKG_FMT = 'ckg'
-EXP_FMT = 'cxp'
-LOG_FMT = 'clg'
+EXP_FMT = 'ckx'
+LOG_FMT = 'log'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
MAX_EXPORT_FRAMES = 100000
PRERENDER_TO_TEXTURE = False
INT_HALF_PERIODS = True
EXPORT_FMTS = ['png']
EXPORT_DIR_SUFFIX = '-anim'
BLOCK_DIR_SUFFIX = '-blks'
FIX_POS = (0, 0)
FIX_RANGE = (20, 20)
FIX_PER = 350
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = {'name': 'untitled',
'fps': 60,
'res': (800, 600),
'bg': (127, 127, 127),
'export_fmt': 'png',
'pre': 0,
'post': 0,
'cross_cols': ((0, 0, 0), (255, 0, 0)),
'cross_times': ('Infinity', 1)}
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
export_fmt -- image format for animation to be exported as
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'export_fmt':
if value not in EXPORT_FMTS:
msg = 'image format not recognized or supported'
raise FileFormatError(msg)
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
vars_to_load = self.__class__.DEFAULTS.keys()
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
vars_to_save = self.__class__.DEFAULTS.keys()
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
- def mkblks(self, length, path=None, folder=True, flags=''):
- """Generates randomized experimental blocks from display groups.
- Each block is saved as a CSV file.
-
- length -- number of repeated trials within a block
-
- path -- directory in which experimental blocks will be saved
-
- folder -- blocks will be saved in a containing folder if true
-
- flags -- string of flags to be issued to the display command when
- block file is run
-
- """
-
- if path == None:
- path = os.getcwd()
-
- if not os.path.isdir(path):
- msg = "specified directory does not exist"
- raise IOError(msg)
-
- if folder:
- path = os.path.join(path, self.name + BLOCK_DIR_SUFFIX)
- if not os.path.isdir(path):
- os.mkdir(path)
-
- group_ids = range(len(self.groups))
- for n, sequence in enumerate(itertools.permutations(group_ids)):
- blkname = 'block{0}.csv'.format(repr(n).zfill(numdigits(length)))
- blkfile = open(os.path.join(path, blkname), 'wb')
- blkwriter = csv.writer(blkfile, dialect='excel-tab')
- blkwriter.writerow(['checkergen experimental block file'])
- blkwriter.writerow(['flags:', flags])
- blkwriter.writerow(['repeats:', length])
- blkwriter.writerow(['sequence:'] + list(sequence))
- blkfile.close()
-
- @staticmethod
- def readblk(path):
- """Reads the information in a block file and returns it in a dict."""
-
- if not os.path.isfile(path):
- msg = "specified file does not exist"
- raise IOError(msg)
-
- blkdict = dict()
- blkfile = open(path, 'rb')
- blkreader = csv.reader(blkfile, dialect='excel-tab')
- for n, row in enumerate(blkreader):
- if n == 1:
- blkdict['flags'] = row[1]
- elif n == 2:
- repeats = int(row[1])
- elif n == 3:
- sequence = row[1:]
- sequence = [int(i) for i in sequence]
- blkfile.close()
- blkdict['idlist'] = ([-1] + sequence) * repeats
- return blkdict
-
- @staticmethod
- def addtoblk(path, idlist, rowlen):
- """Appends a list of group ids to the specified block file."""
-
- if not os.path.isfile(path):
- msg = "specified file does not exist"
- raise IOError(msg)
-
- blkfile = open(path, 'ab')
- blkwriter = csv.writer(blkfile, dialect='excel-tab')
- blkwriter.writerow(['groups added:'])
- # Split idlist into lists of length rowlen, based on grouper recipe
- args = [iter(idlist)] * rowlen
- rowlist = itertools.izip_longest(*args, fillvalue='')
- for row in rowlist:
- blkwriter.writerow(row)
- blkfile.close()
-
def display(self, fullscreen=False, logtime=False, logdur=False,
sigser=False, sigpar=False, fpbs=0,
phototest=False, photoburst=False,
eyetrack=False, etuser=False, etvideo=None,
tryagain=0, trybreak=None, groupq=[]):
"""Displays the project animation on the screen.
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
sigser -- send signals through serial port when each group is shown
sigpar -- send signals through parallel port when each group is shown
fpbs -- flips per board signal, i.e. number of shape color reversals
(flips) that occur for a unique signal to be sent for that shape
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- Append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- Append a wait screen to the group queue every time
after this many groups have been appended to the queue
groupq -- queue of groups to be displayed, defaults to order of
groups in project (i.e. groups[0] first, etc.)
"""
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if phototest:
test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Set-up groups and variables that control their display
if groupq == []:
groupq = list(self.groups)
n = -1
flipped = 0
flip_id = -1
groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Initialize ports
if sigser:
if not signals.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if sigpar:
if not signals.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
signals.init(sigser, sigpar)
# Initialize eyetracking
if eyetrack:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if trybreak == None:
trybreak = len(self.groups)
fixated = False
old_fixated = False
tracked = False
old_tracked = False
cur_fix_fail = False
fail_idlist = []
eyetracking.select_source(etuser, etvideo)
eyetracking.start()
# Stretch to fit screen only if project res does not equal screen res
scaling = False
if fullscreen:
window = pyglet.window.Window(fullscreen=True, visible=False)
if (window.width, window.height) != self.res:
scaling = True
else:
window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
keystates = pyglet.window.key.KeyStateHandler()
window.push_handlers(keystates)
# Create framebuffer object for drawing unscaled scene
if scaling:
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
fbo.end_render()
# Clear window and make visible
window.switch_to()
graphics.set_clear_color(self.bg)
window.clear()
window.set_visible()
# Initialize logging variables
if logtime and logdur:
logstring = ''
stamp = Timer()
dur = Timer()
stamp.start()
dur.start()
elif logtime or logdur:
logstring = ''
timer = Timer()
timer.start()
# Main loop
while not window.has_exit and count < disp_end:
# Clear canvas
if scaling:
fbo.start_render()
fbo.clear()
else:
window.clear()
# Assume no change to group visibility
flipped = 0
signals.set_null()
# Manage groups when they are on_screen
if groups_visible:
# Check whether group changes in visibility
if n >= 0 and groupq[n].visible != groupq[n].old_visible:
flip_id = self.groups.index(groupq[n])
if groupq[n].visible:
flipped = 1
elif groupq[n].old_visible:
flipped = -1
# Get next group from queue
if n < 0 or groupq[n].over:
# Send special signal if waitscreen ends
if isinstance(groupq[n], CkgWaitScreen):
signals.set_user_start()
n += 1
if n >= len(groupq):
groups_visible = False
else:
groupq[n].reset()
if eyetrack:
cur_fix_fail = False
if groupq[n].visible:
flip_id = self.groups.index(groupq[n])
flipped = 1
# Draw and then update group
if n >= 0:
groupq[n].draw(photoburst=photoburst)
groupq[n].update(fps=self.fps,
fpbs=fpbs,
keystates=keystates)
# Send signals upon group visibility change
if flipped == 1:
signals.set_group_start(flip_id)
# Draw test rectangle
if phototest:
test_rect.draw()
elif flipped == -1:
signals.set_group_stop(flip_id)
if eyetrack:
# First check if eye is being tracked and send signals
old_tracked = tracked
tracked = eyetracking.is_tracked()
if tracked:
if not old_tracked:
# Send signal if eye starts being tracked
signals.set_track_start()
else:
if old_tracked:
# Send signal if eye stops being tracked
signals.set_track_stop()
# Next check for fixation
old_fixated = fixated
fixated = eyetracking.is_fixated(FIX_POS, FIX_RANGE, FIX_PER)
if fixated:
# Draw normal cross color if fixating
fix_crosses[0].draw()
if not old_fixated:
# Send signal if fixation starts
signals.set_fix_start()
else:
# Draw alternative cross color if not fixating
fix_crosses[1].draw()
if old_fixated:
# Send signal if fixation stops
signals.set_fix_stop()
# Take note of which groups in which fixation failed
if not cur_fix_fail and groupq[n].visible and\
(tracked and not fixated):
cur_fix_fail = True
if len(fail_idlist) == 0 and trybreak > 0:
groupq.append(CkgWaitScreen(res=self.res))
fail_idlist.append(self.groups.index(groupq[n]))
# Append failed group to group queue
if tryagain > 0:
groupq.append(groupq[n])
groups_stop += groupq[n].duration() * self.fps
disp_end += groupq[n].duration() * self.fps
# Insert waitscreen every trybreak failed groups
if trybreak > 0:
if len(fail_idlist) % trybreak == 0:
groupq.append(CkgWaitScreen())
tryagain -= 1
# Change cross color based on time if eyetracking is not enabled
if not eyetrack:
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Increment count and set whether groups should be shown
if not isinstance(groupq[n], CkgWaitScreen):
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
# Blit canvas to screen if necessary
if scaling:
fbo.end_render()
window.switch_to()
canvas.blit(0, 0)
window.dispatch_events()
window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to log string
if logtime and logdur:
logstring = '\n'.join([logstring, str(stamp.elapsed())])
logstring = '\t'.join([logstring, str(dur.restart())])
elif logtime:
logstring = '\n'.join([logstring, str(timer.elapsed())])
elif logdur:
logstring = '\n'.join([logstring, str(timer.restart())])
# Send signals ASAP after flip
signals.send(sigser, sigpar)
# Log when signals are sent
if logtime or logdur:
if flipped != 0 and (sigser or sigpar):
sigmsg = '{0} sent'.format(signals.STATE)
logstring = '\t'.join([logstring, sigmsg])
# Clean up
if eyetrack:
eyetracking.stop()
window.close()
if scaling:
fbo.delete()
del canvas
signals.quit(sigser, sigpar)
# Write log string to file
if logtime or logdur:
filename = '{0}.log'.format(self.name)
with open(filename, 'w') as logfile:
logfile.write(logstring)
# Return list of ids of failed groups
if eyetrack and len(fail_idlist) > 0:
return fail_idlist
def export(self, export_dir, export_duration, groupq=[],
export_fmt=None, folder=True, force=False):
if not os.path.isdir(export_dir):
msg = 'export path is not a directory'
raise IOError(msg)
if export_fmt == None:
export_fmt = self.export_fmt
# Set-up groups and variables that control their display
if groupq == []:
groupq = list(self.groups)
n = -1
groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Limit export duration to display duration
frames = export_duration * self.fps
frames = min(frames, disp_end)
# Warn user if a lot of frames will be exported
if frames > MAX_EXPORT_FRAMES and not force:
msg = 'very large number ({0}) of frames to be exported'.\
format(frames)
raise FrameOverflowError(msg)
# Create folder to store images if necessary
if folder:
export_dir = os.path.join(export_dir,
self.name + EXPORT_DIR_SUFFIX)
if not os.path.isdir(export_dir):
os.mkdir(export_dir)
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Set up canvas and framebuffer object
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
# Main loop
while count < frames:
fbo.clear()
if groups_visible:
# Get next group from queue
if n < 0 or groupq[n].over:
n += 1
if n >= len(groupq):
groups_visible = False
else:
groupq[n].reset()
# Draw and then update group
if n >= 0:
groupq[n].draw()
groupq[n].update(fps=self.fps, fpbs=0)
# Draw fixation cross based on current count
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Save current frame to file
savepath = \
os.path.join(export_dir,
'{0}{2}.{1}'.
format(self.name, export_fmt,
repr(count).zfill(numdigits(frames-1))))
canvas.save(savepath)
# Increment count and set whether groups should be shown
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
fbo.delete()
class CkgExp:
DEFAULTS = {'name': None, 'proj' : None,
'trials': 1, 'sequences': None,
'flags': '--fullscreen --logtime --logdur'}
def __init__(self, **keywords):
"""Create a checkergen experiment, which specifies how a project
is to be displayed.
path -- if specified, ignore other arguments and load project
from path
name -- name of the experiment
proj -- CkgProj that the experiment is to be created for
trials -- number of times the selected sequence of display groups
will be shown in one block
sequences -- list of possible display group id sequences, from which
one sequence will be randomly selected for display in a block,
defaults to reduced latin square with side length equal to the number
of display groups in the supplied CkgProj
flags -- string passed to the display command as flags
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
if self.name == None and self.proj != None:
self.name = self.proj.name
if self.sequences == None:
if self.proj == None:
msg = "either project or sequences have to be specified"
raise ValueError(msg)
else:
self.gen_latin_square(len(self.proj.groups))
del self.proj
def gen_latin_square(self, n):
"""Set experiment sequences as a cyclic reduced latin square."""
sequence = range(n)
self.sequences = [[sequence[i - j] for i in range(n)]
for j in range(n, 0, -1)]
- def get_idlist(self):
- """Choose random sequence, create idlist from it and return."""
+ def random_blk(self, name):
+ """Choose random sequence, create block from it and return."""
sequence = random.choice(self.sequences)
- idlist = ([-1] + sequence) * self.trials
- return idlist
+ blk = CkgBlk(name=name,
+ flags=self.flags,
+ trials=self.trials,
+ sequence=sequence)
+ return blk
def save(self, path=None):
- """Saves experiment to specified path as a CSV file."""
+ """Saves experiment to specified path in the CSV format."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, EXP_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(EXP_FMT):
path = '{0}.{1}'.format(path, EXP_FMT)
with open(path, 'wb') as expfile:
expwriter = csv.writer(expfile, dialect='excel-tab')
expwriter.writerow(['checkergen experiment file'])
expwriter.writerow(['flags:', self.flags])
expwriter.writerow(['trials:', self.trials])
expwriter.writerow(['sequences:'])
for sequence in self.sequences:
expwriter.writerow(sequence)
def load(self, path):
"""Loads experiment from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, EXP_FMT)
elif ext != '.{0}'.format(EXP_FMT):
msg = "path lacks '.{0}' extension".format(EXP_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
+ self.sequences = []
with open(path, 'rb') as expfile:
expreader = csv.reader(expfile, dialect='excel-tab')
for n, row in enumerate(expreader):
if n == 1:
self.flags = row[1]
elif n == 2:
self.trials = int(row[1])
elif n > 3:
sequence = [int(i) for i in row]
self.sequences.append(sequence)
-
+
+class CkgBlk:
+
+ def __init__(self, name, flags, trials, sequence):
+ """Creates an experimental block."""
+ self.name = name
+ self.flags = flags
+ self.trials = trials
+ self.sequence = sequence
+ self.fail_idlist = None
+ self.timelog = None
+
+ def idlist(self):
+ """Generate idlist from sequence and return it."""
+ idlist = ([-1] + self.sequence) * self.trials
+ return idlist
+
+ def write_log(self, path=None):
+ """Write a log file for the experimental block in the CSV format."""
+
+ if path == None:
+ path = os.path.join(os.getcwd(),
+ '{0}.{1}'.format(self.name, LOG_FMT))
+ else:
+ self.name, ext = os.path.splitext(os.path.basename(path))
+ if ext != '.{0}'.format(LOG_FMT):
+ path = '{0}.{1}'.format(path, LOG_FMT)
+
+ with open(path, 'wb') as blkfile:
+ blkwriter = csv.writer(blkfile, dialect='excel-tab')
+ blkwriter.writerow(['checkergen log file'])
+ blkwriter.writerow(['flags:', self.flags])
+ blkwriter.writerow(['trials:', self.trials])
+ blkwriter.writerow(['sequence:'] + self.sequence)
+ if self.fail_idlist != None:
+ blkwriter.writerow(['groups added:'])
+ rowlist = grouper(len(self.sequence), self.fail_idlist, '')
+ for row in rowlist:
+ blkwriter.writerow(row)
+ if self.timelog != None:
+ pass
+
class CkgDisplayGroup:
DEFAULTS = {'pre': 0, 'disp': 'Infinity', 'post': 0}
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets internal count and all contained shapes."""
self._count = 0
self._start = self.pre
self._stop = self.pre + self.disp
self._end = self.pre + self.disp + self.post
self.over = False
self.old_visible = False
if self._start == 0 and self._stop > 0:
self.visible = True
else:
self.visible = False
if self._end == 0:
self.over = True
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, lazy=False, photoburst=False):
"""Draws all contained shapes during the appropriate interval."""
if self.visible:
for shape in self.shapes:
if lazy:
shape.lazydraw()
else:
shape.draw(photoburst=photoburst)
def update(self, **keywords):
"""Increments internal count, makes group visible when appropriate.
fps -- refresh rate of the display in frames per second
fpbs -- flips per board signal, i.e. number of shape color reversals
(flips) that occur for a unique signal to be sent for that shape
"""
fps = keywords['fps']
fpbs = keywords['fpbs']
if self.visible:
# Set triggers to be sent
if fpbs > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= fpbs:
signals.set_board_flip(n)
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(fps)
# Increment count and set flags for the next frame
self._count += 1
self.old_visible = self.visible
if (self._start * fps) <= self._count < (self._stop * fps):
self.visible = True
else:
self.visible = False
if self._count >= (self._end * fps):
self.over = True
else:
self.over = False
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.visible = False
self.old_visible = False
self.steps_done = 0
self.over = False
- def draw(self):
+ def draw(self, **keywords):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, **keywords):
"""Checks for keypress, sends signal upon end."""
keystates = keywords['keystates']
if max([keystates[key] for key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
if self.steps_done == self.num_steps:
self.over = True
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = {'dims': (5, 5),
'init_unit': (30, 30), 'end_unit': (50, 50),
'position': (0, 0), 'anchor': 'bottomleft',
'cols': ((0, 0, 0), (255, 255, 255)),
'freq': 1, 'phase': 0}
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
if INT_HALF_PERIODS:
frames_per_half_period = round(fps / (self.freq * 2))
degs_per_frame = 180 / to_decimal(frames_per_half_period)
else:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
if PRERENDER_TO_TEXTURE:
init_pos = [(1 - a)* s/to_decimal(2) for s, a in
zip(self._size, graphics.locations[self.anchor])]
else:
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
anchor=self.anchor)
cur_unit_rect.col = self.cols[(i + j) % 2]
cur_unit_rect.add_to_batch(self._batches[0])
cur_unit_rect.col = self.cols[(i + j + 1) % 2]
cur_unit_rect.add_to_batch(self._batches[1])
# Increase x values
cur_unit_pos[0] += \
graphics.locations[self.anchor][0] * cur_unit[0]
cur_unit[0] += unit_grad[0]
# Reset x values
cur_unit_pos[0] = init_pos[0]
cur_unit[0] = init_unit[0]
# Increase y values
cur_unit_pos[1] += \
graphics.locations[self.anchor][1] * cur_unit[1]
cur_unit[1] += unit_grad[1]
if PRERENDER_TO_TEXTURE:
# Create textures
int_size = [int(round(s)) for s in self._size]
self._prerenders =\
[pyglet.image.Texture.create(*int_size) for n in range(2)]
# Set up framebuffer
fbo = graphics.Framebuffer()
for n in range(2):
fbo.attach_texture(self._prerenders[n])
# Draw batch to texture
fbo.start_render()
self._batches[n].draw()
fbo.end_render()
# Anchor textures for correct blitting later
self._prerenders[n].anchor_x, self._prerenders[n].anchor_y =\
[int(round((1 - a)* s/to_decimal(2))) for s, a in
zip(self._size, graphics.locations[self.anchor])]
fbo.delete()
# Delete batches since they won't be used
del self._batches
self._computed = True
def draw(self, photoburst=False, always_compute=False):
"""Draws appropriate prerender depending on current phase.
photoburst -- draw first color for only one frame for testing purposes
always_compute -- recompute what the checkerboard should look like
every frame
"""
if not self._computed or always_compute:
self.compute()
self._cur_phase %= 360
n = int(self._cur_phase // 180)
if photoburst and n == 0 and not self.flipped:
n = 1
if PRERENDER_TO_TEXTURE:
self._prerenders[n].blit(*self.position)
else:
self._batches[n].draw()
def lazydraw(self):
"""Only draws on color reversal."""
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if (cur_n != prev_n) or self._first_draw:
self.draw()
if self._first_draw:
self._first_draw = False
diff --git a/src/utils.py b/src/utils.py
index 108c640..2ff717b 100644
--- a/src/utils.py
+++ b/src/utils.py
@@ -1,84 +1,91 @@
"""Utility functions and classes."""
import os
import time
import math
from decimal import *
+from itertools import *
def numdigits(x):
"""Returns number of digits in a decimal integer."""
if x == 0:
return 1
elif x < 0:
x = -x
return int(math.log(x, 10)) + 1
def public_dir(obj):
"""Returns all 'public' attributes of an object"""
names = dir(obj)
for name in names[:]:
if name[0] == '_' or name[-1] == '_':
names.remove(name)
return names
def to_decimal(s):
"""ValueError raising Decimal converter."""
try:
return Decimal(s)
except (InvalidOperation, TypeError):
try:
return Decimal(str(s))
except (InvalidOperation, TypeError):
raise ValueError
def to_color(s, sep=','):
"""Tries to cast a string to a color (3-tuple)."""
c = tuple([int(x) for x in s.split(sep)])
if len(c) != 3:
raise ValueError
return c
+# From itertools documentation
+def grouper(n, iterable, fillvalue=None):
+ """grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"""
+ args = [iter(iterable)] * n
+ return izip_longest(fillvalue=fillvalue, *args)
+
class Timer:
"""High-res timer that should be cross-platform."""
def __init__(self):
# Assigns appropriate clock function based on OS
if os.name == 'nt':
self.clock = time.clock
self.clock()
elif os.name == 'posix':
self.clock = time.time
self.running = False
def start(self):
self.start_time = self.clock()
self.running = True
def stop(self):
if not self.running:
return None
self.stop_time = self.clock()
self.running = False
return self.stop_time - self.start_time
def elapsed(self):
if not self.running:
return None
cur_time = self.clock()
return cur_time - self.start_time
def restart(self):
old_start_time = self.start_time
self.start_time = self.clock()
self.running = True
return self.start_time - old_start_time
def tick(self, fps):
"""Limits loop to specified fps. To be placed at start of loop."""
fps = float(fps)
ret = self.elapsed()
if self.elapsed() != -1:
while self.elapsed() < (1.0 / fps):
pass
self.start()
if ret != -1:
return ret * 1000
|
ztangent/checkergen
|
ca20ab47c0e20986eab233202be4705019fed08d
|
Removed mkblks command, added mkexp command.
|
diff --git a/src/cli.py b/src/cli.py
index ecb97ed..d216017 100644
--- a/src/cli.py
+++ b/src/cli.py
@@ -493,672 +493,700 @@ class CkgCmd(cmd.Cmd):
help='checkerboard dimensions in unit cells',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--init_unit',
action=store_tuple(2, ',', to_decimal),
help='initial unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--end_unit',
action=store_tuple(2, ',', to_decimal),
help='final unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--position',
action=store_tuple(2, ',', to_decimal),
help='position of checkerboard in pixels',
metavar='X,Y')
ed_parser.add_argument('--anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='LOCATION')
ed_parser.add_argument('--cols', metavar='COLOR1,COLOR2',
action=store_tuple(2, ',', to_color, [';']),
help='''checkerboard colors (color format:
R;G;B, component range
from 0-255)''')
ed_parser.add_argument('--freq', type=to_decimal,
help='frequency of color reversal in Hz')
ed_parser.add_argument('--phase', type=to_decimal,
help='initial phase of animation in degrees')
def help_ed(self):
self.__class__.ed_parser.print_help()
def do_ed(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, please create one first'
return
try:
args = self.__class__.ed_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ed_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_group.shapes) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_shape_attr(self.cur_group, x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.ed_parser.print_usage()
rm_parser = CmdParser(add_help=False, prog='rm',
description='''Removes checkerboards specified
by ids.''')
rm_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''ids of checkerboards in the current group
to be removed''')
rm_parser.add_argument('-a', '--all', action='store_true',
help='''remove all checkerboards in the
current group''')
def help_rm(self):
self.__class__.rm_parser.print_help()
def do_rm(self, line):
"""Removes checkerboards specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, no boards to remove'
return
try:
args = self.__class__.rm_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rm_parser.print_usage()
return
rmlist = []
if args.all:
for shape in self.cur_group.shapes:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
print "all checkerboards removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_group.shapes) or x < 0:
print "checkerboard", x, "does not exist"
continue
rmlist.append(self.cur_group.shapes[x])
print "checkerboard", x, "removed"
for shape in rmlist:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
ls_parser = CmdParser(add_help=False, prog='ls',
description='''Lists project, display group and
checkerboard settings. If no group ids
are specified, all display groups
are listed.''')
ls_parser.add_argument('gidlist', nargs='*', metavar='gid', type=int,
help='''ids of the display groups to be listed''')
ls_group = ls_parser.add_mutually_exclusive_group()
ls_group.add_argument('-s', '--settings', action='store_true',
help='list only project settings')
ls_group.add_argument('-g', '--groups', action='store_true',
help='list only display groups')
def help_ls(self):
self.__class__.ls_parser.print_help()
def do_ls(self, line):
"""Lists project, display group and checkerboard settings."""
def ls_str(s, seps=[',',';']):
"""Special space-saving output formatter."""
if type(s) in [tuple, list]:
if len(seps) > 1:
newseps = seps[1:]
else:
newseps = seps
return seps[0].join([ls_str(i, newseps) for i in s])
else:
return str(s)
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.ls_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ls_parser.print_usage()
return
# Remove duplicates and ascending sort
args.gidlist = sorted(set(args.gidlist))
if len(self.cur_proj.groups) == 0:
if len(args.gidlist) > 0:
print 'this project has no display groups that can be listed'
args.settings = True
else:
for gid in args.gidlist[:]:
if gid >= len(self.cur_proj.groups) or gid < 0:
args.gidlist.remove(gid)
print 'display group', gid, 'does not exist'
if args.gidlist == []:
args.gidlist = range(len(self.cur_proj.groups))
else:
# If any (valid) groups are specified
# don't show project settings
args.groups = True
if not args.groups:
print 'PROJECT SETTINGS'.center(70,'*')
print \
'name'.rjust(16),\
'fps'.rjust(7),\
'resolution'.rjust(14),\
'bg color'.rjust(18)
# 'format'.rjust(7)
print \
ls_str(self.cur_proj.name).rjust(16),\
ls_str(self.cur_proj.fps).rjust(7),\
ls_str(self.cur_proj.res).rjust(14),\
ls_str(self.cur_proj.bg).rjust(18)
# ls_str(self.cur_proj.export_fmt).rjust(7)
print \
'pre-display'.rjust(26),\
'post-display'.rjust(26)
print \
ls_str(self.cur_proj.pre).rjust(26),\
ls_str(self.cur_proj.post).rjust(26)
print \
'cross colors'.rjust(26),\
'cross times'.rjust(26)
print \
ls_str(self.cur_proj.cross_cols).rjust(26),\
ls_str(self.cur_proj.cross_times).rjust(26)
if not args.settings and not args.groups:
# Insert empty line if both groups and project
# settings are listed
print ''
if not args.settings:
for i, n in enumerate(args.gidlist):
if i != 0:
# Print newline seperator between each group
print ''
group = self.cur_proj.groups[n]
print 'GROUP {n}'.format(n=n).center(70,'*')
print \
'pre-display'.rjust(20),\
'display'.rjust(20),\
'post-display'.rjust(20)
print \
ls_str(group.pre).rjust(20),\
ls_str(group.disp).rjust(20),\
ls_str(group.post).rjust(20)
if len(group.shapes) > 0:
print \
''.rjust(2),\
'shape id'.rjust(8),\
'dims'.rjust(10),\
'init_unit'.rjust(14),\
'end_unit'.rjust(14),\
'position'.rjust(14)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.dims).rjust(10),\
ls_str(shape.init_unit).rjust(14),\
ls_str(shape.end_unit).rjust(14),\
ls_str(shape.position).rjust(14)
print '\n',\
''.rjust(2),\
'shape id'.rjust(8),\
'colors'.rjust(27),\
'anchor'.rjust(12),\
'freq'.rjust(6),\
'phase'.rjust(7)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.cols).rjust(27),\
ls_str(shape.anchor).rjust(12),\
ls_str(shape.freq).rjust(6),\
ls_str(shape.phase).rjust(7)
display_parser = CmdParser(add_help=False, prog='display',
description='''Displays the animation in a
window or in fullscreen.''')
display_parser.add_argument('-b', '--block', metavar='PATH',
help='''read flags and dislay group order from
specified file, ignore other flags''')
display_parser.add_argument('-f', '--fullscreen', action='store_true',
help='sets fullscreen mode, ESC to quit')
display_parser.add_argument('-p', '--priority', metavar='LEVEL',
help='''set priority while displaying,
higher priority results in
less dropped frames (choices:
0-3, low, normal, high,
realtime)''')
display_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly display specified display
groups N number of times''')
display_parser.add_argument('-pt', '--phototest', action='store_true',
help='''draw white test rectangle in topleft
corner of screen when groups become
visible for a photodiode to detect''')
display_parser.add_argument('-pb', '--photoburst', action='store_true',
help='''make checkerboards only draw first
color for one frame to facilitate
testing with a photodiode''')
display_parser.add_argument('-lt', '--logtime', action='store_true',
help='output frame timestamps to a log file')
display_parser.add_argument('-ld', '--logdur', action='store_true',
help='output frame durations to a log file')
display_parser.add_argument('-ss', '--sigser', action='store_true',
help='''send signals through the serial port
when shapes are being displayed''')
display_parser.add_argument('-sp', '--sigpar', action='store_true',
help='''send signals through the parallel port
when shapes are being displayed''')
display_parser.add_argument('-fpbs', metavar='M', type=int, default=0,
help='''unique signal corresponding to a
checkerboard is sent after the board
undergoes M color flips (default:
disabled, M=0)''')
display_parser.add_argument('-et', '--eyetrack', action='store_true',
help='''use eyetracking to ensure that subject
fixates on the cross in the center''')
display_parser.add_argument('-eu', '--etuser', action='store_true',
help='''allow user to select eyetracking video
source from a dialog''')
display_parser.add_argument('-ev', '--etvideo', metavar='path',
help='''path (with no spaces) to eyetracking
video file to be used as the source''')
display_parser.add_argument('-ta', '--tryagain', metavar='I',
type=int, default=0,
help='''append groups during which subject
failed to fixate up to I times to the
list of groups to be displayed
(default: disabled, I=0)''')
display_parser.add_argument('-tb', '--trybreak', metavar='J', type=int,
help='''used with --tryagain, append a wait
screen to the list of groups to be
displayed after every J groups have
been appended to the list (default:
J=total number of groups)''')
display_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be displayed
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_display(self):
self.__class__.display_parser.print_help()
def do_display(self, line):
"""Displays the animation in a window or in fullscreen"""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.display_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
if args.block != None:
blkpath = args.block
try:
blkdict = core.CkgProj.readblk(blkpath)
flags = blkdict['flags']
try:
args = self.__class__.\
display_parser.parse_args(shlex.split(flags))
args.idlist = blkdict['idlist']
except (CmdParserError, ValueError):
print 'error: invalid flags stored in block file'
return
except IOError:
print "error:", str(sys.exc_value)
return
else:
blkpath = None
groupq = []
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < -1:
print 'error: group', i, 'does not exist'
return
for i in args.idlist:
if i == -1:
groupq.append(core.CkgWaitScreen(res=
self.cur_proj.res))
else:
groupq.append(self.cur_proj.groups[i])
else:
groupq = list(self.cur_proj.groups)
if args.repeat != None:
groupq = list(groupq * args.repeat)
if args.eyetrack and eyetracking.available:
if not eyetracking.is_calibrated():
try:
self.do_calibrate('',True)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
return
if args.priority != None:
if not priority.available:
print "error: setting priority not avaible on", sys.platform
print "continuing..."
else:
if args.priority.isdigit():
args.priority = int(args.priority)
try:
priority.set(args.priority)
except ValueError:
print "error:", str(sys.exc_value)
print "continuing..."
try:
fail_idlist = self.cur_proj.display(fullscreen=args.fullscreen,
logtime=args.logtime,
logdur=args.logdur,
sigser=args.sigser,
sigpar=args.sigpar,
fpbs=args.fpbs,
phototest=args.phototest,
photoburst=args.photoburst,
eyetrack=args.eyetrack,
etuser=args.etuser,
etvideo=args.etvideo,
tryagain=args.tryagain,
trybreak=args.trybreak,
groupq=groupq)
except (IOError, NotImplementedError, eyetracking.EyetrackingError):
print "error:", str(sys.exc_value)
if args.priority != None:
try:
priority.set('normal')
except:
pass
return
if args.priority != None:
try:
priority.set('normal')
except:
pass
# Append list of ids of failed groups to block file
if fail_idlist != None and blkpath != None:
try:
core.CkgProj.addtoblk(blkpath, fail_idlist,
len(self.cur_proj.groups))
except IOError:
print "error:", str(sys.exc_value)
return
export_parser = CmdParser(add_help=False, prog='export',
description='''Exports animation as an image
sequence (in a folder) to the
specified directory.''')
# export_parser.add_argument('--fmt', dest='export_fmt',
# choices=core.EXPORT_FMTS,
# help='image format for export')
export_parser.add_argument('-n','--nofolder',
dest='folder', action='store_false',
help='''force images not to exported in
a containing folder''')
export_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly export specified display
groups N number of times''')
export_parser.add_argument('duration', nargs='?',
type=to_decimal, default='Infinity',
help='''number of seconds of the animation
that should be exported (default:
as long as the entire animation)''')
export_parser.add_argument('dir', nargs='?', default=os.getcwd(),
help='''destination directory for export
(default: current working directory)''')
export_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be exported
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_export(self):
self.__class__.export_parser.print_help()
def do_export(self, line):
"""Exports animation an image sequence to the specified directory."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.export_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.export_parser.print_usage()
return
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < 0:
print 'error: group', i, 'does not exist'
return
groupq = [self.cur_proj.groups[i] for i in args.idlist]
else:
groupq = list(self.cur_proj.groups)
if args.repeat != None:
groupq = list(groupq * args.repeat)
try:
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
folder=args.folder)
except IOError:
print "error:", str(sys.exc_value)
return
except core.FrameOverflowError:
print "warning:", str(sys.exc_value)
print "Are you sure you want to continue?"
while True:
try:
if self.__class__.yn_parse(raw_input()):
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
export_fmt=None,
folder=args.folder,
force=True)
break
else:
return
except TypeError:
print str(sys.exc_value)
except EOFError:
return
print "Export done."
- mkblks_parser = CmdParser(add_help=False, prog='mkblks',
- description='''Generates randomized experimental
- blocks from display groups and
- saves each as a CSV file.''')
- mkblks_parser.add_argument('-n','--nofolder',
- dest='folder', action='store_false',
- help='''force block files not to be saved in
- a containing folder''')
- mkblks_parser.add_argument('-d','--dir', default=os.getcwd(),
- help='''where to save block files
- (default: current working directory)''')
- mkblks_parser.add_argument('length', type=int,
- help='''no. of repeated trials in a block''')
- mkblks_parser.add_argument('flags', nargs='?', default='',
+ mkexp_parser = CmdParser(add_help=False, prog='mkexp',
+ description='''Create checkergen experiment file
+ which describes how the project
+ is to be displayed.''')
+ mkexp_parser.add_argument('-n', '--name',
+ help='''name of the experiment (default: same
+ name as current project)''')
+ mkexp_parser.add_argument('-t', '--trials', type=int, metavar='N',
+ help='''N trials displayed in a block, i.e.
+ the same sequence will be displayed
+ N times in that block, with waitscreens
+ in between''')
+ mkexp_parser.add_argument('-f', '--flags',
help='''flags passed to the display command
that should be used when the block
file is run (enclose in quotes and use
'+' or '++' in place of '-' or '--')''')
- def help_mkblks(self):
- self.__class__.mkblks_parser.print_help()
+ def help_mkexp(self):
+ self.__class__.mkexp_parser.print_help()
- def do_mkblks(self, line):
- """Generates randomized experimental blocks from display groups."""
+ def do_mkexp(self, line):
+ """Creates checkergen experiment file."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
- args = self.__class__.mkblks_parser.parse_args(shlex.split(line))
+ args = self.__class__.mkexp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
- self.__class__.mkblks_parser.print_usage()
+ self.__class__.mkexp_parser.print_usage()
return
- args.flags = args.flags.replace('+','-')
+ if args.trials == None:
+ print "number of trials:"
+ try:
+ args.trials = int(raw_input().strip())
+ except EOFError:
+ return
+
+ if args.flags != None:
+ args.flags = args.flags.replace('+','-')
+ else:
+ print "flags used with display command (leave blank if none):"
+ try:
+ args.flags = raw_input().strip().strip('"\'')
+ except EOFError:
+ return
+
try:
disp_args = self.__class__.display_parser.\
parse_args(shlex.split(args.flags))
except (CmdParserError, ValueError):
print "error: invalid flags to display command"
print str(sys.exc_value)
self.__class__.display_parser.print_usage()
- return
+ return
+
+ print "list of sequences to choose from in the format",\
+ "'id1,id2,id3;seq2;seq3;seq4':"
+ print "(default: reduced latin square)"
+ try:
+ seqs_str = raw_input().strip()
+ if seqs_str == '':
+ args.sequences = None
+ else:
+ args.sequences = [[int(i) for i in seq_str.split(',')]
+ for seq_str in seqs_str.split(';')]
+ except EOFError:
+ return
try:
- self.cur_proj.mkblks(args.length,
- path=args.dir,
- folder=args.folder,
- flags=args.flags)
+ new_exp = core.CkgExp(name=args.name, proj=self.cur_proj,
+ trials=args.trials,
+ sequences=args.sequences,
+ flags=args.flags)
+ new_exp.save()
except IOError:
print "error:", str(sys.exc_value)
return
- print "Experimental blocks generated."
+ print "Experiment file created."
def do_calibrate(self, line, query=False):
"""Calibrate subject for eyetracking, or load a calibration file."""
if not eyetracking.available:
print "error: eyetracking functionality not available"
return
if query:
print "path to calibration file (leave empty for GUI tool):"
try:
path = raw_input().strip().strip('"\'')
except EOFError:
msg = "calibration cancelled"
raise eyetracking.EyetrackingError(msg)
else:
path = line.strip().strip('"\'')
if len(path) == 0:
path = None
if not eyetracking.is_source_ready():
# Select default source if none has been selected
eyetracking.select_source()
try:
eyetracking.calibrate(path)
except eyetracking.EyetrackingError:
if query:
raise
else:
print "error:", str(sys.exc_value)
return
if len(path) > 0:
print "calibration file successfully loaded"
etsetup_parser = CmdParser(add_help=False, prog='etsetup',
description='''Set various eyetracking
parameters.''')
etsetup_parser.add_argument('-fp', '--fixperiod', type=int, metavar='MS',
help='''time in milliseconds subject
has to stare at the same spot
for fixation to be detected''')
etsetup_parser.add_argument('-fr', '--fixrange', type=float, metavar='MM',
help='''distance in mm beyond which the
eye position cannot change for
a fixation to be detected''')
etsetup_parser.add_argument('-s', '--size', metavar='WIDTH,HEIGHT',
action=store_tuple(2, ',', float),
help='physical screen dimensions in mm')
etsetup_parser.add_argument('-vd', '--viewdist', type=int, metavar='MM',
help='''viewing distance between subject's
eyes and the screen''')
def help_etsetup(self):
self.__class__.etsetup_parser.print_help()
def do_etsetup(self, line):
try:
args = self.__class__.etsetup_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.etsetup_parser.print_usage()
return
try:
eyetracking.setup(viewing_distance=args.viewdist,
screen_dims=args.size,
fixation_period=args.fixperiod,
fixation_range=args.fixrange)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
def do_pwd(self, line):
"""Prints the current working directory."""
print os.getcwd()
def do_cd(self, line):
"""Change working directory to specified path."""
path = line.strip().strip('"\'')
if not os.path.isdir(path):
print "error: specified path is not a directory"
return
os.chdir(path)
def do_quit(self, line):
"""Quits the program."""
if self.save_check():
return
return True
def help_EOF(self):
print "Typing {0} issues this command, which quits the program."\
.format(CMD_EOF_STRING)
def do_EOF(self, line):
"""Typing Ctrl-D issues this command, which quits the program."""
print '\r'
if self.save_check():
return
return True
def help_help(self):
print 'Prints a list of commands.'
print "Type 'help <topic>' for more details on each command."
def default(self, line):
command = line.split()[0]
print \
"'{0}' is not a checkergen command.".format(command),\
"Type 'help' for a list of commands"
diff --git a/src/core.py b/src/core.py
index 3e8c8a2..09056f7 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,1242 +1,1249 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgExp -- A checkergen experiment, describes how a projet is displayed.
CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
+import random
import itertools
from xml.dom import minidom
import pyglet
import graphics
import signals
import eyetracking
from utils import *
CKG_FMT = 'ckg'
-EXP_FMT = 'exp'
-LOG_FMT = 'log'
+EXP_FMT = 'cxp'
+LOG_FMT = 'clg'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
MAX_EXPORT_FRAMES = 100000
PRERENDER_TO_TEXTURE = False
INT_HALF_PERIODS = True
EXPORT_FMTS = ['png']
EXPORT_DIR_SUFFIX = '-anim'
BLOCK_DIR_SUFFIX = '-blks'
FIX_POS = (0, 0)
FIX_RANGE = (20, 20)
FIX_PER = 350
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = {'name': 'untitled',
'fps': 60,
'res': (800, 600),
'bg': (127, 127, 127),
'export_fmt': 'png',
'pre': 0,
'post': 0,
'cross_cols': ((0, 0, 0), (255, 0, 0)),
'cross_times': ('Infinity', 1)}
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
export_fmt -- image format for animation to be exported as
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'export_fmt':
if value not in EXPORT_FMTS:
msg = 'image format not recognized or supported'
raise FileFormatError(msg)
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
vars_to_load = self.__class__.DEFAULTS.keys()
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
vars_to_save = self.__class__.DEFAULTS.keys()
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def mkblks(self, length, path=None, folder=True, flags=''):
"""Generates randomized experimental blocks from display groups.
Each block is saved as a CSV file.
length -- number of repeated trials within a block
path -- directory in which experimental blocks will be saved
folder -- blocks will be saved in a containing folder if true
flags -- string of flags to be issued to the display command when
block file is run
"""
if path == None:
path = os.getcwd()
if not os.path.isdir(path):
msg = "specified directory does not exist"
raise IOError(msg)
if folder:
path = os.path.join(path, self.name + BLOCK_DIR_SUFFIX)
if not os.path.isdir(path):
os.mkdir(path)
group_ids = range(len(self.groups))
for n, sequence in enumerate(itertools.permutations(group_ids)):
blkname = 'block{0}.csv'.format(repr(n).zfill(numdigits(length)))
blkfile = open(os.path.join(path, blkname), 'wb')
blkwriter = csv.writer(blkfile, dialect='excel-tab')
blkwriter.writerow(['checkergen experimental block file'])
blkwriter.writerow(['flags:', flags])
blkwriter.writerow(['repeats:', length])
blkwriter.writerow(['sequence:'] + list(sequence))
blkfile.close()
@staticmethod
def readblk(path):
"""Reads the information in a block file and returns it in a dict."""
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
blkdict = dict()
blkfile = open(path, 'rb')
blkreader = csv.reader(blkfile, dialect='excel-tab')
for n, row in enumerate(blkreader):
if n == 1:
blkdict['flags'] = row[1]
elif n == 2:
repeats = int(row[1])
elif n == 3:
sequence = row[1:]
sequence = [int(i) for i in sequence]
blkfile.close()
blkdict['idlist'] = ([-1] + sequence) * repeats
return blkdict
@staticmethod
def addtoblk(path, idlist, rowlen):
"""Appends a list of group ids to the specified block file."""
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
blkfile = open(path, 'ab')
blkwriter = csv.writer(blkfile, dialect='excel-tab')
blkwriter.writerow(['groups added:'])
# Split idlist into lists of length rowlen, based on grouper recipe
args = [iter(idlist)] * rowlen
rowlist = itertools.izip_longest(*args, fillvalue='')
for row in rowlist:
blkwriter.writerow(row)
blkfile.close()
def display(self, fullscreen=False, logtime=False, logdur=False,
sigser=False, sigpar=False, fpbs=0,
phototest=False, photoburst=False,
eyetrack=False, etuser=False, etvideo=None,
tryagain=0, trybreak=None, groupq=[]):
"""Displays the project animation on the screen.
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
sigser -- send signals through serial port when each group is shown
sigpar -- send signals through parallel port when each group is shown
fpbs -- flips per board signal, i.e. number of shape color reversals
(flips) that occur for a unique signal to be sent for that shape
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- Append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- Append a wait screen to the group queue every time
after this many groups have been appended to the queue
groupq -- queue of groups to be displayed, defaults to order of
groups in project (i.e. groups[0] first, etc.)
"""
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if phototest:
test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Set-up groups and variables that control their display
if groupq == []:
groupq = list(self.groups)
n = -1
flipped = 0
flip_id = -1
groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Initialize ports
if sigser:
if not signals.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if sigpar:
if not signals.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
signals.init(sigser, sigpar)
# Initialize eyetracking
if eyetrack:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if trybreak == None:
trybreak = len(self.groups)
fixated = False
old_fixated = False
tracked = False
old_tracked = False
cur_fix_fail = False
fail_idlist = []
eyetracking.select_source(etuser, etvideo)
eyetracking.start()
# Stretch to fit screen only if project res does not equal screen res
scaling = False
if fullscreen:
window = pyglet.window.Window(fullscreen=True, visible=False)
if (window.width, window.height) != self.res:
scaling = True
else:
window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
keystates = pyglet.window.key.KeyStateHandler()
window.push_handlers(keystates)
# Create framebuffer object for drawing unscaled scene
if scaling:
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
fbo.end_render()
# Clear window and make visible
window.switch_to()
graphics.set_clear_color(self.bg)
window.clear()
window.set_visible()
# Initialize logging variables
if logtime and logdur:
logstring = ''
stamp = Timer()
dur = Timer()
stamp.start()
dur.start()
elif logtime or logdur:
logstring = ''
timer = Timer()
timer.start()
# Main loop
while not window.has_exit and count < disp_end:
# Clear canvas
if scaling:
fbo.start_render()
fbo.clear()
else:
window.clear()
# Assume no change to group visibility
flipped = 0
signals.set_null()
# Manage groups when they are on_screen
if groups_visible:
# Check whether group changes in visibility
if n >= 0 and groupq[n].visible != groupq[n].old_visible:
flip_id = self.groups.index(groupq[n])
if groupq[n].visible:
flipped = 1
elif groupq[n].old_visible:
flipped = -1
# Get next group from queue
if n < 0 or groupq[n].over:
# Send special signal if waitscreen ends
if isinstance(groupq[n], CkgWaitScreen):
signals.set_user_start()
n += 1
if n >= len(groupq):
groups_visible = False
else:
groupq[n].reset()
if eyetrack:
cur_fix_fail = False
if groupq[n].visible:
flip_id = self.groups.index(groupq[n])
flipped = 1
# Draw and then update group
if n >= 0:
groupq[n].draw(photoburst=photoburst)
groupq[n].update(fps=self.fps,
fpbs=fpbs,
keystates=keystates)
# Send signals upon group visibility change
if flipped == 1:
signals.set_group_start(flip_id)
# Draw test rectangle
if phototest:
test_rect.draw()
elif flipped == -1:
signals.set_group_stop(flip_id)
if eyetrack:
# First check if eye is being tracked and send signals
old_tracked = tracked
tracked = eyetracking.is_tracked()
if tracked:
if not old_tracked:
# Send signal if eye starts being tracked
signals.set_track_start()
else:
if old_tracked:
# Send signal if eye stops being tracked
signals.set_track_stop()
# Next check for fixation
old_fixated = fixated
fixated = eyetracking.is_fixated(FIX_POS, FIX_RANGE, FIX_PER)
if fixated:
# Draw normal cross color if fixating
fix_crosses[0].draw()
if not old_fixated:
# Send signal if fixation starts
signals.set_fix_start()
else:
# Draw alternative cross color if not fixating
fix_crosses[1].draw()
if old_fixated:
# Send signal if fixation stops
signals.set_fix_stop()
# Take note of which groups in which fixation failed
if not cur_fix_fail and groupq[n].visible and\
(tracked and not fixated):
cur_fix_fail = True
if len(fail_idlist) == 0 and trybreak > 0:
groupq.append(CkgWaitScreen(res=self.res))
fail_idlist.append(self.groups.index(groupq[n]))
# Append failed group to group queue
if tryagain > 0:
groupq.append(groupq[n])
groups_stop += groupq[n].duration() * self.fps
disp_end += groupq[n].duration() * self.fps
# Insert waitscreen every trybreak failed groups
if trybreak > 0:
if len(fail_idlist) % trybreak == 0:
groupq.append(CkgWaitScreen())
tryagain -= 1
# Change cross color based on time if eyetracking is not enabled
if not eyetrack:
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Increment count and set whether groups should be shown
if not isinstance(groupq[n], CkgWaitScreen):
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
# Blit canvas to screen if necessary
if scaling:
fbo.end_render()
window.switch_to()
canvas.blit(0, 0)
window.dispatch_events()
window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to log string
if logtime and logdur:
logstring = '\n'.join([logstring, str(stamp.elapsed())])
logstring = '\t'.join([logstring, str(dur.restart())])
elif logtime:
logstring = '\n'.join([logstring, str(timer.elapsed())])
elif logdur:
logstring = '\n'.join([logstring, str(timer.restart())])
# Send signals ASAP after flip
signals.send(sigser, sigpar)
# Log when signals are sent
if logtime or logdur:
if flipped != 0 and (sigser or sigpar):
sigmsg = '{0} sent'.format(signals.STATE)
logstring = '\t'.join([logstring, sigmsg])
# Clean up
if eyetrack:
eyetracking.stop()
window.close()
if scaling:
fbo.delete()
del canvas
signals.quit(sigser, sigpar)
# Write log string to file
if logtime or logdur:
filename = '{0}.log'.format(self.name)
with open(filename, 'w') as logfile:
logfile.write(logstring)
# Return list of ids of failed groups
if eyetrack and len(fail_idlist) > 0:
return fail_idlist
def export(self, export_dir, export_duration, groupq=[],
export_fmt=None, folder=True, force=False):
if not os.path.isdir(export_dir):
msg = 'export path is not a directory'
raise IOError(msg)
if export_fmt == None:
export_fmt = self.export_fmt
# Set-up groups and variables that control their display
if groupq == []:
groupq = list(self.groups)
n = -1
groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Limit export duration to display duration
frames = export_duration * self.fps
frames = min(frames, disp_end)
# Warn user if a lot of frames will be exported
if frames > MAX_EXPORT_FRAMES and not force:
msg = 'very large number ({0}) of frames to be exported'.\
format(frames)
raise FrameOverflowError(msg)
# Create folder to store images if necessary
if folder:
export_dir = os.path.join(export_dir,
self.name + EXPORT_DIR_SUFFIX)
if not os.path.isdir(export_dir):
os.mkdir(export_dir)
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Set up canvas and framebuffer object
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
# Main loop
while count < frames:
fbo.clear()
if groups_visible:
# Get next group from queue
if n < 0 or groupq[n].over:
n += 1
if n >= len(groupq):
groups_visible = False
else:
groupq[n].reset()
# Draw and then update group
if n >= 0:
groupq[n].draw()
groupq[n].update(fps=self.fps, fpbs=0)
# Draw fixation cross based on current count
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Save current frame to file
savepath = \
os.path.join(export_dir,
'{0}{2}.{1}'.
format(self.name, export_fmt,
repr(count).zfill(numdigits(frames-1))))
canvas.save(savepath)
# Increment count and set whether groups should be shown
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
fbo.delete()
class CkgExp:
- DEFAULTS = {'name': 'untitled', 'proj' : None,
+ DEFAULTS = {'name': None, 'proj' : None,
'trials': 1, 'sequences': None,
'flags': '--fullscreen --logtime --logdur'}
def __init__(self, **keywords):
"""Create a checkergen experiment, which specifies how a project
is to be displayed.
path -- if specified, ignore other arguments and load project
from path
name -- name of the experiment
proj -- CkgProj that the experiment is to be created for
trials -- number of times the selected sequence of display groups
will be shown in one block
sequences -- list of possible display group id sequences, from which
one sequence will be randomly selected for display in a block,
defaults to reduced latin square with side length equal to the number
of display groups in the supplied CkgProj
flags -- string passed to the display command as flags
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
- if 'name' not in keywords.keys() and self.proj != None:
+ if self.name == None and self.proj != None:
self.name = self.proj.name
if self.sequences == None:
if self.proj == None:
msg = "either project or sequences have to be specified"
raise ValueError(msg)
else:
self.gen_latin_square(len(self.proj.groups))
del self.proj
def gen_latin_square(self, n):
"""Set experiment sequences as a cyclic reduced latin square."""
sequence = range(n)
self.sequences = [[sequence[i - j] for i in range(n)]
for j in range(n, 0, -1)]
+ def get_idlist(self):
+ """Choose random sequence, create idlist from it and return."""
+ sequence = random.choice(self.sequences)
+ idlist = ([-1] + sequence) * self.trials
+ return idlist
+
def save(self, path=None):
"""Saves experiment to specified path as a CSV file."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, EXP_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(EXP_FMT):
path = '{0}.{1}'.format(path, EXP_FMT)
with open(path, 'wb') as expfile:
expwriter = csv.writer(expfile, dialect='excel-tab')
expwriter.writerow(['checkergen experiment file'])
expwriter.writerow(['flags:', self.flags])
expwriter.writerow(['trials:', self.trials])
expwriter.writerow(['sequences:'])
for sequence in self.sequences:
expwriter.writerow(sequence)
def load(self, path):
- """Loads project from specified path."""
+ """Loads experiment from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, EXP_FMT)
elif ext != '.{0}'.format(EXP_FMT):
msg = "path lacks '.{0}' extension".format(EXP_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'rb') as expfile:
expreader = csv.reader(expfile, dialect='excel-tab')
for n, row in enumerate(expreader):
if n == 1:
self.flags = row[1]
elif n == 2:
self.trials = int(row[1])
elif n > 3:
sequence = [int(i) for i in row]
self.sequences.append(sequence)
class CkgDisplayGroup:
DEFAULTS = {'pre': 0, 'disp': 'Infinity', 'post': 0}
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets internal count and all contained shapes."""
self._count = 0
self._start = self.pre
self._stop = self.pre + self.disp
self._end = self.pre + self.disp + self.post
self.over = False
self.old_visible = False
if self._start == 0 and self._stop > 0:
self.visible = True
else:
self.visible = False
if self._end == 0:
self.over = True
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, lazy=False, photoburst=False):
"""Draws all contained shapes during the appropriate interval."""
if self.visible:
for shape in self.shapes:
if lazy:
shape.lazydraw()
else:
shape.draw(photoburst=photoburst)
def update(self, **keywords):
"""Increments internal count, makes group visible when appropriate.
fps -- refresh rate of the display in frames per second
fpbs -- flips per board signal, i.e. number of shape color reversals
(flips) that occur for a unique signal to be sent for that shape
"""
fps = keywords['fps']
fpbs = keywords['fpbs']
if self.visible:
# Set triggers to be sent
if fpbs > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= fpbs:
signals.set_board_flip(n)
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(fps)
# Increment count and set flags for the next frame
self._count += 1
self.old_visible = self.visible
if (self._start * fps) <= self._count < (self._stop * fps):
self.visible = True
else:
self.visible = False
if self._count >= (self._end * fps):
self.over = True
else:
self.over = False
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.visible = False
self.old_visible = False
self.steps_done = 0
self.over = False
def draw(self):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, **keywords):
"""Checks for keypress, sends signal upon end."""
keystates = keywords['keystates']
if max([keystates[key] for key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
if self.steps_done == self.num_steps:
self.over = True
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = {'dims': (5, 5),
'init_unit': (30, 30), 'end_unit': (50, 50),
'position': (0, 0), 'anchor': 'bottomleft',
'cols': ((0, 0, 0), (255, 255, 255)),
'freq': 1, 'phase': 0}
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
if INT_HALF_PERIODS:
frames_per_half_period = round(fps / (self.freq * 2))
degs_per_frame = 180 / to_decimal(frames_per_half_period)
else:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
if PRERENDER_TO_TEXTURE:
init_pos = [(1 - a)* s/to_decimal(2) for s, a in
zip(self._size, graphics.locations[self.anchor])]
else:
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
anchor=self.anchor)
cur_unit_rect.col = self.cols[(i + j) % 2]
cur_unit_rect.add_to_batch(self._batches[0])
cur_unit_rect.col = self.cols[(i + j + 1) % 2]
cur_unit_rect.add_to_batch(self._batches[1])
# Increase x values
cur_unit_pos[0] += \
graphics.locations[self.anchor][0] * cur_unit[0]
cur_unit[0] += unit_grad[0]
# Reset x values
cur_unit_pos[0] = init_pos[0]
cur_unit[0] = init_unit[0]
# Increase y values
cur_unit_pos[1] += \
graphics.locations[self.anchor][1] * cur_unit[1]
cur_unit[1] += unit_grad[1]
if PRERENDER_TO_TEXTURE:
# Create textures
int_size = [int(round(s)) for s in self._size]
self._prerenders =\
[pyglet.image.Texture.create(*int_size) for n in range(2)]
# Set up framebuffer
fbo = graphics.Framebuffer()
for n in range(2):
fbo.attach_texture(self._prerenders[n])
# Draw batch to texture
fbo.start_render()
self._batches[n].draw()
fbo.end_render()
# Anchor textures for correct blitting later
self._prerenders[n].anchor_x, self._prerenders[n].anchor_y =\
[int(round((1 - a)* s/to_decimal(2))) for s, a in
zip(self._size, graphics.locations[self.anchor])]
fbo.delete()
# Delete batches since they won't be used
del self._batches
self._computed = True
def draw(self, photoburst=False, always_compute=False):
"""Draws appropriate prerender depending on current phase.
photoburst -- draw first color for only one frame for testing purposes
always_compute -- recompute what the checkerboard should look like
every frame
"""
if not self._computed or always_compute:
self.compute()
self._cur_phase %= 360
n = int(self._cur_phase // 180)
if photoburst and n == 0 and not self.flipped:
n = 1
if PRERENDER_TO_TEXTURE:
self._prerenders[n].blit(*self.position)
else:
self._batches[n].draw()
def lazydraw(self):
"""Only draws on color reversal."""
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if (cur_n != prev_n) or self._first_draw:
self.draw()
if self._first_draw:
self._first_draw = False
|
ztangent/checkergen
|
26df4df53105f8f3f508ca087dc20a445ed47179
|
Add pwd and cd commands for convenience.
|
diff --git a/src/cli.py b/src/cli.py
index 64b2d87..ecb97ed 100644
--- a/src/cli.py
+++ b/src/cli.py
@@ -614,539 +614,551 @@ class CkgCmd(cmd.Cmd):
help='list only project settings')
ls_group.add_argument('-g', '--groups', action='store_true',
help='list only display groups')
def help_ls(self):
self.__class__.ls_parser.print_help()
def do_ls(self, line):
"""Lists project, display group and checkerboard settings."""
def ls_str(s, seps=[',',';']):
"""Special space-saving output formatter."""
if type(s) in [tuple, list]:
if len(seps) > 1:
newseps = seps[1:]
else:
newseps = seps
return seps[0].join([ls_str(i, newseps) for i in s])
else:
return str(s)
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.ls_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ls_parser.print_usage()
return
# Remove duplicates and ascending sort
args.gidlist = sorted(set(args.gidlist))
if len(self.cur_proj.groups) == 0:
if len(args.gidlist) > 0:
print 'this project has no display groups that can be listed'
args.settings = True
else:
for gid in args.gidlist[:]:
if gid >= len(self.cur_proj.groups) or gid < 0:
args.gidlist.remove(gid)
print 'display group', gid, 'does not exist'
if args.gidlist == []:
args.gidlist = range(len(self.cur_proj.groups))
else:
# If any (valid) groups are specified
# don't show project settings
args.groups = True
if not args.groups:
print 'PROJECT SETTINGS'.center(70,'*')
print \
'name'.rjust(16),\
'fps'.rjust(7),\
'resolution'.rjust(14),\
'bg color'.rjust(18)
# 'format'.rjust(7)
print \
ls_str(self.cur_proj.name).rjust(16),\
ls_str(self.cur_proj.fps).rjust(7),\
ls_str(self.cur_proj.res).rjust(14),\
ls_str(self.cur_proj.bg).rjust(18)
# ls_str(self.cur_proj.export_fmt).rjust(7)
print \
'pre-display'.rjust(26),\
'post-display'.rjust(26)
print \
ls_str(self.cur_proj.pre).rjust(26),\
ls_str(self.cur_proj.post).rjust(26)
print \
'cross colors'.rjust(26),\
'cross times'.rjust(26)
print \
ls_str(self.cur_proj.cross_cols).rjust(26),\
ls_str(self.cur_proj.cross_times).rjust(26)
if not args.settings and not args.groups:
# Insert empty line if both groups and project
# settings are listed
print ''
if not args.settings:
for i, n in enumerate(args.gidlist):
if i != 0:
# Print newline seperator between each group
print ''
group = self.cur_proj.groups[n]
print 'GROUP {n}'.format(n=n).center(70,'*')
print \
'pre-display'.rjust(20),\
'display'.rjust(20),\
'post-display'.rjust(20)
print \
ls_str(group.pre).rjust(20),\
ls_str(group.disp).rjust(20),\
ls_str(group.post).rjust(20)
if len(group.shapes) > 0:
print \
''.rjust(2),\
'shape id'.rjust(8),\
'dims'.rjust(10),\
'init_unit'.rjust(14),\
'end_unit'.rjust(14),\
'position'.rjust(14)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.dims).rjust(10),\
ls_str(shape.init_unit).rjust(14),\
ls_str(shape.end_unit).rjust(14),\
ls_str(shape.position).rjust(14)
print '\n',\
''.rjust(2),\
'shape id'.rjust(8),\
'colors'.rjust(27),\
'anchor'.rjust(12),\
'freq'.rjust(6),\
'phase'.rjust(7)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.cols).rjust(27),\
ls_str(shape.anchor).rjust(12),\
ls_str(shape.freq).rjust(6),\
ls_str(shape.phase).rjust(7)
display_parser = CmdParser(add_help=False, prog='display',
description='''Displays the animation in a
window or in fullscreen.''')
display_parser.add_argument('-b', '--block', metavar='PATH',
help='''read flags and dislay group order from
specified file, ignore other flags''')
display_parser.add_argument('-f', '--fullscreen', action='store_true',
help='sets fullscreen mode, ESC to quit')
display_parser.add_argument('-p', '--priority', metavar='LEVEL',
help='''set priority while displaying,
higher priority results in
less dropped frames (choices:
0-3, low, normal, high,
realtime)''')
display_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly display specified display
groups N number of times''')
display_parser.add_argument('-pt', '--phototest', action='store_true',
help='''draw white test rectangle in topleft
corner of screen when groups become
visible for a photodiode to detect''')
display_parser.add_argument('-pb', '--photoburst', action='store_true',
help='''make checkerboards only draw first
color for one frame to facilitate
testing with a photodiode''')
display_parser.add_argument('-lt', '--logtime', action='store_true',
help='output frame timestamps to a log file')
display_parser.add_argument('-ld', '--logdur', action='store_true',
help='output frame durations to a log file')
display_parser.add_argument('-ss', '--sigser', action='store_true',
help='''send signals through the serial port
when shapes are being displayed''')
display_parser.add_argument('-sp', '--sigpar', action='store_true',
help='''send signals through the parallel port
when shapes are being displayed''')
display_parser.add_argument('-fpbs', metavar='M', type=int, default=0,
help='''unique signal corresponding to a
checkerboard is sent after the board
undergoes M color flips (default:
disabled, M=0)''')
display_parser.add_argument('-et', '--eyetrack', action='store_true',
help='''use eyetracking to ensure that subject
fixates on the cross in the center''')
display_parser.add_argument('-eu', '--etuser', action='store_true',
help='''allow user to select eyetracking video
source from a dialog''')
display_parser.add_argument('-ev', '--etvideo', metavar='path',
help='''path (with no spaces) to eyetracking
video file to be used as the source''')
display_parser.add_argument('-ta', '--tryagain', metavar='I',
type=int, default=0,
help='''append groups during which subject
failed to fixate up to I times to the
list of groups to be displayed
(default: disabled, I=0)''')
display_parser.add_argument('-tb', '--trybreak', metavar='J', type=int,
help='''used with --tryagain, append a wait
screen to the list of groups to be
displayed after every J groups have
been appended to the list (default:
J=total number of groups)''')
display_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be displayed
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_display(self):
self.__class__.display_parser.print_help()
def do_display(self, line):
"""Displays the animation in a window or in fullscreen"""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.display_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
if args.block != None:
blkpath = args.block
try:
blkdict = core.CkgProj.readblk(blkpath)
flags = blkdict['flags']
try:
args = self.__class__.\
display_parser.parse_args(shlex.split(flags))
args.idlist = blkdict['idlist']
except (CmdParserError, ValueError):
print 'error: invalid flags stored in block file'
return
except IOError:
print "error:", str(sys.exc_value)
return
else:
blkpath = None
groupq = []
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < -1:
print 'error: group', i, 'does not exist'
return
for i in args.idlist:
if i == -1:
groupq.append(core.CkgWaitScreen(res=
self.cur_proj.res))
else:
groupq.append(self.cur_proj.groups[i])
else:
groupq = list(self.cur_proj.groups)
if args.repeat != None:
groupq = list(groupq * args.repeat)
if args.eyetrack and eyetracking.available:
if not eyetracking.is_calibrated():
try:
self.do_calibrate('',True)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
return
if args.priority != None:
if not priority.available:
print "error: setting priority not avaible on", sys.platform
print "continuing..."
else:
if args.priority.isdigit():
args.priority = int(args.priority)
try:
priority.set(args.priority)
except ValueError:
print "error:", str(sys.exc_value)
print "continuing..."
try:
fail_idlist = self.cur_proj.display(fullscreen=args.fullscreen,
logtime=args.logtime,
logdur=args.logdur,
sigser=args.sigser,
sigpar=args.sigpar,
fpbs=args.fpbs,
phototest=args.phototest,
photoburst=args.photoburst,
eyetrack=args.eyetrack,
etuser=args.etuser,
etvideo=args.etvideo,
tryagain=args.tryagain,
trybreak=args.trybreak,
groupq=groupq)
except (IOError, NotImplementedError, eyetracking.EyetrackingError):
print "error:", str(sys.exc_value)
if args.priority != None:
try:
priority.set('normal')
except:
pass
return
if args.priority != None:
try:
priority.set('normal')
except:
pass
# Append list of ids of failed groups to block file
if fail_idlist != None and blkpath != None:
try:
core.CkgProj.addtoblk(blkpath, fail_idlist,
len(self.cur_proj.groups))
except IOError:
print "error:", str(sys.exc_value)
return
export_parser = CmdParser(add_help=False, prog='export',
description='''Exports animation as an image
sequence (in a folder) to the
specified directory.''')
# export_parser.add_argument('--fmt', dest='export_fmt',
# choices=core.EXPORT_FMTS,
# help='image format for export')
export_parser.add_argument('-n','--nofolder',
dest='folder', action='store_false',
help='''force images not to exported in
a containing folder''')
export_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly export specified display
groups N number of times''')
export_parser.add_argument('duration', nargs='?',
type=to_decimal, default='Infinity',
help='''number of seconds of the animation
that should be exported (default:
as long as the entire animation)''')
export_parser.add_argument('dir', nargs='?', default=os.getcwd(),
help='''destination directory for export
(default: current working directory)''')
export_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be exported
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_export(self):
self.__class__.export_parser.print_help()
def do_export(self, line):
"""Exports animation an image sequence to the specified directory."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.export_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.export_parser.print_usage()
return
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < 0:
print 'error: group', i, 'does not exist'
return
groupq = [self.cur_proj.groups[i] for i in args.idlist]
else:
groupq = list(self.cur_proj.groups)
if args.repeat != None:
groupq = list(groupq * args.repeat)
try:
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
folder=args.folder)
except IOError:
print "error:", str(sys.exc_value)
return
except core.FrameOverflowError:
print "warning:", str(sys.exc_value)
print "Are you sure you want to continue?"
while True:
try:
if self.__class__.yn_parse(raw_input()):
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
groupq=groupq,
export_fmt=None,
folder=args.folder,
force=True)
break
else:
return
except TypeError:
print str(sys.exc_value)
except EOFError:
return
print "Export done."
mkblks_parser = CmdParser(add_help=False, prog='mkblks',
description='''Generates randomized experimental
blocks from display groups and
saves each as a CSV file.''')
mkblks_parser.add_argument('-n','--nofolder',
dest='folder', action='store_false',
help='''force block files not to be saved in
a containing folder''')
mkblks_parser.add_argument('-d','--dir', default=os.getcwd(),
help='''where to save block files
(default: current working directory)''')
mkblks_parser.add_argument('length', type=int,
help='''no. of repeated trials in a block''')
mkblks_parser.add_argument('flags', nargs='?', default='',
help='''flags passed to the display command
that should be used when the block
file is run (enclose in quotes and use
'+' or '++' in place of '-' or '--')''')
def help_mkblks(self):
self.__class__.mkblks_parser.print_help()
def do_mkblks(self, line):
"""Generates randomized experimental blocks from display groups."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.mkblks_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mkblks_parser.print_usage()
return
args.flags = args.flags.replace('+','-')
try:
disp_args = self.__class__.display_parser.\
parse_args(shlex.split(args.flags))
except (CmdParserError, ValueError):
print "error: invalid flags to display command"
print str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
try:
self.cur_proj.mkblks(args.length,
path=args.dir,
folder=args.folder,
flags=args.flags)
except IOError:
print "error:", str(sys.exc_value)
return
print "Experimental blocks generated."
def do_calibrate(self, line, query=False):
"""Calibrate subject for eyetracking, or load a calibration file."""
if not eyetracking.available:
print "error: eyetracking functionality not available"
return
if query:
print "path to calibration file (leave empty for GUI tool):"
try:
path = raw_input().strip().strip('"\'')
except EOFError:
msg = "calibration cancelled"
raise eyetracking.EyetrackingError(msg)
else:
path = line.strip().strip('"\'')
if len(path) == 0:
path = None
if not eyetracking.is_source_ready():
# Select default source if none has been selected
eyetracking.select_source()
try:
eyetracking.calibrate(path)
except eyetracking.EyetrackingError:
if query:
raise
else:
print "error:", str(sys.exc_value)
return
if len(path) > 0:
print "calibration file successfully loaded"
etsetup_parser = CmdParser(add_help=False, prog='etsetup',
description='''Set various eyetracking
parameters.''')
etsetup_parser.add_argument('-fp', '--fixperiod', type=int, metavar='MS',
help='''time in milliseconds subject
has to stare at the same spot
for fixation to be detected''')
etsetup_parser.add_argument('-fr', '--fixrange', type=float, metavar='MM',
help='''distance in mm beyond which the
eye position cannot change for
a fixation to be detected''')
etsetup_parser.add_argument('-s', '--size', metavar='WIDTH,HEIGHT',
action=store_tuple(2, ',', float),
help='physical screen dimensions in mm')
etsetup_parser.add_argument('-vd', '--viewdist', type=int, metavar='MM',
help='''viewing distance between subject's
eyes and the screen''')
def help_etsetup(self):
self.__class__.etsetup_parser.print_help()
def do_etsetup(self, line):
try:
args = self.__class__.etsetup_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.etsetup_parser.print_usage()
return
try:
eyetracking.setup(viewing_distance=args.viewdist,
screen_dims=args.size,
fixation_period=args.fixperiod,
fixation_range=args.fixrange)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
-
+
+ def do_pwd(self, line):
+ """Prints the current working directory."""
+ print os.getcwd()
+
+ def do_cd(self, line):
+ """Change working directory to specified path."""
+ path = line.strip().strip('"\'')
+ if not os.path.isdir(path):
+ print "error: specified path is not a directory"
+ return
+ os.chdir(path)
+
def do_quit(self, line):
"""Quits the program."""
if self.save_check():
return
return True
def help_EOF(self):
print "Typing {0} issues this command, which quits the program."\
.format(CMD_EOF_STRING)
def do_EOF(self, line):
"""Typing Ctrl-D issues this command, which quits the program."""
print '\r'
if self.save_check():
return
return True
def help_help(self):
print 'Prints a list of commands.'
print "Type 'help <topic>' for more details on each command."
def default(self, line):
command = line.split()[0]
print \
"'{0}' is not a checkergen command.".format(command),\
"Type 'help' for a list of commands"
|
ztangent/checkergen
|
49691c1a81437212b5f9d3961df205a86d2bc019
|
cleaned up display and export functions slightly
|
diff --git a/src/cli.py b/src/cli.py
index 7e10629..64b2d87 100644
--- a/src/cli.py
+++ b/src/cli.py
@@ -332,821 +332,821 @@ class CkgCmd(cmd.Cmd):
for x in args.idlist[:]:
if x >= len(self.cur_proj.groups) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_group_attr(x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.edgrp_parser.print_usage()
rmgrp_parser = CmdParser(add_help=False, prog='rmgrp',
description='''Removes display groups specified
by ids.''')
rmgrp_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='ids of display groups to be removed')
rmgrp_parser.add_argument('-a', '--all', action='store_true',
help='remove all groups from the project')
def help_rmgrp(self):
self.__class__.rmgrp_parser.print_help()
def do_rmgrp(self, line):
"""Removes display groups specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups to remove'
return
try:
args = self.__class__.rmgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rmgrp_parser.print_usage()
return
rmlist = []
if args.all:
for group in self.cur_proj.groups[:]:
self.cur_proj.del_group(group)
print "all display groups removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_proj.groups) or x < 0:
print "display group", x, "does not exist"
continue
rmlist.append(self.cur_proj.groups[x])
print "display group", x, "removed"
for group in rmlist:
self.cur_proj.del_group(group)
# Remember to point self.cur_group somewhere sane
if self.cur_group not in self.cur_proj.groups:
if len(self.cur_proj.groups) == 0:
self.cur_group = None
else:
self.cur_group = self.cur_proj.groups[0]
print "group 0 is now the current display group"
chgrp_parser = CmdParser(add_help=False, prog='chgrp',
description='''Changes display group that is
currently active for editing.
Prints current group id if
no group id is specified''')
chgrp_parser.add_argument('gid', metavar='id', type=int, nargs='?',
help='id of display group to be made active')
def help_chgrp(self):
self.__class__.chgrp_parser.print_help()
def do_chgrp(self, line):
"""Changes group that is currently active for editing."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups that can be made active'
return
try:
args = self.__class__.chgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.chgrp_parser.print_usage()
return
if args.gid == None:
print "group",\
self.cur_proj.groups.index(self.cur_group),\
"is the current display group"
elif args.gid >= len(self.cur_proj.groups) or args.gid < 0:
print "group", args.gid, "does not exist"
else:
self.cur_group = self.cur_proj.groups[args.gid]
print "group", args.gid, "is now the current display group"
mk_parser = CmdParser(add_help=False, prog='mk',
description='''Makes a new checkerboard in the
current group with the given
parameters.''')
mk_parser.add_argument('dims', action=store_tuple(2, ',', to_decimal),
help='''width,height of checkerboard in no. of
unit cells''')
mk_parser.add_argument('init_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of initial unit cell in pixels')
mk_parser.add_argument('end_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of final unit cell in pixels')
mk_parser.add_argument('position', action=store_tuple(2, ',', to_decimal),
help='x,y position of checkerboard in pixels')
mk_parser.add_argument('anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='anchor')
mk_parser.add_argument('cols', action=store_tuple(2, ',', to_color, [';']),
help='''color1,color2 of the checkerboard
(color format: R;G;B,
component range from 0-255)''')
mk_parser.add_argument('freq', type=to_decimal,
help='frequency of color reversal in Hz')
mk_parser.add_argument('phase', type=to_decimal, nargs='?', default='0',
help='initial phase of animation in degrees')
def help_mk(self):
self.__class__.mk_parser.print_help()
def do_mk(self, line):
"""Makes a checkerboard with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
if self.cur_group == None:
print 'automatically adding display group...'
self.do_mkgrp('')
try:
args = self.__class__.mk_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mk_parser.print_usage()
return
shape_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_shape = core.CheckerBoard(**shape_dict)
new_id = self.cur_proj.add_shape_to_group(self.cur_group, new_shape)
print "checkerboard", new_id, "added"
ed_parser = CmdParser(add_help=False, prog='ed',
description='''Edits attributes of checkerboards
specified by ids.''')
ed_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='''ids of checkerboards in the current
group to be edited''')
ed_parser.add_argument('--dims', action=store_tuple(2, ',', to_decimal),
help='checkerboard dimensions in unit cells',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--init_unit',
action=store_tuple(2, ',', to_decimal),
help='initial unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--end_unit',
action=store_tuple(2, ',', to_decimal),
help='final unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--position',
action=store_tuple(2, ',', to_decimal),
help='position of checkerboard in pixels',
metavar='X,Y')
ed_parser.add_argument('--anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='LOCATION')
ed_parser.add_argument('--cols', metavar='COLOR1,COLOR2',
action=store_tuple(2, ',', to_color, [';']),
help='''checkerboard colors (color format:
R;G;B, component range
from 0-255)''')
ed_parser.add_argument('--freq', type=to_decimal,
help='frequency of color reversal in Hz')
ed_parser.add_argument('--phase', type=to_decimal,
help='initial phase of animation in degrees')
def help_ed(self):
self.__class__.ed_parser.print_help()
def do_ed(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, please create one first'
return
try:
args = self.__class__.ed_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ed_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_group.shapes) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_shape_attr(self.cur_group, x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.ed_parser.print_usage()
rm_parser = CmdParser(add_help=False, prog='rm',
description='''Removes checkerboards specified
by ids.''')
rm_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''ids of checkerboards in the current group
to be removed''')
rm_parser.add_argument('-a', '--all', action='store_true',
help='''remove all checkerboards in the
current group''')
def help_rm(self):
self.__class__.rm_parser.print_help()
def do_rm(self, line):
"""Removes checkerboards specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, no boards to remove'
return
try:
args = self.__class__.rm_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rm_parser.print_usage()
return
rmlist = []
if args.all:
for shape in self.cur_group.shapes:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
print "all checkerboards removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_group.shapes) or x < 0:
print "checkerboard", x, "does not exist"
continue
rmlist.append(self.cur_group.shapes[x])
print "checkerboard", x, "removed"
for shape in rmlist:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
ls_parser = CmdParser(add_help=False, prog='ls',
description='''Lists project, display group and
checkerboard settings. If no group ids
are specified, all display groups
are listed.''')
ls_parser.add_argument('gidlist', nargs='*', metavar='gid', type=int,
help='''ids of the display groups to be listed''')
ls_group = ls_parser.add_mutually_exclusive_group()
ls_group.add_argument('-s', '--settings', action='store_true',
help='list only project settings')
ls_group.add_argument('-g', '--groups', action='store_true',
help='list only display groups')
def help_ls(self):
self.__class__.ls_parser.print_help()
def do_ls(self, line):
"""Lists project, display group and checkerboard settings."""
def ls_str(s, seps=[',',';']):
"""Special space-saving output formatter."""
if type(s) in [tuple, list]:
if len(seps) > 1:
newseps = seps[1:]
else:
newseps = seps
return seps[0].join([ls_str(i, newseps) for i in s])
else:
return str(s)
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.ls_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ls_parser.print_usage()
return
# Remove duplicates and ascending sort
args.gidlist = sorted(set(args.gidlist))
if len(self.cur_proj.groups) == 0:
if len(args.gidlist) > 0:
print 'this project has no display groups that can be listed'
args.settings = True
else:
for gid in args.gidlist[:]:
if gid >= len(self.cur_proj.groups) or gid < 0:
args.gidlist.remove(gid)
print 'display group', gid, 'does not exist'
if args.gidlist == []:
args.gidlist = range(len(self.cur_proj.groups))
else:
# If any (valid) groups are specified
# don't show project settings
args.groups = True
if not args.groups:
print 'PROJECT SETTINGS'.center(70,'*')
print \
'name'.rjust(16),\
'fps'.rjust(7),\
'resolution'.rjust(14),\
'bg color'.rjust(18)
# 'format'.rjust(7)
print \
ls_str(self.cur_proj.name).rjust(16),\
ls_str(self.cur_proj.fps).rjust(7),\
ls_str(self.cur_proj.res).rjust(14),\
ls_str(self.cur_proj.bg).rjust(18)
# ls_str(self.cur_proj.export_fmt).rjust(7)
print \
'pre-display'.rjust(26),\
'post-display'.rjust(26)
print \
ls_str(self.cur_proj.pre).rjust(26),\
ls_str(self.cur_proj.post).rjust(26)
print \
'cross colors'.rjust(26),\
'cross times'.rjust(26)
print \
ls_str(self.cur_proj.cross_cols).rjust(26),\
ls_str(self.cur_proj.cross_times).rjust(26)
if not args.settings and not args.groups:
# Insert empty line if both groups and project
# settings are listed
print ''
if not args.settings:
for i, n in enumerate(args.gidlist):
if i != 0:
# Print newline seperator between each group
print ''
group = self.cur_proj.groups[n]
print 'GROUP {n}'.format(n=n).center(70,'*')
print \
'pre-display'.rjust(20),\
'display'.rjust(20),\
'post-display'.rjust(20)
print \
ls_str(group.pre).rjust(20),\
ls_str(group.disp).rjust(20),\
ls_str(group.post).rjust(20)
if len(group.shapes) > 0:
print \
''.rjust(2),\
'shape id'.rjust(8),\
'dims'.rjust(10),\
'init_unit'.rjust(14),\
'end_unit'.rjust(14),\
'position'.rjust(14)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.dims).rjust(10),\
ls_str(shape.init_unit).rjust(14),\
ls_str(shape.end_unit).rjust(14),\
ls_str(shape.position).rjust(14)
print '\n',\
''.rjust(2),\
'shape id'.rjust(8),\
'colors'.rjust(27),\
'anchor'.rjust(12),\
'freq'.rjust(6),\
'phase'.rjust(7)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.cols).rjust(27),\
ls_str(shape.anchor).rjust(12),\
ls_str(shape.freq).rjust(6),\
ls_str(shape.phase).rjust(7)
display_parser = CmdParser(add_help=False, prog='display',
description='''Displays the animation in a
window or in fullscreen.''')
display_parser.add_argument('-b', '--block', metavar='PATH',
help='''read flags and dislay group order from
specified file, ignore other flags''')
display_parser.add_argument('-f', '--fullscreen', action='store_true',
help='sets fullscreen mode, ESC to quit')
display_parser.add_argument('-p', '--priority', metavar='LEVEL',
help='''set priority while displaying,
higher priority results in
less dropped frames (choices:
0-3, low, normal, high,
realtime)''')
display_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly display specified display
groups N number of times''')
display_parser.add_argument('-pt', '--phototest', action='store_true',
help='''draw white test rectangle in topleft
corner of screen when groups become
visible for a photodiode to detect''')
display_parser.add_argument('-pb', '--photoburst', action='store_true',
help='''make checkerboards only draw first
color for one frame to facilitate
testing with a photodiode''')
display_parser.add_argument('-lt', '--logtime', action='store_true',
help='output frame timestamps to a log file')
display_parser.add_argument('-ld', '--logdur', action='store_true',
help='output frame durations to a log file')
display_parser.add_argument('-ss', '--sigser', action='store_true',
help='''send signals through the serial port
when shapes are being displayed''')
display_parser.add_argument('-sp', '--sigpar', action='store_true',
help='''send signals through the parallel port
when shapes are being displayed''')
display_parser.add_argument('-fpbs', metavar='M', type=int, default=0,
help='''unique signal corresponding to a
checkerboard is sent after the board
undergoes M color flips (default:
disabled, M=0)''')
display_parser.add_argument('-et', '--eyetrack', action='store_true',
help='''use eyetracking to ensure that subject
fixates on the cross in the center''')
display_parser.add_argument('-eu', '--etuser', action='store_true',
help='''allow user to select eyetracking video
source from a dialog''')
display_parser.add_argument('-ev', '--etvideo', metavar='path',
help='''path (with no spaces) to eyetracking
video file to be used as the source''')
display_parser.add_argument('-ta', '--tryagain', metavar='I',
type=int, default=0,
help='''append groups during which subject
failed to fixate up to I times to the
list of groups to be displayed
(default: disabled, I=0)''')
display_parser.add_argument('-tb', '--trybreak', metavar='J', type=int,
help='''used with --tryagain, append a wait
screen to the list of groups to be
displayed after every J groups have
been appended to the list (default:
J=total number of groups)''')
display_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be displayed
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_display(self):
self.__class__.display_parser.print_help()
def do_display(self, line):
"""Displays the animation in a window or in fullscreen"""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.display_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
if args.block != None:
blkpath = args.block
try:
blkdict = core.CkgProj.readblk(blkpath)
flags = blkdict['flags']
try:
args = self.__class__.\
display_parser.parse_args(shlex.split(flags))
args.idlist = blkdict['idlist']
except (CmdParserError, ValueError):
print 'error: invalid flags stored in block file'
return
except IOError:
print "error:", str(sys.exc_value)
return
else:
blkpath = None
- group_queue = []
+ groupq = []
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < -1:
print 'error: group', i, 'does not exist'
return
for i in args.idlist:
if i == -1:
- group_queue.append(core.CkgWaitScreen(res=
+ groupq.append(core.CkgWaitScreen(res=
self.cur_proj.res))
else:
- group_queue.append(self.cur_proj.groups[i])
+ groupq.append(self.cur_proj.groups[i])
else:
- group_queue = list(self.cur_proj.groups)
+ groupq = list(self.cur_proj.groups)
if args.repeat != None:
- group_queue = list(group_queue * args.repeat)
+ groupq = list(groupq * args.repeat)
if args.eyetrack and eyetracking.available:
if not eyetracking.is_calibrated():
try:
self.do_calibrate('',True)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
return
if args.priority != None:
if not priority.available:
print "error: setting priority not avaible on", sys.platform
print "continuing..."
else:
if args.priority.isdigit():
args.priority = int(args.priority)
try:
priority.set(args.priority)
except ValueError:
print "error:", str(sys.exc_value)
print "continuing..."
try:
fail_idlist = self.cur_proj.display(fullscreen=args.fullscreen,
logtime=args.logtime,
logdur=args.logdur,
sigser=args.sigser,
sigpar=args.sigpar,
fpbs=args.fpbs,
phototest=args.phototest,
photoburst=args.photoburst,
eyetrack=args.eyetrack,
etuser=args.etuser,
etvideo=args.etvideo,
tryagain=args.tryagain,
trybreak=args.trybreak,
- group_queue=group_queue)
+ groupq=groupq)
except (IOError, NotImplementedError, eyetracking.EyetrackingError):
print "error:", str(sys.exc_value)
if args.priority != None:
try:
priority.set('normal')
except:
pass
return
if args.priority != None:
try:
priority.set('normal')
except:
pass
# Append list of ids of failed groups to block file
if fail_idlist != None and blkpath != None:
try:
core.CkgProj.addtoblk(blkpath, fail_idlist,
len(self.cur_proj.groups))
except IOError:
print "error:", str(sys.exc_value)
return
export_parser = CmdParser(add_help=False, prog='export',
description='''Exports animation as an image
sequence (in a folder) to the
specified directory.''')
# export_parser.add_argument('--fmt', dest='export_fmt',
# choices=core.EXPORT_FMTS,
# help='image format for export')
export_parser.add_argument('-n','--nofolder',
dest='folder', action='store_false',
help='''force images not to exported in
a containing folder''')
export_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly export specified display
groups N number of times''')
export_parser.add_argument('duration', nargs='?',
type=to_decimal, default='Infinity',
help='''number of seconds of the animation
that should be exported (default:
as long as the entire animation)''')
export_parser.add_argument('dir', nargs='?', default=os.getcwd(),
help='''destination directory for export
(default: current working directory)''')
export_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be exported
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_export(self):
self.__class__.export_parser.print_help()
def do_export(self, line):
"""Exports animation an image sequence to the specified directory."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.export_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.export_parser.print_usage()
return
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < 0:
print 'error: group', i, 'does not exist'
return
- group_queue = [self.cur_proj.groups[i] for i in args.idlist]
+ groupq = [self.cur_proj.groups[i] for i in args.idlist]
else:
- group_queue = list(self.cur_proj.groups)
+ groupq = list(self.cur_proj.groups)
if args.repeat != None:
- group_queue = list(group_queue * args.repeat)
+ groupq = list(groupq * args.repeat)
try:
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
- group_queue=group_queue,
+ groupq=groupq,
folder=args.folder)
except IOError:
print "error:", str(sys.exc_value)
return
except core.FrameOverflowError:
print "warning:", str(sys.exc_value)
print "Are you sure you want to continue?"
while True:
try:
if self.__class__.yn_parse(raw_input()):
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
- group_queue=group_queue,
+ groupq=groupq,
export_fmt=None,
folder=args.folder,
force=True)
break
else:
return
except TypeError:
print str(sys.exc_value)
except EOFError:
return
print "Export done."
mkblks_parser = CmdParser(add_help=False, prog='mkblks',
description='''Generates randomized experimental
blocks from display groups and
saves each as a CSV file.''')
mkblks_parser.add_argument('-n','--nofolder',
dest='folder', action='store_false',
help='''force block files not to be saved in
a containing folder''')
mkblks_parser.add_argument('-d','--dir', default=os.getcwd(),
help='''where to save block files
(default: current working directory)''')
mkblks_parser.add_argument('length', type=int,
help='''no. of repeated trials in a block''')
mkblks_parser.add_argument('flags', nargs='?', default='',
help='''flags passed to the display command
that should be used when the block
file is run (enclose in quotes and use
'+' or '++' in place of '-' or '--')''')
def help_mkblks(self):
self.__class__.mkblks_parser.print_help()
def do_mkblks(self, line):
"""Generates randomized experimental blocks from display groups."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.mkblks_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mkblks_parser.print_usage()
return
args.flags = args.flags.replace('+','-')
try:
disp_args = self.__class__.display_parser.\
parse_args(shlex.split(args.flags))
except (CmdParserError, ValueError):
print "error: invalid flags to display command"
print str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
try:
self.cur_proj.mkblks(args.length,
path=args.dir,
folder=args.folder,
flags=args.flags)
except IOError:
print "error:", str(sys.exc_value)
return
print "Experimental blocks generated."
def do_calibrate(self, line, query=False):
"""Calibrate subject for eyetracking, or load a calibration file."""
if not eyetracking.available:
print "error: eyetracking functionality not available"
return
if query:
print "path to calibration file (leave empty for GUI tool):"
try:
path = raw_input().strip().strip('"\'')
except EOFError:
msg = "calibration cancelled"
raise eyetracking.EyetrackingError(msg)
else:
path = line.strip().strip('"\'')
if len(path) == 0:
path = None
if not eyetracking.is_source_ready():
# Select default source if none has been selected
eyetracking.select_source()
try:
eyetracking.calibrate(path)
except eyetracking.EyetrackingError:
if query:
raise
else:
print "error:", str(sys.exc_value)
return
if len(path) > 0:
print "calibration file successfully loaded"
etsetup_parser = CmdParser(add_help=False, prog='etsetup',
description='''Set various eyetracking
parameters.''')
etsetup_parser.add_argument('-fp', '--fixperiod', type=int, metavar='MS',
help='''time in milliseconds subject
has to stare at the same spot
for fixation to be detected''')
etsetup_parser.add_argument('-fr', '--fixrange', type=float, metavar='MM',
help='''distance in mm beyond which the
eye position cannot change for
a fixation to be detected''')
etsetup_parser.add_argument('-s', '--size', metavar='WIDTH,HEIGHT',
action=store_tuple(2, ',', float),
help='physical screen dimensions in mm')
etsetup_parser.add_argument('-vd', '--viewdist', type=int, metavar='MM',
help='''viewing distance between subject's
eyes and the screen''')
def help_etsetup(self):
self.__class__.etsetup_parser.print_help()
def do_etsetup(self, line):
try:
args = self.__class__.etsetup_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.etsetup_parser.print_usage()
return
try:
eyetracking.setup(viewing_distance=args.viewdist,
screen_dims=args.size,
fixation_period=args.fixperiod,
fixation_range=args.fixrange)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
def do_quit(self, line):
"""Quits the program."""
if self.save_check():
return
return True
def help_EOF(self):
print "Typing {0} issues this command, which quits the program."\
.format(CMD_EOF_STRING)
def do_EOF(self, line):
"""Typing Ctrl-D issues this command, which quits the program."""
print '\r'
if self.save_check():
return
return True
def help_help(self):
print 'Prints a list of commands.'
print "Type 'help <topic>' for more details on each command."
def default(self, line):
command = line.split()[0]
print \
"'{0}' is not a checkergen command.".format(command),\
"Type 'help' for a list of commands"
diff --git a/src/core.py b/src/core.py
index 6e4749f..3e8c8a2 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,1250 +1,1242 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgExp -- A checkergen experiment, describes how a projet is displayed.
CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import itertools
from xml.dom import minidom
import pyglet
import graphics
import signals
import eyetracking
from utils import *
CKG_FMT = 'ckg'
EXP_FMT = 'exp'
LOG_FMT = 'log'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
MAX_EXPORT_FRAMES = 100000
PRERENDER_TO_TEXTURE = False
INT_HALF_PERIODS = True
EXPORT_FMTS = ['png']
EXPORT_DIR_SUFFIX = '-anim'
BLOCK_DIR_SUFFIX = '-blks'
FIX_POS = (0, 0)
FIX_RANGE = (20, 20)
FIX_PER = 350
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = {'name': 'untitled',
'fps': 60,
'res': (800, 600),
'bg': (127, 127, 127),
'export_fmt': 'png',
'pre': 0,
'post': 0,
'cross_cols': ((0, 0, 0), (255, 0, 0)),
'cross_times': ('Infinity', 1)}
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
export_fmt -- image format for animation to be exported as
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'export_fmt':
if value not in EXPORT_FMTS:
msg = 'image format not recognized or supported'
raise FileFormatError(msg)
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, CKG_FMT)
elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
vars_to_load = self.__class__.DEFAULTS.keys()
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
vars_to_save = self.__class__.DEFAULTS.keys()
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def mkblks(self, length, path=None, folder=True, flags=''):
"""Generates randomized experimental blocks from display groups.
Each block is saved as a CSV file.
length -- number of repeated trials within a block
path -- directory in which experimental blocks will be saved
folder -- blocks will be saved in a containing folder if true
flags -- string of flags to be issued to the display command when
block file is run
"""
if path == None:
path = os.getcwd()
if not os.path.isdir(path):
msg = "specified directory does not exist"
raise IOError(msg)
if folder:
path = os.path.join(path, self.name + BLOCK_DIR_SUFFIX)
if not os.path.isdir(path):
os.mkdir(path)
group_ids = range(len(self.groups))
for n, sequence in enumerate(itertools.permutations(group_ids)):
blkname = 'block{0}.csv'.format(repr(n).zfill(numdigits(length)))
blkfile = open(os.path.join(path, blkname), 'wb')
blkwriter = csv.writer(blkfile, dialect='excel-tab')
blkwriter.writerow(['checkergen experimental block file'])
blkwriter.writerow(['flags:', flags])
blkwriter.writerow(['repeats:', length])
blkwriter.writerow(['sequence:'] + list(sequence))
blkfile.close()
@staticmethod
def readblk(path):
"""Reads the information in a block file and returns it in a dict."""
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
blkdict = dict()
blkfile = open(path, 'rb')
blkreader = csv.reader(blkfile, dialect='excel-tab')
for n, row in enumerate(blkreader):
if n == 1:
blkdict['flags'] = row[1]
elif n == 2:
repeats = int(row[1])
elif n == 3:
sequence = row[1:]
sequence = [int(i) for i in sequence]
blkfile.close()
blkdict['idlist'] = ([-1] + sequence) * repeats
return blkdict
@staticmethod
def addtoblk(path, idlist, rowlen):
"""Appends a list of group ids to the specified block file."""
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
blkfile = open(path, 'ab')
blkwriter = csv.writer(blkfile, dialect='excel-tab')
blkwriter.writerow(['groups added:'])
# Split idlist into lists of length rowlen, based on grouper recipe
args = [iter(idlist)] * rowlen
rowlist = itertools.izip_longest(*args, fillvalue='')
for row in rowlist:
blkwriter.writerow(row)
blkfile.close()
def display(self, fullscreen=False, logtime=False, logdur=False,
sigser=False, sigpar=False, fpbs=0,
phototest=False, photoburst=False,
eyetrack=False, etuser=False, etvideo=None,
- tryagain=0, trybreak=None, group_queue=[]):
+ tryagain=0, trybreak=None, groupq=[]):
"""Displays the project animation on the screen.
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
sigser -- send signals through serial port when each group is shown
sigpar -- send signals through parallel port when each group is shown
fpbs -- flips per board signal, i.e. number of shape color reversals
(flips) that occur for a unique signal to be sent for that shape
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- Append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- Append a wait screen to the group queue every time
after this many groups have been appended to the queue
- group_queue -- queue of groups to be displayed, defaults to order of
+ groupq -- queue of groups to be displayed, defaults to order of
groups in project (i.e. groups[0] first, etc.)
"""
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if phototest:
test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Set-up groups and variables that control their display
- if group_queue == []:
- group_queue = list(self.groups)
- cur_group = None
- cur_id = -1
+ if groupq == []:
+ groupq = list(self.groups)
+ n = -1
flipped = 0
flip_id = -1
- groups_duration = sum([group.duration() for group in group_queue])
+ groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Initialize ports
if sigser:
if not signals.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if sigpar:
if not signals.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
signals.init(sigser, sigpar)
# Initialize eyetracking
if eyetrack:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if trybreak == None:
trybreak = len(self.groups)
fixated = False
old_fixated = False
tracked = False
old_tracked = False
cur_fix_fail = False
fail_idlist = []
eyetracking.select_source(etuser, etvideo)
eyetracking.start()
# Stretch to fit screen only if project res does not equal screen res
scaling = False
if fullscreen:
window = pyglet.window.Window(fullscreen=True, visible=False)
if (window.width, window.height) != self.res:
scaling = True
else:
window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
keystates = pyglet.window.key.KeyStateHandler()
window.push_handlers(keystates)
# Create framebuffer object for drawing unscaled scene
if scaling:
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
fbo.end_render()
# Clear window and make visible
window.switch_to()
graphics.set_clear_color(self.bg)
window.clear()
window.set_visible()
# Initialize logging variables
if logtime and logdur:
logstring = ''
stamp = Timer()
dur = Timer()
stamp.start()
dur.start()
elif logtime or logdur:
logstring = ''
timer = Timer()
timer.start()
# Main loop
while not window.has_exit and count < disp_end:
# Clear canvas
if scaling:
fbo.start_render()
fbo.clear()
else:
window.clear()
# Assume no change to group visibility
flipped = 0
signals.set_null()
# Manage groups when they are on_screen
if groups_visible:
- # Send special signal if waitscreen ends
- if isinstance(cur_group, CkgWaitScreen):
- if cur_group.over:
- signals.set_user_start()
- cur_group = None
- elif cur_group != None:
- # Check whether group changes in visibility
- if cur_group.visible != cur_group.old_visible:
- flip_id = self.groups.index(cur_group)
- if cur_group.visible:
- flipped = 1
- elif cur_group.old_visible:
- flipped = -1
- # Check if current group is over
- if cur_group.over:
- cur_group = None
+ # Check whether group changes in visibility
+ if n >= 0 and groupq[n].visible != groupq[n].old_visible:
+ flip_id = self.groups.index(groupq[n])
+ if groupq[n].visible:
+ flipped = 1
+ elif groupq[n].old_visible:
+ flipped = -1
# Get next group from queue
- if cur_group == None:
- cur_id += 1
- if cur_id >= len(group_queue):
+ if n < 0 or groupq[n].over:
+ # Send special signal if waitscreen ends
+ if isinstance(groupq[n], CkgWaitScreen):
+ signals.set_user_start()
+ n += 1
+ if n >= len(groupq):
groups_visible = False
else:
- cur_group = group_queue[cur_id]
- cur_group.reset()
+ groupq[n].reset()
if eyetrack:
cur_fix_fail = False
- if cur_group.visible:
- flip_id = self.groups.index(cur_group)
+ if groupq[n].visible:
+ flip_id = self.groups.index(groupq[n])
flipped = 1
# Draw and then update group
- if cur_group != None:
- cur_group.draw(photoburst=photoburst)
- cur_group.update(fps=self.fps,
+ if n >= 0:
+ groupq[n].draw(photoburst=photoburst)
+ groupq[n].update(fps=self.fps,
fpbs=fpbs,
keystates=keystates)
# Send signals upon group visibility change
if flipped == 1:
signals.set_group_start(flip_id)
# Draw test rectangle
if phototest:
test_rect.draw()
elif flipped == -1:
signals.set_group_stop(flip_id)
if eyetrack:
# First check if eye is being tracked and send signals
old_tracked = tracked
tracked = eyetracking.is_tracked()
if tracked:
if not old_tracked:
# Send signal if eye starts being tracked
signals.set_track_start()
else:
if old_tracked:
# Send signal if eye stops being tracked
signals.set_track_stop()
# Next check for fixation
old_fixated = fixated
fixated = eyetracking.is_fixated(FIX_POS, FIX_RANGE, FIX_PER)
if fixated:
# Draw normal cross color if fixating
fix_crosses[0].draw()
if not old_fixated:
# Send signal if fixation starts
signals.set_fix_start()
else:
# Draw alternative cross color if not fixating
fix_crosses[1].draw()
if old_fixated:
# Send signal if fixation stops
signals.set_fix_stop()
# Take note of which groups in which fixation failed
- if not cur_fix_fail and cur_group.visible and\
+ if not cur_fix_fail and groupq[n].visible and\
(tracked and not fixated):
cur_fix_fail = True
if len(fail_idlist) == 0 and trybreak > 0:
- group_queue.append(CkgWaitScreen(res=self.res))
- fail_idlist.append(self.groups.index(cur_group))
+ groupq.append(CkgWaitScreen(res=self.res))
+ fail_idlist.append(self.groups.index(groupq[n]))
# Append failed group to group queue
if tryagain > 0:
- group_queue.append(cur_group)
- groups_stop += cur_group.duration() * self.fps
- disp_end += cur_group.duration() * self.fps
+ groupq.append(groupq[n])
+ groups_stop += groupq[n].duration() * self.fps
+ disp_end += groupq[n].duration() * self.fps
# Insert waitscreen every trybreak failed groups
if trybreak > 0:
if len(fail_idlist) % trybreak == 0:
- group_queue.append(CkgWaitScreen())
+ groupq.append(CkgWaitScreen())
tryagain -= 1
# Change cross color based on time if eyetracking is not enabled
if not eyetrack:
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Increment count and set whether groups should be shown
- if not isinstance(cur_group, CkgWaitScreen):
+ if not isinstance(groupq[n], CkgWaitScreen):
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
# Blit canvas to screen if necessary
if scaling:
fbo.end_render()
window.switch_to()
canvas.blit(0, 0)
window.dispatch_events()
window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to log string
if logtime and logdur:
logstring = '\n'.join([logstring, str(stamp.elapsed())])
logstring = '\t'.join([logstring, str(dur.restart())])
elif logtime:
logstring = '\n'.join([logstring, str(timer.elapsed())])
elif logdur:
logstring = '\n'.join([logstring, str(timer.restart())])
# Send signals ASAP after flip
signals.send(sigser, sigpar)
# Log when signals are sent
if logtime or logdur:
if flipped != 0 and (sigser or sigpar):
sigmsg = '{0} sent'.format(signals.STATE)
logstring = '\t'.join([logstring, sigmsg])
# Clean up
if eyetrack:
eyetracking.stop()
window.close()
if scaling:
fbo.delete()
del canvas
signals.quit(sigser, sigpar)
# Write log string to file
if logtime or logdur:
filename = '{0}.log'.format(self.name)
with open(filename, 'w') as logfile:
logfile.write(logstring)
# Return list of ids of failed groups
if eyetrack and len(fail_idlist) > 0:
return fail_idlist
- def export(self, export_dir, export_duration, group_queue=[],
+ def export(self, export_dir, export_duration, groupq=[],
export_fmt=None, folder=True, force=False):
if not os.path.isdir(export_dir):
msg = 'export path is not a directory'
raise IOError(msg)
if export_fmt == None:
export_fmt = self.export_fmt
# Set-up groups and variables that control their display
- if group_queue == []:
- group_queue = list(self.groups)
- cur_group = None
- cur_id = -1
- groups_duration = sum([group.duration() for group in group_queue])
+ if groupq == []:
+ groupq = list(self.groups)
+ n = -1
+ groups_duration = sum([group.duration() for group in groupq])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Limit export duration to display duration
frames = export_duration * self.fps
frames = min(frames, disp_end)
# Warn user if a lot of frames will be exported
if frames > MAX_EXPORT_FRAMES and not force:
msg = 'very large number ({0}) of frames to be exported'.\
format(frames)
raise FrameOverflowError(msg)
# Create folder to store images if necessary
if folder:
export_dir = os.path.join(export_dir,
self.name + EXPORT_DIR_SUFFIX)
if not os.path.isdir(export_dir):
os.mkdir(export_dir)
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Set up canvas and framebuffer object
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
# Main loop
while count < frames:
fbo.clear()
if groups_visible:
- # Check if current group is over
- if cur_group != None:
- if cur_group.over:
- cur_group = None
# Get next group from queue
- if cur_group == None:
- cur_id += 1
- if cur_id >= len(group_queue):
+ if n < 0 or groupq[n].over:
+ n += 1
+ if n >= len(groupq):
groups_visible = False
else:
- cur_group = group_queue[cur_id]
- cur_group.reset()
+ groupq[n].reset()
# Draw and then update group
- if cur_group != None:
- cur_group.draw()
- cur_group.update(fps=self.fps, fpbs=0)
+ if n >= 0:
+ groupq[n].draw()
+ groupq[n].update(fps=self.fps, fpbs=0)
+
# Draw fixation cross based on current count
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Save current frame to file
savepath = \
os.path.join(export_dir,
'{0}{2}.{1}'.
format(self.name, export_fmt,
repr(count).zfill(numdigits(frames-1))))
canvas.save(savepath)
# Increment count and set whether groups should be shown
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
fbo.delete()
class CkgExp:
DEFAULTS = {'name': 'untitled', 'proj' : None,
'trials': 1, 'sequences': None,
'flags': '--fullscreen --logtime --logdur'}
def __init__(self, **keywords):
"""Create a checkergen experiment, which specifies how a project
is to be displayed.
+ path -- if specified, ignore other arguments and load project
+ from path
+
+ name -- name of the experiment
+
proj -- CkgProj that the experiment is to be created for
trials -- number of times the selected sequence of display groups
will be shown in one block
sequences -- list of possible display group id sequences, from which
one sequence will be randomly selected for display in a block,
defaults to reduced latin square with side length equal to the number
of display groups in the supplied CkgProj
flags -- string passed to the display command as flags
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
if 'name' not in keywords.keys() and self.proj != None:
self.name = self.proj.name
if self.sequences == None:
if self.proj == None:
msg = "either project or sequences have to be specified"
raise ValueError(msg)
else:
self.gen_latin_square(len(self.proj.groups))
del self.proj
def gen_latin_square(self, n):
"""Set experiment sequences as a cyclic reduced latin square."""
sequence = range(n)
self.sequences = [[sequence[i - j] for i in range(n)]
for j in range(n, 0, -1)]
def save(self, path=None):
"""Saves experiment to specified path as a CSV file."""
if path == None:
path = os.path.join(os.getcwd(),
'{0}.{1}'.format(self.name, EXP_FMT))
else:
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(EXP_FMT):
path = '{0}.{1}'.format(path, EXP_FMT)
with open(path, 'wb') as expfile:
expwriter = csv.writer(expfile, dialect='excel-tab')
expwriter.writerow(['checkergen experiment file'])
expwriter.writerow(['flags:', self.flags])
expwriter.writerow(['trials:', self.trials])
expwriter.writerow(['sequences:'])
for sequence in self.sequences:
expwriter.writerow(sequence)
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if len(ext) == 0:
path = '{0}.{1}'.format(path, EXP_FMT)
elif ext != '.{0}'.format(EXP_FMT):
msg = "path lacks '.{0}' extension".format(EXP_FMT)
raise FileFormatError(msg)
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
self.name = name
with open(path, 'rb') as expfile:
expreader = csv.reader(expfile, dialect='excel-tab')
for n, row in enumerate(expreader):
if n == 1:
self.flags = row[1]
elif n == 2:
self.trials = int(row[1])
elif n > 3:
sequence = [int(i) for i in row]
self.sequences.append(sequence)
class CkgDisplayGroup:
DEFAULTS = {'pre': 0, 'disp': 'Infinity', 'post': 0}
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets internal count and all contained shapes."""
self._count = 0
self._start = self.pre
self._stop = self.pre + self.disp
self._end = self.pre + self.disp + self.post
self.over = False
self.old_visible = False
if self._start == 0 and self._stop > 0:
self.visible = True
else:
self.visible = False
if self._end == 0:
self.over = True
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, lazy=False, photoburst=False):
"""Draws all contained shapes during the appropriate interval."""
if self.visible:
for shape in self.shapes:
if lazy:
shape.lazydraw()
else:
shape.draw(photoburst=photoburst)
def update(self, **keywords):
"""Increments internal count, makes group visible when appropriate.
fps -- refresh rate of the display in frames per second
fpbs -- flips per board signal, i.e. number of shape color reversals
(flips) that occur for a unique signal to be sent for that shape
"""
fps = keywords['fps']
fpbs = keywords['fpbs']
if self.visible:
# Set triggers to be sent
if fpbs > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= fpbs:
signals.set_board_flip(n)
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(fps)
# Increment count and set flags for the next frame
self._count += 1
self.old_visible = self.visible
if (self._start * fps) <= self._count < (self._stop * fps):
self.visible = True
else:
self.visible = False
if self._count >= (self._end * fps):
self.over = True
else:
self.over = False
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.visible = False
self.old_visible = False
self.steps_done = 0
self.over = False
def draw(self):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, **keywords):
"""Checks for keypress, sends signal upon end."""
keystates = keywords['keystates']
if max([keystates[key] for key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
if self.steps_done == self.num_steps:
self.over = True
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = {'dims': (5, 5),
'init_unit': (30, 30), 'end_unit': (50, 50),
'position': (0, 0), 'anchor': 'bottomleft',
'cols': ((0, 0, 0), (255, 255, 255)),
'freq': 1, 'phase': 0}
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
if INT_HALF_PERIODS:
frames_per_half_period = round(fps / (self.freq * 2))
degs_per_frame = 180 / to_decimal(frames_per_half_period)
else:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
if PRERENDER_TO_TEXTURE:
init_pos = [(1 - a)* s/to_decimal(2) for s, a in
zip(self._size, graphics.locations[self.anchor])]
else:
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
anchor=self.anchor)
cur_unit_rect.col = self.cols[(i + j) % 2]
cur_unit_rect.add_to_batch(self._batches[0])
cur_unit_rect.col = self.cols[(i + j + 1) % 2]
cur_unit_rect.add_to_batch(self._batches[1])
# Increase x values
cur_unit_pos[0] += \
graphics.locations[self.anchor][0] * cur_unit[0]
cur_unit[0] += unit_grad[0]
# Reset x values
cur_unit_pos[0] = init_pos[0]
cur_unit[0] = init_unit[0]
# Increase y values
cur_unit_pos[1] += \
graphics.locations[self.anchor][1] * cur_unit[1]
cur_unit[1] += unit_grad[1]
if PRERENDER_TO_TEXTURE:
# Create textures
int_size = [int(round(s)) for s in self._size]
self._prerenders =\
[pyglet.image.Texture.create(*int_size) for n in range(2)]
# Set up framebuffer
fbo = graphics.Framebuffer()
for n in range(2):
fbo.attach_texture(self._prerenders[n])
# Draw batch to texture
fbo.start_render()
self._batches[n].draw()
fbo.end_render()
# Anchor textures for correct blitting later
self._prerenders[n].anchor_x, self._prerenders[n].anchor_y =\
[int(round((1 - a)* s/to_decimal(2))) for s, a in
zip(self._size, graphics.locations[self.anchor])]
fbo.delete()
# Delete batches since they won't be used
del self._batches
self._computed = True
def draw(self, photoburst=False, always_compute=False):
"""Draws appropriate prerender depending on current phase.
photoburst -- draw first color for only one frame for testing purposes
always_compute -- recompute what the checkerboard should look like
every frame
"""
if not self._computed or always_compute:
self.compute()
self._cur_phase %= 360
n = int(self._cur_phase // 180)
if photoburst and n == 0 and not self.flipped:
n = 1
if PRERENDER_TO_TEXTURE:
self._prerenders[n].blit(*self.position)
else:
self._batches[n].draw()
def lazydraw(self):
"""Only draws on color reversal."""
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if (cur_n != prev_n) or self._first_draw:
self.draw()
if self._first_draw:
self._first_draw = False
|
ztangent/checkergen
|
2f94104afccbbab9788ef03d13b11db1715b8732
|
Introduced CkgExp class, improved loading, saving.
|
diff --git a/src/cli.py b/src/cli.py
index 5b3070c..7e10629 100644
--- a/src/cli.py
+++ b/src/cli.py
@@ -1,670 +1,667 @@
"""Defines command-line-interface for checkergen."""
import os
import sys
if os.name == 'posix':
import readline
import argparse
import cmd
import shlex
import core
import priority
import eyetracking
from graphics import locations
from utils import *
CMD_PROMPT = '(ckg) '
CMD_EOF_STRING = 'Ctrl-D'
if sys.platform == 'win32':
CMD_EOF_STRING = 'Ctrl-Z + Enter'
CMD_INTRO = '\n'.join(["Enter 'help' for a list of commands.",
"Enter 'quit' or {0} to exit.".format(CMD_EOF_STRING)])
def store_tuple(nargs, sep, typecast=None, castargs=[]):
"""Returns argparse action that stores a tuple."""
class TupleAction(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
vallist = values.split(sep)
if len(vallist) != nargs:
msg = ("argument '{f}' should be a list of " +
"{nargs} values separated by '{sep}'").\
format(f=self.dest,nargs=nargs,sep=sep)
raise argparse.ArgumentError(self, msg)
if typecast != None:
for n, val in enumerate(vallist):
try:
val = typecast(*([val] + castargs))
vallist[n] = val
except (ValueError, TypeError):
msg = ("element '{val}' of argument '{f}' " +
"is of the wrong type").\
format(val=vallist[n],f=self.dest)
raise argparse.ArgumentError(self, msg)
setattr(args, self.dest, tuple(vallist))
return TupleAction
# The main parser invoked at the command-line
PARSER = argparse.ArgumentParser(
description='''Generate flashing checkerboard patterns for display
or export as a series of images, intended for use in
psychophysics experiments. Enters interactive command
line mode if no options are specified.''')
PARSER.add_argument('-c', '--cmd', dest='cmd_mode', action='store_true',
help='enter command line mode regardless of other options')
PARSER.add_argument('-d', '--display',
dest='display_flag', action='store_true',
help='displays the animation on the screen')
PARSER.add_argument('-e', '--export', dest='export_dur', metavar='DUR',
help='export DUR seconds of the project animation')
PARSER.add_argument('-f', '--fullscreen', action='store_true',
help='animation displayed in fullscreen mode')
# PARSER.add_argument('--fmt', dest='export_fmt', choices=core.EXPORT_FMTS,
# help='image format for animation to be exported as')
PARSER.add_argument('--dir', dest='export_dir',
default=os.getcwd(), metavar='PATH',
help='''destination directory for export
(default: current working directory)''')
PARSER.add_argument('path', metavar='project', nargs='?', type=file,
help='checkergen project file to open')
def process_args(args):
"""Further processes the arguments returned by the main parser."""
if args.export_dur != None:
args.export_flag = True
else:
args.export_flag = False
if not args.display_flag and not args.export_flag:
args.cmd_mode = True
if args.path != None:
if not os.path.isfile(args.path):
msg = 'error: path specified is not a file'
return msg
args.proj = core.CkgProj(path=args.path)
os.chdir(os.path.dirname(os.path.abspath(args.path)))
try:
args.group = args.proj.groups[0]
except IndexError:
args.group = None
else:
args.proj = None
args.group = None
if args.display_flag or args.export_flag:
msg = 'error: no project file specified for display or export'
return msg
class CmdParserError(Exception):
"""To be raised when CmdParser encounters an error."""
pass
class CmdParser(argparse.ArgumentParser):
"""Override ArgumentParser so that it doesn't exit the program."""
def error(self, msg):
raise CmdParserError(msg)
class CkgCmd(cmd.Cmd):
@staticmethod
def yn_parse(s):
if s in ['y', 'Y', 'yes', 'YES', 'Yes']:
return True
elif s in ['n', 'N', 'no', 'NO', 'No']:
return False
else:
msg = "only 'y','n' or variants accepted"
raise ValueError(msg)
def save_check(self, msg=None):
"""Checks and prompts the user to save if necessary."""
if self.cur_proj == None:
return
if not self.cur_proj.is_dirty():
return
if msg == None:
msg = 'Would you like to save the current project first? (y/n)'
print msg
while True:
try:
if self.__class__.yn_parse(raw_input()):
self.do_save('')
break
except TypeError:
print str(sys.exc_value)
except EOFError:
return True
def do_new(self, line):
"""Creates new project with given name (can contain whitespace)."""
name = line.strip().strip('"\'')
if len(name) == 0:
name = 'untitled'
if self.save_check():
return
self.cur_proj = core.CkgProj(name=name)
print 'project \'{0}\' created'.format(self.cur_proj.name)
def do_open(self, line):
"""Open specified project file."""
path = line.strip().strip('"\'')
if len(path) == 0:
print 'error: no path specified'
return
- if not os.path.isfile(path):
- print 'error: path specified is not a file'
- return
if self.save_check():
return
try:
self.cur_proj = core.CkgProj(path=path)
except (core.FileFormatError, IOError):
print "error:", str(sys.exc_value)
return
os.chdir(os.path.dirname(os.path.abspath(path)))
try:
self.cur_group = self.cur_proj.groups[0]
except IndexError:
self.cur_group = None
print 'project \'{0}\' loaded'.format(self.cur_proj.name)
def do_close(self, line):
"""Prompts the user to save, then closes current project."""
if self.cur_proj == None:
print 'no project to close'
return
if self.save_check():
return
self.cur_proj = None
print 'project closed'
def do_save(self, line):
"""Saves the current project to the specified path."""
if self.cur_proj == None:
print 'no project to save'
return
path = line.strip().strip('"\'')
if len(path) == 0:
path = os.getcwd()
path = os.path.abspath(path)
if os.path.isdir(path):
path = os.path.join(path,
'.'.join([self.cur_proj.name, core.CKG_FMT]))
elif os.path.isdir(os.path.dirname(path)):
pass
else:
print 'error: specified directory does not exist'
return
# project save will add file extension if necessary
try:
path = self.cur_proj.save(path)
except IOError:
print "error:", str(sys.exc_value)
return
print 'project saved to "{0}"'.format(path)
set_parser = CmdParser(add_help=False, prog='set',
description='''Sets various project settings.''')
set_parser.add_argument('--name', help='''project name, always the same as
the filename without
the extension''')
set_parser.add_argument('--fps', type=to_decimal,
help='''number of animation frames
rendered per second''')
set_parser.add_argument('--res', action=store_tuple(2, ',', int),
help='animation canvas size/resolution in pixels',
metavar='WIDTH,HEIGHT')
set_parser.add_argument('--bg', metavar='COLOR', type=to_color,
help='''background color of the canvas
(color format: R,G,B,
component range from 0-255)''')
# set_parser.add_argument('--fmt', dest='export_fmt',
# choices=core.EXPORT_FMTS,
# help='''image format for animation
# to be exported as''')
set_parser.add_argument('--pre', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown before any display groups''')
set_parser.add_argument('--post', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown after all display groups''')
set_parser.add_argument('--cross_cols', metavar='COLOR1,COLOR2',
action=store_tuple(2, ',', to_color, [';']),
help='''fixation cross coloration
(color format: R;G;B,
component range from 0-255)''')
set_parser.add_argument('--cross_times', metavar='TIME1,TIME2',
action=store_tuple(2, ',', to_decimal),
help='''time in seconds each cross color
will be displayed''')
def help_set(self):
self.__class__.set_parser.print_help()
def do_set(self, line):
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
try:
args = self.__class__.set_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.set_parser.print_usage()
return
names = public_dir(args)
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
setattr(self.cur_proj, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.set_parser.print_usage()
mkgrp_parser = CmdParser(add_help=False, prog='mkgrp',
formatter_class=
argparse.ArgumentDefaultsHelpFormatter,
description='''Makes a new display group
with the given parameters.''')
mkgrp_parser.add_argument('pre', type=to_decimal, default=0, nargs='?',
help='''time in seconds a blank screen will
be shown before shapes are displayed''')
mkgrp_parser.add_argument('disp', type=to_decimal,
nargs='?', default='Infinity',
help='''time in seconds shapes will be
displayed''')
mkgrp_parser.add_argument('post', type=to_decimal, default=0, nargs='?',
help='''time in seconds a blank screen will
be shown after shapes are displayed''')
def help_mkgrp(self):
self.__class__.mkgrp_parser.print_help()
def do_mkgrp(self, line):
"""Makes a display group with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
try:
args = self.__class__.mkgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mkgrp_parser.print_usage()
return
group_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_group = core.CkgDisplayGroup(**group_dict)
new_id = self.cur_proj.add_group(new_group)
print "display group", new_id, "added"
self.cur_group = new_group
print "group", new_id, "is now the current display group"
edgrp_parser = CmdParser(add_help=False, prog='edgrp',
description='''Edits attributes of display groups
specified by ids.''')
edgrp_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='ids of display groups to be edited')
edgrp_parser.add_argument('--pre', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown before shapes are displayed''')
edgrp_parser.add_argument('--disp', type=to_decimal, metavar='SECONDS',
help='''time in seconds shapes will be
displayed''')
edgrp_parser.add_argument('--post', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown after shapes are displayed''')
def help_edgrp(self):
self.__class__.edgrp_parser.print_help()
def do_edgrp(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.edgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.edgrp_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_proj.groups) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_group_attr(x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.edgrp_parser.print_usage()
rmgrp_parser = CmdParser(add_help=False, prog='rmgrp',
description='''Removes display groups specified
by ids.''')
rmgrp_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='ids of display groups to be removed')
rmgrp_parser.add_argument('-a', '--all', action='store_true',
help='remove all groups from the project')
def help_rmgrp(self):
self.__class__.rmgrp_parser.print_help()
def do_rmgrp(self, line):
"""Removes display groups specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups to remove'
return
try:
args = self.__class__.rmgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rmgrp_parser.print_usage()
return
rmlist = []
if args.all:
for group in self.cur_proj.groups[:]:
self.cur_proj.del_group(group)
print "all display groups removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_proj.groups) or x < 0:
print "display group", x, "does not exist"
continue
rmlist.append(self.cur_proj.groups[x])
print "display group", x, "removed"
for group in rmlist:
self.cur_proj.del_group(group)
# Remember to point self.cur_group somewhere sane
if self.cur_group not in self.cur_proj.groups:
if len(self.cur_proj.groups) == 0:
self.cur_group = None
else:
self.cur_group = self.cur_proj.groups[0]
print "group 0 is now the current display group"
chgrp_parser = CmdParser(add_help=False, prog='chgrp',
description='''Changes display group that is
currently active for editing.
Prints current group id if
no group id is specified''')
chgrp_parser.add_argument('gid', metavar='id', type=int, nargs='?',
help='id of display group to be made active')
def help_chgrp(self):
self.__class__.chgrp_parser.print_help()
def do_chgrp(self, line):
"""Changes group that is currently active for editing."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups that can be made active'
return
try:
args = self.__class__.chgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.chgrp_parser.print_usage()
return
if args.gid == None:
print "group",\
self.cur_proj.groups.index(self.cur_group),\
"is the current display group"
elif args.gid >= len(self.cur_proj.groups) or args.gid < 0:
print "group", args.gid, "does not exist"
else:
self.cur_group = self.cur_proj.groups[args.gid]
print "group", args.gid, "is now the current display group"
mk_parser = CmdParser(add_help=False, prog='mk',
description='''Makes a new checkerboard in the
current group with the given
parameters.''')
mk_parser.add_argument('dims', action=store_tuple(2, ',', to_decimal),
help='''width,height of checkerboard in no. of
unit cells''')
mk_parser.add_argument('init_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of initial unit cell in pixels')
mk_parser.add_argument('end_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of final unit cell in pixels')
mk_parser.add_argument('position', action=store_tuple(2, ',', to_decimal),
help='x,y position of checkerboard in pixels')
mk_parser.add_argument('anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='anchor')
mk_parser.add_argument('cols', action=store_tuple(2, ',', to_color, [';']),
help='''color1,color2 of the checkerboard
(color format: R;G;B,
component range from 0-255)''')
mk_parser.add_argument('freq', type=to_decimal,
help='frequency of color reversal in Hz')
mk_parser.add_argument('phase', type=to_decimal, nargs='?', default='0',
help='initial phase of animation in degrees')
def help_mk(self):
self.__class__.mk_parser.print_help()
def do_mk(self, line):
"""Makes a checkerboard with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
if self.cur_group == None:
print 'automatically adding display group...'
self.do_mkgrp('')
try:
args = self.__class__.mk_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mk_parser.print_usage()
return
shape_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_shape = core.CheckerBoard(**shape_dict)
new_id = self.cur_proj.add_shape_to_group(self.cur_group, new_shape)
print "checkerboard", new_id, "added"
ed_parser = CmdParser(add_help=False, prog='ed',
description='''Edits attributes of checkerboards
specified by ids.''')
ed_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='''ids of checkerboards in the current
group to be edited''')
ed_parser.add_argument('--dims', action=store_tuple(2, ',', to_decimal),
help='checkerboard dimensions in unit cells',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--init_unit',
action=store_tuple(2, ',', to_decimal),
help='initial unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--end_unit',
action=store_tuple(2, ',', to_decimal),
help='final unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--position',
action=store_tuple(2, ',', to_decimal),
help='position of checkerboard in pixels',
metavar='X,Y')
ed_parser.add_argument('--anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='LOCATION')
ed_parser.add_argument('--cols', metavar='COLOR1,COLOR2',
action=store_tuple(2, ',', to_color, [';']),
help='''checkerboard colors (color format:
R;G;B, component range
from 0-255)''')
ed_parser.add_argument('--freq', type=to_decimal,
help='frequency of color reversal in Hz')
ed_parser.add_argument('--phase', type=to_decimal,
help='initial phase of animation in degrees')
def help_ed(self):
self.__class__.ed_parser.print_help()
def do_ed(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, please create one first'
return
try:
args = self.__class__.ed_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ed_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_group.shapes) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_shape_attr(self.cur_group, x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.ed_parser.print_usage()
rm_parser = CmdParser(add_help=False, prog='rm',
description='''Removes checkerboards specified
by ids.''')
rm_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''ids of checkerboards in the current group
to be removed''')
rm_parser.add_argument('-a', '--all', action='store_true',
help='''remove all checkerboards in the
current group''')
def help_rm(self):
self.__class__.rm_parser.print_help()
def do_rm(self, line):
"""Removes checkerboards specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, no boards to remove'
return
try:
args = self.__class__.rm_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rm_parser.print_usage()
return
rmlist = []
if args.all:
for shape in self.cur_group.shapes:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
print "all checkerboards removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_group.shapes) or x < 0:
print "checkerboard", x, "does not exist"
continue
rmlist.append(self.cur_group.shapes[x])
print "checkerboard", x, "removed"
for shape in rmlist:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
ls_parser = CmdParser(add_help=False, prog='ls',
description='''Lists project, display group and
checkerboard settings. If no group ids
are specified, all display groups
are listed.''')
ls_parser.add_argument('gidlist', nargs='*', metavar='gid', type=int,
help='''ids of the display groups to be listed''')
ls_group = ls_parser.add_mutually_exclusive_group()
ls_group.add_argument('-s', '--settings', action='store_true',
help='list only project settings')
ls_group.add_argument('-g', '--groups', action='store_true',
help='list only display groups')
def help_ls(self):
self.__class__.ls_parser.print_help()
def do_ls(self, line):
"""Lists project, display group and checkerboard settings."""
def ls_str(s, seps=[',',';']):
"""Special space-saving output formatter."""
if type(s) in [tuple, list]:
if len(seps) > 1:
newseps = seps[1:]
else:
newseps = seps
return seps[0].join([ls_str(i, newseps) for i in s])
else:
return str(s)
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.ls_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ls_parser.print_usage()
return
# Remove duplicates and ascending sort
args.gidlist = sorted(set(args.gidlist))
if len(self.cur_proj.groups) == 0:
if len(args.gidlist) > 0:
print 'this project has no display groups that can be listed'
args.settings = True
else:
for gid in args.gidlist[:]:
if gid >= len(self.cur_proj.groups) or gid < 0:
args.gidlist.remove(gid)
print 'display group', gid, 'does not exist'
if args.gidlist == []:
args.gidlist = range(len(self.cur_proj.groups))
else:
# If any (valid) groups are specified
# don't show project settings
args.groups = True
if not args.groups:
print 'PROJECT SETTINGS'.center(70,'*')
print \
'name'.rjust(16),\
diff --git a/src/core.py b/src/core.py
index 624edc2..6e4749f 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,1147 +1,1250 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
+CkgExp -- A checkergen experiment, describes how a projet is displayed.
CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import itertools
from xml.dom import minidom
import pyglet
import graphics
import signals
import eyetracking
from utils import *
CKG_FMT = 'ckg'
+EXP_FMT = 'exp'
+LOG_FMT = 'log'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
MAX_EXPORT_FRAMES = 100000
PRERENDER_TO_TEXTURE = False
INT_HALF_PERIODS = True
EXPORT_FMTS = ['png']
EXPORT_DIR_SUFFIX = '-anim'
BLOCK_DIR_SUFFIX = '-blks'
FIX_POS = (0, 0)
FIX_RANGE = (20, 20)
FIX_PER = 350
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = {'name': 'untitled',
'fps': 60,
'res': (800, 600),
'bg': (127, 127, 127),
'export_fmt': 'png',
'pre': 0,
'post': 0,
'cross_cols': ((0, 0, 0), (255, 0, 0)),
'cross_times': ('Infinity', 1)}
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
export_fmt -- image format for animation to be exported as
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'export_fmt':
if value not in EXPORT_FMTS:
msg = 'image format not recognized or supported'
raise FileFormatError(msg)
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
- if ext == '.{0}'.format(CKG_FMT):
- self.name = name
- else:
+ if len(ext) == 0:
+ path = '{0}.{1}'.format(path, CKG_FMT)
+ elif ext != '.{0}'.format(CKG_FMT):
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
+ if not os.path.isfile(path):
+ msg = "specified file does not exist"
+ raise IOError(msg)
+ self.name = name
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
vars_to_load = self.__class__.DEFAULTS.keys()
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
vars_to_save = self.__class__.DEFAULTS.keys()
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def mkblks(self, length, path=None, folder=True, flags=''):
"""Generates randomized experimental blocks from display groups.
Each block is saved as a CSV file.
length -- number of repeated trials within a block
path -- directory in which experimental blocks will be saved
folder -- blocks will be saved in a containing folder if true
flags -- string of flags to be issued to the display command when
block file is run
"""
if path == None:
path = os.getcwd()
if not os.path.isdir(path):
msg = "specified directory does not exist"
raise IOError(msg)
if folder:
path = os.path.join(path, self.name + BLOCK_DIR_SUFFIX)
if not os.path.isdir(path):
os.mkdir(path)
group_ids = range(len(self.groups))
for n, sequence in enumerate(itertools.permutations(group_ids)):
blkname = 'block{0}.csv'.format(repr(n).zfill(numdigits(length)))
blkfile = open(os.path.join(path, blkname), 'wb')
blkwriter = csv.writer(blkfile, dialect='excel-tab')
blkwriter.writerow(['checkergen experimental block file'])
blkwriter.writerow(['flags:', flags])
blkwriter.writerow(['repeats:', length])
blkwriter.writerow(['sequence:'] + list(sequence))
blkfile.close()
@staticmethod
def readblk(path):
"""Reads the information in a block file and returns it in a dict."""
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
blkdict = dict()
blkfile = open(path, 'rb')
blkreader = csv.reader(blkfile, dialect='excel-tab')
for n, row in enumerate(blkreader):
if n == 1:
blkdict['flags'] = row[1]
elif n == 2:
repeats = int(row[1])
elif n == 3:
sequence = row[1:]
sequence = [int(i) for i in sequence]
blkfile.close()
blkdict['idlist'] = ([-1] + sequence) * repeats
return blkdict
@staticmethod
def addtoblk(path, idlist, rowlen):
"""Appends a list of group ids to the specified block file."""
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
blkfile = open(path, 'ab')
blkwriter = csv.writer(blkfile, dialect='excel-tab')
blkwriter.writerow(['groups added:'])
# Split idlist into lists of length rowlen, based on grouper recipe
args = [iter(idlist)] * rowlen
rowlist = itertools.izip_longest(*args, fillvalue='')
for row in rowlist:
blkwriter.writerow(row)
blkfile.close()
def display(self, fullscreen=False, logtime=False, logdur=False,
sigser=False, sigpar=False, fpbs=0,
phototest=False, photoburst=False,
eyetrack=False, etuser=False, etvideo=None,
tryagain=0, trybreak=None, group_queue=[]):
"""Displays the project animation on the screen.
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
sigser -- send signals through serial port when each group is shown
sigpar -- send signals through parallel port when each group is shown
fpbs -- flips per board signal, i.e. number of shape color reversals
(flips) that occur for a unique signal to be sent for that shape
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- Append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- Append a wait screen to the group queue every time
after this many groups have been appended to the queue
group_queue -- queue of groups to be displayed, defaults to order of
groups in project (i.e. groups[0] first, etc.)
"""
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if phototest:
test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Set-up groups and variables that control their display
if group_queue == []:
group_queue = list(self.groups)
cur_group = None
cur_id = -1
flipped = 0
flip_id = -1
groups_duration = sum([group.duration() for group in group_queue])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Initialize ports
if sigser:
if not signals.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if sigpar:
if not signals.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
signals.init(sigser, sigpar)
# Initialize eyetracking
if eyetrack:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if trybreak == None:
trybreak = len(self.groups)
fixated = False
old_fixated = False
tracked = False
old_tracked = False
cur_fix_fail = False
fail_idlist = []
eyetracking.select_source(etuser, etvideo)
eyetracking.start()
# Stretch to fit screen only if project res does not equal screen res
scaling = False
if fullscreen:
window = pyglet.window.Window(fullscreen=True, visible=False)
if (window.width, window.height) != self.res:
scaling = True
else:
window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
keystates = pyglet.window.key.KeyStateHandler()
window.push_handlers(keystates)
# Create framebuffer object for drawing unscaled scene
if scaling:
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
fbo.end_render()
# Clear window and make visible
window.switch_to()
graphics.set_clear_color(self.bg)
window.clear()
window.set_visible()
# Initialize logging variables
if logtime and logdur:
logstring = ''
stamp = Timer()
dur = Timer()
stamp.start()
dur.start()
elif logtime or logdur:
logstring = ''
timer = Timer()
timer.start()
# Main loop
while not window.has_exit and count < disp_end:
# Clear canvas
if scaling:
fbo.start_render()
fbo.clear()
else:
window.clear()
# Assume no change to group visibility
flipped = 0
signals.set_null()
# Manage groups when they are on_screen
if groups_visible:
# Send special signal if waitscreen ends
if isinstance(cur_group, CkgWaitScreen):
if cur_group.over:
signals.set_user_start()
cur_group = None
elif cur_group != None:
# Check whether group changes in visibility
if cur_group.visible != cur_group.old_visible:
flip_id = self.groups.index(cur_group)
if cur_group.visible:
flipped = 1
elif cur_group.old_visible:
flipped = -1
# Check if current group is over
if cur_group.over:
cur_group = None
# Get next group from queue
if cur_group == None:
cur_id += 1
if cur_id >= len(group_queue):
groups_visible = False
else:
cur_group = group_queue[cur_id]
cur_group.reset()
if eyetrack:
cur_fix_fail = False
if cur_group.visible:
flip_id = self.groups.index(cur_group)
flipped = 1
# Draw and then update group
if cur_group != None:
cur_group.draw(photoburst=photoburst)
cur_group.update(fps=self.fps,
fpbs=fpbs,
keystates=keystates)
# Send signals upon group visibility change
if flipped == 1:
signals.set_group_start(flip_id)
# Draw test rectangle
if phototest:
test_rect.draw()
elif flipped == -1:
signals.set_group_stop(flip_id)
if eyetrack:
# First check if eye is being tracked and send signals
old_tracked = tracked
tracked = eyetracking.is_tracked()
if tracked:
if not old_tracked:
# Send signal if eye starts being tracked
signals.set_track_start()
else:
if old_tracked:
# Send signal if eye stops being tracked
signals.set_track_stop()
# Next check for fixation
old_fixated = fixated
fixated = eyetracking.is_fixated(FIX_POS, FIX_RANGE, FIX_PER)
if fixated:
# Draw normal cross color if fixating
fix_crosses[0].draw()
if not old_fixated:
# Send signal if fixation starts
signals.set_fix_start()
else:
# Draw alternative cross color if not fixating
fix_crosses[1].draw()
if old_fixated:
# Send signal if fixation stops
signals.set_fix_stop()
# Take note of which groups in which fixation failed
if not cur_fix_fail and cur_group.visible and\
(tracked and not fixated):
cur_fix_fail = True
if len(fail_idlist) == 0 and trybreak > 0:
group_queue.append(CkgWaitScreen(res=self.res))
fail_idlist.append(self.groups.index(cur_group))
# Append failed group to group queue
if tryagain > 0:
group_queue.append(cur_group)
groups_stop += cur_group.duration() * self.fps
disp_end += cur_group.duration() * self.fps
# Insert waitscreen every trybreak failed groups
if trybreak > 0:
if len(fail_idlist) % trybreak == 0:
group_queue.append(CkgWaitScreen())
tryagain -= 1
# Change cross color based on time if eyetracking is not enabled
if not eyetrack:
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Increment count and set whether groups should be shown
if not isinstance(cur_group, CkgWaitScreen):
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
# Blit canvas to screen if necessary
if scaling:
fbo.end_render()
window.switch_to()
canvas.blit(0, 0)
window.dispatch_events()
window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to log string
if logtime and logdur:
logstring = '\n'.join([logstring, str(stamp.elapsed())])
logstring = '\t'.join([logstring, str(dur.restart())])
elif logtime:
logstring = '\n'.join([logstring, str(timer.elapsed())])
elif logdur:
logstring = '\n'.join([logstring, str(timer.restart())])
# Send signals ASAP after flip
signals.send(sigser, sigpar)
# Log when signals are sent
if logtime or logdur:
if flipped != 0 and (sigser or sigpar):
sigmsg = '{0} sent'.format(signals.STATE)
logstring = '\t'.join([logstring, sigmsg])
# Clean up
if eyetrack:
eyetracking.stop()
window.close()
if scaling:
fbo.delete()
del canvas
signals.quit(sigser, sigpar)
# Write log string to file
if logtime or logdur:
filename = '{0}.log'.format(self.name)
with open(filename, 'w') as logfile:
logfile.write(logstring)
# Return list of ids of failed groups
if eyetrack and len(fail_idlist) > 0:
return fail_idlist
def export(self, export_dir, export_duration, group_queue=[],
export_fmt=None, folder=True, force=False):
if not os.path.isdir(export_dir):
msg = 'export path is not a directory'
raise IOError(msg)
if export_fmt == None:
export_fmt = self.export_fmt
# Set-up groups and variables that control their display
if group_queue == []:
group_queue = list(self.groups)
cur_group = None
cur_id = -1
groups_duration = sum([group.duration() for group in group_queue])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Limit export duration to display duration
frames = export_duration * self.fps
frames = min(frames, disp_end)
# Warn user if a lot of frames will be exported
if frames > MAX_EXPORT_FRAMES and not force:
msg = 'very large number ({0}) of frames to be exported'.\
format(frames)
raise FrameOverflowError(msg)
# Create folder to store images if necessary
if folder:
export_dir = os.path.join(export_dir,
self.name + EXPORT_DIR_SUFFIX)
if not os.path.isdir(export_dir):
os.mkdir(export_dir)
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Set up canvas and framebuffer object
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
# Main loop
while count < frames:
fbo.clear()
if groups_visible:
# Check if current group is over
if cur_group != None:
if cur_group.over:
cur_group = None
# Get next group from queue
if cur_group == None:
cur_id += 1
if cur_id >= len(group_queue):
groups_visible = False
else:
cur_group = group_queue[cur_id]
cur_group.reset()
# Draw and then update group
if cur_group != None:
cur_group.draw()
cur_group.update(fps=self.fps, fpbs=0)
# Draw fixation cross based on current count
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Save current frame to file
savepath = \
os.path.join(export_dir,
'{0}{2}.{1}'.
format(self.name, export_fmt,
repr(count).zfill(numdigits(frames-1))))
canvas.save(savepath)
# Increment count and set whether groups should be shown
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
fbo.delete()
+class CkgExp:
+
+ DEFAULTS = {'name': 'untitled', 'proj' : None,
+ 'trials': 1, 'sequences': None,
+ 'flags': '--fullscreen --logtime --logdur'}
+
+ def __init__(self, **keywords):
+ """Create a checkergen experiment, which specifies how a project
+ is to be displayed.
+
+ proj -- CkgProj that the experiment is to be created for
+
+ trials -- number of times the selected sequence of display groups
+ will be shown in one block
+
+ sequences -- list of possible display group id sequences, from which
+ one sequence will be randomly selected for display in a block,
+ defaults to reduced latin square with side length equal to the number
+ of display groups in the supplied CkgProj
+
+ flags -- string passed to the display command as flags
+
+ """
+ if 'path' in keywords.keys():
+ self.load(keywords['path'])
+ return
+ for kw in self.__class__.DEFAULTS.keys():
+ if kw in keywords.keys():
+ setattr(self, kw, keywords[kw])
+ else:
+ setattr(self, kw, self.__class__.DEFAULTS[kw])
+
+ if 'name' not in keywords.keys() and self.proj != None:
+ self.name = self.proj.name
+
+ if self.sequences == None:
+ if self.proj == None:
+ msg = "either project or sequences have to be specified"
+ raise ValueError(msg)
+ else:
+ self.gen_latin_square(len(self.proj.groups))
+
+ del self.proj
+
+ def gen_latin_square(self, n):
+ """Set experiment sequences as a cyclic reduced latin square."""
+ sequence = range(n)
+ self.sequences = [[sequence[i - j] for i in range(n)]
+ for j in range(n, 0, -1)]
+
+ def save(self, path=None):
+ """Saves experiment to specified path as a CSV file."""
+
+ if path == None:
+ path = os.path.join(os.getcwd(),
+ '{0}.{1}'.format(self.name, EXP_FMT))
+ else:
+ self.name, ext = os.path.splitext(os.path.basename(path))
+ if ext != '.{0}'.format(EXP_FMT):
+ path = '{0}.{1}'.format(path, EXP_FMT)
+
+ with open(path, 'wb') as expfile:
+ expwriter = csv.writer(expfile, dialect='excel-tab')
+ expwriter.writerow(['checkergen experiment file'])
+ expwriter.writerow(['flags:', self.flags])
+ expwriter.writerow(['trials:', self.trials])
+ expwriter.writerow(['sequences:'])
+ for sequence in self.sequences:
+ expwriter.writerow(sequence)
+
+ def load(self, path):
+ """Loads project from specified path."""
+
+ # Get project name from filename
+ name, ext = os.path.splitext(os.path.basename(path))
+ if len(ext) == 0:
+ path = '{0}.{1}'.format(path, EXP_FMT)
+ elif ext != '.{0}'.format(EXP_FMT):
+ msg = "path lacks '.{0}' extension".format(EXP_FMT)
+ raise FileFormatError(msg)
+ if not os.path.isfile(path):
+ msg = "specified file does not exist"
+ raise IOError(msg)
+ self.name = name
+
+ with open(path, 'rb') as expfile:
+ expreader = csv.reader(expfile, dialect='excel-tab')
+ for n, row in enumerate(expreader):
+ if n == 1:
+ self.flags = row[1]
+ elif n == 2:
+ self.trials = int(row[1])
+ elif n > 3:
+ sequence = [int(i) for i in row]
+ self.sequences.append(sequence)
+
class CkgDisplayGroup:
DEFAULTS = {'pre': 0, 'disp': 'Infinity', 'post': 0}
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets internal count and all contained shapes."""
self._count = 0
self._start = self.pre
self._stop = self.pre + self.disp
self._end = self.pre + self.disp + self.post
self.over = False
self.old_visible = False
if self._start == 0 and self._stop > 0:
self.visible = True
else:
self.visible = False
if self._end == 0:
self.over = True
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, lazy=False, photoburst=False):
"""Draws all contained shapes during the appropriate interval."""
if self.visible:
for shape in self.shapes:
if lazy:
shape.lazydraw()
else:
shape.draw(photoburst=photoburst)
def update(self, **keywords):
"""Increments internal count, makes group visible when appropriate.
fps -- refresh rate of the display in frames per second
fpbs -- flips per board signal, i.e. number of shape color reversals
(flips) that occur for a unique signal to be sent for that shape
"""
fps = keywords['fps']
fpbs = keywords['fpbs']
if self.visible:
# Set triggers to be sent
if fpbs > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= fpbs:
signals.set_board_flip(n)
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(fps)
# Increment count and set flags for the next frame
self._count += 1
self.old_visible = self.visible
if (self._start * fps) <= self._count < (self._stop * fps):
self.visible = True
else:
self.visible = False
if self._count >= (self._end * fps):
self.over = True
else:
self.over = False
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.visible = False
self.old_visible = False
self.steps_done = 0
self.over = False
def draw(self):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, **keywords):
"""Checks for keypress, sends signal upon end."""
keystates = keywords['keystates']
if max([keystates[key] for key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
if self.steps_done == self.num_steps:
self.over = True
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = {'dims': (5, 5),
'init_unit': (30, 30), 'end_unit': (50, 50),
'position': (0, 0), 'anchor': 'bottomleft',
'cols': ((0, 0, 0), (255, 255, 255)),
'freq': 1, 'phase': 0}
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
if INT_HALF_PERIODS:
frames_per_half_period = round(fps / (self.freq * 2))
degs_per_frame = 180 / to_decimal(frames_per_half_period)
else:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
if PRERENDER_TO_TEXTURE:
init_pos = [(1 - a)* s/to_decimal(2) for s, a in
zip(self._size, graphics.locations[self.anchor])]
else:
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
anchor=self.anchor)
cur_unit_rect.col = self.cols[(i + j) % 2]
cur_unit_rect.add_to_batch(self._batches[0])
cur_unit_rect.col = self.cols[(i + j + 1) % 2]
cur_unit_rect.add_to_batch(self._batches[1])
# Increase x values
cur_unit_pos[0] += \
graphics.locations[self.anchor][0] * cur_unit[0]
cur_unit[0] += unit_grad[0]
# Reset x values
cur_unit_pos[0] = init_pos[0]
cur_unit[0] = init_unit[0]
# Increase y values
cur_unit_pos[1] += \
graphics.locations[self.anchor][1] * cur_unit[1]
cur_unit[1] += unit_grad[1]
if PRERENDER_TO_TEXTURE:
# Create textures
int_size = [int(round(s)) for s in self._size]
self._prerenders =\
[pyglet.image.Texture.create(*int_size) for n in range(2)]
# Set up framebuffer
fbo = graphics.Framebuffer()
for n in range(2):
fbo.attach_texture(self._prerenders[n])
# Draw batch to texture
fbo.start_render()
self._batches[n].draw()
fbo.end_render()
# Anchor textures for correct blitting later
self._prerenders[n].anchor_x, self._prerenders[n].anchor_y =\
[int(round((1 - a)* s/to_decimal(2))) for s, a in
zip(self._size, graphics.locations[self.anchor])]
fbo.delete()
# Delete batches since they won't be used
del self._batches
self._computed = True
def draw(self, photoburst=False, always_compute=False):
"""Draws appropriate prerender depending on current phase.
photoburst -- draw first color for only one frame for testing purposes
always_compute -- recompute what the checkerboard should look like
every frame
"""
if not self._computed or always_compute:
self.compute()
self._cur_phase %= 360
n = int(self._cur_phase // 180)
if photoburst and n == 0 and not self.flipped:
n = 1
if PRERENDER_TO_TEXTURE:
self._prerenders[n].blit(*self.position)
else:
self._batches[n].draw()
def lazydraw(self):
"""Only draws on color reversal."""
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if (cur_n != prev_n) or self._first_draw:
self.draw()
if self._first_draw:
self._first_draw = False
|
ztangent/checkergen
|
55d390cf45a2c5d5c141d7d4c4d91c6ad2429c1b
|
Small fixes to previous commit.
|
diff --git a/src/core.py b/src/core.py
index f6f524d..624edc2 100755
--- a/src/core.py
+++ b/src/core.py
@@ -15,1137 +15,1133 @@ CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
import os
import sys
import re
import csv
import itertools
from xml.dom import minidom
import pyglet
import graphics
import signals
import eyetracking
from utils import *
CKG_FMT = 'ckg'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
MAX_EXPORT_FRAMES = 100000
PRERENDER_TO_TEXTURE = False
INT_HALF_PERIODS = True
EXPORT_FMTS = ['png']
EXPORT_DIR_SUFFIX = '-anim'
BLOCK_DIR_SUFFIX = '-blks'
FIX_POS = (0, 0)
FIX_RANGE = (20, 20)
FIX_PER = 350
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = {'name': 'untitled',
'fps': 60,
'res': (800, 600),
'bg': (127, 127, 127),
'export_fmt': 'png',
'pre': 0,
'post': 0,
'cross_cols': ((0, 0, 0), (255, 0, 0)),
'cross_times': ('Infinity', 1)}
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
export_fmt -- image format for animation to be exported as
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'export_fmt':
if value not in EXPORT_FMTS:
msg = 'image format not recognized or supported'
raise FileFormatError(msg)
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if ext == '.{0}'.format(CKG_FMT):
self.name = name
else:
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
vars_to_load = self.__class__.DEFAULTS.keys()
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
vars_to_save = self.__class__.DEFAULTS.keys()
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def mkblks(self, length, path=None, folder=True, flags=''):
"""Generates randomized experimental blocks from display groups.
Each block is saved as a CSV file.
length -- number of repeated trials within a block
path -- directory in which experimental blocks will be saved
folder -- blocks will be saved in a containing folder if true
flags -- string of flags to be issued to the display command when
block file is run
"""
if path == None:
path = os.getcwd()
if not os.path.isdir(path):
msg = "specified directory does not exist"
raise IOError(msg)
if folder:
path = os.path.join(path, self.name + BLOCK_DIR_SUFFIX)
if not os.path.isdir(path):
os.mkdir(path)
group_ids = range(len(self.groups))
for n, sequence in enumerate(itertools.permutations(group_ids)):
blkname = 'block{0}.csv'.format(repr(n).zfill(numdigits(length)))
blkfile = open(os.path.join(path, blkname), 'wb')
blkwriter = csv.writer(blkfile, dialect='excel-tab')
blkwriter.writerow(['checkergen experimental block file'])
blkwriter.writerow(['flags:', flags])
blkwriter.writerow(['repeats:', length])
blkwriter.writerow(['sequence:'] + list(sequence))
blkfile.close()
@staticmethod
def readblk(path):
"""Reads the information in a block file and returns it in a dict."""
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
blkdict = dict()
blkfile = open(path, 'rb')
blkreader = csv.reader(blkfile, dialect='excel-tab')
for n, row in enumerate(blkreader):
if n == 1:
blkdict['flags'] = row[1]
elif n == 2:
repeats = int(row[1])
elif n == 3:
sequence = row[1:]
sequence = [int(i) for i in sequence]
blkfile.close()
blkdict['idlist'] = ([-1] + sequence) * repeats
return blkdict
@staticmethod
def addtoblk(path, idlist, rowlen):
"""Appends a list of group ids to the specified block file."""
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
blkfile = open(path, 'ab')
blkwriter = csv.writer(blkfile, dialect='excel-tab')
blkwriter.writerow(['groups added:'])
# Split idlist into lists of length rowlen, based on grouper recipe
args = [iter(idlist)] * rowlen
rowlist = itertools.izip_longest(*args, fillvalue='')
for row in rowlist:
blkwriter.writerow(row)
blkfile.close()
def display(self, fullscreen=False, logtime=False, logdur=False,
sigser=False, sigpar=False, fpbs=0,
phototest=False, photoburst=False,
eyetrack=False, etuser=False, etvideo=None,
tryagain=0, trybreak=None, group_queue=[]):
"""Displays the project animation on the screen.
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
sigser -- send signals through serial port when each group is shown
sigpar -- send signals through parallel port when each group is shown
fpbs -- flips per board signal, i.e. number of shape color reversals
(flips) that occur for a unique signal to be sent for that shape
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
photoburst -- make checkerboards only draw first color for one frame
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- Append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- Append a wait screen to the group queue every time
after this many groups have been appended to the queue
group_queue -- queue of groups to be displayed, defaults to order of
groups in project (i.e. groups[0] first, etc.)
"""
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if phototest:
test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Set-up groups and variables that control their display
if group_queue == []:
group_queue = list(self.groups)
cur_group = None
cur_id = -1
flipped = 0
flip_id = -1
groups_duration = sum([group.duration() for group in group_queue])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Initialize ports
if sigser:
if not signals.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if sigpar:
if not signals.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
signals.init(sigser, sigpar)
# Initialize eyetracking
if eyetrack:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if trybreak == None:
trybreak = len(self.groups)
fixated = False
old_fixated = False
tracked = False
old_tracked = False
cur_fix_fail = False
fail_idlist = []
eyetracking.select_source(etuser, etvideo)
eyetracking.start()
# Stretch to fit screen only if project res does not equal screen res
scaling = False
if fullscreen:
window = pyglet.window.Window(fullscreen=True, visible=False)
if (window.width, window.height) != self.res:
scaling = True
else:
window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
keystates = pyglet.window.key.KeyStateHandler()
window.push_handlers(keystates)
# Create framebuffer object for drawing unscaled scene
if scaling:
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
fbo.end_render()
# Clear window and make visible
window.switch_to()
graphics.set_clear_color(self.bg)
window.clear()
window.set_visible()
# Initialize logging variables
if logtime and logdur:
logstring = ''
stamp = Timer()
dur = Timer()
stamp.start()
dur.start()
elif logtime or logdur:
logstring = ''
timer = Timer()
timer.start()
# Main loop
while not window.has_exit and count < disp_end:
# Clear canvas
if scaling:
fbo.start_render()
fbo.clear()
else:
window.clear()
# Assume no change to group visibility
flipped = 0
signals.set_null()
# Manage groups when they are on_screen
if groups_visible:
# Send special signal if waitscreen ends
if isinstance(cur_group, CkgWaitScreen):
if cur_group.over:
signals.set_user_start()
cur_group = None
elif cur_group != None:
# Check whether group changes in visibility
if cur_group.visible != cur_group.old_visible:
flip_id = self.groups.index(cur_group)
if cur_group.visible:
flipped = 1
elif cur_group.old_visible:
flipped = -1
# Check if current group is over
if cur_group.over:
cur_group = None
# Get next group from queue
if cur_group == None:
cur_id += 1
if cur_id >= len(group_queue):
groups_visible = False
else:
cur_group = group_queue[cur_id]
cur_group.reset()
if eyetrack:
cur_fix_fail = False
if cur_group.visible:
flip_id = self.groups.index(cur_group)
flipped = 1
# Draw and then update group
if cur_group != None:
- cur_group.draw(photoburst=True)
+ cur_group.draw(photoburst=photoburst)
cur_group.update(fps=self.fps,
fpbs=fpbs,
keystates=keystates)
# Send signals upon group visibility change
if flipped == 1:
signals.set_group_start(flip_id)
# Draw test rectangle
if phototest:
test_rect.draw()
elif flipped == -1:
signals.set_group_stop(flip_id)
if eyetrack:
# First check if eye is being tracked and send signals
old_tracked = tracked
tracked = eyetracking.is_tracked()
if tracked:
if not old_tracked:
# Send signal if eye starts being tracked
signals.set_track_start()
else:
if old_tracked:
# Send signal if eye stops being tracked
signals.set_track_stop()
# Next check for fixation
old_fixated = fixated
fixated = eyetracking.is_fixated(FIX_POS, FIX_RANGE, FIX_PER)
if fixated:
# Draw normal cross color if fixating
fix_crosses[0].draw()
if not old_fixated:
# Send signal if fixation starts
signals.set_fix_start()
else:
# Draw alternative cross color if not fixating
fix_crosses[1].draw()
if old_fixated:
# Send signal if fixation stops
signals.set_fix_stop()
# Take note of which groups in which fixation failed
if not cur_fix_fail and cur_group.visible and\
(tracked and not fixated):
cur_fix_fail = True
if len(fail_idlist) == 0 and trybreak > 0:
group_queue.append(CkgWaitScreen(res=self.res))
fail_idlist.append(self.groups.index(cur_group))
# Append failed group to group queue
if tryagain > 0:
group_queue.append(cur_group)
groups_stop += cur_group.duration() * self.fps
disp_end += cur_group.duration() * self.fps
# Insert waitscreen every trybreak failed groups
if trybreak > 0:
if len(fail_idlist) % trybreak == 0:
group_queue.append(CkgWaitScreen())
tryagain -= 1
# Change cross color based on time if eyetracking is not enabled
if not eyetrack:
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Increment count and set whether groups should be shown
if not isinstance(cur_group, CkgWaitScreen):
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
# Blit canvas to screen if necessary
if scaling:
fbo.end_render()
window.switch_to()
canvas.blit(0, 0)
window.dispatch_events()
window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to log string
if logtime and logdur:
logstring = '\n'.join([logstring, str(stamp.elapsed())])
logstring = '\t'.join([logstring, str(dur.restart())])
elif logtime:
logstring = '\n'.join([logstring, str(timer.elapsed())])
elif logdur:
logstring = '\n'.join([logstring, str(timer.restart())])
# Send signals ASAP after flip
signals.send(sigser, sigpar)
# Log when signals are sent
if logtime or logdur:
if flipped != 0 and (sigser or sigpar):
sigmsg = '{0} sent'.format(signals.STATE)
logstring = '\t'.join([logstring, sigmsg])
# Clean up
if eyetrack:
eyetracking.stop()
window.close()
if scaling:
fbo.delete()
del canvas
signals.quit(sigser, sigpar)
# Write log string to file
if logtime or logdur:
filename = '{0}.log'.format(self.name)
with open(filename, 'w') as logfile:
logfile.write(logstring)
# Return list of ids of failed groups
if eyetrack and len(fail_idlist) > 0:
return fail_idlist
def export(self, export_dir, export_duration, group_queue=[],
export_fmt=None, folder=True, force=False):
if not os.path.isdir(export_dir):
msg = 'export path is not a directory'
raise IOError(msg)
if export_fmt == None:
export_fmt = self.export_fmt
# Set-up groups and variables that control their display
if group_queue == []:
group_queue = list(self.groups)
cur_group = None
cur_id = -1
groups_duration = sum([group.duration() for group in group_queue])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Limit export duration to display duration
frames = export_duration * self.fps
frames = min(frames, disp_end)
# Warn user if a lot of frames will be exported
if frames > MAX_EXPORT_FRAMES and not force:
msg = 'very large number ({0}) of frames to be exported'.\
format(frames)
raise FrameOverflowError(msg)
# Create folder to store images if necessary
if folder:
export_dir = os.path.join(export_dir,
self.name + EXPORT_DIR_SUFFIX)
if not os.path.isdir(export_dir):
os.mkdir(export_dir)
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Set up canvas and framebuffer object
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
# Main loop
while count < frames:
fbo.clear()
if groups_visible:
# Check if current group is over
if cur_group != None:
if cur_group.over:
cur_group = None
# Get next group from queue
if cur_group == None:
cur_id += 1
if cur_id >= len(group_queue):
groups_visible = False
else:
cur_group = group_queue[cur_id]
cur_group.reset()
# Draw and then update group
if cur_group != None:
cur_group.draw()
cur_group.update(fps=self.fps, fpbs=0)
# Draw fixation cross based on current count
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Save current frame to file
savepath = \
os.path.join(export_dir,
'{0}{2}.{1}'.
format(self.name, export_fmt,
repr(count).zfill(numdigits(frames-1))))
canvas.save(savepath)
# Increment count and set whether groups should be shown
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
fbo.delete()
class CkgDisplayGroup:
DEFAULTS = {'pre': 0, 'disp': 'Infinity', 'post': 0}
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets internal count and all contained shapes."""
self._count = 0
self._start = self.pre
self._stop = self.pre + self.disp
self._end = self.pre + self.disp + self.post
self.over = False
self.old_visible = False
if self._start == 0 and self._stop > 0:
self.visible = True
else:
self.visible = False
if self._end == 0:
self.over = True
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, lazy=False, photoburst=False):
"""Draws all contained shapes during the appropriate interval."""
if self.visible:
for shape in self.shapes:
if lazy:
shape.lazydraw()
else:
shape.draw(photoburst=photoburst)
def update(self, **keywords):
"""Increments internal count, makes group visible when appropriate.
fps -- refresh rate of the display in frames per second
fpbs -- flips per board signal, i.e. number of shape color reversals
(flips) that occur for a unique signal to be sent for that shape
"""
fps = keywords['fps']
fpbs = keywords['fpbs']
if self.visible:
# Set triggers to be sent
if fpbs > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= fpbs:
signals.set_board_flip(n)
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(fps)
# Increment count and set flags for the next frame
self._count += 1
self.old_visible = self.visible
if (self._start * fps) <= self._count < (self._stop * fps):
self.visible = True
else:
self.visible = False
if self._count >= (self._end * fps):
self.over = True
else:
self.over = False
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.visible = False
self.old_visible = False
self.steps_done = 0
self.over = False
def draw(self):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, **keywords):
"""Checks for keypress, sends signal upon end."""
keystates = keywords['keystates']
if max([keystates[key] for key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
if self.steps_done == self.num_steps:
self.over = True
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = {'dims': (5, 5),
'init_unit': (30, 30), 'end_unit': (50, 50),
'position': (0, 0), 'anchor': 'bottomleft',
'cols': ((0, 0, 0), (255, 255, 255)),
'freq': 1, 'phase': 0}
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
if INT_HALF_PERIODS:
frames_per_half_period = round(fps / (self.freq * 2))
degs_per_frame = 180 / to_decimal(frames_per_half_period)
else:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
if PRERENDER_TO_TEXTURE:
init_pos = [(1 - a)* s/to_decimal(2) for s, a in
zip(self._size, graphics.locations[self.anchor])]
else:
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
anchor=self.anchor)
cur_unit_rect.col = self.cols[(i + j) % 2]
cur_unit_rect.add_to_batch(self._batches[0])
cur_unit_rect.col = self.cols[(i + j + 1) % 2]
cur_unit_rect.add_to_batch(self._batches[1])
# Increase x values
cur_unit_pos[0] += \
graphics.locations[self.anchor][0] * cur_unit[0]
cur_unit[0] += unit_grad[0]
# Reset x values
cur_unit_pos[0] = init_pos[0]
cur_unit[0] = init_unit[0]
# Increase y values
cur_unit_pos[1] += \
graphics.locations[self.anchor][1] * cur_unit[1]
cur_unit[1] += unit_grad[1]
if PRERENDER_TO_TEXTURE:
# Create textures
int_size = [int(round(s)) for s in self._size]
self._prerenders =\
[pyglet.image.Texture.create(*int_size) for n in range(2)]
# Set up framebuffer
fbo = graphics.Framebuffer()
for n in range(2):
fbo.attach_texture(self._prerenders[n])
# Draw batch to texture
fbo.start_render()
self._batches[n].draw()
fbo.end_render()
# Anchor textures for correct blitting later
self._prerenders[n].anchor_x, self._prerenders[n].anchor_y =\
[int(round((1 - a)* s/to_decimal(2))) for s, a in
zip(self._size, graphics.locations[self.anchor])]
fbo.delete()
# Delete batches since they won't be used
del self._batches
self._computed = True
def draw(self, photoburst=False, always_compute=False):
"""Draws appropriate prerender depending on current phase.
photoburst -- draw first color for only one frame for testing purposes
always_compute -- recompute what the checkerboard should look like
every frame
"""
if not self._computed or always_compute:
self.compute()
self._cur_phase %= 360
- if not photoburst:
- n = int(self._cur_phase // 180)
- else:
- if self._cur_phase == self.phase:
- n = 0
- else:
- n = 1
+ n = int(self._cur_phase // 180)
+ if photoburst and n == 0 and not self.flipped:
+ n = 1
if PRERENDER_TO_TEXTURE:
self._prerenders[n].blit(*self.position)
else:
self._batches[n].draw()
def lazydraw(self):
"""Only draws on color reversal."""
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if (cur_n != prev_n) or self._first_draw:
self.draw()
if self._first_draw:
self._first_draw = False
|
ztangent/checkergen
|
0de91eadb7c97ac19c736de707e0f5446a0ef28a
|
Add photoburst flag to help with photodiode testing.
|
diff --git a/src/cli.py b/src/cli.py
index c8c87d8..5b3070c 100644
--- a/src/cli.py
+++ b/src/cli.py
@@ -256,895 +256,900 @@ class CkgCmd(cmd.Cmd):
names = public_dir(args)
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
setattr(self.cur_proj, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.set_parser.print_usage()
mkgrp_parser = CmdParser(add_help=False, prog='mkgrp',
formatter_class=
argparse.ArgumentDefaultsHelpFormatter,
description='''Makes a new display group
with the given parameters.''')
mkgrp_parser.add_argument('pre', type=to_decimal, default=0, nargs='?',
help='''time in seconds a blank screen will
be shown before shapes are displayed''')
mkgrp_parser.add_argument('disp', type=to_decimal,
nargs='?', default='Infinity',
help='''time in seconds shapes will be
displayed''')
mkgrp_parser.add_argument('post', type=to_decimal, default=0, nargs='?',
help='''time in seconds a blank screen will
be shown after shapes are displayed''')
def help_mkgrp(self):
self.__class__.mkgrp_parser.print_help()
def do_mkgrp(self, line):
"""Makes a display group with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
try:
args = self.__class__.mkgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mkgrp_parser.print_usage()
return
group_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_group = core.CkgDisplayGroup(**group_dict)
new_id = self.cur_proj.add_group(new_group)
print "display group", new_id, "added"
self.cur_group = new_group
print "group", new_id, "is now the current display group"
edgrp_parser = CmdParser(add_help=False, prog='edgrp',
description='''Edits attributes of display groups
specified by ids.''')
edgrp_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='ids of display groups to be edited')
edgrp_parser.add_argument('--pre', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown before shapes are displayed''')
edgrp_parser.add_argument('--disp', type=to_decimal, metavar='SECONDS',
help='''time in seconds shapes will be
displayed''')
edgrp_parser.add_argument('--post', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown after shapes are displayed''')
def help_edgrp(self):
self.__class__.edgrp_parser.print_help()
def do_edgrp(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.edgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.edgrp_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_proj.groups) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_group_attr(x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.edgrp_parser.print_usage()
rmgrp_parser = CmdParser(add_help=False, prog='rmgrp',
description='''Removes display groups specified
by ids.''')
rmgrp_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='ids of display groups to be removed')
rmgrp_parser.add_argument('-a', '--all', action='store_true',
help='remove all groups from the project')
def help_rmgrp(self):
self.__class__.rmgrp_parser.print_help()
def do_rmgrp(self, line):
"""Removes display groups specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups to remove'
return
try:
args = self.__class__.rmgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rmgrp_parser.print_usage()
return
rmlist = []
if args.all:
for group in self.cur_proj.groups[:]:
self.cur_proj.del_group(group)
print "all display groups removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_proj.groups) or x < 0:
print "display group", x, "does not exist"
continue
rmlist.append(self.cur_proj.groups[x])
print "display group", x, "removed"
for group in rmlist:
self.cur_proj.del_group(group)
# Remember to point self.cur_group somewhere sane
if self.cur_group not in self.cur_proj.groups:
if len(self.cur_proj.groups) == 0:
self.cur_group = None
else:
self.cur_group = self.cur_proj.groups[0]
print "group 0 is now the current display group"
chgrp_parser = CmdParser(add_help=False, prog='chgrp',
description='''Changes display group that is
currently active for editing.
Prints current group id if
no group id is specified''')
chgrp_parser.add_argument('gid', metavar='id', type=int, nargs='?',
help='id of display group to be made active')
def help_chgrp(self):
self.__class__.chgrp_parser.print_help()
def do_chgrp(self, line):
"""Changes group that is currently active for editing."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups that can be made active'
return
try:
args = self.__class__.chgrp_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.chgrp_parser.print_usage()
return
if args.gid == None:
print "group",\
self.cur_proj.groups.index(self.cur_group),\
"is the current display group"
elif args.gid >= len(self.cur_proj.groups) or args.gid < 0:
print "group", args.gid, "does not exist"
else:
self.cur_group = self.cur_proj.groups[args.gid]
print "group", args.gid, "is now the current display group"
mk_parser = CmdParser(add_help=False, prog='mk',
description='''Makes a new checkerboard in the
current group with the given
parameters.''')
mk_parser.add_argument('dims', action=store_tuple(2, ',', to_decimal),
help='''width,height of checkerboard in no. of
unit cells''')
mk_parser.add_argument('init_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of initial unit cell in pixels')
mk_parser.add_argument('end_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of final unit cell in pixels')
mk_parser.add_argument('position', action=store_tuple(2, ',', to_decimal),
help='x,y position of checkerboard in pixels')
mk_parser.add_argument('anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='anchor')
mk_parser.add_argument('cols', action=store_tuple(2, ',', to_color, [';']),
help='''color1,color2 of the checkerboard
(color format: R;G;B,
component range from 0-255)''')
mk_parser.add_argument('freq', type=to_decimal,
help='frequency of color reversal in Hz')
mk_parser.add_argument('phase', type=to_decimal, nargs='?', default='0',
help='initial phase of animation in degrees')
def help_mk(self):
self.__class__.mk_parser.print_help()
def do_mk(self, line):
"""Makes a checkerboard with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
if self.cur_group == None:
print 'automatically adding display group...'
self.do_mkgrp('')
try:
args = self.__class__.mk_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mk_parser.print_usage()
return
shape_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_shape = core.CheckerBoard(**shape_dict)
new_id = self.cur_proj.add_shape_to_group(self.cur_group, new_shape)
print "checkerboard", new_id, "added"
ed_parser = CmdParser(add_help=False, prog='ed',
description='''Edits attributes of checkerboards
specified by ids.''')
ed_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='''ids of checkerboards in the current
group to be edited''')
ed_parser.add_argument('--dims', action=store_tuple(2, ',', to_decimal),
help='checkerboard dimensions in unit cells',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--init_unit',
action=store_tuple(2, ',', to_decimal),
help='initial unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--end_unit',
action=store_tuple(2, ',', to_decimal),
help='final unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--position',
action=store_tuple(2, ',', to_decimal),
help='position of checkerboard in pixels',
metavar='X,Y')
ed_parser.add_argument('--anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='LOCATION')
ed_parser.add_argument('--cols', metavar='COLOR1,COLOR2',
action=store_tuple(2, ',', to_color, [';']),
help='''checkerboard colors (color format:
R;G;B, component range
from 0-255)''')
ed_parser.add_argument('--freq', type=to_decimal,
help='frequency of color reversal in Hz')
ed_parser.add_argument('--phase', type=to_decimal,
help='initial phase of animation in degrees')
def help_ed(self):
self.__class__.ed_parser.print_help()
def do_ed(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, please create one first'
return
try:
args = self.__class__.ed_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ed_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_group.shapes) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_shape_attr(self.cur_group, x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.ed_parser.print_usage()
rm_parser = CmdParser(add_help=False, prog='rm',
description='''Removes checkerboards specified
by ids.''')
rm_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''ids of checkerboards in the current group
to be removed''')
rm_parser.add_argument('-a', '--all', action='store_true',
help='''remove all checkerboards in the
current group''')
def help_rm(self):
self.__class__.rm_parser.print_help()
def do_rm(self, line):
"""Removes checkerboards specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, no boards to remove'
return
try:
args = self.__class__.rm_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rm_parser.print_usage()
return
rmlist = []
if args.all:
for shape in self.cur_group.shapes:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
print "all checkerboards removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_group.shapes) or x < 0:
print "checkerboard", x, "does not exist"
continue
rmlist.append(self.cur_group.shapes[x])
print "checkerboard", x, "removed"
for shape in rmlist:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
ls_parser = CmdParser(add_help=False, prog='ls',
description='''Lists project, display group and
checkerboard settings. If no group ids
are specified, all display groups
are listed.''')
ls_parser.add_argument('gidlist', nargs='*', metavar='gid', type=int,
help='''ids of the display groups to be listed''')
ls_group = ls_parser.add_mutually_exclusive_group()
ls_group.add_argument('-s', '--settings', action='store_true',
help='list only project settings')
ls_group.add_argument('-g', '--groups', action='store_true',
help='list only display groups')
def help_ls(self):
self.__class__.ls_parser.print_help()
def do_ls(self, line):
"""Lists project, display group and checkerboard settings."""
def ls_str(s, seps=[',',';']):
"""Special space-saving output formatter."""
if type(s) in [tuple, list]:
if len(seps) > 1:
newseps = seps[1:]
else:
newseps = seps
return seps[0].join([ls_str(i, newseps) for i in s])
else:
return str(s)
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.ls_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ls_parser.print_usage()
return
# Remove duplicates and ascending sort
args.gidlist = sorted(set(args.gidlist))
if len(self.cur_proj.groups) == 0:
if len(args.gidlist) > 0:
print 'this project has no display groups that can be listed'
args.settings = True
else:
for gid in args.gidlist[:]:
if gid >= len(self.cur_proj.groups) or gid < 0:
args.gidlist.remove(gid)
print 'display group', gid, 'does not exist'
if args.gidlist == []:
args.gidlist = range(len(self.cur_proj.groups))
else:
# If any (valid) groups are specified
# don't show project settings
args.groups = True
if not args.groups:
print 'PROJECT SETTINGS'.center(70,'*')
print \
'name'.rjust(16),\
'fps'.rjust(7),\
'resolution'.rjust(14),\
'bg color'.rjust(18)
# 'format'.rjust(7)
print \
ls_str(self.cur_proj.name).rjust(16),\
ls_str(self.cur_proj.fps).rjust(7),\
ls_str(self.cur_proj.res).rjust(14),\
ls_str(self.cur_proj.bg).rjust(18)
# ls_str(self.cur_proj.export_fmt).rjust(7)
print \
'pre-display'.rjust(26),\
'post-display'.rjust(26)
print \
ls_str(self.cur_proj.pre).rjust(26),\
ls_str(self.cur_proj.post).rjust(26)
print \
'cross colors'.rjust(26),\
'cross times'.rjust(26)
print \
ls_str(self.cur_proj.cross_cols).rjust(26),\
ls_str(self.cur_proj.cross_times).rjust(26)
if not args.settings and not args.groups:
# Insert empty line if both groups and project
# settings are listed
print ''
if not args.settings:
for i, n in enumerate(args.gidlist):
if i != 0:
# Print newline seperator between each group
print ''
group = self.cur_proj.groups[n]
print 'GROUP {n}'.format(n=n).center(70,'*')
print \
'pre-display'.rjust(20),\
'display'.rjust(20),\
'post-display'.rjust(20)
print \
ls_str(group.pre).rjust(20),\
ls_str(group.disp).rjust(20),\
ls_str(group.post).rjust(20)
if len(group.shapes) > 0:
print \
''.rjust(2),\
'shape id'.rjust(8),\
'dims'.rjust(10),\
'init_unit'.rjust(14),\
'end_unit'.rjust(14),\
'position'.rjust(14)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.dims).rjust(10),\
ls_str(shape.init_unit).rjust(14),\
ls_str(shape.end_unit).rjust(14),\
ls_str(shape.position).rjust(14)
print '\n',\
''.rjust(2),\
'shape id'.rjust(8),\
'colors'.rjust(27),\
'anchor'.rjust(12),\
'freq'.rjust(6),\
'phase'.rjust(7)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.cols).rjust(27),\
ls_str(shape.anchor).rjust(12),\
ls_str(shape.freq).rjust(6),\
ls_str(shape.phase).rjust(7)
display_parser = CmdParser(add_help=False, prog='display',
description='''Displays the animation in a
window or in fullscreen.''')
display_parser.add_argument('-b', '--block', metavar='PATH',
help='''read flags and dislay group order from
specified file, ignore other flags''')
display_parser.add_argument('-f', '--fullscreen', action='store_true',
help='sets fullscreen mode, ESC to quit')
display_parser.add_argument('-p', '--priority', metavar='LEVEL',
help='''set priority while displaying,
higher priority results in
less dropped frames (choices:
0-3, low, normal, high,
realtime)''')
display_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly display specified display
groups N number of times''')
display_parser.add_argument('-pt', '--phototest', action='store_true',
help='''draw white test rectangle in topleft
corner of screen when groups become
visible for a photodiode to detect''')
+ display_parser.add_argument('-pb', '--photoburst', action='store_true',
+ help='''make checkerboards only draw first
+ color for one frame to facilitate
+ testing with a photodiode''')
display_parser.add_argument('-lt', '--logtime', action='store_true',
help='output frame timestamps to a log file')
display_parser.add_argument('-ld', '--logdur', action='store_true',
help='output frame durations to a log file')
display_parser.add_argument('-ss', '--sigser', action='store_true',
help='''send signals through the serial port
when shapes are being displayed''')
display_parser.add_argument('-sp', '--sigpar', action='store_true',
help='''send signals through the parallel port
when shapes are being displayed''')
display_parser.add_argument('-fpbs', metavar='M', type=int, default=0,
help='''unique signal corresponding to a
checkerboard is sent after the board
undergoes M color flips (default:
disabled, M=0)''')
display_parser.add_argument('-et', '--eyetrack', action='store_true',
help='''use eyetracking to ensure that subject
fixates on the cross in the center''')
display_parser.add_argument('-eu', '--etuser', action='store_true',
help='''allow user to select eyetracking video
source from a dialog''')
display_parser.add_argument('-ev', '--etvideo', metavar='path',
help='''path (with no spaces) to eyetracking
video file to be used as the source''')
display_parser.add_argument('-ta', '--tryagain', metavar='I',
type=int, default=0,
help='''append groups during which subject
failed to fixate up to I times to the
list of groups to be displayed
(default: disabled, I=0)''')
display_parser.add_argument('-tb', '--trybreak', metavar='J', type=int,
help='''used with --tryagain, append a wait
screen to the list of groups to be
displayed after every J groups have
been appended to the list (default:
J=total number of groups)''')
display_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be displayed
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_display(self):
self.__class__.display_parser.print_help()
def do_display(self, line):
"""Displays the animation in a window or in fullscreen"""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.display_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
if args.block != None:
blkpath = args.block
try:
blkdict = core.CkgProj.readblk(blkpath)
flags = blkdict['flags']
try:
args = self.__class__.\
display_parser.parse_args(shlex.split(flags))
args.idlist = blkdict['idlist']
except (CmdParserError, ValueError):
print 'error: invalid flags stored in block file'
return
except IOError:
print "error:", str(sys.exc_value)
return
else:
blkpath = None
group_queue = []
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < -1:
print 'error: group', i, 'does not exist'
return
for i in args.idlist:
if i == -1:
group_queue.append(core.CkgWaitScreen(res=
self.cur_proj.res))
else:
group_queue.append(self.cur_proj.groups[i])
else:
group_queue = list(self.cur_proj.groups)
if args.repeat != None:
group_queue = list(group_queue * args.repeat)
if args.eyetrack and eyetracking.available:
if not eyetracking.is_calibrated():
try:
self.do_calibrate('',True)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
return
if args.priority != None:
if not priority.available:
print "error: setting priority not avaible on", sys.platform
print "continuing..."
else:
if args.priority.isdigit():
args.priority = int(args.priority)
try:
priority.set(args.priority)
except ValueError:
print "error:", str(sys.exc_value)
print "continuing..."
try:
fail_idlist = self.cur_proj.display(fullscreen=args.fullscreen,
logtime=args.logtime,
logdur=args.logdur,
sigser=args.sigser,
sigpar=args.sigpar,
fpbs=args.fpbs,
phototest=args.phototest,
+ photoburst=args.photoburst,
eyetrack=args.eyetrack,
etuser=args.etuser,
etvideo=args.etvideo,
tryagain=args.tryagain,
trybreak=args.trybreak,
group_queue=group_queue)
except (IOError, NotImplementedError, eyetracking.EyetrackingError):
print "error:", str(sys.exc_value)
if args.priority != None:
try:
priority.set('normal')
except:
pass
return
if args.priority != None:
try:
priority.set('normal')
except:
pass
# Append list of ids of failed groups to block file
if fail_idlist != None and blkpath != None:
try:
core.CkgProj.addtoblk(blkpath, fail_idlist,
len(self.cur_proj.groups))
except IOError:
print "error:", str(sys.exc_value)
return
export_parser = CmdParser(add_help=False, prog='export',
description='''Exports animation as an image
sequence (in a folder) to the
specified directory.''')
# export_parser.add_argument('--fmt', dest='export_fmt',
# choices=core.EXPORT_FMTS,
# help='image format for export')
export_parser.add_argument('-n','--nofolder',
dest='folder', action='store_false',
help='''force images not to exported in
a containing folder''')
export_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly export specified display
groups N number of times''')
export_parser.add_argument('duration', nargs='?',
type=to_decimal, default='Infinity',
help='''number of seconds of the animation
that should be exported (default:
as long as the entire animation)''')
export_parser.add_argument('dir', nargs='?', default=os.getcwd(),
help='''destination directory for export
(default: current working directory)''')
export_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be exported
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_export(self):
self.__class__.export_parser.print_help()
def do_export(self, line):
"""Exports animation an image sequence to the specified directory."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.export_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.export_parser.print_usage()
return
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < 0:
print 'error: group', i, 'does not exist'
return
group_queue = [self.cur_proj.groups[i] for i in args.idlist]
else:
group_queue = list(self.cur_proj.groups)
if args.repeat != None:
group_queue = list(group_queue * args.repeat)
try:
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
group_queue=group_queue,
folder=args.folder)
except IOError:
print "error:", str(sys.exc_value)
return
except core.FrameOverflowError:
print "warning:", str(sys.exc_value)
print "Are you sure you want to continue?"
while True:
try:
if self.__class__.yn_parse(raw_input()):
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
group_queue=group_queue,
export_fmt=None,
folder=args.folder,
force=True)
break
else:
return
except TypeError:
print str(sys.exc_value)
except EOFError:
return
print "Export done."
mkblks_parser = CmdParser(add_help=False, prog='mkblks',
description='''Generates randomized experimental
blocks from display groups and
saves each as a CSV file.''')
mkblks_parser.add_argument('-n','--nofolder',
dest='folder', action='store_false',
help='''force block files not to be saved in
a containing folder''')
mkblks_parser.add_argument('-d','--dir', default=os.getcwd(),
help='''where to save block files
(default: current working directory)''')
mkblks_parser.add_argument('length', type=int,
help='''no. of repeated trials in a block''')
mkblks_parser.add_argument('flags', nargs='?', default='',
help='''flags passed to the display command
that should be used when the block
file is run (enclose in quotes and use
'+' or '++' in place of '-' or '--')''')
def help_mkblks(self):
self.__class__.mkblks_parser.print_help()
def do_mkblks(self, line):
"""Generates randomized experimental blocks from display groups."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.mkblks_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mkblks_parser.print_usage()
return
args.flags = args.flags.replace('+','-')
try:
disp_args = self.__class__.display_parser.\
parse_args(shlex.split(args.flags))
except (CmdParserError, ValueError):
print "error: invalid flags to display command"
print str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
try:
self.cur_proj.mkblks(args.length,
path=args.dir,
folder=args.folder,
flags=args.flags)
except IOError:
print "error:", str(sys.exc_value)
return
print "Experimental blocks generated."
def do_calibrate(self, line, query=False):
"""Calibrate subject for eyetracking, or load a calibration file."""
if not eyetracking.available:
print "error: eyetracking functionality not available"
return
if query:
print "path to calibration file (leave empty for GUI tool):"
try:
path = raw_input().strip().strip('"\'')
except EOFError:
msg = "calibration cancelled"
raise eyetracking.EyetrackingError(msg)
else:
path = line.strip().strip('"\'')
if len(path) == 0:
path = None
if not eyetracking.is_source_ready():
# Select default source if none has been selected
eyetracking.select_source()
try:
eyetracking.calibrate(path)
except eyetracking.EyetrackingError:
if query:
raise
else:
print "error:", str(sys.exc_value)
return
if len(path) > 0:
print "calibration file successfully loaded"
etsetup_parser = CmdParser(add_help=False, prog='etsetup',
description='''Set various eyetracking
parameters.''')
etsetup_parser.add_argument('-fp', '--fixperiod', type=int, metavar='MS',
help='''time in milliseconds subject
has to stare at the same spot
for fixation to be detected''')
etsetup_parser.add_argument('-fr', '--fixrange', type=float, metavar='MM',
help='''distance in mm beyond which the
eye position cannot change for
a fixation to be detected''')
etsetup_parser.add_argument('-s', '--size', metavar='WIDTH,HEIGHT',
action=store_tuple(2, ',', float),
help='physical screen dimensions in mm')
etsetup_parser.add_argument('-vd', '--viewdist', type=int, metavar='MM',
help='''viewing distance between subject's
eyes and the screen''')
def help_etsetup(self):
self.__class__.etsetup_parser.print_help()
def do_etsetup(self, line):
try:
args = self.__class__.etsetup_parser.parse_args(shlex.split(line))
except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.etsetup_parser.print_usage()
return
try:
eyetracking.setup(viewing_distance=args.viewdist,
screen_dims=args.size,
fixation_period=args.fixperiod,
fixation_range=args.fixrange)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
def do_quit(self, line):
"""Quits the program."""
if self.save_check():
return
return True
def help_EOF(self):
print "Typing {0} issues this command, which quits the program."\
.format(CMD_EOF_STRING)
def do_EOF(self, line):
"""Typing Ctrl-D issues this command, which quits the program."""
print '\r'
if self.save_check():
return
return True
def help_help(self):
print 'Prints a list of commands.'
print "Type 'help <topic>' for more details on each command."
def default(self, line):
command = line.split()[0]
print \
"'{0}' is not a checkergen command.".format(command),\
"Type 'help' for a list of commands"
diff --git a/src/core.py b/src/core.py
index 8f800d1..f6f524d 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,1135 +1,1151 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import itertools
from xml.dom import minidom
import pyglet
import graphics
import signals
import eyetracking
from utils import *
CKG_FMT = 'ckg'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
MAX_EXPORT_FRAMES = 100000
PRERENDER_TO_TEXTURE = False
INT_HALF_PERIODS = True
EXPORT_FMTS = ['png']
EXPORT_DIR_SUFFIX = '-anim'
BLOCK_DIR_SUFFIX = '-blks'
FIX_POS = (0, 0)
FIX_RANGE = (20, 20)
FIX_PER = 350
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = {'name': 'untitled',
'fps': 60,
'res': (800, 600),
'bg': (127, 127, 127),
'export_fmt': 'png',
'pre': 0,
'post': 0,
'cross_cols': ((0, 0, 0), (255, 0, 0)),
'cross_times': ('Infinity', 1)}
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
export_fmt -- image format for animation to be exported as
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'export_fmt':
if value not in EXPORT_FMTS:
msg = 'image format not recognized or supported'
raise FileFormatError(msg)
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if ext == '.{0}'.format(CKG_FMT):
self.name = name
else:
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
vars_to_load = self.__class__.DEFAULTS.keys()
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
vars_to_save = self.__class__.DEFAULTS.keys()
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def mkblks(self, length, path=None, folder=True, flags=''):
"""Generates randomized experimental blocks from display groups.
Each block is saved as a CSV file.
length -- number of repeated trials within a block
path -- directory in which experimental blocks will be saved
folder -- blocks will be saved in a containing folder if true
flags -- string of flags to be issued to the display command when
block file is run
"""
if path == None:
path = os.getcwd()
if not os.path.isdir(path):
msg = "specified directory does not exist"
raise IOError(msg)
if folder:
path = os.path.join(path, self.name + BLOCK_DIR_SUFFIX)
if not os.path.isdir(path):
os.mkdir(path)
group_ids = range(len(self.groups))
for n, sequence in enumerate(itertools.permutations(group_ids)):
blkname = 'block{0}.csv'.format(repr(n).zfill(numdigits(length)))
blkfile = open(os.path.join(path, blkname), 'wb')
blkwriter = csv.writer(blkfile, dialect='excel-tab')
blkwriter.writerow(['checkergen experimental block file'])
blkwriter.writerow(['flags:', flags])
blkwriter.writerow(['repeats:', length])
blkwriter.writerow(['sequence:'] + list(sequence))
blkfile.close()
@staticmethod
def readblk(path):
"""Reads the information in a block file and returns it in a dict."""
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
blkdict = dict()
blkfile = open(path, 'rb')
blkreader = csv.reader(blkfile, dialect='excel-tab')
for n, row in enumerate(blkreader):
if n == 1:
blkdict['flags'] = row[1]
elif n == 2:
repeats = int(row[1])
elif n == 3:
sequence = row[1:]
sequence = [int(i) for i in sequence]
blkfile.close()
blkdict['idlist'] = ([-1] + sequence) * repeats
return blkdict
@staticmethod
def addtoblk(path, idlist, rowlen):
"""Appends a list of group ids to the specified block file."""
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
blkfile = open(path, 'ab')
blkwriter = csv.writer(blkfile, dialect='excel-tab')
blkwriter.writerow(['groups added:'])
# Split idlist into lists of length rowlen, based on grouper recipe
args = [iter(idlist)] * rowlen
rowlist = itertools.izip_longest(*args, fillvalue='')
for row in rowlist:
blkwriter.writerow(row)
blkfile.close()
def display(self, fullscreen=False, logtime=False, logdur=False,
- sigser=False, sigpar=False, fpbs=0, phototest=False,
+ sigser=False, sigpar=False, fpbs=0,
+ phototest=False, photoburst=False,
eyetrack=False, etuser=False, etvideo=None,
tryagain=0, trybreak=None, group_queue=[]):
"""Displays the project animation on the screen.
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
sigser -- send signals through serial port when each group is shown
sigpar -- send signals through parallel port when each group is shown
fpbs -- flips per board signal, i.e. number of shape color reversals
(flips) that occur for a unique signal to be sent for that shape
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
+ photoburst -- make checkerboards only draw first color for one frame
+
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- Append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- Append a wait screen to the group queue every time
after this many groups have been appended to the queue
group_queue -- queue of groups to be displayed, defaults to order of
groups in project (i.e. groups[0] first, etc.)
"""
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if phototest:
test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Set-up groups and variables that control their display
if group_queue == []:
group_queue = list(self.groups)
cur_group = None
cur_id = -1
flipped = 0
flip_id = -1
groups_duration = sum([group.duration() for group in group_queue])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Initialize ports
if sigser:
if not signals.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if sigpar:
if not signals.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
signals.init(sigser, sigpar)
# Initialize eyetracking
if eyetrack:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if trybreak == None:
trybreak = len(self.groups)
fixated = False
old_fixated = False
tracked = False
old_tracked = False
cur_fix_fail = False
fail_idlist = []
eyetracking.select_source(etuser, etvideo)
eyetracking.start()
# Stretch to fit screen only if project res does not equal screen res
scaling = False
if fullscreen:
window = pyglet.window.Window(fullscreen=True, visible=False)
if (window.width, window.height) != self.res:
scaling = True
else:
window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
keystates = pyglet.window.key.KeyStateHandler()
window.push_handlers(keystates)
# Create framebuffer object for drawing unscaled scene
if scaling:
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
fbo.end_render()
# Clear window and make visible
window.switch_to()
graphics.set_clear_color(self.bg)
window.clear()
window.set_visible()
# Initialize logging variables
if logtime and logdur:
logstring = ''
stamp = Timer()
dur = Timer()
stamp.start()
dur.start()
elif logtime or logdur:
logstring = ''
timer = Timer()
timer.start()
# Main loop
while not window.has_exit and count < disp_end:
# Clear canvas
if scaling:
fbo.start_render()
fbo.clear()
else:
window.clear()
# Assume no change to group visibility
flipped = 0
signals.set_null()
# Manage groups when they are on_screen
if groups_visible:
# Send special signal if waitscreen ends
if isinstance(cur_group, CkgWaitScreen):
if cur_group.over:
signals.set_user_start()
cur_group = None
elif cur_group != None:
# Check whether group changes in visibility
if cur_group.visible != cur_group.old_visible:
flip_id = self.groups.index(cur_group)
if cur_group.visible:
flipped = 1
elif cur_group.old_visible:
flipped = -1
# Check if current group is over
if cur_group.over:
cur_group = None
# Get next group from queue
if cur_group == None:
cur_id += 1
if cur_id >= len(group_queue):
groups_visible = False
else:
cur_group = group_queue[cur_id]
cur_group.reset()
if eyetrack:
cur_fix_fail = False
if cur_group.visible:
flip_id = self.groups.index(cur_group)
flipped = 1
# Draw and then update group
if cur_group != None:
- cur_group.draw()
+ cur_group.draw(photoburst=True)
cur_group.update(fps=self.fps,
fpbs=fpbs,
keystates=keystates)
# Send signals upon group visibility change
if flipped == 1:
signals.set_group_start(flip_id)
# Draw test rectangle
if phototest:
test_rect.draw()
elif flipped == -1:
signals.set_group_stop(flip_id)
if eyetrack:
# First check if eye is being tracked and send signals
old_tracked = tracked
tracked = eyetracking.is_tracked()
if tracked:
if not old_tracked:
# Send signal if eye starts being tracked
signals.set_track_start()
else:
if old_tracked:
# Send signal if eye stops being tracked
signals.set_track_stop()
# Next check for fixation
old_fixated = fixated
fixated = eyetracking.is_fixated(FIX_POS, FIX_RANGE, FIX_PER)
if fixated:
# Draw normal cross color if fixating
fix_crosses[0].draw()
if not old_fixated:
# Send signal if fixation starts
signals.set_fix_start()
else:
# Draw alternative cross color if not fixating
fix_crosses[1].draw()
if old_fixated:
# Send signal if fixation stops
signals.set_fix_stop()
# Take note of which groups in which fixation failed
if not cur_fix_fail and cur_group.visible and\
(tracked and not fixated):
cur_fix_fail = True
if len(fail_idlist) == 0 and trybreak > 0:
group_queue.append(CkgWaitScreen(res=self.res))
fail_idlist.append(self.groups.index(cur_group))
# Append failed group to group queue
if tryagain > 0:
group_queue.append(cur_group)
groups_stop += cur_group.duration() * self.fps
disp_end += cur_group.duration() * self.fps
# Insert waitscreen every trybreak failed groups
if trybreak > 0:
if len(fail_idlist) % trybreak == 0:
group_queue.append(CkgWaitScreen())
tryagain -= 1
# Change cross color based on time if eyetracking is not enabled
if not eyetrack:
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Increment count and set whether groups should be shown
if not isinstance(cur_group, CkgWaitScreen):
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
# Blit canvas to screen if necessary
if scaling:
fbo.end_render()
window.switch_to()
canvas.blit(0, 0)
window.dispatch_events()
window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to log string
if logtime and logdur:
logstring = '\n'.join([logstring, str(stamp.elapsed())])
logstring = '\t'.join([logstring, str(dur.restart())])
elif logtime:
logstring = '\n'.join([logstring, str(timer.elapsed())])
elif logdur:
logstring = '\n'.join([logstring, str(timer.restart())])
# Send signals ASAP after flip
signals.send(sigser, sigpar)
# Log when signals are sent
if logtime or logdur:
if flipped != 0 and (sigser or sigpar):
sigmsg = '{0} sent'.format(signals.STATE)
logstring = '\t'.join([logstring, sigmsg])
# Clean up
if eyetrack:
eyetracking.stop()
window.close()
if scaling:
fbo.delete()
del canvas
signals.quit(sigser, sigpar)
# Write log string to file
if logtime or logdur:
filename = '{0}.log'.format(self.name)
with open(filename, 'w') as logfile:
logfile.write(logstring)
# Return list of ids of failed groups
if eyetrack and len(fail_idlist) > 0:
return fail_idlist
def export(self, export_dir, export_duration, group_queue=[],
export_fmt=None, folder=True, force=False):
if not os.path.isdir(export_dir):
msg = 'export path is not a directory'
raise IOError(msg)
if export_fmt == None:
export_fmt = self.export_fmt
# Set-up groups and variables that control their display
if group_queue == []:
group_queue = list(self.groups)
cur_group = None
cur_id = -1
groups_duration = sum([group.duration() for group in group_queue])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Limit export duration to display duration
frames = export_duration * self.fps
frames = min(frames, disp_end)
# Warn user if a lot of frames will be exported
if frames > MAX_EXPORT_FRAMES and not force:
msg = 'very large number ({0}) of frames to be exported'.\
format(frames)
raise FrameOverflowError(msg)
# Create folder to store images if necessary
if folder:
export_dir = os.path.join(export_dir,
self.name + EXPORT_DIR_SUFFIX)
if not os.path.isdir(export_dir):
os.mkdir(export_dir)
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Set up canvas and framebuffer object
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
# Main loop
while count < frames:
fbo.clear()
if groups_visible:
# Check if current group is over
if cur_group != None:
if cur_group.over:
cur_group = None
# Get next group from queue
if cur_group == None:
cur_id += 1
if cur_id >= len(group_queue):
groups_visible = False
else:
cur_group = group_queue[cur_id]
cur_group.reset()
# Draw and then update group
if cur_group != None:
cur_group.draw()
cur_group.update(fps=self.fps, fpbs=0)
# Draw fixation cross based on current count
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Save current frame to file
savepath = \
os.path.join(export_dir,
'{0}{2}.{1}'.
format(self.name, export_fmt,
repr(count).zfill(numdigits(frames-1))))
canvas.save(savepath)
# Increment count and set whether groups should be shown
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
fbo.delete()
class CkgDisplayGroup:
DEFAULTS = {'pre': 0, 'disp': 'Infinity', 'post': 0}
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets internal count and all contained shapes."""
self._count = 0
self._start = self.pre
self._stop = self.pre + self.disp
self._end = self.pre + self.disp + self.post
self.over = False
self.old_visible = False
if self._start == 0 and self._stop > 0:
self.visible = True
else:
self.visible = False
if self._end == 0:
self.over = True
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
- def draw(self, lazy=False):
+ def draw(self, lazy=False, photoburst=False):
"""Draws all contained shapes during the appropriate interval."""
if self.visible:
for shape in self.shapes:
if lazy:
shape.lazydraw()
else:
- shape.draw()
+ shape.draw(photoburst=photoburst)
def update(self, **keywords):
"""Increments internal count, makes group visible when appropriate.
fps -- refresh rate of the display in frames per second
fpbs -- flips per board signal, i.e. number of shape color reversals
(flips) that occur for a unique signal to be sent for that shape
"""
fps = keywords['fps']
fpbs = keywords['fpbs']
if self.visible:
# Set triggers to be sent
if fpbs > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= fpbs:
signals.set_board_flip(n)
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(fps)
# Increment count and set flags for the next frame
self._count += 1
self.old_visible = self.visible
if (self._start * fps) <= self._count < (self._stop * fps):
self.visible = True
else:
self.visible = False
if self._count >= (self._end * fps):
self.over = True
else:
self.over = False
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.visible = False
self.old_visible = False
self.steps_done = 0
self.over = False
def draw(self):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, **keywords):
"""Checks for keypress, sends signal upon end."""
keystates = keywords['keystates']
if max([keystates[key] for key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
if self.steps_done == self.num_steps:
self.over = True
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = {'dims': (5, 5),
'init_unit': (30, 30), 'end_unit': (50, 50),
'position': (0, 0), 'anchor': 'bottomleft',
'cols': ((0, 0, 0), (255, 255, 255)),
'freq': 1, 'phase': 0}
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
if INT_HALF_PERIODS:
frames_per_half_period = round(fps / (self.freq * 2))
degs_per_frame = 180 / to_decimal(frames_per_half_period)
else:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
if PRERENDER_TO_TEXTURE:
init_pos = [(1 - a)* s/to_decimal(2) for s, a in
zip(self._size, graphics.locations[self.anchor])]
else:
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
anchor=self.anchor)
cur_unit_rect.col = self.cols[(i + j) % 2]
cur_unit_rect.add_to_batch(self._batches[0])
cur_unit_rect.col = self.cols[(i + j + 1) % 2]
cur_unit_rect.add_to_batch(self._batches[1])
# Increase x values
cur_unit_pos[0] += \
graphics.locations[self.anchor][0] * cur_unit[0]
cur_unit[0] += unit_grad[0]
# Reset x values
cur_unit_pos[0] = init_pos[0]
cur_unit[0] = init_unit[0]
# Increase y values
cur_unit_pos[1] += \
graphics.locations[self.anchor][1] * cur_unit[1]
cur_unit[1] += unit_grad[1]
if PRERENDER_TO_TEXTURE:
# Create textures
int_size = [int(round(s)) for s in self._size]
self._prerenders =\
[pyglet.image.Texture.create(*int_size) for n in range(2)]
# Set up framebuffer
fbo = graphics.Framebuffer()
for n in range(2):
fbo.attach_texture(self._prerenders[n])
# Draw batch to texture
fbo.start_render()
self._batches[n].draw()
fbo.end_render()
# Anchor textures for correct blitting later
self._prerenders[n].anchor_x, self._prerenders[n].anchor_y =\
[int(round((1 - a)* s/to_decimal(2))) for s, a in
zip(self._size, graphics.locations[self.anchor])]
fbo.delete()
# Delete batches since they won't be used
del self._batches
self._computed = True
- def draw(self, always_compute=False):
- """Draws appropriate prerender depending on current phase."""
+ def draw(self, photoburst=False, always_compute=False):
+ """Draws appropriate prerender depending on current phase.
+
+ photoburst -- draw first color for only one frame for testing purposes
+
+ always_compute -- recompute what the checkerboard should look like
+ every frame
+
+ """
if not self._computed or always_compute:
self.compute()
self._cur_phase %= 360
- n = int(self._cur_phase // 180)
+ if not photoburst:
+ n = int(self._cur_phase // 180)
+ else:
+ if self._cur_phase == self.phase:
+ n = 0
+ else:
+ n = 1
if PRERENDER_TO_TEXTURE:
self._prerenders[n].blit(*self.position)
else:
self._batches[n].draw()
def lazydraw(self):
"""Only draws on color reversal."""
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if (cur_n != prev_n) or self._first_draw:
self.draw()
if self._first_draw:
self._first_draw = False
|
ztangent/checkergen
|
4b39774d1ad7e17543dac9d94169121203a6a4c1
|
Improve eyetracking error handling a little.
|
diff --git a/src/core.py b/src/core.py
index 348e8da..8f800d1 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,1135 +1,1135 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import itertools
from xml.dom import minidom
import pyglet
import graphics
import signals
import eyetracking
from utils import *
CKG_FMT = 'ckg'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
MAX_EXPORT_FRAMES = 100000
PRERENDER_TO_TEXTURE = False
-INTEGER_CYCLES = True
+INT_HALF_PERIODS = True
EXPORT_FMTS = ['png']
EXPORT_DIR_SUFFIX = '-anim'
BLOCK_DIR_SUFFIX = '-blks'
FIX_POS = (0, 0)
FIX_RANGE = (20, 20)
FIX_PER = 350
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = {'name': 'untitled',
'fps': 60,
'res': (800, 600),
'bg': (127, 127, 127),
'export_fmt': 'png',
'pre': 0,
'post': 0,
'cross_cols': ((0, 0, 0), (255, 0, 0)),
'cross_times': ('Infinity', 1)}
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
export_fmt -- image format for animation to be exported as
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'export_fmt':
if value not in EXPORT_FMTS:
msg = 'image format not recognized or supported'
raise FileFormatError(msg)
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if ext == '.{0}'.format(CKG_FMT):
self.name = name
else:
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
vars_to_load = self.__class__.DEFAULTS.keys()
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
vars_to_save = self.__class__.DEFAULTS.keys()
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def mkblks(self, length, path=None, folder=True, flags=''):
"""Generates randomized experimental blocks from display groups.
Each block is saved as a CSV file.
length -- number of repeated trials within a block
path -- directory in which experimental blocks will be saved
folder -- blocks will be saved in a containing folder if true
flags -- string of flags to be issued to the display command when
block file is run
"""
if path == None:
path = os.getcwd()
if not os.path.isdir(path):
msg = "specified directory does not exist"
raise IOError(msg)
if folder:
path = os.path.join(path, self.name + BLOCK_DIR_SUFFIX)
if not os.path.isdir(path):
os.mkdir(path)
group_ids = range(len(self.groups))
for n, sequence in enumerate(itertools.permutations(group_ids)):
blkname = 'block{0}.csv'.format(repr(n).zfill(numdigits(length)))
blkfile = open(os.path.join(path, blkname), 'wb')
blkwriter = csv.writer(blkfile, dialect='excel-tab')
blkwriter.writerow(['checkergen experimental block file'])
blkwriter.writerow(['flags:', flags])
blkwriter.writerow(['repeats:', length])
blkwriter.writerow(['sequence:'] + list(sequence))
blkfile.close()
@staticmethod
def readblk(path):
"""Reads the information in a block file and returns it in a dict."""
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
blkdict = dict()
blkfile = open(path, 'rb')
blkreader = csv.reader(blkfile, dialect='excel-tab')
for n, row in enumerate(blkreader):
if n == 1:
blkdict['flags'] = row[1]
elif n == 2:
repeats = int(row[1])
elif n == 3:
sequence = row[1:]
sequence = [int(i) for i in sequence]
blkfile.close()
blkdict['idlist'] = ([-1] + sequence) * repeats
return blkdict
@staticmethod
def addtoblk(path, idlist, rowlen):
"""Appends a list of group ids to the specified block file."""
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
blkfile = open(path, 'ab')
blkwriter = csv.writer(blkfile, dialect='excel-tab')
blkwriter.writerow(['groups added:'])
# Split idlist into lists of length rowlen, based on grouper recipe
args = [iter(idlist)] * rowlen
rowlist = itertools.izip_longest(*args, fillvalue='')
for row in rowlist:
blkwriter.writerow(row)
blkfile.close()
def display(self, fullscreen=False, logtime=False, logdur=False,
sigser=False, sigpar=False, fpbs=0, phototest=False,
eyetrack=False, etuser=False, etvideo=None,
tryagain=0, trybreak=None, group_queue=[]):
"""Displays the project animation on the screen.
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
sigser -- send signals through serial port when each group is shown
sigpar -- send signals through parallel port when each group is shown
fpbs -- flips per board signal, i.e. number of shape color reversals
(flips) that occur for a unique signal to be sent for that shape
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- Append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- Append a wait screen to the group queue every time
after this many groups have been appended to the queue
group_queue -- queue of groups to be displayed, defaults to order of
groups in project (i.e. groups[0] first, etc.)
"""
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if phototest:
test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Set-up groups and variables that control their display
if group_queue == []:
group_queue = list(self.groups)
cur_group = None
cur_id = -1
flipped = 0
flip_id = -1
groups_duration = sum([group.duration() for group in group_queue])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Initialize ports
if sigser:
if not signals.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if sigpar:
if not signals.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
signals.init(sigser, sigpar)
# Initialize eyetracking
if eyetrack:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if trybreak == None:
trybreak = len(self.groups)
fixated = False
old_fixated = False
tracked = False
old_tracked = False
cur_fix_fail = False
fail_idlist = []
eyetracking.select_source(etuser, etvideo)
eyetracking.start()
# Stretch to fit screen only if project res does not equal screen res
scaling = False
if fullscreen:
window = pyglet.window.Window(fullscreen=True, visible=False)
if (window.width, window.height) != self.res:
scaling = True
else:
window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
keystates = pyglet.window.key.KeyStateHandler()
window.push_handlers(keystates)
# Create framebuffer object for drawing unscaled scene
if scaling:
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
fbo.end_render()
# Clear window and make visible
window.switch_to()
graphics.set_clear_color(self.bg)
window.clear()
window.set_visible()
# Initialize logging variables
if logtime and logdur:
logstring = ''
stamp = Timer()
dur = Timer()
stamp.start()
dur.start()
elif logtime or logdur:
logstring = ''
timer = Timer()
timer.start()
# Main loop
while not window.has_exit and count < disp_end:
# Clear canvas
if scaling:
fbo.start_render()
fbo.clear()
else:
window.clear()
# Assume no change to group visibility
flipped = 0
signals.set_null()
# Manage groups when they are on_screen
if groups_visible:
# Send special signal if waitscreen ends
if isinstance(cur_group, CkgWaitScreen):
if cur_group.over:
signals.set_user_start()
cur_group = None
elif cur_group != None:
# Check whether group changes in visibility
if cur_group.visible != cur_group.old_visible:
flip_id = self.groups.index(cur_group)
if cur_group.visible:
flipped = 1
elif cur_group.old_visible:
flipped = -1
# Check if current group is over
if cur_group.over:
cur_group = None
# Get next group from queue
if cur_group == None:
cur_id += 1
if cur_id >= len(group_queue):
groups_visible = False
else:
cur_group = group_queue[cur_id]
cur_group.reset()
if eyetrack:
cur_fix_fail = False
if cur_group.visible:
flip_id = self.groups.index(cur_group)
flipped = 1
# Draw and then update group
if cur_group != None:
cur_group.draw()
cur_group.update(fps=self.fps,
fpbs=fpbs,
keystates=keystates)
# Send signals upon group visibility change
if flipped == 1:
signals.set_group_start(flip_id)
# Draw test rectangle
if phototest:
test_rect.draw()
elif flipped == -1:
signals.set_group_stop(flip_id)
if eyetrack:
# First check if eye is being tracked and send signals
old_tracked = tracked
tracked = eyetracking.is_tracked()
if tracked:
if not old_tracked:
# Send signal if eye starts being tracked
signals.set_track_start()
else:
if old_tracked:
# Send signal if eye stops being tracked
signals.set_track_stop()
# Next check for fixation
old_fixated = fixated
fixated = eyetracking.is_fixated(FIX_POS, FIX_RANGE, FIX_PER)
if fixated:
# Draw normal cross color if fixating
fix_crosses[0].draw()
if not old_fixated:
# Send signal if fixation starts
signals.set_fix_start()
else:
# Draw alternative cross color if not fixating
fix_crosses[1].draw()
if old_fixated:
# Send signal if fixation stops
signals.set_fix_stop()
# Take note of which groups in which fixation failed
if not cur_fix_fail and cur_group.visible and\
(tracked and not fixated):
cur_fix_fail = True
if len(fail_idlist) == 0 and trybreak > 0:
group_queue.append(CkgWaitScreen(res=self.res))
fail_idlist.append(self.groups.index(cur_group))
# Append failed group to group queue
if tryagain > 0:
group_queue.append(cur_group)
groups_stop += cur_group.duration() * self.fps
disp_end += cur_group.duration() * self.fps
# Insert waitscreen every trybreak failed groups
if trybreak > 0:
if len(fail_idlist) % trybreak == 0:
group_queue.append(CkgWaitScreen())
tryagain -= 1
# Change cross color based on time if eyetracking is not enabled
if not eyetrack:
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Increment count and set whether groups should be shown
if not isinstance(cur_group, CkgWaitScreen):
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
# Blit canvas to screen if necessary
if scaling:
fbo.end_render()
window.switch_to()
canvas.blit(0, 0)
window.dispatch_events()
window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to log string
if logtime and logdur:
logstring = '\n'.join([logstring, str(stamp.elapsed())])
logstring = '\t'.join([logstring, str(dur.restart())])
elif logtime:
logstring = '\n'.join([logstring, str(timer.elapsed())])
elif logdur:
logstring = '\n'.join([logstring, str(timer.restart())])
# Send signals ASAP after flip
signals.send(sigser, sigpar)
# Log when signals are sent
if logtime or logdur:
if flipped != 0 and (sigser or sigpar):
sigmsg = '{0} sent'.format(signals.STATE)
logstring = '\t'.join([logstring, sigmsg])
# Clean up
if eyetrack:
eyetracking.stop()
window.close()
if scaling:
fbo.delete()
del canvas
signals.quit(sigser, sigpar)
# Write log string to file
if logtime or logdur:
filename = '{0}.log'.format(self.name)
with open(filename, 'w') as logfile:
logfile.write(logstring)
# Return list of ids of failed groups
if eyetrack and len(fail_idlist) > 0:
return fail_idlist
def export(self, export_dir, export_duration, group_queue=[],
export_fmt=None, folder=True, force=False):
if not os.path.isdir(export_dir):
msg = 'export path is not a directory'
raise IOError(msg)
if export_fmt == None:
export_fmt = self.export_fmt
# Set-up groups and variables that control their display
if group_queue == []:
group_queue = list(self.groups)
cur_group = None
cur_id = -1
groups_duration = sum([group.duration() for group in group_queue])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Limit export duration to display duration
frames = export_duration * self.fps
frames = min(frames, disp_end)
# Warn user if a lot of frames will be exported
if frames > MAX_EXPORT_FRAMES and not force:
msg = 'very large number ({0}) of frames to be exported'.\
format(frames)
raise FrameOverflowError(msg)
# Create folder to store images if necessary
if folder:
export_dir = os.path.join(export_dir,
self.name + EXPORT_DIR_SUFFIX)
if not os.path.isdir(export_dir):
os.mkdir(export_dir)
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Set up canvas and framebuffer object
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
# Main loop
while count < frames:
fbo.clear()
if groups_visible:
# Check if current group is over
if cur_group != None:
if cur_group.over:
cur_group = None
# Get next group from queue
if cur_group == None:
cur_id += 1
if cur_id >= len(group_queue):
groups_visible = False
else:
cur_group = group_queue[cur_id]
cur_group.reset()
# Draw and then update group
if cur_group != None:
cur_group.draw()
cur_group.update(fps=self.fps, fpbs=0)
# Draw fixation cross based on current count
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Save current frame to file
savepath = \
os.path.join(export_dir,
'{0}{2}.{1}'.
format(self.name, export_fmt,
repr(count).zfill(numdigits(frames-1))))
canvas.save(savepath)
# Increment count and set whether groups should be shown
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
fbo.delete()
class CkgDisplayGroup:
DEFAULTS = {'pre': 0, 'disp': 'Infinity', 'post': 0}
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets internal count and all contained shapes."""
self._count = 0
self._start = self.pre
self._stop = self.pre + self.disp
self._end = self.pre + self.disp + self.post
self.over = False
self.old_visible = False
if self._start == 0 and self._stop > 0:
self.visible = True
else:
self.visible = False
if self._end == 0:
self.over = True
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, lazy=False):
"""Draws all contained shapes during the appropriate interval."""
if self.visible:
for shape in self.shapes:
if lazy:
shape.lazydraw()
else:
shape.draw()
def update(self, **keywords):
"""Increments internal count, makes group visible when appropriate.
fps -- refresh rate of the display in frames per second
fpbs -- flips per board signal, i.e. number of shape color reversals
(flips) that occur for a unique signal to be sent for that shape
"""
fps = keywords['fps']
fpbs = keywords['fpbs']
if self.visible:
# Set triggers to be sent
if fpbs > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= fpbs:
signals.set_board_flip(n)
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(fps)
# Increment count and set flags for the next frame
self._count += 1
self.old_visible = self.visible
if (self._start * fps) <= self._count < (self._stop * fps):
self.visible = True
else:
self.visible = False
if self._count >= (self._end * fps):
self.over = True
else:
self.over = False
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.visible = False
self.old_visible = False
self.steps_done = 0
self.over = False
def draw(self):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, **keywords):
"""Checks for keypress, sends signal upon end."""
keystates = keywords['keystates']
if max([keystates[key] for key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
if self.steps_done == self.num_steps:
self.over = True
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = {'dims': (5, 5),
'init_unit': (30, 30), 'end_unit': (50, 50),
'position': (0, 0), 'anchor': 'bottomleft',
'cols': ((0, 0, 0), (255, 255, 255)),
'freq': 1, 'phase': 0}
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
- if INTEGER_CYCLES:
- frames_per_half_cycle = round(fps / (self.freq * 2))
- degs_per_frame = 180 / to_decimal(frames_per_half_cycle)
+ if INT_HALF_PERIODS:
+ frames_per_half_period = round(fps / (self.freq * 2))
+ degs_per_frame = 180 / to_decimal(frames_per_half_period)
else:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
if PRERENDER_TO_TEXTURE:
init_pos = [(1 - a)* s/to_decimal(2) for s, a in
zip(self._size, graphics.locations[self.anchor])]
else:
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
anchor=self.anchor)
cur_unit_rect.col = self.cols[(i + j) % 2]
cur_unit_rect.add_to_batch(self._batches[0])
cur_unit_rect.col = self.cols[(i + j + 1) % 2]
cur_unit_rect.add_to_batch(self._batches[1])
# Increase x values
cur_unit_pos[0] += \
graphics.locations[self.anchor][0] * cur_unit[0]
cur_unit[0] += unit_grad[0]
# Reset x values
cur_unit_pos[0] = init_pos[0]
cur_unit[0] = init_unit[0]
# Increase y values
cur_unit_pos[1] += \
graphics.locations[self.anchor][1] * cur_unit[1]
cur_unit[1] += unit_grad[1]
if PRERENDER_TO_TEXTURE:
# Create textures
int_size = [int(round(s)) for s in self._size]
self._prerenders =\
[pyglet.image.Texture.create(*int_size) for n in range(2)]
# Set up framebuffer
fbo = graphics.Framebuffer()
for n in range(2):
fbo.attach_texture(self._prerenders[n])
# Draw batch to texture
fbo.start_render()
self._batches[n].draw()
fbo.end_render()
# Anchor textures for correct blitting later
self._prerenders[n].anchor_x, self._prerenders[n].anchor_y =\
[int(round((1 - a)* s/to_decimal(2))) for s, a in
zip(self._size, graphics.locations[self.anchor])]
fbo.delete()
# Delete batches since they won't be used
del self._batches
self._computed = True
def draw(self, always_compute=False):
"""Draws appropriate prerender depending on current phase."""
if not self._computed or always_compute:
self.compute()
self._cur_phase %= 360
n = int(self._cur_phase // 180)
if PRERENDER_TO_TEXTURE:
self._prerenders[n].blit(*self.position)
else:
self._batches[n].draw()
def lazydraw(self):
"""Only draws on color reversal."""
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if (cur_n != prev_n) or self._first_draw:
self.draw()
if self._first_draw:
self._first_draw = False
diff --git a/src/eyetracking.py b/src/eyetracking.py
index c7db8c1..8449c8e 100644
--- a/src/eyetracking.py
+++ b/src/eyetracking.py
@@ -1,154 +1,163 @@
"""Provides support for CRS VideoEyetracker Toolbox."""
import os.path
try:
import win32com.client
available = True
except ImportError:
available = False
# COM ProgID of the Toolbox
ProgID = "crsVET.VideoEyeTracker"
RecordName = "etResultSet"
# VET application object
VET = None
class EyetrackingError(Exception):
"""Raised when something goes wrong with VET."""
pass
if available:
# Try dispatching object, else unavailable
try:
from win32com.client import gencache
# Ensure makepy module is generated
gencache.EnsureModule('{248DBF0C-A874-4032-82CE-DC5B307BB6E7}',
0, 3, 11)
VET = win32com.client.Dispatch(ProgID)
DummyResultSet = win32com.client.Record(RecordName, VET)
except:
available = False
if available:
# For easier access to constants and standardization with MATLAB interface
CRS = win32com.client.constants
lastgoodstamp = 0
def select_source(user_select = False, path = None):
if user_select:
if not VET.SelectVideoSource(CRS.vsUserSelect, ''):
msg = 'could not select video source'
raise EyetrackingError(msg)
elif path != None:
# Open from file
if not VET.SelectVideoSource(CRS.vsFile, path):
msg = 'could not use path as video source'
raise EyetrackingError(msg)
else:
# Default to 250 Hz High Speed Camera
if not VET.SelectVideoSource(CRS.vsHighSpeedCamera250, ''):
msg = 'could not select video source'
raise EyetrackingError(msg)
def is_source_ready():
"""Returns true if a video source has been selected."""
if VET.VideoSourceType == 0:
return False
else:
return True
def show_camera():
VET.CreateCameraScreen(0)
def quit_camera():
VET.DestroyCameraScreen()
def setup(viewing_distance=None, screen_dims=None,
fixation_period=None, fixation_range=None):
"""Calibrates the display and sets fixation properties."""
if viewing_distance != None and screen_dims != None:
if len(screen_dims) != 2:
msg = 'screen_dims must be a 2-tuple'
raise ValueError(msg)
VET.SetDeviceParameters(CRS.deUser, viewing_distance,
screen_dims[0], screen_dims[1])
if fixation_period != None:
VET.FixationPeriod = fixation_period
if fixation_range != None:
VET.FixationRange = fixation_range
def calibrate(path = None):
"""Calibrate the subject.
Optionally supply a path with no spaces to a
calibration file to load."""
+ if not is_source_ready():
+ select_source()
+ if not VET.Tracking:
+ start()
if path == None:
if not VET.Calibrate():
msg = 'calibration failed'
raise EyetrackingError(msg)
else:
if not os.path.isfile(path):
msg = 'specified file does not exist'
raise EyetrackingError(msg)
if not VET.LoadCalibrationFile(path):
msg = 'file could not be loaded'
raise EyetrackingError(msg)
-
+ if not is_calibrated():
+ msg = 'calibration failed'
+ raise EyetrackingError(msg)
+
def is_calibrated():
if VET.CalibrationStatus()[0] != 0:
return True
else:
return False
def start():
"""Start tracking the eye."""
global lastgoodstamp
- if VET.CalibrationStatus()[0] == 0:
+ if not is_source_ready():
+ select_source()
+ if not is_calibrated():
msg = 'subject not yet calibrated'
raise EyetrackingError(msg)
lastgoodstamp = 0
VET.ClearDataBuffer()
VET.StartTracking()
def stop():
"""Stop tracking the eye."""
VET.StopTracking()
def is_tracked():
"""Returns true if the eye is being tracked."""
data = VET.GetLatestEyePosition(DummyResultSet)[1]
return data.Tracked
def is_fixated(fix_pos, fix_range, fix_period):
"""Checks whether subject is fixating on specificied location.
fix_pos -- (x, y) position of desired fixation location in mm
from center of screen
fix_range -- (width, height) of box surrounding fix_pos within
which fixation is allowed (in mm)
fix_period -- duration in milliseconds within which subject is
assumed to continue fixating after fixation is detected at a
specific time
"""
global lastgoodstamp
if VET.CalibrationStatus()[0] == 0:
msg = 'subject not yet calibrated'
raise EyetrackingError(msg)
data = VET.GetLatestEyePosition(DummyResultSet)[1]
pos = (data.ScreenPositionXmm, data.ScreenPositionYmm)
diff = [abs(p - fp) for p, fp in zip(pos, fix_pos)]
if data.Tracked == True:
if diff[0] < fix_range[0] and diff[1] < fix_range[1]:
lastgoodstamp = data.TimeStamp
return True
elif (data.Timestamp - lastgoodstamp) <= fix_period:
return True
elif (data.Timestamp - lastgoodstamp) <= fix_period:
return True
return False
|
ztangent/checkergen
|
df14d2623a836e87fdac963fe451bddd924d7465
|
Fixed to_decimal, force half-periods of checkerboards to be integer no. of frames.
|
diff --git a/src/core.py b/src/core.py
index 7517841..348e8da 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,1130 +1,1135 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import itertools
from xml.dom import minidom
import pyglet
import graphics
import signals
import eyetracking
from utils import *
CKG_FMT = 'ckg'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
MAX_EXPORT_FRAMES = 100000
PRERENDER_TO_TEXTURE = False
+INTEGER_CYCLES = True
EXPORT_FMTS = ['png']
EXPORT_DIR_SUFFIX = '-anim'
BLOCK_DIR_SUFFIX = '-blks'
FIX_POS = (0, 0)
FIX_RANGE = (20, 20)
FIX_PER = 350
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = {'name': 'untitled',
'fps': 60,
'res': (800, 600),
'bg': (127, 127, 127),
'export_fmt': 'png',
'pre': 0,
'post': 0,
'cross_cols': ((0, 0, 0), (255, 0, 0)),
'cross_times': ('Infinity', 1)}
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
export_fmt -- image format for animation to be exported as
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'export_fmt':
if value not in EXPORT_FMTS:
msg = 'image format not recognized or supported'
raise FileFormatError(msg)
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if ext == '.{0}'.format(CKG_FMT):
self.name = name
else:
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
vars_to_load = self.__class__.DEFAULTS.keys()
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
vars_to_save = self.__class__.DEFAULTS.keys()
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def mkblks(self, length, path=None, folder=True, flags=''):
"""Generates randomized experimental blocks from display groups.
Each block is saved as a CSV file.
length -- number of repeated trials within a block
path -- directory in which experimental blocks will be saved
folder -- blocks will be saved in a containing folder if true
flags -- string of flags to be issued to the display command when
block file is run
"""
if path == None:
path = os.getcwd()
if not os.path.isdir(path):
msg = "specified directory does not exist"
raise IOError(msg)
if folder:
path = os.path.join(path, self.name + BLOCK_DIR_SUFFIX)
if not os.path.isdir(path):
os.mkdir(path)
group_ids = range(len(self.groups))
for n, sequence in enumerate(itertools.permutations(group_ids)):
blkname = 'block{0}.csv'.format(repr(n).zfill(numdigits(length)))
blkfile = open(os.path.join(path, blkname), 'wb')
blkwriter = csv.writer(blkfile, dialect='excel-tab')
blkwriter.writerow(['checkergen experimental block file'])
blkwriter.writerow(['flags:', flags])
blkwriter.writerow(['repeats:', length])
blkwriter.writerow(['sequence:'] + list(sequence))
blkfile.close()
@staticmethod
def readblk(path):
"""Reads the information in a block file and returns it in a dict."""
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
blkdict = dict()
blkfile = open(path, 'rb')
blkreader = csv.reader(blkfile, dialect='excel-tab')
for n, row in enumerate(blkreader):
if n == 1:
blkdict['flags'] = row[1]
elif n == 2:
repeats = int(row[1])
elif n == 3:
sequence = row[1:]
sequence = [int(i) for i in sequence]
blkfile.close()
blkdict['idlist'] = ([-1] + sequence) * repeats
return blkdict
@staticmethod
def addtoblk(path, idlist, rowlen):
"""Appends a list of group ids to the specified block file."""
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
blkfile = open(path, 'ab')
blkwriter = csv.writer(blkfile, dialect='excel-tab')
blkwriter.writerow(['groups added:'])
# Split idlist into lists of length rowlen, based on grouper recipe
args = [iter(idlist)] * rowlen
rowlist = itertools.izip_longest(*args, fillvalue='')
for row in rowlist:
blkwriter.writerow(row)
blkfile.close()
def display(self, fullscreen=False, logtime=False, logdur=False,
sigser=False, sigpar=False, fpbs=0, phototest=False,
eyetrack=False, etuser=False, etvideo=None,
tryagain=0, trybreak=None, group_queue=[]):
"""Displays the project animation on the screen.
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
sigser -- send signals through serial port when each group is shown
sigpar -- send signals through parallel port when each group is shown
fpbs -- flips per board signal, i.e. number of shape color reversals
(flips) that occur for a unique signal to be sent for that shape
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- Append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- Append a wait screen to the group queue every time
after this many groups have been appended to the queue
group_queue -- queue of groups to be displayed, defaults to order of
groups in project (i.e. groups[0] first, etc.)
"""
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if phototest:
test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Set-up groups and variables that control their display
if group_queue == []:
group_queue = list(self.groups)
cur_group = None
cur_id = -1
flipped = 0
flip_id = -1
groups_duration = sum([group.duration() for group in group_queue])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Initialize ports
if sigser:
if not signals.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if sigpar:
if not signals.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
signals.init(sigser, sigpar)
# Initialize eyetracking
if eyetrack:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
if trybreak == None:
trybreak = len(self.groups)
fixated = False
old_fixated = False
tracked = False
old_tracked = False
cur_fix_fail = False
fail_idlist = []
eyetracking.select_source(etuser, etvideo)
eyetracking.start()
# Stretch to fit screen only if project res does not equal screen res
scaling = False
if fullscreen:
window = pyglet.window.Window(fullscreen=True, visible=False)
if (window.width, window.height) != self.res:
scaling = True
else:
window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
keystates = pyglet.window.key.KeyStateHandler()
window.push_handlers(keystates)
# Create framebuffer object for drawing unscaled scene
if scaling:
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
fbo.end_render()
# Clear window and make visible
window.switch_to()
graphics.set_clear_color(self.bg)
window.clear()
window.set_visible()
# Initialize logging variables
if logtime and logdur:
logstring = ''
stamp = Timer()
dur = Timer()
stamp.start()
dur.start()
elif logtime or logdur:
logstring = ''
timer = Timer()
timer.start()
# Main loop
while not window.has_exit and count < disp_end:
# Clear canvas
if scaling:
fbo.start_render()
fbo.clear()
else:
window.clear()
# Assume no change to group visibility
flipped = 0
signals.set_null()
# Manage groups when they are on_screen
if groups_visible:
# Send special signal if waitscreen ends
if isinstance(cur_group, CkgWaitScreen):
if cur_group.over:
signals.set_user_start()
cur_group = None
elif cur_group != None:
# Check whether group changes in visibility
if cur_group.visible != cur_group.old_visible:
flip_id = self.groups.index(cur_group)
if cur_group.visible:
flipped = 1
elif cur_group.old_visible:
flipped = -1
# Check if current group is over
if cur_group.over:
cur_group = None
# Get next group from queue
if cur_group == None:
cur_id += 1
if cur_id >= len(group_queue):
groups_visible = False
else:
cur_group = group_queue[cur_id]
cur_group.reset()
if eyetrack:
cur_fix_fail = False
if cur_group.visible:
flip_id = self.groups.index(cur_group)
flipped = 1
# Draw and then update group
if cur_group != None:
cur_group.draw()
cur_group.update(fps=self.fps,
fpbs=fpbs,
keystates=keystates)
# Send signals upon group visibility change
if flipped == 1:
signals.set_group_start(flip_id)
# Draw test rectangle
if phototest:
test_rect.draw()
elif flipped == -1:
signals.set_group_stop(flip_id)
if eyetrack:
# First check if eye is being tracked and send signals
old_tracked = tracked
tracked = eyetracking.is_tracked()
if tracked:
if not old_tracked:
# Send signal if eye starts being tracked
signals.set_track_start()
else:
if old_tracked:
# Send signal if eye stops being tracked
signals.set_track_stop()
# Next check for fixation
old_fixated = fixated
fixated = eyetracking.is_fixated(FIX_POS, FIX_RANGE, FIX_PER)
if fixated:
# Draw normal cross color if fixating
fix_crosses[0].draw()
if not old_fixated:
# Send signal if fixation starts
signals.set_fix_start()
else:
# Draw alternative cross color if not fixating
fix_crosses[1].draw()
if old_fixated:
# Send signal if fixation stops
signals.set_fix_stop()
# Take note of which groups in which fixation failed
if not cur_fix_fail and cur_group.visible and\
(tracked and not fixated):
cur_fix_fail = True
if len(fail_idlist) == 0 and trybreak > 0:
group_queue.append(CkgWaitScreen(res=self.res))
fail_idlist.append(self.groups.index(cur_group))
# Append failed group to group queue
if tryagain > 0:
group_queue.append(cur_group)
groups_stop += cur_group.duration() * self.fps
disp_end += cur_group.duration() * self.fps
# Insert waitscreen every trybreak failed groups
if trybreak > 0:
if len(fail_idlist) % trybreak == 0:
group_queue.append(CkgWaitScreen())
tryagain -= 1
# Change cross color based on time if eyetracking is not enabled
if not eyetrack:
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Increment count and set whether groups should be shown
if not isinstance(cur_group, CkgWaitScreen):
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
# Blit canvas to screen if necessary
if scaling:
fbo.end_render()
window.switch_to()
canvas.blit(0, 0)
window.dispatch_events()
window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to log string
if logtime and logdur:
logstring = '\n'.join([logstring, str(stamp.elapsed())])
logstring = '\t'.join([logstring, str(dur.restart())])
elif logtime:
logstring = '\n'.join([logstring, str(timer.elapsed())])
elif logdur:
logstring = '\n'.join([logstring, str(timer.restart())])
# Send signals ASAP after flip
signals.send(sigser, sigpar)
# Log when signals are sent
if logtime or logdur:
if flipped != 0 and (sigser or sigpar):
sigmsg = '{0} sent'.format(signals.STATE)
logstring = '\t'.join([logstring, sigmsg])
# Clean up
if eyetrack:
eyetracking.stop()
window.close()
if scaling:
fbo.delete()
del canvas
signals.quit(sigser, sigpar)
# Write log string to file
if logtime or logdur:
filename = '{0}.log'.format(self.name)
with open(filename, 'w') as logfile:
logfile.write(logstring)
# Return list of ids of failed groups
if eyetrack and len(fail_idlist) > 0:
return fail_idlist
def export(self, export_dir, export_duration, group_queue=[],
export_fmt=None, folder=True, force=False):
if not os.path.isdir(export_dir):
msg = 'export path is not a directory'
raise IOError(msg)
if export_fmt == None:
export_fmt = self.export_fmt
# Set-up groups and variables that control their display
if group_queue == []:
group_queue = list(self.groups)
cur_group = None
cur_id = -1
groups_duration = sum([group.duration() for group in group_queue])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Limit export duration to display duration
frames = export_duration * self.fps
frames = min(frames, disp_end)
# Warn user if a lot of frames will be exported
if frames > MAX_EXPORT_FRAMES and not force:
msg = 'very large number ({0}) of frames to be exported'.\
format(frames)
raise FrameOverflowError(msg)
# Create folder to store images if necessary
if folder:
export_dir = os.path.join(export_dir,
self.name + EXPORT_DIR_SUFFIX)
if not os.path.isdir(export_dir):
os.mkdir(export_dir)
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Set up canvas and framebuffer object
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
# Main loop
while count < frames:
fbo.clear()
if groups_visible:
# Check if current group is over
if cur_group != None:
if cur_group.over:
cur_group = None
# Get next group from queue
if cur_group == None:
cur_id += 1
if cur_id >= len(group_queue):
groups_visible = False
else:
cur_group = group_queue[cur_id]
cur_group.reset()
# Draw and then update group
if cur_group != None:
cur_group.draw()
cur_group.update(fps=self.fps, fpbs=0)
# Draw fixation cross based on current count
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Save current frame to file
savepath = \
os.path.join(export_dir,
'{0}{2}.{1}'.
format(self.name, export_fmt,
repr(count).zfill(numdigits(frames-1))))
canvas.save(savepath)
# Increment count and set whether groups should be shown
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
fbo.delete()
class CkgDisplayGroup:
DEFAULTS = {'pre': 0, 'disp': 'Infinity', 'post': 0}
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets internal count and all contained shapes."""
self._count = 0
self._start = self.pre
self._stop = self.pre + self.disp
self._end = self.pre + self.disp + self.post
self.over = False
self.old_visible = False
if self._start == 0 and self._stop > 0:
self.visible = True
else:
self.visible = False
if self._end == 0:
self.over = True
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, lazy=False):
"""Draws all contained shapes during the appropriate interval."""
if self.visible:
for shape in self.shapes:
if lazy:
shape.lazydraw()
else:
shape.draw()
def update(self, **keywords):
"""Increments internal count, makes group visible when appropriate.
fps -- refresh rate of the display in frames per second
fpbs -- flips per board signal, i.e. number of shape color reversals
(flips) that occur for a unique signal to be sent for that shape
"""
fps = keywords['fps']
fpbs = keywords['fpbs']
if self.visible:
# Set triggers to be sent
if fpbs > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= fpbs:
signals.set_board_flip(n)
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(fps)
# Increment count and set flags for the next frame
self._count += 1
self.old_visible = self.visible
if (self._start * fps) <= self._count < (self._stop * fps):
self.visible = True
else:
self.visible = False
if self._count >= (self._end * fps):
self.over = True
else:
self.over = False
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.visible = False
self.old_visible = False
self.steps_done = 0
self.over = False
def draw(self):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, **keywords):
"""Checks for keypress, sends signal upon end."""
keystates = keywords['keystates']
if max([keystates[key] for key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
if self.steps_done == self.num_steps:
self.over = True
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = {'dims': (5, 5),
'init_unit': (30, 30), 'end_unit': (50, 50),
'position': (0, 0), 'anchor': 'bottomleft',
'cols': ((0, 0, 0), (255, 255, 255)),
'freq': 1, 'phase': 0}
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
- degs_per_frame = 360 * self.freq / fps
+ if INTEGER_CYCLES:
+ frames_per_half_cycle = round(fps / (self.freq * 2))
+ degs_per_frame = 180 / to_decimal(frames_per_half_cycle)
+ else:
+ degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
if PRERENDER_TO_TEXTURE:
init_pos = [(1 - a)* s/to_decimal(2) for s, a in
zip(self._size, graphics.locations[self.anchor])]
else:
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
anchor=self.anchor)
cur_unit_rect.col = self.cols[(i + j) % 2]
cur_unit_rect.add_to_batch(self._batches[0])
cur_unit_rect.col = self.cols[(i + j + 1) % 2]
cur_unit_rect.add_to_batch(self._batches[1])
# Increase x values
cur_unit_pos[0] += \
graphics.locations[self.anchor][0] * cur_unit[0]
cur_unit[0] += unit_grad[0]
# Reset x values
cur_unit_pos[0] = init_pos[0]
cur_unit[0] = init_unit[0]
# Increase y values
cur_unit_pos[1] += \
graphics.locations[self.anchor][1] * cur_unit[1]
cur_unit[1] += unit_grad[1]
if PRERENDER_TO_TEXTURE:
# Create textures
int_size = [int(round(s)) for s in self._size]
self._prerenders =\
[pyglet.image.Texture.create(*int_size) for n in range(2)]
# Set up framebuffer
fbo = graphics.Framebuffer()
for n in range(2):
fbo.attach_texture(self._prerenders[n])
# Draw batch to texture
fbo.start_render()
self._batches[n].draw()
fbo.end_render()
# Anchor textures for correct blitting later
self._prerenders[n].anchor_x, self._prerenders[n].anchor_y =\
[int(round((1 - a)* s/to_decimal(2))) for s, a in
zip(self._size, graphics.locations[self.anchor])]
fbo.delete()
# Delete batches since they won't be used
del self._batches
self._computed = True
def draw(self, always_compute=False):
"""Draws appropriate prerender depending on current phase."""
if not self._computed or always_compute:
self.compute()
self._cur_phase %= 360
n = int(self._cur_phase // 180)
if PRERENDER_TO_TEXTURE:
self._prerenders[n].blit(*self.position)
else:
self._batches[n].draw()
def lazydraw(self):
"""Only draws on color reversal."""
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if (cur_n != prev_n) or self._first_draw:
self.draw()
if self._first_draw:
self._first_draw = False
diff --git a/src/utils.py b/src/utils.py
index 313649c..108c640 100644
--- a/src/utils.py
+++ b/src/utils.py
@@ -1,84 +1,84 @@
"""Utility functions and classes."""
import os
import time
import math
from decimal import *
def numdigits(x):
"""Returns number of digits in a decimal integer."""
if x == 0:
return 1
elif x < 0:
x = -x
return int(math.log(x, 10)) + 1
def public_dir(obj):
"""Returns all 'public' attributes of an object"""
names = dir(obj)
for name in names[:]:
if name[0] == '_' or name[-1] == '_':
names.remove(name)
return names
def to_decimal(s):
"""ValueError raising Decimal converter."""
try:
return Decimal(s)
- except InvalidOperation:
+ except (InvalidOperation, TypeError):
try:
return Decimal(str(s))
- except InvalidOperation:
+ except (InvalidOperation, TypeError):
raise ValueError
def to_color(s, sep=','):
"""Tries to cast a string to a color (3-tuple)."""
c = tuple([int(x) for x in s.split(sep)])
if len(c) != 3:
raise ValueError
return c
class Timer:
"""High-res timer that should be cross-platform."""
def __init__(self):
# Assigns appropriate clock function based on OS
if os.name == 'nt':
self.clock = time.clock
self.clock()
elif os.name == 'posix':
self.clock = time.time
self.running = False
def start(self):
self.start_time = self.clock()
self.running = True
def stop(self):
if not self.running:
return None
self.stop_time = self.clock()
self.running = False
return self.stop_time - self.start_time
def elapsed(self):
if not self.running:
return None
cur_time = self.clock()
return cur_time - self.start_time
def restart(self):
old_start_time = self.start_time
self.start_time = self.clock()
self.running = True
return self.start_time - old_start_time
def tick(self, fps):
"""Limits loop to specified fps. To be placed at start of loop."""
fps = float(fps)
ret = self.elapsed()
if self.elapsed() != -1:
while self.elapsed() < (1.0 / fps):
pass
self.start()
if ret != -1:
return ret * 1000
|
ztangent/checkergen
|
a4e4dfe5469c0f3bd816ce34c0d7bd46bc7de308
|
Failed groups now get logged to block files. Catch shlex errors.
|
diff --git a/src/cli.py b/src/cli.py
index 105e3bd..c8c87d8 100644
--- a/src/cli.py
+++ b/src/cli.py
@@ -1,1119 +1,1150 @@
"""Defines command-line-interface for checkergen."""
import os
import sys
if os.name == 'posix':
import readline
import argparse
import cmd
import shlex
import core
import priority
import eyetracking
from graphics import locations
from utils import *
CMD_PROMPT = '(ckg) '
CMD_EOF_STRING = 'Ctrl-D'
if sys.platform == 'win32':
CMD_EOF_STRING = 'Ctrl-Z + Enter'
CMD_INTRO = '\n'.join(["Enter 'help' for a list of commands.",
"Enter 'quit' or {0} to exit.".format(CMD_EOF_STRING)])
def store_tuple(nargs, sep, typecast=None, castargs=[]):
"""Returns argparse action that stores a tuple."""
class TupleAction(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
vallist = values.split(sep)
if len(vallist) != nargs:
msg = ("argument '{f}' should be a list of " +
"{nargs} values separated by '{sep}'").\
format(f=self.dest,nargs=nargs,sep=sep)
raise argparse.ArgumentError(self, msg)
if typecast != None:
for n, val in enumerate(vallist):
try:
val = typecast(*([val] + castargs))
vallist[n] = val
except (ValueError, TypeError):
msg = ("element '{val}' of argument '{f}' " +
"is of the wrong type").\
format(val=vallist[n],f=self.dest)
raise argparse.ArgumentError(self, msg)
setattr(args, self.dest, tuple(vallist))
return TupleAction
# The main parser invoked at the command-line
PARSER = argparse.ArgumentParser(
description='''Generate flashing checkerboard patterns for display
or export as a series of images, intended for use in
psychophysics experiments. Enters interactive command
line mode if no options are specified.''')
PARSER.add_argument('-c', '--cmd', dest='cmd_mode', action='store_true',
help='enter command line mode regardless of other options')
PARSER.add_argument('-d', '--display',
dest='display_flag', action='store_true',
help='displays the animation on the screen')
PARSER.add_argument('-e', '--export', dest='export_dur', metavar='DUR',
help='export DUR seconds of the project animation')
PARSER.add_argument('-f', '--fullscreen', action='store_true',
help='animation displayed in fullscreen mode')
# PARSER.add_argument('--fmt', dest='export_fmt', choices=core.EXPORT_FMTS,
# help='image format for animation to be exported as')
PARSER.add_argument('--dir', dest='export_dir',
default=os.getcwd(), metavar='PATH',
help='''destination directory for export
(default: current working directory)''')
PARSER.add_argument('path', metavar='project', nargs='?', type=file,
help='checkergen project file to open')
def process_args(args):
"""Further processes the arguments returned by the main parser."""
if args.export_dur != None:
args.export_flag = True
else:
args.export_flag = False
if not args.display_flag and not args.export_flag:
args.cmd_mode = True
if args.path != None:
if not os.path.isfile(args.path):
msg = 'error: path specified is not a file'
return msg
args.proj = core.CkgProj(path=args.path)
os.chdir(os.path.dirname(os.path.abspath(args.path)))
try:
args.group = args.proj.groups[0]
except IndexError:
args.group = None
else:
args.proj = None
args.group = None
if args.display_flag or args.export_flag:
msg = 'error: no project file specified for display or export'
return msg
class CmdParserError(Exception):
"""To be raised when CmdParser encounters an error."""
pass
class CmdParser(argparse.ArgumentParser):
"""Override ArgumentParser so that it doesn't exit the program."""
def error(self, msg):
raise CmdParserError(msg)
class CkgCmd(cmd.Cmd):
@staticmethod
def yn_parse(s):
if s in ['y', 'Y', 'yes', 'YES', 'Yes']:
return True
elif s in ['n', 'N', 'no', 'NO', 'No']:
return False
else:
msg = "only 'y','n' or variants accepted"
raise ValueError(msg)
def save_check(self, msg=None):
"""Checks and prompts the user to save if necessary."""
if self.cur_proj == None:
return
if not self.cur_proj.is_dirty():
return
if msg == None:
msg = 'Would you like to save the current project first? (y/n)'
print msg
while True:
try:
if self.__class__.yn_parse(raw_input()):
self.do_save('')
break
except TypeError:
print str(sys.exc_value)
except EOFError:
return True
def do_new(self, line):
"""Creates new project with given name (can contain whitespace)."""
name = line.strip().strip('"\'')
if len(name) == 0:
name = 'untitled'
if self.save_check():
return
self.cur_proj = core.CkgProj(name=name)
print 'project \'{0}\' created'.format(self.cur_proj.name)
def do_open(self, line):
"""Open specified project file."""
path = line.strip().strip('"\'')
if len(path) == 0:
print 'error: no path specified'
return
if not os.path.isfile(path):
print 'error: path specified is not a file'
return
if self.save_check():
return
try:
self.cur_proj = core.CkgProj(path=path)
except (core.FileFormatError, IOError):
print "error:", str(sys.exc_value)
return
os.chdir(os.path.dirname(os.path.abspath(path)))
try:
self.cur_group = self.cur_proj.groups[0]
except IndexError:
self.cur_group = None
print 'project \'{0}\' loaded'.format(self.cur_proj.name)
def do_close(self, line):
"""Prompts the user to save, then closes current project."""
if self.cur_proj == None:
print 'no project to close'
return
if self.save_check():
return
self.cur_proj = None
print 'project closed'
def do_save(self, line):
"""Saves the current project to the specified path."""
if self.cur_proj == None:
print 'no project to save'
return
path = line.strip().strip('"\'')
if len(path) == 0:
path = os.getcwd()
path = os.path.abspath(path)
if os.path.isdir(path):
path = os.path.join(path,
'.'.join([self.cur_proj.name, core.CKG_FMT]))
elif os.path.isdir(os.path.dirname(path)):
pass
else:
print 'error: specified directory does not exist'
return
# project save will add file extension if necessary
try:
path = self.cur_proj.save(path)
except IOError:
print "error:", str(sys.exc_value)
return
print 'project saved to "{0}"'.format(path)
set_parser = CmdParser(add_help=False, prog='set',
description='''Sets various project settings.''')
set_parser.add_argument('--name', help='''project name, always the same as
the filename without
the extension''')
set_parser.add_argument('--fps', type=to_decimal,
help='''number of animation frames
rendered per second''')
set_parser.add_argument('--res', action=store_tuple(2, ',', int),
help='animation canvas size/resolution in pixels',
metavar='WIDTH,HEIGHT')
set_parser.add_argument('--bg', metavar='COLOR', type=to_color,
help='''background color of the canvas
(color format: R,G,B,
component range from 0-255)''')
# set_parser.add_argument('--fmt', dest='export_fmt',
# choices=core.EXPORT_FMTS,
# help='''image format for animation
# to be exported as''')
set_parser.add_argument('--pre', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown before any display groups''')
set_parser.add_argument('--post', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown after all display groups''')
set_parser.add_argument('--cross_cols', metavar='COLOR1,COLOR2',
action=store_tuple(2, ',', to_color, [';']),
help='''fixation cross coloration
(color format: R;G;B,
component range from 0-255)''')
set_parser.add_argument('--cross_times', metavar='TIME1,TIME2',
action=store_tuple(2, ',', to_decimal),
help='''time in seconds each cross color
will be displayed''')
def help_set(self):
self.__class__.set_parser.print_help()
def do_set(self, line):
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
try:
args = self.__class__.set_parser.parse_args(shlex.split(line))
- except CmdParserError:
+ except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.set_parser.print_usage()
return
names = public_dir(args)
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
setattr(self.cur_proj, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.set_parser.print_usage()
mkgrp_parser = CmdParser(add_help=False, prog='mkgrp',
formatter_class=
argparse.ArgumentDefaultsHelpFormatter,
description='''Makes a new display group
with the given parameters.''')
mkgrp_parser.add_argument('pre', type=to_decimal, default=0, nargs='?',
help='''time in seconds a blank screen will
be shown before shapes are displayed''')
mkgrp_parser.add_argument('disp', type=to_decimal,
nargs='?', default='Infinity',
help='''time in seconds shapes will be
displayed''')
mkgrp_parser.add_argument('post', type=to_decimal, default=0, nargs='?',
help='''time in seconds a blank screen will
be shown after shapes are displayed''')
def help_mkgrp(self):
self.__class__.mkgrp_parser.print_help()
def do_mkgrp(self, line):
"""Makes a display group with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
try:
args = self.__class__.mkgrp_parser.parse_args(shlex.split(line))
- except CmdParserError:
+ except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mkgrp_parser.print_usage()
return
group_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_group = core.CkgDisplayGroup(**group_dict)
new_id = self.cur_proj.add_group(new_group)
print "display group", new_id, "added"
self.cur_group = new_group
print "group", new_id, "is now the current display group"
edgrp_parser = CmdParser(add_help=False, prog='edgrp',
description='''Edits attributes of display groups
specified by ids.''')
edgrp_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='ids of display groups to be edited')
edgrp_parser.add_argument('--pre', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown before shapes are displayed''')
edgrp_parser.add_argument('--disp', type=to_decimal, metavar='SECONDS',
help='''time in seconds shapes will be
displayed''')
edgrp_parser.add_argument('--post', type=to_decimal, metavar='SECONDS',
help='''time in seconds a blank screen will
be shown after shapes are displayed''')
def help_edgrp(self):
self.__class__.edgrp_parser.print_help()
def do_edgrp(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.edgrp_parser.parse_args(shlex.split(line))
- except CmdParserError:
+ except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.edgrp_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_proj.groups) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_group_attr(x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.edgrp_parser.print_usage()
rmgrp_parser = CmdParser(add_help=False, prog='rmgrp',
description='''Removes display groups specified
by ids.''')
rmgrp_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='ids of display groups to be removed')
rmgrp_parser.add_argument('-a', '--all', action='store_true',
help='remove all groups from the project')
def help_rmgrp(self):
self.__class__.rmgrp_parser.print_help()
def do_rmgrp(self, line):
"""Removes display groups specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups to remove'
return
try:
args = self.__class__.rmgrp_parser.parse_args(shlex.split(line))
- except CmdParserError:
+ except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rmgrp_parser.print_usage()
return
rmlist = []
if args.all:
for group in self.cur_proj.groups[:]:
self.cur_proj.del_group(group)
print "all display groups removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_proj.groups) or x < 0:
print "display group", x, "does not exist"
continue
rmlist.append(self.cur_proj.groups[x])
print "display group", x, "removed"
for group in rmlist:
self.cur_proj.del_group(group)
# Remember to point self.cur_group somewhere sane
if self.cur_group not in self.cur_proj.groups:
if len(self.cur_proj.groups) == 0:
self.cur_group = None
else:
self.cur_group = self.cur_proj.groups[0]
print "group 0 is now the current display group"
chgrp_parser = CmdParser(add_help=False, prog='chgrp',
description='''Changes display group that is
currently active for editing.
Prints current group id if
no group id is specified''')
chgrp_parser.add_argument('gid', metavar='id', type=int, nargs='?',
help='id of display group to be made active')
def help_chgrp(self):
self.__class__.chgrp_parser.print_help()
def do_chgrp(self, line):
"""Changes group that is currently active for editing."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups that can be made active'
return
try:
args = self.__class__.chgrp_parser.parse_args(shlex.split(line))
- except CmdParserError:
+ except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.chgrp_parser.print_usage()
return
if args.gid == None:
print "group",\
self.cur_proj.groups.index(self.cur_group),\
"is the current display group"
elif args.gid >= len(self.cur_proj.groups) or args.gid < 0:
print "group", args.gid, "does not exist"
else:
self.cur_group = self.cur_proj.groups[args.gid]
print "group", args.gid, "is now the current display group"
mk_parser = CmdParser(add_help=False, prog='mk',
description='''Makes a new checkerboard in the
current group with the given
parameters.''')
mk_parser.add_argument('dims', action=store_tuple(2, ',', to_decimal),
help='''width,height of checkerboard in no. of
unit cells''')
mk_parser.add_argument('init_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of initial unit cell in pixels')
mk_parser.add_argument('end_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of final unit cell in pixels')
mk_parser.add_argument('position', action=store_tuple(2, ',', to_decimal),
help='x,y position of checkerboard in pixels')
mk_parser.add_argument('anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='anchor')
mk_parser.add_argument('cols', action=store_tuple(2, ',', to_color, [';']),
help='''color1,color2 of the checkerboard
(color format: R;G;B,
component range from 0-255)''')
mk_parser.add_argument('freq', type=to_decimal,
help='frequency of color reversal in Hz')
mk_parser.add_argument('phase', type=to_decimal, nargs='?', default='0',
help='initial phase of animation in degrees')
def help_mk(self):
self.__class__.mk_parser.print_help()
def do_mk(self, line):
"""Makes a checkerboard with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
if self.cur_group == None:
print 'automatically adding display group...'
self.do_mkgrp('')
try:
args = self.__class__.mk_parser.parse_args(shlex.split(line))
- except CmdParserError:
+ except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mk_parser.print_usage()
return
shape_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_shape = core.CheckerBoard(**shape_dict)
new_id = self.cur_proj.add_shape_to_group(self.cur_group, new_shape)
print "checkerboard", new_id, "added"
ed_parser = CmdParser(add_help=False, prog='ed',
description='''Edits attributes of checkerboards
specified by ids.''')
ed_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='''ids of checkerboards in the current
group to be edited''')
ed_parser.add_argument('--dims', action=store_tuple(2, ',', to_decimal),
help='checkerboard dimensions in unit cells',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--init_unit',
action=store_tuple(2, ',', to_decimal),
help='initial unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--end_unit',
action=store_tuple(2, ',', to_decimal),
help='final unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--position',
action=store_tuple(2, ',', to_decimal),
help='position of checkerboard in pixels',
metavar='X,Y')
ed_parser.add_argument('--anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='LOCATION')
ed_parser.add_argument('--cols', metavar='COLOR1,COLOR2',
action=store_tuple(2, ',', to_color, [';']),
help='''checkerboard colors (color format:
R;G;B, component range
from 0-255)''')
ed_parser.add_argument('--freq', type=to_decimal,
help='frequency of color reversal in Hz')
ed_parser.add_argument('--phase', type=to_decimal,
help='initial phase of animation in degrees')
def help_ed(self):
self.__class__.ed_parser.print_help()
def do_ed(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, please create one first'
return
try:
args = self.__class__.ed_parser.parse_args(shlex.split(line))
- except CmdParserError:
+ except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ed_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_group.shapes) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_shape_attr(self.cur_group, x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.ed_parser.print_usage()
rm_parser = CmdParser(add_help=False, prog='rm',
description='''Removes checkerboards specified
by ids.''')
rm_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''ids of checkerboards in the current group
to be removed''')
rm_parser.add_argument('-a', '--all', action='store_true',
help='''remove all checkerboards in the
current group''')
def help_rm(self):
self.__class__.rm_parser.print_help()
def do_rm(self, line):
"""Removes checkerboards specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, no boards to remove'
return
try:
args = self.__class__.rm_parser.parse_args(shlex.split(line))
- except CmdParserError:
+ except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.rm_parser.print_usage()
return
rmlist = []
if args.all:
for shape in self.cur_group.shapes:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
print "all checkerboards removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_group.shapes) or x < 0:
print "checkerboard", x, "does not exist"
continue
rmlist.append(self.cur_group.shapes[x])
print "checkerboard", x, "removed"
for shape in rmlist:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
ls_parser = CmdParser(add_help=False, prog='ls',
description='''Lists project, display group and
checkerboard settings. If no group ids
are specified, all display groups
are listed.''')
ls_parser.add_argument('gidlist', nargs='*', metavar='gid', type=int,
help='''ids of the display groups to be listed''')
ls_group = ls_parser.add_mutually_exclusive_group()
ls_group.add_argument('-s', '--settings', action='store_true',
help='list only project settings')
ls_group.add_argument('-g', '--groups', action='store_true',
help='list only display groups')
def help_ls(self):
self.__class__.ls_parser.print_help()
def do_ls(self, line):
"""Lists project, display group and checkerboard settings."""
def ls_str(s, seps=[',',';']):
"""Special space-saving output formatter."""
if type(s) in [tuple, list]:
if len(seps) > 1:
newseps = seps[1:]
else:
newseps = seps
return seps[0].join([ls_str(i, newseps) for i in s])
else:
return str(s)
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.ls_parser.parse_args(shlex.split(line))
- except CmdParserError:
+ except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.ls_parser.print_usage()
return
# Remove duplicates and ascending sort
args.gidlist = sorted(set(args.gidlist))
if len(self.cur_proj.groups) == 0:
if len(args.gidlist) > 0:
print 'this project has no display groups that can be listed'
args.settings = True
else:
for gid in args.gidlist[:]:
if gid >= len(self.cur_proj.groups) or gid < 0:
args.gidlist.remove(gid)
print 'display group', gid, 'does not exist'
if args.gidlist == []:
args.gidlist = range(len(self.cur_proj.groups))
else:
# If any (valid) groups are specified
# don't show project settings
args.groups = True
if not args.groups:
print 'PROJECT SETTINGS'.center(70,'*')
print \
'name'.rjust(16),\
'fps'.rjust(7),\
'resolution'.rjust(14),\
'bg color'.rjust(18)
# 'format'.rjust(7)
print \
ls_str(self.cur_proj.name).rjust(16),\
ls_str(self.cur_proj.fps).rjust(7),\
ls_str(self.cur_proj.res).rjust(14),\
ls_str(self.cur_proj.bg).rjust(18)
# ls_str(self.cur_proj.export_fmt).rjust(7)
print \
'pre-display'.rjust(26),\
'post-display'.rjust(26)
print \
ls_str(self.cur_proj.pre).rjust(26),\
ls_str(self.cur_proj.post).rjust(26)
print \
'cross colors'.rjust(26),\
'cross times'.rjust(26)
print \
ls_str(self.cur_proj.cross_cols).rjust(26),\
ls_str(self.cur_proj.cross_times).rjust(26)
if not args.settings and not args.groups:
# Insert empty line if both groups and project
# settings are listed
print ''
if not args.settings:
for i, n in enumerate(args.gidlist):
if i != 0:
# Print newline seperator between each group
print ''
group = self.cur_proj.groups[n]
print 'GROUP {n}'.format(n=n).center(70,'*')
print \
'pre-display'.rjust(20),\
'display'.rjust(20),\
'post-display'.rjust(20)
print \
ls_str(group.pre).rjust(20),\
ls_str(group.disp).rjust(20),\
ls_str(group.post).rjust(20)
if len(group.shapes) > 0:
print \
''.rjust(2),\
'shape id'.rjust(8),\
'dims'.rjust(10),\
'init_unit'.rjust(14),\
'end_unit'.rjust(14),\
'position'.rjust(14)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.dims).rjust(10),\
ls_str(shape.init_unit).rjust(14),\
ls_str(shape.end_unit).rjust(14),\
ls_str(shape.position).rjust(14)
print '\n',\
''.rjust(2),\
'shape id'.rjust(8),\
'colors'.rjust(27),\
'anchor'.rjust(12),\
'freq'.rjust(6),\
'phase'.rjust(7)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.cols).rjust(27),\
ls_str(shape.anchor).rjust(12),\
ls_str(shape.freq).rjust(6),\
ls_str(shape.phase).rjust(7)
display_parser = CmdParser(add_help=False, prog='display',
description='''Displays the animation in a
window or in fullscreen.''')
display_parser.add_argument('-b', '--block', metavar='PATH',
help='''read flags and dislay group order from
specified file, ignore other flags''')
display_parser.add_argument('-f', '--fullscreen', action='store_true',
help='sets fullscreen mode, ESC to quit')
display_parser.add_argument('-p', '--priority', metavar='LEVEL',
help='''set priority while displaying,
higher priority results in
less dropped frames (choices:
0-3, low, normal, high,
realtime)''')
display_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly display specified display
groups N number of times''')
display_parser.add_argument('-pt', '--phototest', action='store_true',
help='''draw white test rectangle in topleft
corner of screen when groups become
visible for a photodiode to detect''')
display_parser.add_argument('-lt', '--logtime', action='store_true',
help='output frame timestamps to a log file')
display_parser.add_argument('-ld', '--logdur', action='store_true',
help='output frame durations to a log file')
display_parser.add_argument('-ss', '--sigser', action='store_true',
help='''send signals through the serial port
when shapes are being displayed''')
display_parser.add_argument('-sp', '--sigpar', action='store_true',
help='''send signals through the parallel port
when shapes are being displayed''')
- display_parser.add_argument('-fpbs', metavar='N', type=int, default=0,
+ display_parser.add_argument('-fpbs', metavar='M', type=int, default=0,
help='''unique signal corresponding to a
checkerboard is sent after the board
- undergoes N color reversals (flips),
- set to 0 to disable''')
+ undergoes M color flips (default:
+ disabled, M=0)''')
display_parser.add_argument('-et', '--eyetrack', action='store_true',
help='''use eyetracking to ensure that subject
fixates on the cross in the center''')
display_parser.add_argument('-eu', '--etuser', action='store_true',
help='''allow user to select eyetracking video
source from a dialog''')
display_parser.add_argument('-ev', '--etvideo', metavar='path',
help='''path (with no spaces) to eyetracking
video file to be used as the source''')
+ display_parser.add_argument('-ta', '--tryagain', metavar='I',
+ type=int, default=0,
+ help='''append groups during which subject
+ failed to fixate up to I times to the
+ list of groups to be displayed
+ (default: disabled, I=0)''')
+ display_parser.add_argument('-tb', '--trybreak', metavar='J', type=int,
+ help='''used with --tryagain, append a wait
+ screen to the list of groups to be
+ displayed after every J groups have
+ been appended to the list (default:
+ J=total number of groups)''')
display_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be displayed
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_display(self):
self.__class__.display_parser.print_help()
def do_display(self, line):
"""Displays the animation in a window or in fullscreen"""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.display_parser.parse_args(shlex.split(line))
- except CmdParserError:
+ except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
if args.block != None:
+ blkpath = args.block
try:
- blkdict = core.CkgProj.readblk(args.block)
+ blkdict = core.CkgProj.readblk(blkpath)
flags = blkdict['flags']
try:
args = self.__class__.\
display_parser.parse_args(shlex.split(flags))
args.idlist = blkdict['idlist']
- except CmdParserError:
+ except (CmdParserError, ValueError):
print 'error: invalid flags stored in block file'
return
except IOError:
print "error:", str(sys.exc_value)
return
+ else:
+ blkpath = None
group_queue = []
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < -1:
print 'error: group', i, 'does not exist'
return
for i in args.idlist:
if i == -1:
group_queue.append(core.CkgWaitScreen(res=
self.cur_proj.res))
else:
group_queue.append(self.cur_proj.groups[i])
else:
group_queue = list(self.cur_proj.groups)
if args.repeat != None:
group_queue = list(group_queue * args.repeat)
+ if args.eyetrack and eyetracking.available:
+ if not eyetracking.is_calibrated():
+ try:
+ self.do_calibrate('',True)
+ except eyetracking.EyetrackingError:
+ print "error:", str(sys.exc_value)
+ return
+
if args.priority != None:
if not priority.available:
print "error: setting priority not avaible on", sys.platform
print "continuing..."
else:
if args.priority.isdigit():
args.priority = int(args.priority)
try:
priority.set(args.priority)
except ValueError:
print "error:", str(sys.exc_value)
print "continuing..."
- if args.eyetrack and eyetracking.available:
- if not eyetracking.is_calibrated():
- try:
- self.do_calibrate('',True)
- except eyetracking.EyetrackingError:
- print "error:", str(sys.exc_value)
- return
-
try:
- self.cur_proj.display(fullscreen=args.fullscreen,
- logtime=args.logtime,
- logdur=args.logdur,
- sigser=args.sigser,
- sigpar=args.sigpar,
- fpbs=args.fpbs,
- phototest=args.phototest,
- eyetrack=args.eyetrack,
- etuser=args.etuser,
- etvideo=args.etvideo,
- group_queue=group_queue)
+ fail_idlist = self.cur_proj.display(fullscreen=args.fullscreen,
+ logtime=args.logtime,
+ logdur=args.logdur,
+ sigser=args.sigser,
+ sigpar=args.sigpar,
+ fpbs=args.fpbs,
+ phototest=args.phototest,
+ eyetrack=args.eyetrack,
+ etuser=args.etuser,
+ etvideo=args.etvideo,
+ tryagain=args.tryagain,
+ trybreak=args.trybreak,
+ group_queue=group_queue)
except (IOError, NotImplementedError, eyetracking.EyetrackingError):
print "error:", str(sys.exc_value)
+ if args.priority != None:
+ try:
+ priority.set('normal')
+ except:
+ pass
return
if args.priority != None:
try:
priority.set('normal')
except:
pass
+ # Append list of ids of failed groups to block file
+ if fail_idlist != None and blkpath != None:
+ try:
+ core.CkgProj.addtoblk(blkpath, fail_idlist,
+ len(self.cur_proj.groups))
+ except IOError:
+ print "error:", str(sys.exc_value)
+ return
+
export_parser = CmdParser(add_help=False, prog='export',
description='''Exports animation as an image
sequence (in a folder) to the
specified directory.''')
# export_parser.add_argument('--fmt', dest='export_fmt',
# choices=core.EXPORT_FMTS,
# help='image format for export')
export_parser.add_argument('-n','--nofolder',
dest='folder', action='store_false',
help='''force images not to exported in
a containing folder''')
export_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly export specified display
groups N number of times''')
export_parser.add_argument('duration', nargs='?',
type=to_decimal, default='Infinity',
help='''number of seconds of the animation
that should be exported (default:
as long as the entire animation)''')
export_parser.add_argument('dir', nargs='?', default=os.getcwd(),
help='''destination directory for export
(default: current working directory)''')
export_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be exported
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_export(self):
self.__class__.export_parser.print_help()
def do_export(self, line):
"""Exports animation an image sequence to the specified directory."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.export_parser.parse_args(shlex.split(line))
- except CmdParserError:
+ except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.export_parser.print_usage()
return
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < 0:
print 'error: group', i, 'does not exist'
return
group_queue = [self.cur_proj.groups[i] for i in args.idlist]
else:
group_queue = list(self.cur_proj.groups)
if args.repeat != None:
group_queue = list(group_queue * args.repeat)
try:
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
group_queue=group_queue,
folder=args.folder)
except IOError:
print "error:", str(sys.exc_value)
return
except core.FrameOverflowError:
print "warning:", str(sys.exc_value)
print "Are you sure you want to continue?"
while True:
try:
if self.__class__.yn_parse(raw_input()):
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
group_queue=group_queue,
export_fmt=None,
folder=args.folder,
force=True)
break
else:
return
except TypeError:
print str(sys.exc_value)
except EOFError:
return
print "Export done."
mkblks_parser = CmdParser(add_help=False, prog='mkblks',
description='''Generates randomized experimental
blocks from display groups and
saves each as a CSV file.''')
mkblks_parser.add_argument('-n','--nofolder',
dest='folder', action='store_false',
help='''force block files not to be saved in
a containing folder''')
mkblks_parser.add_argument('-d','--dir', default=os.getcwd(),
help='''where to save block files
(default: current working directory)''')
mkblks_parser.add_argument('length', type=int,
help='''no. of repeated trials in a block''')
mkblks_parser.add_argument('flags', nargs='?', default='',
help='''flags passed to the display command
that should be used when the block
file is run (enclose in quotes and use
'+' or '++' in place of '-' or '--')''')
def help_mkblks(self):
self.__class__.mkblks_parser.print_help()
def do_mkblks(self, line):
"""Generates randomized experimental blocks from display groups."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.mkblks_parser.parse_args(shlex.split(line))
- except CmdParserError:
+ except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.mkblks_parser.print_usage()
return
args.flags = args.flags.replace('+','-')
try:
disp_args = self.__class__.display_parser.\
parse_args(shlex.split(args.flags))
- except CmdParserError:
+ except (CmdParserError, ValueError):
print "error: invalid flags to display command"
print str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
try:
self.cur_proj.mkblks(args.length,
path=args.dir,
folder=args.folder,
flags=args.flags)
except IOError:
print "error:", str(sys.exc_value)
return
print "Experimental blocks generated."
def do_calibrate(self, line, query=False):
"""Calibrate subject for eyetracking, or load a calibration file."""
if not eyetracking.available:
print "error: eyetracking functionality not available"
return
if query:
print "path to calibration file (leave empty for GUI tool):"
try:
path = raw_input().strip().strip('"\'')
except EOFError:
msg = "calibration cancelled"
raise eyetracking.EyetrackingError(msg)
else:
path = line.strip().strip('"\'')
if len(path) == 0:
path = None
if not eyetracking.is_source_ready():
# Select default source if none has been selected
eyetracking.select_source()
try:
eyetracking.calibrate(path)
except eyetracking.EyetrackingError:
if query:
raise
else:
print "error:", str(sys.exc_value)
return
if len(path) > 0:
print "calibration file successfully loaded"
etsetup_parser = CmdParser(add_help=False, prog='etsetup',
description='''Set various eyetracking
parameters.''')
etsetup_parser.add_argument('-fp', '--fixperiod', type=int, metavar='MS',
help='''time in milliseconds subject
has to stare at the same spot
for fixation to be detected''')
etsetup_parser.add_argument('-fr', '--fixrange', type=float, metavar='MM',
help='''distance in mm beyond which the
eye position cannot change for
a fixation to be detected''')
etsetup_parser.add_argument('-s', '--size', metavar='WIDTH,HEIGHT',
action=store_tuple(2, ',', float),
help='physical screen dimensions in mm')
etsetup_parser.add_argument('-vd', '--viewdist', type=int, metavar='MM',
help='''viewing distance between subject's
eyes and the screen''')
def help_etsetup(self):
self.__class__.etsetup_parser.print_help()
def do_etsetup(self, line):
try:
args = self.__class__.etsetup_parser.parse_args(shlex.split(line))
- except CmdParserError:
+ except (CmdParserError, ValueError):
print "error:", str(sys.exc_value)
self.__class__.etsetup_parser.print_usage()
return
try:
eyetracking.setup(viewing_distance=args.viewdist,
screen_dims=args.size,
fixation_period=args.fixperiod,
fixation_range=args.fixrange)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
def do_quit(self, line):
"""Quits the program."""
if self.save_check():
return
return True
def help_EOF(self):
print "Typing {0} issues this command, which quits the program."\
.format(CMD_EOF_STRING)
def do_EOF(self, line):
"""Typing Ctrl-D issues this command, which quits the program."""
print '\r'
if self.save_check():
return
return True
def help_help(self):
print 'Prints a list of commands.'
print "Type 'help <topic>' for more details on each command."
def default(self, line):
command = line.split()[0]
print \
"'{0}' is not a checkergen command.".format(command),\
"Type 'help' for a list of commands"
diff --git a/src/core.py b/src/core.py
index ef816ca..7517841 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,1110 +1,1130 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import itertools
from xml.dom import minidom
import pyglet
import graphics
import signals
import eyetracking
from utils import *
CKG_FMT = 'ckg'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
MAX_EXPORT_FRAMES = 100000
PRERENDER_TO_TEXTURE = False
EXPORT_FMTS = ['png']
EXPORT_DIR_SUFFIX = '-anim'
BLOCK_DIR_SUFFIX = '-blks'
FIX_POS = (0, 0)
FIX_RANGE = (20, 20)
FIX_PER = 350
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = {'name': 'untitled',
'fps': 60,
'res': (800, 600),
'bg': (127, 127, 127),
'export_fmt': 'png',
'pre': 0,
'post': 0,
'cross_cols': ((0, 0, 0), (255, 0, 0)),
'cross_times': ('Infinity', 1)}
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
export_fmt -- image format for animation to be exported as
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'export_fmt':
if value not in EXPORT_FMTS:
msg = 'image format not recognized or supported'
raise FileFormatError(msg)
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if ext == '.{0}'.format(CKG_FMT):
self.name = name
else:
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
vars_to_load = self.__class__.DEFAULTS.keys()
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
vars_to_save = self.__class__.DEFAULTS.keys()
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def mkblks(self, length, path=None, folder=True, flags=''):
"""Generates randomized experimental blocks from display groups.
Each block is saved as a CSV file.
length -- number of repeated trials within a block
path -- directory in which experimental blocks will be saved
folder -- blocks will be saved in a containing folder if true
flags -- string of flags to be issued to the display command when
block file is run
"""
if path == None:
path = os.getcwd()
if not os.path.isdir(path):
msg = "specified directory does not exist"
raise IOError(msg)
if folder:
path = os.path.join(path, self.name + BLOCK_DIR_SUFFIX)
if not os.path.isdir(path):
os.mkdir(path)
group_ids = range(len(self.groups))
for n, sequence in enumerate(itertools.permutations(group_ids)):
blkname = 'block{0}.csv'.format(repr(n).zfill(numdigits(length)))
blkfile = open(os.path.join(path, blkname), 'wb')
blkwriter = csv.writer(blkfile, dialect='excel-tab')
blkwriter.writerow(['checkergen experimental block file'])
blkwriter.writerow(['flags:', flags])
blkwriter.writerow(['repeats:', length])
blkwriter.writerow(['sequence:'] + list(sequence))
blkfile.close()
@staticmethod
def readblk(path):
"""Reads the information in a block file and returns it in a dict."""
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
blkdict = dict()
blkfile = open(path, 'rb')
blkreader = csv.reader(blkfile, dialect='excel-tab')
for n, row in enumerate(blkreader):
if n == 1:
blkdict['flags'] = row[1]
elif n == 2:
repeats = int(row[1])
elif n == 3:
sequence = row[1:]
sequence = [int(i) for i in sequence]
blkfile.close()
blkdict['idlist'] = ([-1] + sequence) * repeats
return blkdict
+ @staticmethod
+ def addtoblk(path, idlist, rowlen):
+ """Appends a list of group ids to the specified block file."""
+
+ if not os.path.isfile(path):
+ msg = "specified file does not exist"
+ raise IOError(msg)
+
+ blkfile = open(path, 'ab')
+ blkwriter = csv.writer(blkfile, dialect='excel-tab')
+ blkwriter.writerow(['groups added:'])
+ # Split idlist into lists of length rowlen, based on grouper recipe
+ args = [iter(idlist)] * rowlen
+ rowlist = itertools.izip_longest(*args, fillvalue='')
+ for row in rowlist:
+ blkwriter.writerow(row)
+ blkfile.close()
+
def display(self, fullscreen=False, logtime=False, logdur=False,
sigser=False, sigpar=False, fpbs=0, phototest=False,
eyetrack=False, etuser=False, etvideo=None,
- tryagain=0, trybreak=0, group_queue=[]):
+ tryagain=0, trybreak=None, group_queue=[]):
"""Displays the project animation on the screen.
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
sigser -- send signals through serial port when each group is shown
sigpar -- send signals through parallel port when each group is shown
fpbs -- flips per board signal, i.e. number of shape color reversals
(flips) that occur for a unique signal to be sent for that shape
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
- tryagain -- Append groups during which subject failed to fixated up to
+ tryagain -- Append groups during which subject failed to fixate up to
this number of times to the group queue
trybreak -- Append a wait screen to the group queue every time
after this many groups have been appended to the queue
group_queue -- queue of groups to be displayed, defaults to order of
groups in project (i.e. groups[0] first, etc.)
"""
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if phototest:
test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Set-up groups and variables that control their display
if group_queue == []:
group_queue = list(self.groups)
cur_group = None
cur_id = -1
flipped = 0
flip_id = -1
groups_duration = sum([group.duration() for group in group_queue])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Initialize ports
if sigser:
if not signals.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if sigpar:
if not signals.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
signals.init(sigser, sigpar)
# Initialize eyetracking
if eyetrack:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
+ if trybreak == None:
+ trybreak = len(self.groups)
fixated = False
old_fixated = False
tracked = False
old_tracked = False
cur_fix_fail = False
- fix_fail_queue = []
+ fail_idlist = []
eyetracking.select_source(etuser, etvideo)
eyetracking.start()
# Stretch to fit screen only if project res does not equal screen res
scaling = False
if fullscreen:
window = pyglet.window.Window(fullscreen=True, visible=False)
if (window.width, window.height) != self.res:
scaling = True
else:
window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
keystates = pyglet.window.key.KeyStateHandler()
window.push_handlers(keystates)
# Create framebuffer object for drawing unscaled scene
if scaling:
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
fbo.end_render()
# Clear window and make visible
window.switch_to()
graphics.set_clear_color(self.bg)
window.clear()
window.set_visible()
# Initialize logging variables
if logtime and logdur:
logstring = ''
stamp = Timer()
dur = Timer()
stamp.start()
dur.start()
elif logtime or logdur:
logstring = ''
timer = Timer()
timer.start()
# Main loop
while not window.has_exit and count < disp_end:
# Clear canvas
if scaling:
fbo.start_render()
fbo.clear()
else:
window.clear()
# Assume no change to group visibility
flipped = 0
signals.set_null()
# Manage groups when they are on_screen
if groups_visible:
# Send special signal if waitscreen ends
if isinstance(cur_group, CkgWaitScreen):
if cur_group.over:
signals.set_user_start()
cur_group = None
elif cur_group != None:
# Check whether group changes in visibility
if cur_group.visible != cur_group.old_visible:
flip_id = self.groups.index(cur_group)
if cur_group.visible:
flipped = 1
elif cur_group.old_visible:
flipped = -1
# Check if current group is over
if cur_group.over:
cur_group = None
# Get next group from queue
if cur_group == None:
cur_id += 1
if cur_id >= len(group_queue):
groups_visible = False
else:
cur_group = group_queue[cur_id]
cur_group.reset()
if eyetrack:
cur_fix_fail = False
if cur_group.visible:
flip_id = self.groups.index(cur_group)
flipped = 1
# Draw and then update group
if cur_group != None:
cur_group.draw()
cur_group.update(fps=self.fps,
fpbs=fpbs,
keystates=keystates)
# Send signals upon group visibility change
if flipped == 1:
signals.set_group_start(flip_id)
# Draw test rectangle
if phototest:
test_rect.draw()
elif flipped == -1:
signals.set_group_stop(flip_id)
if eyetrack:
# First check if eye is being tracked and send signals
old_tracked = tracked
tracked = eyetracking.is_tracked()
if tracked:
if not old_tracked:
# Send signal if eye starts being tracked
signals.set_track_start()
else:
if old_tracked:
# Send signal if eye stops being tracked
signals.set_track_stop()
# Next check for fixation
old_fixated = fixated
fixated = eyetracking.is_fixated(FIX_POS, FIX_RANGE, FIX_PER)
if fixated:
# Draw normal cross color if fixating
fix_crosses[0].draw()
if not old_fixated:
# Send signal if fixation starts
signals.set_fix_start()
else:
# Draw alternative cross color if not fixating
fix_crosses[1].draw()
if old_fixated:
# Send signal if fixation stops
signals.set_fix_stop()
# Take note of which groups in which fixation failed
if not cur_fix_fail and cur_group.visible and\
(tracked and not fixated):
cur_fix_fail = True
- if len(fix_fail_queue) == 0 and trybreak > 0:
+ if len(fail_idlist) == 0 and trybreak > 0:
group_queue.append(CkgWaitScreen(res=self.res))
- fix_fail_queue.append(self.groups.index(cur_group))
+ fail_idlist.append(self.groups.index(cur_group))
# Append failed group to group queue
if tryagain > 0:
group_queue.append(cur_group)
groups_stop += cur_group.duration() * self.fps
disp_end += cur_group.duration() * self.fps
# Insert waitscreen every trybreak failed groups
if trybreak > 0:
- if len(fix_fail_queue) % trybreak == 0:
+ if len(fail_idlist) % trybreak == 0:
group_queue.append(CkgWaitScreen())
tryagain -= 1
# Change cross color based on time if eyetracking is not enabled
if not eyetrack:
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Increment count and set whether groups should be shown
if not isinstance(cur_group, CkgWaitScreen):
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
# Blit canvas to screen if necessary
if scaling:
fbo.end_render()
window.switch_to()
canvas.blit(0, 0)
window.dispatch_events()
window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to log string
if logtime and logdur:
logstring = '\n'.join([logstring, str(stamp.elapsed())])
logstring = '\t'.join([logstring, str(dur.restart())])
elif logtime:
logstring = '\n'.join([logstring, str(timer.elapsed())])
elif logdur:
logstring = '\n'.join([logstring, str(timer.restart())])
# Send signals ASAP after flip
signals.send(sigser, sigpar)
# Log when signals are sent
if logtime or logdur:
if flipped != 0 and (sigser or sigpar):
sigmsg = '{0} sent'.format(signals.STATE)
logstring = '\t'.join([logstring, sigmsg])
# Clean up
if eyetrack:
eyetracking.stop()
window.close()
if scaling:
fbo.delete()
del canvas
signals.quit(sigser, sigpar)
# Write log string to file
if logtime or logdur:
filename = '{0}.log'.format(self.name)
with open(filename, 'w') as logfile:
logfile.write(logstring)
# Return list of ids of failed groups
- if eyetrack:
- return fix_fail_queue
+ if eyetrack and len(fail_idlist) > 0:
+ return fail_idlist
def export(self, export_dir, export_duration, group_queue=[],
export_fmt=None, folder=True, force=False):
if not os.path.isdir(export_dir):
msg = 'export path is not a directory'
raise IOError(msg)
if export_fmt == None:
export_fmt = self.export_fmt
# Set-up groups and variables that control their display
if group_queue == []:
group_queue = list(self.groups)
cur_group = None
cur_id = -1
groups_duration = sum([group.duration() for group in group_queue])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Limit export duration to display duration
frames = export_duration * self.fps
frames = min(frames, disp_end)
# Warn user if a lot of frames will be exported
if frames > MAX_EXPORT_FRAMES and not force:
msg = 'very large number ({0}) of frames to be exported'.\
format(frames)
raise FrameOverflowError(msg)
# Create folder to store images if necessary
if folder:
export_dir = os.path.join(export_dir,
self.name + EXPORT_DIR_SUFFIX)
if not os.path.isdir(export_dir):
os.mkdir(export_dir)
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Set up canvas and framebuffer object
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
# Main loop
while count < frames:
fbo.clear()
if groups_visible:
# Check if current group is over
if cur_group != None:
if cur_group.over:
cur_group = None
# Get next group from queue
if cur_group == None:
cur_id += 1
if cur_id >= len(group_queue):
groups_visible = False
else:
cur_group = group_queue[cur_id]
cur_group.reset()
# Draw and then update group
if cur_group != None:
cur_group.draw()
cur_group.update(fps=self.fps, fpbs=0)
# Draw fixation cross based on current count
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Save current frame to file
savepath = \
os.path.join(export_dir,
'{0}{2}.{1}'.
format(self.name, export_fmt,
repr(count).zfill(numdigits(frames-1))))
canvas.save(savepath)
# Increment count and set whether groups should be shown
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
fbo.delete()
class CkgDisplayGroup:
DEFAULTS = {'pre': 0, 'disp': 'Infinity', 'post': 0}
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets internal count and all contained shapes."""
self._count = 0
self._start = self.pre
self._stop = self.pre + self.disp
self._end = self.pre + self.disp + self.post
self.over = False
self.old_visible = False
if self._start == 0 and self._stop > 0:
self.visible = True
else:
self.visible = False
if self._end == 0:
self.over = True
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, lazy=False):
"""Draws all contained shapes during the appropriate interval."""
if self.visible:
for shape in self.shapes:
if lazy:
shape.lazydraw()
else:
shape.draw()
def update(self, **keywords):
"""Increments internal count, makes group visible when appropriate.
fps -- refresh rate of the display in frames per second
fpbs -- flips per board signal, i.e. number of shape color reversals
(flips) that occur for a unique signal to be sent for that shape
"""
fps = keywords['fps']
fpbs = keywords['fpbs']
if self.visible:
# Set triggers to be sent
if fpbs > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= fpbs:
signals.set_board_flip(n)
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(fps)
# Increment count and set flags for the next frame
self._count += 1
self.old_visible = self.visible
if (self._start * fps) <= self._count < (self._stop * fps):
self.visible = True
else:
self.visible = False
if self._count >= (self._end * fps):
self.over = True
else:
self.over = False
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
(pyglet.window.key.SPACE,)],
'infos': ["press enter when ready",
"the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
'font_size': 16,
'bold': True,
'info_pos': (1/2.0, 16/30.0),
'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
if len(self.cont_keys) != len(self.infos):
msg = 'list length mismatch between cont_keys and infos'
raise IndexError(msg)
else:
self.num_steps = len(self.infos)
self.labels = [pyglet.text.Label(info,
font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
bold=self.bold,
x=int(self.res[0]*self.info_pos[0]),
y=int(self.res[1]*self.info_pos[1]),
anchor_x=self.info_anchor[0],
anchor_y=self.info_anchor[1])
for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.visible = False
self.old_visible = False
self.steps_done = 0
self.over = False
def draw(self):
"""Draw informative text."""
self.labels[self.steps_done].draw()
def update(self, **keywords):
"""Checks for keypress, sends signal upon end."""
keystates = keywords['keystates']
if max([keystates[key] for key in self.cont_keys[self.steps_done]]):
self.steps_done += 1
if self.steps_done == self.num_steps:
self.over = True
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = {'dims': (5, 5),
'init_unit': (30, 30), 'end_unit': (50, 50),
'position': (0, 0), 'anchor': 'bottomleft',
'cols': ((0, 0, 0), (255, 255, 255)),
'freq': 1, 'phase': 0}
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
if PRERENDER_TO_TEXTURE:
init_pos = [(1 - a)* s/to_decimal(2) for s, a in
zip(self._size, graphics.locations[self.anchor])]
else:
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
anchor=self.anchor)
cur_unit_rect.col = self.cols[(i + j) % 2]
cur_unit_rect.add_to_batch(self._batches[0])
cur_unit_rect.col = self.cols[(i + j + 1) % 2]
cur_unit_rect.add_to_batch(self._batches[1])
# Increase x values
cur_unit_pos[0] += \
graphics.locations[self.anchor][0] * cur_unit[0]
cur_unit[0] += unit_grad[0]
# Reset x values
cur_unit_pos[0] = init_pos[0]
cur_unit[0] = init_unit[0]
# Increase y values
cur_unit_pos[1] += \
graphics.locations[self.anchor][1] * cur_unit[1]
cur_unit[1] += unit_grad[1]
if PRERENDER_TO_TEXTURE:
# Create textures
int_size = [int(round(s)) for s in self._size]
self._prerenders =\
[pyglet.image.Texture.create(*int_size) for n in range(2)]
# Set up framebuffer
fbo = graphics.Framebuffer()
for n in range(2):
fbo.attach_texture(self._prerenders[n])
# Draw batch to texture
fbo.start_render()
self._batches[n].draw()
fbo.end_render()
# Anchor textures for correct blitting later
self._prerenders[n].anchor_x, self._prerenders[n].anchor_y =\
[int(round((1 - a)* s/to_decimal(2))) for s, a in
zip(self._size, graphics.locations[self.anchor])]
fbo.delete()
# Delete batches since they won't be used
del self._batches
self._computed = True
def draw(self, always_compute=False):
"""Draws appropriate prerender depending on current phase."""
if not self._computed or always_compute:
self.compute()
self._cur_phase %= 360
n = int(self._cur_phase // 180)
if PRERENDER_TO_TEXTURE:
self._prerenders[n].blit(*self.position)
else:
self._batches[n].draw()
def lazydraw(self):
"""Only draws on color reversal."""
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if (cur_n != prev_n) or self._first_draw:
self.draw()
if self._first_draw:
self._first_draw = False
|
ztangent/checkergen
|
1d6642b1e93890bb2335f9970c4e5d1076261d05
|
Cleaned up waitscreen implementation, tweaked is_fixated.
|
diff --git a/src/cli.py b/src/cli.py
index 7e9df75..105e3bd 100644
--- a/src/cli.py
+++ b/src/cli.py
@@ -324,795 +324,796 @@ class CkgCmd(cmd.Cmd):
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.edgrp_parser.parse_args(shlex.split(line))
except CmdParserError:
print "error:", str(sys.exc_value)
self.__class__.edgrp_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_proj.groups) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_group_attr(x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.edgrp_parser.print_usage()
rmgrp_parser = CmdParser(add_help=False, prog='rmgrp',
description='''Removes display groups specified
by ids.''')
rmgrp_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='ids of display groups to be removed')
rmgrp_parser.add_argument('-a', '--all', action='store_true',
help='remove all groups from the project')
def help_rmgrp(self):
self.__class__.rmgrp_parser.print_help()
def do_rmgrp(self, line):
"""Removes display groups specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups to remove'
return
try:
args = self.__class__.rmgrp_parser.parse_args(shlex.split(line))
except CmdParserError:
print "error:", str(sys.exc_value)
self.__class__.rmgrp_parser.print_usage()
return
rmlist = []
if args.all:
for group in self.cur_proj.groups[:]:
self.cur_proj.del_group(group)
print "all display groups removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_proj.groups) or x < 0:
print "display group", x, "does not exist"
continue
rmlist.append(self.cur_proj.groups[x])
print "display group", x, "removed"
for group in rmlist:
self.cur_proj.del_group(group)
# Remember to point self.cur_group somewhere sane
if self.cur_group not in self.cur_proj.groups:
if len(self.cur_proj.groups) == 0:
self.cur_group = None
else:
self.cur_group = self.cur_proj.groups[0]
print "group 0 is now the current display group"
chgrp_parser = CmdParser(add_help=False, prog='chgrp',
description='''Changes display group that is
currently active for editing.
Prints current group id if
no group id is specified''')
chgrp_parser.add_argument('gid', metavar='id', type=int, nargs='?',
help='id of display group to be made active')
def help_chgrp(self):
self.__class__.chgrp_parser.print_help()
def do_chgrp(self, line):
"""Changes group that is currently active for editing."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups that can be made active'
return
try:
args = self.__class__.chgrp_parser.parse_args(shlex.split(line))
except CmdParserError:
print "error:", str(sys.exc_value)
self.__class__.chgrp_parser.print_usage()
return
if args.gid == None:
print "group",\
self.cur_proj.groups.index(self.cur_group),\
"is the current display group"
elif args.gid >= len(self.cur_proj.groups) or args.gid < 0:
print "group", args.gid, "does not exist"
else:
self.cur_group = self.cur_proj.groups[args.gid]
print "group", args.gid, "is now the current display group"
mk_parser = CmdParser(add_help=False, prog='mk',
description='''Makes a new checkerboard in the
current group with the given
parameters.''')
mk_parser.add_argument('dims', action=store_tuple(2, ',', to_decimal),
help='''width,height of checkerboard in no. of
unit cells''')
mk_parser.add_argument('init_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of initial unit cell in pixels')
mk_parser.add_argument('end_unit', action=store_tuple(2, ',', to_decimal),
help='width,height of final unit cell in pixels')
mk_parser.add_argument('position', action=store_tuple(2, ',', to_decimal),
help='x,y position of checkerboard in pixels')
mk_parser.add_argument('anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='anchor')
mk_parser.add_argument('cols', action=store_tuple(2, ',', to_color, [';']),
help='''color1,color2 of the checkerboard
(color format: R;G;B,
component range from 0-255)''')
mk_parser.add_argument('freq', type=to_decimal,
help='frequency of color reversal in Hz')
mk_parser.add_argument('phase', type=to_decimal, nargs='?', default='0',
help='initial phase of animation in degrees')
def help_mk(self):
self.__class__.mk_parser.print_help()
def do_mk(self, line):
"""Makes a checkerboard with the given parameters."""
if self.cur_proj == None:
print 'no project open, automatically creating project...'
self.do_new('')
if self.cur_group == None:
print 'automatically adding display group...'
self.do_mkgrp('')
try:
args = self.__class__.mk_parser.parse_args(shlex.split(line))
except CmdParserError:
print "error:", str(sys.exc_value)
self.__class__.mk_parser.print_usage()
return
shape_dict = dict([(name, getattr(args, name)) for
name in public_dir(args)])
new_shape = core.CheckerBoard(**shape_dict)
new_id = self.cur_proj.add_shape_to_group(self.cur_group, new_shape)
print "checkerboard", new_id, "added"
ed_parser = CmdParser(add_help=False, prog='ed',
description='''Edits attributes of checkerboards
specified by ids.''')
ed_parser.add_argument('idlist', nargs='+', metavar='id', type=int,
help='''ids of checkerboards in the current
group to be edited''')
ed_parser.add_argument('--dims', action=store_tuple(2, ',', to_decimal),
help='checkerboard dimensions in unit cells',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--init_unit',
action=store_tuple(2, ',', to_decimal),
help='initial unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--end_unit',
action=store_tuple(2, ',', to_decimal),
help='final unit cell dimensions in pixels',
metavar='WIDTH,HEIGHT')
ed_parser.add_argument('--position',
action=store_tuple(2, ',', to_decimal),
help='position of checkerboard in pixels',
metavar='X,Y')
ed_parser.add_argument('--anchor', choices=sorted(locations.keys()),
help='''location of anchor point of checkerboard
(choices: %(choices)s)''',
metavar='LOCATION')
ed_parser.add_argument('--cols', metavar='COLOR1,COLOR2',
action=store_tuple(2, ',', to_color, [';']),
help='''checkerboard colors (color format:
R;G;B, component range
from 0-255)''')
ed_parser.add_argument('--freq', type=to_decimal,
help='frequency of color reversal in Hz')
ed_parser.add_argument('--phase', type=to_decimal,
help='initial phase of animation in degrees')
def help_ed(self):
self.__class__.ed_parser.print_help()
def do_ed(self, line):
"""Edits attributes of checkerboards specified by ids."""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, please create one first'
return
try:
args = self.__class__.ed_parser.parse_args(shlex.split(line))
except CmdParserError:
print "error:", str(sys.exc_value)
self.__class__.ed_parser.print_usage()
return
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist[:]:
if x >= len(self.cur_group.shapes) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_shape_attr(self.cur_group, x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.ed_parser.print_usage()
rm_parser = CmdParser(add_help=False, prog='rm',
description='''Removes checkerboards specified
by ids.''')
rm_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''ids of checkerboards in the current group
to be removed''')
rm_parser.add_argument('-a', '--all', action='store_true',
help='''remove all checkerboards in the
current group''')
def help_rm(self):
self.__class__.rm_parser.print_help()
def do_rm(self, line):
"""Removes checkerboards specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, no boards to remove'
return
try:
args = self.__class__.rm_parser.parse_args(shlex.split(line))
except CmdParserError:
print "error:", str(sys.exc_value)
self.__class__.rm_parser.print_usage()
return
rmlist = []
if args.all:
for shape in self.cur_group.shapes:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
print "all checkerboards removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_group.shapes) or x < 0:
print "checkerboard", x, "does not exist"
continue
rmlist.append(self.cur_group.shapes[x])
print "checkerboard", x, "removed"
for shape in rmlist:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
ls_parser = CmdParser(add_help=False, prog='ls',
description='''Lists project, display group and
checkerboard settings. If no group ids
are specified, all display groups
are listed.''')
ls_parser.add_argument('gidlist', nargs='*', metavar='gid', type=int,
help='''ids of the display groups to be listed''')
ls_group = ls_parser.add_mutually_exclusive_group()
ls_group.add_argument('-s', '--settings', action='store_true',
help='list only project settings')
ls_group.add_argument('-g', '--groups', action='store_true',
help='list only display groups')
def help_ls(self):
self.__class__.ls_parser.print_help()
def do_ls(self, line):
"""Lists project, display group and checkerboard settings."""
def ls_str(s, seps=[',',';']):
"""Special space-saving output formatter."""
if type(s) in [tuple, list]:
if len(seps) > 1:
newseps = seps[1:]
else:
newseps = seps
return seps[0].join([ls_str(i, newseps) for i in s])
else:
return str(s)
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.ls_parser.parse_args(shlex.split(line))
except CmdParserError:
print "error:", str(sys.exc_value)
self.__class__.ls_parser.print_usage()
return
# Remove duplicates and ascending sort
args.gidlist = sorted(set(args.gidlist))
if len(self.cur_proj.groups) == 0:
if len(args.gidlist) > 0:
print 'this project has no display groups that can be listed'
args.settings = True
else:
for gid in args.gidlist[:]:
if gid >= len(self.cur_proj.groups) or gid < 0:
args.gidlist.remove(gid)
print 'display group', gid, 'does not exist'
if args.gidlist == []:
args.gidlist = range(len(self.cur_proj.groups))
else:
# If any (valid) groups are specified
# don't show project settings
args.groups = True
if not args.groups:
print 'PROJECT SETTINGS'.center(70,'*')
print \
'name'.rjust(16),\
'fps'.rjust(7),\
'resolution'.rjust(14),\
'bg color'.rjust(18)
# 'format'.rjust(7)
print \
ls_str(self.cur_proj.name).rjust(16),\
ls_str(self.cur_proj.fps).rjust(7),\
ls_str(self.cur_proj.res).rjust(14),\
ls_str(self.cur_proj.bg).rjust(18)
# ls_str(self.cur_proj.export_fmt).rjust(7)
print \
'pre-display'.rjust(26),\
'post-display'.rjust(26)
print \
ls_str(self.cur_proj.pre).rjust(26),\
ls_str(self.cur_proj.post).rjust(26)
print \
'cross colors'.rjust(26),\
'cross times'.rjust(26)
print \
ls_str(self.cur_proj.cross_cols).rjust(26),\
ls_str(self.cur_proj.cross_times).rjust(26)
if not args.settings and not args.groups:
# Insert empty line if both groups and project
# settings are listed
print ''
if not args.settings:
for i, n in enumerate(args.gidlist):
if i != 0:
# Print newline seperator between each group
print ''
group = self.cur_proj.groups[n]
print 'GROUP {n}'.format(n=n).center(70,'*')
print \
'pre-display'.rjust(20),\
'display'.rjust(20),\
'post-display'.rjust(20)
print \
ls_str(group.pre).rjust(20),\
ls_str(group.disp).rjust(20),\
ls_str(group.post).rjust(20)
if len(group.shapes) > 0:
print \
''.rjust(2),\
'shape id'.rjust(8),\
'dims'.rjust(10),\
'init_unit'.rjust(14),\
'end_unit'.rjust(14),\
'position'.rjust(14)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.dims).rjust(10),\
ls_str(shape.init_unit).rjust(14),\
ls_str(shape.end_unit).rjust(14),\
ls_str(shape.position).rjust(14)
print '\n',\
''.rjust(2),\
'shape id'.rjust(8),\
'colors'.rjust(27),\
'anchor'.rjust(12),\
'freq'.rjust(6),\
'phase'.rjust(7)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.cols).rjust(27),\
ls_str(shape.anchor).rjust(12),\
ls_str(shape.freq).rjust(6),\
ls_str(shape.phase).rjust(7)
display_parser = CmdParser(add_help=False, prog='display',
description='''Displays the animation in a
window or in fullscreen.''')
display_parser.add_argument('-b', '--block', metavar='PATH',
help='''read flags and dislay group order from
specified file, ignore other flags''')
display_parser.add_argument('-f', '--fullscreen', action='store_true',
help='sets fullscreen mode, ESC to quit')
display_parser.add_argument('-p', '--priority', metavar='LEVEL',
help='''set priority while displaying,
higher priority results in
less dropped frames (choices:
0-3, low, normal, high,
realtime)''')
display_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly display specified display
groups N number of times''')
display_parser.add_argument('-pt', '--phototest', action='store_true',
help='''draw white test rectangle in topleft
corner of screen when groups become
visible for a photodiode to detect''')
display_parser.add_argument('-lt', '--logtime', action='store_true',
help='output frame timestamps to a log file')
display_parser.add_argument('-ld', '--logdur', action='store_true',
help='output frame durations to a log file')
display_parser.add_argument('-ss', '--sigser', action='store_true',
help='''send signals through the serial port
when shapes are being displayed''')
display_parser.add_argument('-sp', '--sigpar', action='store_true',
help='''send signals through the parallel port
when shapes are being displayed''')
display_parser.add_argument('-fpbs', metavar='N', type=int, default=0,
help='''unique signal corresponding to a
checkerboard is sent after the board
undergoes N color reversals (flips),
set to 0 to disable''')
display_parser.add_argument('-et', '--eyetrack', action='store_true',
help='''use eyetracking to ensure that subject
fixates on the cross in the center''')
display_parser.add_argument('-eu', '--etuser', action='store_true',
help='''allow user to select eyetracking video
source from a dialog''')
display_parser.add_argument('-ev', '--etvideo', metavar='path',
help='''path (with no spaces) to eyetracking
video file to be used as the source''')
display_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be displayed
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_display(self):
self.__class__.display_parser.print_help()
def do_display(self, line):
"""Displays the animation in a window or in fullscreen"""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.display_parser.parse_args(shlex.split(line))
except CmdParserError:
print "error:", str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
if args.block != None:
try:
blkdict = core.CkgProj.readblk(args.block)
flags = blkdict['flags']
try:
args = self.__class__.\
display_parser.parse_args(shlex.split(flags))
args.idlist = blkdict['idlist']
except CmdParserError:
print 'error: invalid flags stored in block file'
return
except IOError:
print "error:", str(sys.exc_value)
return
group_queue = []
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < -1:
print 'error: group', i, 'does not exist'
return
for i in args.idlist:
if i == -1:
- group_queue.append(core.CkgWaitScreen())
+ group_queue.append(core.CkgWaitScreen(res=
+ self.cur_proj.res))
else:
group_queue.append(self.cur_proj.groups[i])
else:
group_queue = list(self.cur_proj.groups)
if args.repeat != None:
group_queue = list(group_queue * args.repeat)
if args.priority != None:
if not priority.available:
print "error: setting priority not avaible on", sys.platform
print "continuing..."
else:
if args.priority.isdigit():
args.priority = int(args.priority)
try:
priority.set(args.priority)
except ValueError:
print "error:", str(sys.exc_value)
print "continuing..."
if args.eyetrack and eyetracking.available:
if not eyetracking.is_calibrated():
try:
self.do_calibrate('',True)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
return
try:
self.cur_proj.display(fullscreen=args.fullscreen,
logtime=args.logtime,
logdur=args.logdur,
sigser=args.sigser,
sigpar=args.sigpar,
fpbs=args.fpbs,
phototest=args.phototest,
eyetrack=args.eyetrack,
etuser=args.etuser,
etvideo=args.etvideo,
group_queue=group_queue)
except (IOError, NotImplementedError, eyetracking.EyetrackingError):
print "error:", str(sys.exc_value)
return
if args.priority != None:
try:
priority.set('normal')
except:
pass
export_parser = CmdParser(add_help=False, prog='export',
description='''Exports animation as an image
sequence (in a folder) to the
specified directory.''')
# export_parser.add_argument('--fmt', dest='export_fmt',
# choices=core.EXPORT_FMTS,
# help='image format for export')
export_parser.add_argument('-n','--nofolder',
dest='folder', action='store_false',
help='''force images not to exported in
a containing folder''')
export_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly export specified display
groups N number of times''')
export_parser.add_argument('duration', nargs='?',
type=to_decimal, default='Infinity',
help='''number of seconds of the animation
that should be exported (default:
as long as the entire animation)''')
export_parser.add_argument('dir', nargs='?', default=os.getcwd(),
help='''destination directory for export
(default: current working directory)''')
export_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be exported
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_export(self):
self.__class__.export_parser.print_help()
def do_export(self, line):
"""Exports animation an image sequence to the specified directory."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.export_parser.parse_args(shlex.split(line))
except CmdParserError:
print "error:", str(sys.exc_value)
self.__class__.export_parser.print_usage()
return
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < 0:
print 'error: group', i, 'does not exist'
return
group_queue = [self.cur_proj.groups[i] for i in args.idlist]
else:
group_queue = list(self.cur_proj.groups)
if args.repeat != None:
group_queue = list(group_queue * args.repeat)
try:
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
group_queue=group_queue,
folder=args.folder)
except IOError:
print "error:", str(sys.exc_value)
return
except core.FrameOverflowError:
print "warning:", str(sys.exc_value)
print "Are you sure you want to continue?"
while True:
try:
if self.__class__.yn_parse(raw_input()):
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
group_queue=group_queue,
export_fmt=None,
folder=args.folder,
force=True)
break
else:
return
except TypeError:
print str(sys.exc_value)
except EOFError:
return
print "Export done."
mkblks_parser = CmdParser(add_help=False, prog='mkblks',
description='''Generates randomized experimental
blocks from display groups and
saves each as a CSV file.''')
mkblks_parser.add_argument('-n','--nofolder',
dest='folder', action='store_false',
help='''force block files not to be saved in
a containing folder''')
mkblks_parser.add_argument('-d','--dir', default=os.getcwd(),
help='''where to save block files
(default: current working directory)''')
mkblks_parser.add_argument('length', type=int,
help='''no. of repeated trials in a block''')
mkblks_parser.add_argument('flags', nargs='?', default='',
help='''flags passed to the display command
that should be used when the block
file is run (enclose in quotes and use
'+' or '++' in place of '-' or '--')''')
def help_mkblks(self):
self.__class__.mkblks_parser.print_help()
def do_mkblks(self, line):
"""Generates randomized experimental blocks from display groups."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.mkblks_parser.parse_args(shlex.split(line))
except CmdParserError:
print "error:", str(sys.exc_value)
self.__class__.mkblks_parser.print_usage()
return
args.flags = args.flags.replace('+','-')
try:
disp_args = self.__class__.display_parser.\
parse_args(shlex.split(args.flags))
except CmdParserError:
print "error: invalid flags to display command"
print str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
try:
self.cur_proj.mkblks(args.length,
path=args.dir,
folder=args.folder,
flags=args.flags)
except IOError:
print "error:", str(sys.exc_value)
return
print "Experimental blocks generated."
def do_calibrate(self, line, query=False):
"""Calibrate subject for eyetracking, or load a calibration file."""
if not eyetracking.available:
print "error: eyetracking functionality not available"
return
if query:
print "path to calibration file (leave empty for GUI tool):"
try:
path = raw_input().strip().strip('"\'')
except EOFError:
msg = "calibration cancelled"
raise eyetracking.EyetrackingError(msg)
else:
path = line.strip().strip('"\'')
if len(path) == 0:
path = None
if not eyetracking.is_source_ready():
# Select default source if none has been selected
eyetracking.select_source()
try:
eyetracking.calibrate(path)
except eyetracking.EyetrackingError:
if query:
raise
else:
print "error:", str(sys.exc_value)
return
if len(path) > 0:
print "calibration file successfully loaded"
etsetup_parser = CmdParser(add_help=False, prog='etsetup',
description='''Set various eyetracking
parameters.''')
etsetup_parser.add_argument('-fp', '--fixperiod', type=int, metavar='MS',
help='''time in milliseconds subject
has to stare at the same spot
for fixation to be detected''')
etsetup_parser.add_argument('-fr', '--fixrange', type=float, metavar='MM',
help='''distance in mm beyond which the
eye position cannot change for
a fixation to be detected''')
etsetup_parser.add_argument('-s', '--size', metavar='WIDTH,HEIGHT',
action=store_tuple(2, ',', float),
help='physical screen dimensions in mm')
etsetup_parser.add_argument('-vd', '--viewdist', type=int, metavar='MM',
help='''viewing distance between subject's
eyes and the screen''')
def help_etsetup(self):
self.__class__.etsetup_parser.print_help()
def do_etsetup(self, line):
try:
args = self.__class__.etsetup_parser.parse_args(shlex.split(line))
except CmdParserError:
print "error:", str(sys.exc_value)
self.__class__.etsetup_parser.print_usage()
return
try:
eyetracking.setup(viewing_distance=args.viewdist,
screen_dims=args.size,
fixation_period=args.fixperiod,
fixation_range=args.fixrange)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
def do_quit(self, line):
"""Quits the program."""
if self.save_check():
return
return True
def help_EOF(self):
print "Typing {0} issues this command, which quits the program."\
.format(CMD_EOF_STRING)
def do_EOF(self, line):
"""Typing Ctrl-D issues this command, which quits the program."""
print '\r'
if self.save_check():
return
return True
def help_help(self):
print 'Prints a list of commands.'
print "Type 'help <topic>' for more details on each command."
def default(self, line):
command = line.split()[0]
print \
"'{0}' is not a checkergen command.".format(command),\
"Type 'help' for a list of commands"
diff --git a/src/core.py b/src/core.py
index c427d9f..ef816ca 100755
--- a/src/core.py
+++ b/src/core.py
@@ -39,1080 +39,1072 @@ FIX_PER = 350
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = {'name': 'untitled',
'fps': 60,
'res': (800, 600),
'bg': (127, 127, 127),
'export_fmt': 'png',
'pre': 0,
'post': 0,
'cross_cols': ((0, 0, 0), (255, 0, 0)),
'cross_times': ('Infinity', 1)}
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
export_fmt -- image format for animation to be exported as
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'export_fmt':
if value not in EXPORT_FMTS:
msg = 'image format not recognized or supported'
raise FileFormatError(msg)
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if ext == '.{0}'.format(CKG_FMT):
self.name = name
else:
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
vars_to_load = self.__class__.DEFAULTS.keys()
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
vars_to_save = self.__class__.DEFAULTS.keys()
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def mkblks(self, length, path=None, folder=True, flags=''):
"""Generates randomized experimental blocks from display groups.
Each block is saved as a CSV file.
length -- number of repeated trials within a block
path -- directory in which experimental blocks will be saved
folder -- blocks will be saved in a containing folder if true
flags -- string of flags to be issued to the display command when
block file is run
"""
if path == None:
path = os.getcwd()
if not os.path.isdir(path):
msg = "specified directory does not exist"
raise IOError(msg)
if folder:
path = os.path.join(path, self.name + BLOCK_DIR_SUFFIX)
if not os.path.isdir(path):
os.mkdir(path)
group_ids = range(len(self.groups))
for n, sequence in enumerate(itertools.permutations(group_ids)):
blkname = 'block{0}.csv'.format(repr(n).zfill(numdigits(length)))
blkfile = open(os.path.join(path, blkname), 'wb')
blkwriter = csv.writer(blkfile, dialect='excel-tab')
blkwriter.writerow(['checkergen experimental block file'])
blkwriter.writerow(['flags:', flags])
blkwriter.writerow(['repeats:', length])
blkwriter.writerow(['sequence:'] + list(sequence))
blkfile.close()
@staticmethod
def readblk(path):
"""Reads the information in a block file and returns it in a dict."""
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
blkdict = dict()
blkfile = open(path, 'rb')
blkreader = csv.reader(blkfile, dialect='excel-tab')
for n, row in enumerate(blkreader):
if n == 1:
blkdict['flags'] = row[1]
elif n == 2:
repeats = int(row[1])
elif n == 3:
sequence = row[1:]
sequence = [int(i) for i in sequence]
blkfile.close()
blkdict['idlist'] = ([-1] + sequence) * repeats
return blkdict
def display(self, fullscreen=False, logtime=False, logdur=False,
sigser=False, sigpar=False, fpbs=0, phototest=False,
eyetrack=False, etuser=False, etvideo=None,
tryagain=0, trybreak=0, group_queue=[]):
"""Displays the project animation on the screen.
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
sigser -- send signals through serial port when each group is shown
sigpar -- send signals through parallel port when each group is shown
fpbs -- flips per board signal, i.e. number of shape color reversals
(flips) that occur for a unique signal to be sent for that shape
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- Append groups during which subject failed to fixated up to
this number of times to the group queue
trybreak -- Append a wait screen to the group queue every time
after this many groups have been appended to the queue
group_queue -- queue of groups to be displayed, defaults to order of
groups in project (i.e. groups[0] first, etc.)
"""
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if phototest:
test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Set-up groups and variables that control their display
if group_queue == []:
group_queue = list(self.groups)
cur_group = None
cur_id = -1
flipped = 0
flip_id = -1
groups_duration = sum([group.duration() for group in group_queue])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Initialize ports
if sigser:
if not signals.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if sigpar:
if not signals.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
signals.init(sigser, sigpar)
# Initialize eyetracking
if eyetrack:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
fixated = False
old_fixated = False
tracked = False
old_tracked = False
cur_fix_fail = False
fix_fail_queue = []
eyetracking.select_source(etuser, etvideo)
eyetracking.start()
# Stretch to fit screen only if project res does not equal screen res
scaling = False
if fullscreen:
window = pyglet.window.Window(fullscreen=True, visible=False)
if (window.width, window.height) != self.res:
scaling = True
else:
window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
keystates = pyglet.window.key.KeyStateHandler()
window.push_handlers(keystates)
# Create framebuffer object for drawing unscaled scene
if scaling:
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
fbo.end_render()
# Clear window and make visible
window.switch_to()
graphics.set_clear_color(self.bg)
window.clear()
window.set_visible()
# Initialize logging variables
if logtime and logdur:
logstring = ''
stamp = Timer()
dur = Timer()
stamp.start()
dur.start()
elif logtime or logdur:
logstring = ''
timer = Timer()
timer.start()
# Main loop
while not window.has_exit and count < disp_end:
# Clear canvas
if scaling:
fbo.start_render()
fbo.clear()
else:
window.clear()
# Assume no change to group visibility
flipped = 0
signals.set_null()
# Manage groups when they are on_screen
if groups_visible:
# Send special signal if waitscreen ends
if isinstance(cur_group, CkgWaitScreen):
if cur_group.over:
signals.set_user_start()
cur_group = None
elif cur_group != None:
# Check whether group changes in visibility
if cur_group.visible != cur_group.old_visible:
flip_id = self.groups.index(cur_group)
if cur_group.visible:
flipped = 1
elif cur_group.old_visible:
flipped = -1
# Check if current group is over
if cur_group.over:
cur_group = None
# Get next group from queue
if cur_group == None:
cur_id += 1
if cur_id >= len(group_queue):
groups_visible = False
else:
cur_group = group_queue[cur_id]
cur_group.reset()
if eyetrack:
cur_fix_fail = False
if cur_group.visible:
flip_id = self.groups.index(cur_group)
flipped = 1
# Draw and then update group
if cur_group != None:
cur_group.draw()
cur_group.update(fps=self.fps,
fpbs=fpbs,
keystates=keystates)
# Send signals upon group visibility change
if flipped == 1:
signals.set_group_start(flip_id)
# Draw test rectangle
if phototest:
test_rect.draw()
elif flipped == -1:
signals.set_group_stop(flip_id)
if eyetrack:
# First check if eye is being tracked and send signals
old_tracked = tracked
tracked = eyetracking.is_tracked()
if tracked:
if not old_tracked:
# Send signal if eye starts being tracked
signals.set_track_start()
else:
if old_tracked:
# Send signal if eye stops being tracked
signals.set_track_stop()
# Next check for fixation
old_fixated = fixated
fixated = eyetracking.is_fixated(FIX_POS, FIX_RANGE, FIX_PER)
if fixated:
# Draw normal cross color if fixating
fix_crosses[0].draw()
if not old_fixated:
# Send signal if fixation starts
signals.set_fix_start()
else:
# Draw alternative cross color if not fixating
fix_crosses[1].draw()
if old_fixated:
# Send signal if fixation stops
signals.set_fix_stop()
# Take note of which groups in which fixation failed
if not cur_fix_fail and cur_group.visible and\
(tracked and not fixated):
cur_fix_fail = True
if len(fix_fail_queue) == 0 and trybreak > 0:
- group_queue.append(CkgWaitScreen())
+ group_queue.append(CkgWaitScreen(res=self.res))
fix_fail_queue.append(self.groups.index(cur_group))
# Append failed group to group queue
if tryagain > 0:
group_queue.append(cur_group)
groups_stop += cur_group.duration() * self.fps
disp_end += cur_group.duration() * self.fps
- # Insert waitscreen every tryagainbreak failed groups
+ # Insert waitscreen every trybreak failed groups
if trybreak > 0:
if len(fix_fail_queue) % trybreak == 0:
group_queue.append(CkgWaitScreen())
tryagain -= 1
# Change cross color based on time if eyetracking is not enabled
if not eyetrack:
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Increment count and set whether groups should be shown
if not isinstance(cur_group, CkgWaitScreen):
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
# Blit canvas to screen if necessary
if scaling:
fbo.end_render()
window.switch_to()
canvas.blit(0, 0)
window.dispatch_events()
window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to log string
if logtime and logdur:
logstring = '\n'.join([logstring, str(stamp.elapsed())])
logstring = '\t'.join([logstring, str(dur.restart())])
elif logtime:
logstring = '\n'.join([logstring, str(timer.elapsed())])
elif logdur:
logstring = '\n'.join([logstring, str(timer.restart())])
# Send signals ASAP after flip
signals.send(sigser, sigpar)
# Log when signals are sent
if logtime or logdur:
if flipped != 0 and (sigser or sigpar):
sigmsg = '{0} sent'.format(signals.STATE)
logstring = '\t'.join([logstring, sigmsg])
# Clean up
if eyetrack:
eyetracking.stop()
window.close()
if scaling:
fbo.delete()
del canvas
signals.quit(sigser, sigpar)
# Write log string to file
if logtime or logdur:
filename = '{0}.log'.format(self.name)
with open(filename, 'w') as logfile:
logfile.write(logstring)
# Return list of ids of failed groups
if eyetrack:
return fix_fail_queue
def export(self, export_dir, export_duration, group_queue=[],
export_fmt=None, folder=True, force=False):
if not os.path.isdir(export_dir):
msg = 'export path is not a directory'
raise IOError(msg)
if export_fmt == None:
export_fmt = self.export_fmt
# Set-up groups and variables that control their display
if group_queue == []:
group_queue = list(self.groups)
cur_group = None
cur_id = -1
groups_duration = sum([group.duration() for group in group_queue])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Limit export duration to display duration
frames = export_duration * self.fps
frames = min(frames, disp_end)
# Warn user if a lot of frames will be exported
if frames > MAX_EXPORT_FRAMES and not force:
msg = 'very large number ({0}) of frames to be exported'.\
format(frames)
raise FrameOverflowError(msg)
# Create folder to store images if necessary
if folder:
export_dir = os.path.join(export_dir,
self.name + EXPORT_DIR_SUFFIX)
if not os.path.isdir(export_dir):
os.mkdir(export_dir)
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Set up canvas and framebuffer object
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
# Main loop
while count < frames:
fbo.clear()
if groups_visible:
# Check if current group is over
if cur_group != None:
if cur_group.over:
cur_group = None
# Get next group from queue
if cur_group == None:
cur_id += 1
if cur_id >= len(group_queue):
groups_visible = False
else:
cur_group = group_queue[cur_id]
cur_group.reset()
# Draw and then update group
if cur_group != None:
cur_group.draw()
cur_group.update(fps=self.fps, fpbs=0)
# Draw fixation cross based on current count
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Save current frame to file
savepath = \
os.path.join(export_dir,
'{0}{2}.{1}'.
format(self.name, export_fmt,
repr(count).zfill(numdigits(frames-1))))
canvas.save(savepath)
# Increment count and set whether groups should be shown
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
fbo.delete()
class CkgDisplayGroup:
DEFAULTS = {'pre': 0, 'disp': 'Infinity', 'post': 0}
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets internal count and all contained shapes."""
self._count = 0
self._start = self.pre
self._stop = self.pre + self.disp
self._end = self.pre + self.disp + self.post
self.over = False
self.old_visible = False
if self._start == 0 and self._stop > 0:
self.visible = True
else:
self.visible = False
if self._end == 0:
self.over = True
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, lazy=False):
"""Draws all contained shapes during the appropriate interval."""
if self.visible:
for shape in self.shapes:
if lazy:
shape.lazydraw()
else:
shape.draw()
def update(self, **keywords):
"""Increments internal count, makes group visible when appropriate.
fps -- refresh rate of the display in frames per second
fpbs -- flips per board signal, i.e. number of shape color reversals
(flips) that occur for a unique signal to be sent for that shape
"""
fps = keywords['fps']
fpbs = keywords['fpbs']
if self.visible:
# Set triggers to be sent
if fpbs > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= fpbs:
signals.set_board_flip(n)
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(fps)
# Increment count and set flags for the next frame
self._count += 1
self.old_visible = self.visible
if (self._start * fps) <= self._count < (self._stop * fps):
self.visible = True
else:
self.visible = False
if self._count >= (self._end * fps):
self.over = True
else:
self.over = False
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
- DEFAULTS = {'g_keys': (pyglet.window.key.SPACE,),
- 'r_keys': (pyglet.window.key.NUM_ENTER,
- pyglet.window.key.ENTER),
+ DEFAULTS = {'cont_keys': [(pyglet.window.key.NUM_ENTER,
+ pyglet.window.key.ENTER),
+ (pyglet.window.key.SPACE,)],
+ 'infos': ["press enter when ready",
+ "the experiment will start soon"],
'res': CkgProj.DEFAULTS['res'],
- 'g_info': "the experiment will start soon",
- 'r_info': "press enter when ready",
+ 'font_name': SANS_SERIF,
'font_color': (0, 0, 0, 255),
- 'font_size': 16}
+ 'font_size': 16,
+ 'bold': True,
+ 'info_pos': (1/2.0, 16/30.0),
+ 'info_anchor': ('center', 'center')}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
- self.g_label = pyglet.text.Label(self.g_info,
- font_name=SANS_SERIF,
- font_size=self.font_size,
- color=self.font_color,
- bold=True,
- x=self.res[0]//2,
- y=self.res[1]*16//30,
- anchor_x='center',
- anchor_y='center')
- self.r_label = pyglet.text.Label(self.r_info,
- font_name=SANS_SERIF,
+ if len(self.cont_keys) != len(self.infos):
+ msg = 'list length mismatch between cont_keys and infos'
+ raise IndexError(msg)
+ else:
+ self.num_steps = len(self.infos)
+ self.labels = [pyglet.text.Label(info,
+ font_name=self.font_name,
font_size=self.font_size,
color=self.font_color,
- bold=True,
- x=self.res[0]//2,
- y=self.res[1]*16//30,
- anchor_x='center',
- anchor_y='center')
+ bold=self.bold,
+ x=int(self.res[0]*self.info_pos[0]),
+ y=int(self.res[1]*self.info_pos[1]),
+ anchor_x=self.info_anchor[0],
+ anchor_y=self.info_anchor[1])
+ for info in self.infos]
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.visible = False
self.old_visible = False
- self.ready = False
+ self.steps_done = 0
self.over = False
def draw(self):
"""Draw informative text."""
- if not self.ready:
- self.r_label.draw()
- else:
- self.g_label.draw()
+ self.labels[self.steps_done].draw()
def update(self, **keywords):
"""Checks for keypress, sends signal upon end."""
keystates = keywords['keystates']
- if self.r_keys == None:
- if max([keystates[key] for key in self.g_keys]):
- self.ready = True
- self.over = True
- elif not self.ready:
- if max([keystates[key] for key in self.r_keys]):
- self.ready = True
- else:
- if max([keystates[key] for key in self.g_keys]):
- self.over = True
+ if max([keystates[key] for key in self.cont_keys[self.steps_done]]):
+ self.steps_done += 1
+ if self.steps_done == self.num_steps:
+ self.over = True
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = {'dims': (5, 5),
'init_unit': (30, 30), 'end_unit': (50, 50),
'position': (0, 0), 'anchor': 'bottomleft',
'cols': ((0, 0, 0), (255, 255, 255)),
'freq': 1, 'phase': 0}
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
if PRERENDER_TO_TEXTURE:
init_pos = [(1 - a)* s/to_decimal(2) for s, a in
zip(self._size, graphics.locations[self.anchor])]
else:
init_pos = list(self.position)
init_unit = [c + m/2 for c, m in zip(self.init_unit, unit_grad)]
cur_unit = list(init_unit)
cur_unit_pos = list(init_pos)
# Add unit cells to batches in nested for loop
for j in range(self.dims[1]):
for i in range(self.dims[0]):
cur_unit_rect = graphics.Rect(cur_unit_pos, cur_unit,
anchor=self.anchor)
cur_unit_rect.col = self.cols[(i + j) % 2]
cur_unit_rect.add_to_batch(self._batches[0])
cur_unit_rect.col = self.cols[(i + j + 1) % 2]
cur_unit_rect.add_to_batch(self._batches[1])
# Increase x values
cur_unit_pos[0] += \
graphics.locations[self.anchor][0] * cur_unit[0]
cur_unit[0] += unit_grad[0]
# Reset x values
cur_unit_pos[0] = init_pos[0]
cur_unit[0] = init_unit[0]
# Increase y values
cur_unit_pos[1] += \
graphics.locations[self.anchor][1] * cur_unit[1]
cur_unit[1] += unit_grad[1]
if PRERENDER_TO_TEXTURE:
# Create textures
int_size = [int(round(s)) for s in self._size]
self._prerenders =\
[pyglet.image.Texture.create(*int_size) for n in range(2)]
# Set up framebuffer
fbo = graphics.Framebuffer()
for n in range(2):
fbo.attach_texture(self._prerenders[n])
# Draw batch to texture
fbo.start_render()
self._batches[n].draw()
fbo.end_render()
# Anchor textures for correct blitting later
self._prerenders[n].anchor_x, self._prerenders[n].anchor_y =\
[int(round((1 - a)* s/to_decimal(2))) for s, a in
zip(self._size, graphics.locations[self.anchor])]
fbo.delete()
# Delete batches since they won't be used
del self._batches
self._computed = True
def draw(self, always_compute=False):
"""Draws appropriate prerender depending on current phase."""
if not self._computed or always_compute:
self.compute()
self._cur_phase %= 360
n = int(self._cur_phase // 180)
if PRERENDER_TO_TEXTURE:
self._prerenders[n].blit(*self.position)
else:
self._batches[n].draw()
def lazydraw(self):
"""Only draws on color reversal."""
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if (cur_n != prev_n) or self._first_draw:
self.draw()
if self._first_draw:
self._first_draw = False
diff --git a/src/eyetracking.py b/src/eyetracking.py
index 897343e..c7db8c1 100644
--- a/src/eyetracking.py
+++ b/src/eyetracking.py
@@ -1,147 +1,154 @@
"""Provides support for CRS VideoEyetracker Toolbox."""
import os.path
try:
import win32com.client
available = True
except ImportError:
available = False
# COM ProgID of the Toolbox
ProgID = "crsVET.VideoEyeTracker"
RecordName = "etResultSet"
# VET application object
VET = None
class EyetrackingError(Exception):
"""Raised when something goes wrong with VET."""
pass
if available:
# Try dispatching object, else unavailable
try:
from win32com.client import gencache
# Ensure makepy module is generated
gencache.EnsureModule('{248DBF0C-A874-4032-82CE-DC5B307BB6E7}',
0, 3, 11)
VET = win32com.client.Dispatch(ProgID)
DummyResultSet = win32com.client.Record(RecordName, VET)
except:
available = False
if available:
# For easier access to constants and standardization with MATLAB interface
CRS = win32com.client.constants
lastgoodstamp = 0
def select_source(user_select = False, path = None):
if user_select:
if not VET.SelectVideoSource(CRS.vsUserSelect, ''):
msg = 'could not select video source'
raise EyetrackingError(msg)
elif path != None:
# Open from file
if not VET.SelectVideoSource(CRS.vsFile, path):
msg = 'could not use path as video source'
raise EyetrackingError(msg)
else:
# Default to 250 Hz High Speed Camera
if not VET.SelectVideoSource(CRS.vsHighSpeedCamera250, ''):
msg = 'could not select video source'
raise EyetrackingError(msg)
def is_source_ready():
"""Returns true if a video source has been selected."""
if VET.VideoSourceType == 0:
return False
else:
return True
def show_camera():
VET.CreateCameraScreen(0)
def quit_camera():
VET.DestroyCameraScreen()
def setup(viewing_distance=None, screen_dims=None,
fixation_period=None, fixation_range=None):
"""Calibrates the display and sets fixation properties."""
if viewing_distance != None and screen_dims != None:
if len(screen_dims) != 2:
msg = 'screen_dims must be a 2-tuple'
raise ValueError(msg)
VET.SetDeviceParameters(CRS.deUser, viewing_distance,
screen_dims[0], screen_dims[1])
if fixation_period != None:
VET.FixationPeriod = fixation_period
if fixation_range != None:
VET.FixationRange = fixation_range
def calibrate(path = None):
"""Calibrate the subject.
Optionally supply a path with no spaces to a
calibration file to load."""
if path == None:
if not VET.Calibrate():
msg = 'calibration failed'
raise EyetrackingError(msg)
else:
if not os.path.isfile(path):
msg = 'specified file does not exist'
raise EyetrackingError(msg)
if not VET.LoadCalibrationFile(path):
msg = 'file could not be loaded'
raise EyetrackingError(msg)
def is_calibrated():
if VET.CalibrationStatus()[0] != 0:
return True
else:
return False
def start():
"""Start tracking the eye."""
global lastgoodstamp
if VET.CalibrationStatus()[0] == 0:
msg = 'subject not yet calibrated'
raise EyetrackingError(msg)
lastgoodstamp = 0
VET.ClearDataBuffer()
VET.StartTracking()
def stop():
"""Stop tracking the eye."""
VET.StopTracking()
def is_tracked():
"""Returns true if the eye is being tracked."""
data = VET.GetLatestEyePosition(DummyResultSet)[1]
return data.Tracked
def is_fixated(fix_pos, fix_range, fix_period):
"""Checks whether subject is fixating on specificied location.
fix_pos -- (x, y) position of desired fixation location in mm
from center of screen
fix_range -- (width, height) of box surrounding fix_pos within
which fixation is allowed (in mm)
+ fix_period -- duration in milliseconds within which subject is
+ assumed to continue fixating after fixation is detected at a
+ specific time
+
"""
global lastgoodstamp
if VET.CalibrationStatus()[0] == 0:
msg = 'subject not yet calibrated'
raise EyetrackingError(msg)
data = VET.GetLatestEyePosition(DummyResultSet)[1]
pos = (data.ScreenPositionXmm, data.ScreenPositionYmm)
diff = [abs(p - fp) for p, fp in zip(pos, fix_pos)]
- if (data.Timestamp - lastgoodstamp) <= fix_period:
- return True
if data.Tracked == True:
if diff[0] < fix_range[0] and diff[1] < fix_range[1]:
lastgoodstamp = data.TimeStamp
return True
+ elif (data.Timestamp - lastgoodstamp) <= fix_period:
+ return True
+ elif (data.Timestamp - lastgoodstamp) <= fix_period:
+ return True
+
return False
|
ztangent/checkergen
|
dab29d6391200e60a1e1d6c8781c0f0794a718dc
|
Reimplemented is_fixated function, no longer reliant on VET.
|
diff --git a/src/core.py b/src/core.py
index 1af042c..c427d9f 100755
--- a/src/core.py
+++ b/src/core.py
@@ -1,1043 +1,1044 @@
"""Contains core functionality of checkergen.
Errors and Exceptions:
FileFormatError
FrameOverflowError
Classes:
CkgProj -- A checkergen project, contains settings and CkgDisplayGroups.
CkgDisplayGroup -- A set of CheckerShapes to be displayed simultaneously.
CheckerShapes -- Abstract checkered shape class
CheckerBoard -- A (distorted) checkerboard pattern, can color-flip.
"""
import os
import sys
import re
import csv
import itertools
from xml.dom import minidom
import pyglet
import graphics
import signals
import eyetracking
from utils import *
CKG_FMT = 'ckg'
XML_NAMESPACE = 'http://github.com/ZOMGxuan/checkergen'
MAX_EXPORT_FRAMES = 100000
PRERENDER_TO_TEXTURE = False
EXPORT_FMTS = ['png']
EXPORT_DIR_SUFFIX = '-anim'
BLOCK_DIR_SUFFIX = '-blks'
FIX_POS = (0, 0)
FIX_RANGE = (20, 20)
+FIX_PER = 350
SANS_SERIF = ('Helvetica', 'Arial', 'FreeSans')
def xml_get(parent, namespace, name, index=0):
"""Returns concatenated text node values inside an element."""
element = [node for node in parent.childNodes if
node.localName == name and
node.namespaceURI == namespace][index]
strings = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
strings.append(node.data)
return ''.join(strings)
def xml_set(document, parent, name, string):
"""Stores value as a text node in a new DOM element."""
element = document.createElement(name)
parent.appendChild(element)
text = document.createTextNode(string)
element.appendChild(text)
def xml_pretty_print(document, indent):
"""Hack to prettify minidom's not so pretty print."""
ugly_xml = document.toprettyxml(indent=indent)
prettifier_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</',
re.DOTALL)
pretty_xml = prettifier_re.sub('>\g<1></', ugly_xml)
return pretty_xml
class FileFormatError(ValueError):
"""Raised when correct file format/extension is not supplied."""
pass
class FrameOverflowError(Exception):
"""Raised when more than MAX_EXPORT_FRAMES are going to be exported."""
pass
class CkgProj:
"""Defines a checkergen project, with checkerboards and other settings."""
DEFAULTS = {'name': 'untitled',
'fps': 60,
'res': (800, 600),
'bg': (127, 127, 127),
'export_fmt': 'png',
'pre': 0,
'post': 0,
'cross_cols': ((0, 0, 0), (255, 0, 0)),
'cross_times': ('Infinity', 1)}
def __init__(self, **keywords):
"""Initializes a new project, or loads it from a path.
path -- if specified, ignore other arguments and load project
from path
name -- name of the project, always the same as the
filename without the extension
fps -- frames per second of the animation to be displayed
res -- screen resolution / window size at which project
will be displayed
bg -- background color of the animation as a 3-tuple (R, G, B)
export_fmt -- image format for animation to be exported as
pre -- time in seconds a blank screen will be shown before any
display groups
post --time in seconds a blank screen will be shown after any
display groups
"""
if 'path' in keywords.keys():
self.load(keywords['path'])
return
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.groups = []
def __setattr__(self, name, value):
# Type conversions
if name == 'name':
value = str(value)
elif name in ['fps', 'pre', 'post']:
value = to_decimal(value)
elif name == 'res':
if len(value) != 2:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'bg':
if len(value) != 3:
raise ValueError
value = tuple([int(v) for v in value])
elif name == 'export_fmt':
if value not in EXPORT_FMTS:
msg = 'image format not recognized or supported'
raise FileFormatError(msg)
elif name == 'cross_cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name == 'cross_times':
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
# Store value
self.__dict__[name] = value
# Set dirty bit
if name != '_dirty':
self._dirty = True
def add_group(self, group):
"""Append group to list and set dirty bit."""
self.groups.append(group)
self._dirty = True
return self.groups.index(group)
def del_group(self, group):
"""Remove group to list and set dirty bit."""
self.groups.remove(group)
self._dirty = True
def add_shape_to_group(self, group, shape):
"""Add shape to group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.append(shape)
self._dirty = True
return group.shapes.index(shape)
def del_shape_from_group(self, group, shape):
"""Removes shape from group specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
group.shapes.remove(shape)
self._dirty = True
def set_group_attr(self, gid, name, value):
"""Set attribute of a group specified by id and set dirty bit."""
setattr(self.groups[gid], name, value)
self._dirty = True
def set_shape_attr(self, group, sid, name, value):
"""Set attribute of a shape specified by id and set dirty bit."""
if group not in self.groups:
raise ValueError
setattr(group.shapes[sid], name, value)
self._dirty = True
def is_dirty(self):
return self._dirty
def load(self, path):
"""Loads project from specified path."""
# Get project name from filename
name, ext = os.path.splitext(os.path.basename(path))
if ext == '.{0}'.format(CKG_FMT):
self.name = name
else:
msg = "path lacks '.{0}' extension".format(CKG_FMT)
raise FileFormatError(msg)
with open(path, 'r') as project_file:
doc = minidom.parse(project_file)
project = doc.documentElement
vars_to_load = self.__class__.DEFAULTS.keys()
# Name is not stored in project file
vars_to_load.remove('name')
for var in vars_to_load:
try:
value = eval(xml_get(project, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
self.groups = []
group_els = [node for node in project.childNodes if
node.localName == 'group' and
node.namespaceURI == XML_NAMESPACE]
for group_el in group_els:
new_group = CkgDisplayGroup()
new_group.load(group_el)
self.groups.append(new_group)
self._dirty = False
def save(self, path):
"""Saves project to specified path as an XML document."""
self.name, ext = os.path.splitext(os.path.basename(path))
if ext != '.{0}'.format(CKG_FMT):
path = '{0}.{1}'.format(path, CKG_FMT)
impl = minidom.getDOMImplementation()
doc = impl.createDocument(XML_NAMESPACE, 'project', None)
project = doc.documentElement
# Hack below because minidom doesn't support namespaces properly
project.setAttribute('xmlns', XML_NAMESPACE)
vars_to_save = self.__class__.DEFAULTS.keys()
# Name is not stored in project file
vars_to_save.remove('name')
for var in vars_to_save:
xml_set(doc, project, var, repr(getattr(self, var)))
for group in self.groups:
group.save(doc, project)
with open(path, 'w') as project_file:
project_file.write(xml_pretty_print(doc,indent=' '))
self._dirty = False
return path
def mkblks(self, length, path=None, folder=True, flags=''):
"""Generates randomized experimental blocks from display groups.
Each block is saved as a CSV file.
length -- number of repeated trials within a block
path -- directory in which experimental blocks will be saved
folder -- blocks will be saved in a containing folder if true
flags -- string of flags to be issued to the display command when
block file is run
"""
if path == None:
path = os.getcwd()
if not os.path.isdir(path):
msg = "specified directory does not exist"
raise IOError(msg)
if folder:
path = os.path.join(path, self.name + BLOCK_DIR_SUFFIX)
if not os.path.isdir(path):
os.mkdir(path)
group_ids = range(len(self.groups))
for n, sequence in enumerate(itertools.permutations(group_ids)):
blkname = 'block{0}.csv'.format(repr(n).zfill(numdigits(length)))
blkfile = open(os.path.join(path, blkname), 'wb')
blkwriter = csv.writer(blkfile, dialect='excel-tab')
blkwriter.writerow(['checkergen experimental block file'])
blkwriter.writerow(['flags:', flags])
blkwriter.writerow(['repeats:', length])
blkwriter.writerow(['sequence:'] + list(sequence))
blkfile.close()
@staticmethod
def readblk(path):
"""Reads the information in a block file and returns it in a dict."""
if not os.path.isfile(path):
msg = "specified file does not exist"
raise IOError(msg)
blkdict = dict()
blkfile = open(path, 'rb')
blkreader = csv.reader(blkfile, dialect='excel-tab')
for n, row in enumerate(blkreader):
if n == 1:
blkdict['flags'] = row[1]
elif n == 2:
repeats = int(row[1])
elif n == 3:
sequence = row[1:]
sequence = [int(i) for i in sequence]
blkfile.close()
blkdict['idlist'] = ([-1] + sequence) * repeats
return blkdict
def display(self, fullscreen=False, logtime=False, logdur=False,
sigser=False, sigpar=False, fpbs=0, phototest=False,
eyetrack=False, etuser=False, etvideo=None,
tryagain=0, trybreak=0, group_queue=[]):
"""Displays the project animation on the screen.
fullscreen -- animation is displayed fullscreen if true, stretched
to fit if necessary
logtime -- timestamp of each frame is saved to a logfile if true
logdur -- duration of each frame is saved to a logfile if true
sigser -- send signals through serial port when each group is shown
sigpar -- send signals through parallel port when each group is shown
fpbs -- flips per board signal, i.e. number of shape color reversals
(flips) that occur for a unique signal to be sent for that shape
phototest -- draw white rectangle in topleft corner when each group is
shown for photodiode to detect
eyetrack -- use eyetracking to ensure subject is fixating on cross
etuser -- if true, user gets to select eyetracking video source in GUI
etvideo -- optional eyetracking video source file to use instead of
live feed
tryagain -- Append groups during which subject failed to fixated up to
this number of times to the group queue
trybreak -- Append a wait screen to the group queue every time
after this many groups have been appended to the queue
group_queue -- queue of groups to be displayed, defaults to order of
groups in project (i.e. groups[0] first, etc.)
"""
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Create test rectangle
if phototest:
test_rect = graphics.Rect((0, self.res[1]),
[r/8 for r in self.res],
anchor='topleft')
# Set-up groups and variables that control their display
if group_queue == []:
group_queue = list(self.groups)
cur_group = None
cur_id = -1
flipped = 0
flip_id = -1
groups_duration = sum([group.duration() for group in group_queue])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Initialize ports
if sigser:
if not signals.available['serial']:
msg = 'serial port functionality not available'
raise NotImplementedError(msg)
if sigpar:
if not signals.available['parallel']:
msg = 'parallel port functionality not available'
raise NotImplementedError(msg)
signals.init(sigser, sigpar)
# Initialize eyetracking
if eyetrack:
if not eyetracking.available:
msg = 'eyetracking functionality not available'
raise NotImplementedError(msg)
fixated = False
old_fixated = False
tracked = False
old_tracked = False
cur_fix_fail = False
fix_fail_queue = []
eyetracking.select_source(etuser, etvideo)
eyetracking.start()
# Stretch to fit screen only if project res does not equal screen res
scaling = False
if fullscreen:
window = pyglet.window.Window(fullscreen=True, visible=False)
if (window.width, window.height) != self.res:
scaling = True
else:
window = pyglet.window.Window(*self.res, visible=False)
# Set up KeyStateHandler to handle keyboard input
keystates = pyglet.window.key.KeyStateHandler()
window.push_handlers(keystates)
# Create framebuffer object for drawing unscaled scene
if scaling:
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
fbo.end_render()
# Clear window and make visible
window.switch_to()
graphics.set_clear_color(self.bg)
window.clear()
window.set_visible()
# Initialize logging variables
if logtime and logdur:
logstring = ''
stamp = Timer()
dur = Timer()
stamp.start()
dur.start()
elif logtime or logdur:
logstring = ''
timer = Timer()
timer.start()
# Main loop
while not window.has_exit and count < disp_end:
# Clear canvas
if scaling:
fbo.start_render()
fbo.clear()
else:
window.clear()
# Assume no change to group visibility
flipped = 0
signals.set_null()
# Manage groups when they are on_screen
if groups_visible:
# Send special signal if waitscreen ends
if isinstance(cur_group, CkgWaitScreen):
if cur_group.over:
signals.set_user_start()
cur_group = None
elif cur_group != None:
# Check whether group changes in visibility
if cur_group.visible != cur_group.old_visible:
flip_id = self.groups.index(cur_group)
if cur_group.visible:
flipped = 1
elif cur_group.old_visible:
flipped = -1
# Check if current group is over
if cur_group.over:
cur_group = None
# Get next group from queue
if cur_group == None:
cur_id += 1
if cur_id >= len(group_queue):
groups_visible = False
else:
cur_group = group_queue[cur_id]
cur_group.reset()
if eyetrack:
cur_fix_fail = False
if cur_group.visible:
flip_id = self.groups.index(cur_group)
flipped = 1
# Draw and then update group
if cur_group != None:
cur_group.draw()
cur_group.update(fps=self.fps,
fpbs=fpbs,
keystates=keystates)
# Send signals upon group visibility change
if flipped == 1:
signals.set_group_start(flip_id)
# Draw test rectangle
if phototest:
test_rect.draw()
elif flipped == -1:
signals.set_group_stop(flip_id)
if eyetrack:
# First check if eye is being tracked and send signals
old_tracked = tracked
tracked = eyetracking.is_tracked()
if tracked:
if not old_tracked:
# Send signal if eye starts being tracked
signals.set_track_start()
else:
if old_tracked:
# Send signal if eye stops being tracked
signals.set_track_stop()
# Next check for fixation
old_fixated = fixated
- fixated = eyetracking.is_fixated(FIX_POS, FIX_RANGE)
+ fixated = eyetracking.is_fixated(FIX_POS, FIX_RANGE, FIX_PER)
if fixated:
# Draw normal cross color if fixating
fix_crosses[0].draw()
if not old_fixated:
# Send signal if fixation starts
signals.set_fix_start()
else:
# Draw alternative cross color if not fixating
fix_crosses[1].draw()
if old_fixated:
# Send signal if fixation stops
signals.set_fix_stop()
# Take note of which groups in which fixation failed
if not cur_fix_fail and cur_group.visible and\
(tracked and not fixated):
cur_fix_fail = True
if len(fix_fail_queue) == 0 and trybreak > 0:
group_queue.append(CkgWaitScreen())
fix_fail_queue.append(self.groups.index(cur_group))
# Append failed group to group queue
if tryagain > 0:
group_queue.append(cur_group)
groups_stop += cur_group.duration() * self.fps
disp_end += cur_group.duration() * self.fps
# Insert waitscreen every tryagainbreak failed groups
if trybreak > 0:
if len(fix_fail_queue) % trybreak == 0:
group_queue.append(CkgWaitScreen())
tryagain -= 1
# Change cross color based on time if eyetracking is not enabled
if not eyetrack:
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Increment count and set whether groups should be shown
if not isinstance(cur_group, CkgWaitScreen):
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
# Blit canvas to screen if necessary
if scaling:
fbo.end_render()
window.switch_to()
canvas.blit(0, 0)
window.dispatch_events()
window.flip()
# Make sure everything has been drawn
pyglet.gl.glFinish()
# Append time information to log string
if logtime and logdur:
logstring = '\n'.join([logstring, str(stamp.elapsed())])
logstring = '\t'.join([logstring, str(dur.restart())])
elif logtime:
logstring = '\n'.join([logstring, str(timer.elapsed())])
elif logdur:
logstring = '\n'.join([logstring, str(timer.restart())])
# Send signals ASAP after flip
signals.send(sigser, sigpar)
# Log when signals are sent
if logtime or logdur:
if flipped != 0 and (sigser or sigpar):
sigmsg = '{0} sent'.format(signals.STATE)
logstring = '\t'.join([logstring, sigmsg])
# Clean up
if eyetrack:
eyetracking.stop()
window.close()
if scaling:
fbo.delete()
del canvas
signals.quit(sigser, sigpar)
# Write log string to file
if logtime or logdur:
filename = '{0}.log'.format(self.name)
with open(filename, 'w') as logfile:
logfile.write(logstring)
# Return list of ids of failed groups
if eyetrack:
return fix_fail_queue
def export(self, export_dir, export_duration, group_queue=[],
export_fmt=None, folder=True, force=False):
if not os.path.isdir(export_dir):
msg = 'export path is not a directory'
raise IOError(msg)
if export_fmt == None:
export_fmt = self.export_fmt
# Set-up groups and variables that control their display
if group_queue == []:
group_queue = list(self.groups)
cur_group = None
cur_id = -1
groups_duration = sum([group.duration() for group in group_queue])
groups_start = self.pre * self.fps
groups_stop = (self.pre + groups_duration) * self.fps
disp_end = (self.pre + groups_duration + self.post) * self.fps
if groups_start == 0 and groups_stop > 0:
groups_visible = True
else:
groups_visible = False
count = 0
# Limit export duration to display duration
frames = export_duration * self.fps
frames = min(frames, disp_end)
# Warn user if a lot of frames will be exported
if frames > MAX_EXPORT_FRAMES and not force:
msg = 'very large number ({0}) of frames to be exported'.\
format(frames)
raise FrameOverflowError(msg)
# Create folder to store images if necessary
if folder:
export_dir = os.path.join(export_dir,
self.name + EXPORT_DIR_SUFFIX)
if not os.path.isdir(export_dir):
os.mkdir(export_dir)
# Create fixation crosses
fix_crosses = [graphics.Cross([r/2 for r in self.res],
(20, 20), col = cross_col)
for cross_col in self.cross_cols]
# Set up canvas and framebuffer object
canvas = pyglet.image.Texture.create(*self.res)
fbo = graphics.Framebuffer(canvas)
fbo.start_render()
graphics.set_clear_color(self.bg)
fbo.clear()
# Main loop
while count < frames:
fbo.clear()
if groups_visible:
# Check if current group is over
if cur_group != None:
if cur_group.over:
cur_group = None
# Get next group from queue
if cur_group == None:
cur_id += 1
if cur_id >= len(group_queue):
groups_visible = False
else:
cur_group = group_queue[cur_id]
cur_group.reset()
# Draw and then update group
if cur_group != None:
cur_group.draw()
cur_group.update(fps=self.fps, fpbs=0)
# Draw fixation cross based on current count
if (count % (sum(self.cross_times) * self.fps)
< self.cross_times[0] * self.fps):
fix_crosses[0].draw()
else:
fix_crosses[1].draw()
# Save current frame to file
savepath = \
os.path.join(export_dir,
'{0}{2}.{1}'.
format(self.name, export_fmt,
repr(count).zfill(numdigits(frames-1))))
canvas.save(savepath)
# Increment count and set whether groups should be shown
count += 1
if groups_start <= count < groups_stop:
groups_visible = True
else:
groups_visible = False
fbo.delete()
class CkgDisplayGroup:
DEFAULTS = {'pre': 0, 'disp': 'Infinity', 'post': 0}
def __init__(self, **keywords):
"""Create a new group of shapes to be displayed together.
pre -- time in seconds a blank screen is shown before
shapes in group are displayed
disp -- time in seconds the shapes in the group are displayed,
negative numbers result in shapes being displayed forever
post -- time in seconds a blank screen is shown after
shapes in group are displayed
"""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.shapes = []
self.reset()
def __setattr__(self, name, value):
if name in self.__class__.DEFAULTS:
value = to_decimal(value)
self.__dict__[name] = value
def duration(self):
"""Returns total duration of display group."""
return self.pre + self.disp + self.post
def reset(self):
"""Resets internal count and all contained shapes."""
self._count = 0
self._start = self.pre
self._stop = self.pre + self.disp
self._end = self.pre + self.disp + self.post
self.over = False
self.old_visible = False
if self._start == 0 and self._stop > 0:
self.visible = True
else:
self.visible = False
if self._end == 0:
self.over = True
self._flip_count = [0] * len(self.shapes)
for shape in self.shapes:
shape.reset()
def draw(self, lazy=False):
"""Draws all contained shapes during the appropriate interval."""
if self.visible:
for shape in self.shapes:
if lazy:
shape.lazydraw()
else:
shape.draw()
def update(self, **keywords):
"""Increments internal count, makes group visible when appropriate.
fps -- refresh rate of the display in frames per second
fpbs -- flips per board signal, i.e. number of shape color reversals
(flips) that occur for a unique signal to be sent for that shape
"""
fps = keywords['fps']
fpbs = keywords['fpbs']
if self.visible:
# Set triggers to be sent
if fpbs > 0:
for n, shape in enumerate(self.shapes):
if shape.flipped:
self._flip_count[n] += 1
if self._flip_count[n] >= fpbs:
signals.set_board_flip(n)
self._flip_count[n] = 0
# Update contained shapes
for shape in self.shapes:
shape.update(fps)
# Increment count and set flags for the next frame
self._count += 1
self.old_visible = self.visible
if (self._start * fps) <= self._count < (self._stop * fps):
self.visible = True
else:
self.visible = False
if self._count >= (self._end * fps):
self.over = True
else:
self.over = False
def save(self, document, parent):
"""Saves group in specified XML document as child of parent."""
group_el = document.createElement('group')
parent.appendChild(group_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, group_el, var, repr(getattr(self, var)))
for shape in self.shapes:
shape.save(document, group_el)
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
shape_els = [node for node in element.childNodes if
node.localName == 'shape' and
node.namespaceURI == XML_NAMESPACE]
for shape_el in shape_els:
# TODO: Make load code shape-agnostic
new_shape = CheckerBoard()
new_shape.load(shape_el)
self.shapes.append(new_shape)
class CkgWaitScreen(CkgDisplayGroup):
"""Dummy display group, waits for user input to proceed."""
DEFAULTS = {'g_keys': (pyglet.window.key.SPACE,),
'r_keys': (pyglet.window.key.NUM_ENTER,
pyglet.window.key.ENTER),
'res': CkgProj.DEFAULTS['res'],
'g_info': "the experiment will start soon",
'r_info': "press enter when ready",
'font_color': (0, 0, 0, 255),
'font_size': 16}
def __init__(self, **keywords):
"""Create an informative waitscreen that proceeds after user input."""
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.g_label = pyglet.text.Label(self.g_info,
font_name=SANS_SERIF,
font_size=self.font_size,
color=self.font_color,
bold=True,
x=self.res[0]//2,
y=self.res[1]*16//30,
anchor_x='center',
anchor_y='center')
self.r_label = pyglet.text.Label(self.r_info,
font_name=SANS_SERIF,
font_size=self.font_size,
color=self.font_color,
bold=True,
x=self.res[0]//2,
y=self.res[1]*16//30,
anchor_x='center',
anchor_y='center')
self.reset()
def __setattr__(self, name, value):
self.__dict__[name] = value
def duration(self):
"""Returns zero since wait times are arbitrary."""
return to_decimal(0)
def reset(self):
"""Resets some flags."""
self.visible = False
self.old_visible = False
self.ready = False
self.over = False
def draw(self):
"""Draw informative text."""
if not self.ready:
self.r_label.draw()
else:
self.g_label.draw()
def update(self, **keywords):
"""Checks for keypress, sends signal upon end."""
keystates = keywords['keystates']
if self.r_keys == None:
if max([keystates[key] for key in self.g_keys]):
self.ready = True
self.over = True
elif not self.ready:
if max([keystates[key] for key in self.r_keys]):
self.ready = True
else:
if max([keystates[key] for key in self.g_keys]):
self.over = True
class CheckerShape:
# Abstract class, to be implemented.
pass
class CheckerDisc(CheckerShape):
# Circular checker pattern, to be implemented
pass
class CheckerBoard(CheckerShape):
DEFAULTS = {'dims': (5, 5),
'init_unit': (30, 30), 'end_unit': (50, 50),
'position': (0, 0), 'anchor': 'bottomleft',
'cols': ((0, 0, 0), (255, 255, 255)),
'freq': 1, 'phase': 0}
# TODO: Reimplement mid/center anchor functionality in cool new way
def __init__(self, **keywords):
for kw in self.__class__.DEFAULTS.keys():
if kw in keywords.keys():
setattr(self, kw, keywords[kw])
else:
setattr(self, kw, self.__class__.DEFAULTS[kw])
self.reset()
def __setattr__(self, name, value):
# Type conversions
if name == 'dims':
if len(value) != 2:
raise ValueError
value = tuple([int(x) for x in value])
elif name in ['init_unit', 'end_unit', 'position']:
if len(value) != 2:
raise ValueError
value = tuple([to_decimal(x) for x in value])
elif name == 'anchor':
if value not in graphics.locations.keys():
raise ValueError
elif name == 'cols':
if len(value) != 2:
raise ValueError
for col in value:
if len(col) != 3:
raise ValueError
value = tuple([tuple([int(c) for c in col]) for col in value])
elif name in ['freq', 'phase']:
value = to_decimal(value)
# Store value
self.__dict__[name] = value
# Recompute if necessary
if name in ['dims', 'init_unit', 'end_unit',
'position', 'anchor','cols']:
self._computed = False
def save(self, document, parent):
"""Saves board in specified XML document as child of parent."""
board_el = document.createElement('shape')
board_el.setAttribute('type', 'board')
parent.appendChild(board_el)
for var in self.__class__.DEFAULTS.keys():
xml_set(document, board_el, var, repr(getattr(self, var)))
def load(self, element):
"""Loads group from XML DOM element."""
for var in self.__class__.DEFAULTS.keys():
try:
value = eval(xml_get(element, XML_NAMESPACE, var))
except IndexError:
print "warning: missing attribute '{0}'".format(var)
value = self.__class__.DEFAULTS[var]
print "using default value '{0}' instead...".format(value)
setattr(self, var, value)
def reset(self, new_phase=None):
"""Resets checkerboard animation back to initial phase."""
if new_phase == None:
new_phase = self.phase
self._cur_phase = new_phase
self._prev_phase = new_phase
self.flipped = False
self._first_draw = True
if not self._computed:
self.compute()
def update(self, fps):
"""Increase the current phase of the checkerboard animation."""
self._prev_phase = self._cur_phase
if self.freq != 0:
degs_per_frame = 360 * self.freq / fps
self._cur_phase += degs_per_frame
if self._cur_phase >= 360:
self._cur_phase %= 360
cur_n = int(self._cur_phase // 180)
prev_n = int(self._prev_phase // 180)
if cur_n != prev_n:
self.flipped = True
else:
self.flipped = False
def compute(self):
"""Computes a model of the checkerboard for drawing later."""
# Create batches to store model
self._batches = [pyglet.graphics.Batch() for n in range(2)]
# Calculate size of checkerboard in pixels
self._size = tuple([(y1 + y2) / 2 * n for y1, y2, n in
zip(self.init_unit, self.end_unit, self.dims)])
# Calculate unit size gradient
unit_grad = tuple([(2 if (flag == 0) else 1) *
(y2 - y1) / n for y1, y2, n, flag in
zip(self.init_unit, self.end_unit, self.dims,
graphics.locations[self.anchor])])
# Set initial values
if PRERENDER_TO_TEXTURE:
init_pos = [(1 - a)* s/to_decimal(2) for s, a in
diff --git a/src/eyetracking.py b/src/eyetracking.py
index 982780a..897343e 100644
--- a/src/eyetracking.py
+++ b/src/eyetracking.py
@@ -1,138 +1,147 @@
"""Provides support for CRS VideoEyetracker Toolbox."""
import os.path
try:
import win32com.client
available = True
except ImportError:
available = False
# COM ProgID of the Toolbox
ProgID = "crsVET.VideoEyeTracker"
RecordName = "etResultSet"
# VET application object
VET = None
class EyetrackingError(Exception):
"""Raised when something goes wrong with VET."""
pass
if available:
# Try dispatching object, else unavailable
try:
from win32com.client import gencache
# Ensure makepy module is generated
gencache.EnsureModule('{248DBF0C-A874-4032-82CE-DC5B307BB6E7}',
0, 3, 11)
VET = win32com.client.Dispatch(ProgID)
DummyResultSet = win32com.client.Record(RecordName, VET)
except:
available = False
if available:
# For easier access to constants and standardization with MATLAB interface
CRS = win32com.client.constants
+
+ lastgoodstamp = 0
def select_source(user_select = False, path = None):
if user_select:
if not VET.SelectVideoSource(CRS.vsUserSelect, ''):
msg = 'could not select video source'
raise EyetrackingError(msg)
elif path != None:
# Open from file
if not VET.SelectVideoSource(CRS.vsFile, path):
msg = 'could not use path as video source'
raise EyetrackingError(msg)
else:
# Default to 250 Hz High Speed Camera
if not VET.SelectVideoSource(CRS.vsHighSpeedCamera250, ''):
msg = 'could not select video source'
raise EyetrackingError(msg)
def is_source_ready():
"""Returns true if a video source has been selected."""
if VET.VideoSourceType == 0:
return False
else:
return True
def show_camera():
VET.CreateCameraScreen(0)
def quit_camera():
VET.DestroyCameraScreen()
def setup(viewing_distance=None, screen_dims=None,
fixation_period=None, fixation_range=None):
"""Calibrates the display and sets fixation properties."""
if viewing_distance != None and screen_dims != None:
if len(screen_dims) != 2:
msg = 'screen_dims must be a 2-tuple'
raise ValueError(msg)
VET.SetDeviceParameters(CRS.deUser, viewing_distance,
screen_dims[0], screen_dims[1])
if fixation_period != None:
VET.FixationPeriod = fixation_period
if fixation_range != None:
VET.FixationRange = fixation_range
def calibrate(path = None):
"""Calibrate the subject.
Optionally supply a path with no spaces to a
calibration file to load."""
if path == None:
if not VET.Calibrate():
msg = 'calibration failed'
raise EyetrackingError(msg)
else:
if not os.path.isfile(path):
msg = 'specified file does not exist'
raise EyetrackingError(msg)
if not VET.LoadCalibrationFile(path):
msg = 'file could not be loaded'
raise EyetrackingError(msg)
def is_calibrated():
if VET.CalibrationStatus()[0] != 0:
return True
else:
return False
def start():
"""Start tracking the eye."""
+ global lastgoodstamp
if VET.CalibrationStatus()[0] == 0:
msg = 'subject not yet calibrated'
raise EyetrackingError(msg)
+ lastgoodstamp = 0
VET.ClearDataBuffer()
VET.StartTracking()
def stop():
"""Stop tracking the eye."""
VET.StopTracking()
def is_tracked():
"""Returns true if the eye is being tracked."""
data = VET.GetLatestEyePosition(DummyResultSet)[1]
return data.Tracked
- def is_fixated(fix_pos, fix_range):
+ def is_fixated(fix_pos, fix_range, fix_period):
"""Checks whether subject is fixating on specificied location.
fix_pos -- (x, y) position of desired fixation location in mm
from center of screen
fix_range -- (width, height) of box surrounding fix_pos within
which fixation is allowed (in mm)
"""
+ global lastgoodstamp
if VET.CalibrationStatus()[0] == 0:
msg = 'subject not yet calibrated'
raise EyetrackingError(msg)
- if VET.FixationLocation.Fixation:
- xdiff = abs(VET.FixationLocation.Xposition - fix_pos[0])
- ydiff = abs(VET.FixationLocation.Yposition - fix_pos[1])
- if (xdiff <= fix_range[0]/2) and (ydiff <= fix_range[1]/2):
+ data = VET.GetLatestEyePosition(DummyResultSet)[1]
+ pos = (data.ScreenPositionXmm, data.ScreenPositionYmm)
+ diff = [abs(p - fp) for p, fp in zip(pos, fix_pos)]
+ if (data.Timestamp - lastgoodstamp) <= fix_period:
+ return True
+ if data.Tracked == True:
+ if diff[0] < fix_range[0] and diff[1] < fix_range[1]:
+ lastgoodstamp = data.TimeStamp
return True
return False
|
ztangent/checkergen
|
16b10a719c6b65373d88eb7d653ceb57537fe97f
|
Added etsetup command.
|
diff --git a/src/cli.py b/src/cli.py
index 38fceb9..7e9df75 100644
--- a/src/cli.py
+++ b/src/cli.py
@@ -544,539 +544,575 @@ class CkgCmd(cmd.Cmd):
if x >= len(self.cur_group.shapes) or x < 0:
args.idlist.remove(x)
print "checkerboard", x, "does not exist"
if args.idlist == []:
return
names = public_dir(args)
names.remove('idlist')
noflags = True
for name in names:
val = getattr(args, name)
if val != None:
for x in args.idlist:
self.cur_proj.set_shape_attr(self.cur_group, x, name, val)
noflags = False
if noflags:
print "no options specified, please specify at least one"
self.__class__.ed_parser.print_usage()
rm_parser = CmdParser(add_help=False, prog='rm',
description='''Removes checkerboards specified
by ids.''')
rm_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''ids of checkerboards in the current group
to be removed''')
rm_parser.add_argument('-a', '--all', action='store_true',
help='''remove all checkerboards in the
current group''')
def help_rm(self):
self.__class__.rm_parser.print_help()
def do_rm(self, line):
"""Removes checkerboards specified by ids"""
if self.cur_proj == None:
print 'please create or open a project first'
return
elif self.cur_group == None:
print 'current project has no groups, no boards to remove'
return
try:
args = self.__class__.rm_parser.parse_args(shlex.split(line))
except CmdParserError:
print "error:", str(sys.exc_value)
self.__class__.rm_parser.print_usage()
return
rmlist = []
if args.all:
for shape in self.cur_group.shapes:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
print "all checkerboards removed"
return
elif len(args.idlist) == 0:
print "please specify at least one id"
# Remove duplicates and ascending sort
args.idlist = sorted(set(args.idlist))
for x in args.idlist:
if x >= len(self.cur_group.shapes) or x < 0:
print "checkerboard", x, "does not exist"
continue
rmlist.append(self.cur_group.shapes[x])
print "checkerboard", x, "removed"
for shape in rmlist:
self.cur_proj.del_shape_from_group(self.cur_group, shape)
ls_parser = CmdParser(add_help=False, prog='ls',
description='''Lists project, display group and
checkerboard settings. If no group ids
are specified, all display groups
are listed.''')
ls_parser.add_argument('gidlist', nargs='*', metavar='gid', type=int,
help='''ids of the display groups to be listed''')
ls_group = ls_parser.add_mutually_exclusive_group()
ls_group.add_argument('-s', '--settings', action='store_true',
help='list only project settings')
ls_group.add_argument('-g', '--groups', action='store_true',
help='list only display groups')
def help_ls(self):
self.__class__.ls_parser.print_help()
def do_ls(self, line):
"""Lists project, display group and checkerboard settings."""
def ls_str(s, seps=[',',';']):
"""Special space-saving output formatter."""
if type(s) in [tuple, list]:
if len(seps) > 1:
newseps = seps[1:]
else:
newseps = seps
return seps[0].join([ls_str(i, newseps) for i in s])
else:
return str(s)
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.ls_parser.parse_args(shlex.split(line))
except CmdParserError:
print "error:", str(sys.exc_value)
self.__class__.ls_parser.print_usage()
return
# Remove duplicates and ascending sort
args.gidlist = sorted(set(args.gidlist))
if len(self.cur_proj.groups) == 0:
if len(args.gidlist) > 0:
print 'this project has no display groups that can be listed'
args.settings = True
else:
for gid in args.gidlist[:]:
if gid >= len(self.cur_proj.groups) or gid < 0:
args.gidlist.remove(gid)
print 'display group', gid, 'does not exist'
if args.gidlist == []:
args.gidlist = range(len(self.cur_proj.groups))
else:
# If any (valid) groups are specified
# don't show project settings
args.groups = True
if not args.groups:
print 'PROJECT SETTINGS'.center(70,'*')
print \
'name'.rjust(16),\
'fps'.rjust(7),\
'resolution'.rjust(14),\
'bg color'.rjust(18)
# 'format'.rjust(7)
print \
ls_str(self.cur_proj.name).rjust(16),\
ls_str(self.cur_proj.fps).rjust(7),\
ls_str(self.cur_proj.res).rjust(14),\
ls_str(self.cur_proj.bg).rjust(18)
# ls_str(self.cur_proj.export_fmt).rjust(7)
print \
'pre-display'.rjust(26),\
'post-display'.rjust(26)
print \
ls_str(self.cur_proj.pre).rjust(26),\
ls_str(self.cur_proj.post).rjust(26)
print \
'cross colors'.rjust(26),\
'cross times'.rjust(26)
print \
ls_str(self.cur_proj.cross_cols).rjust(26),\
ls_str(self.cur_proj.cross_times).rjust(26)
if not args.settings and not args.groups:
# Insert empty line if both groups and project
# settings are listed
print ''
if not args.settings:
for i, n in enumerate(args.gidlist):
if i != 0:
# Print newline seperator between each group
print ''
group = self.cur_proj.groups[n]
print 'GROUP {n}'.format(n=n).center(70,'*')
print \
'pre-display'.rjust(20),\
'display'.rjust(20),\
'post-display'.rjust(20)
print \
ls_str(group.pre).rjust(20),\
ls_str(group.disp).rjust(20),\
ls_str(group.post).rjust(20)
if len(group.shapes) > 0:
print \
''.rjust(2),\
'shape id'.rjust(8),\
'dims'.rjust(10),\
'init_unit'.rjust(14),\
'end_unit'.rjust(14),\
'position'.rjust(14)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.dims).rjust(10),\
ls_str(shape.init_unit).rjust(14),\
ls_str(shape.end_unit).rjust(14),\
ls_str(shape.position).rjust(14)
print '\n',\
''.rjust(2),\
'shape id'.rjust(8),\
'colors'.rjust(27),\
'anchor'.rjust(12),\
'freq'.rjust(6),\
'phase'.rjust(7)
for m, shape in enumerate(group.shapes):
print \
''.rjust(2),\
ls_str(m).rjust(8),\
ls_str(shape.cols).rjust(27),\
ls_str(shape.anchor).rjust(12),\
ls_str(shape.freq).rjust(6),\
ls_str(shape.phase).rjust(7)
display_parser = CmdParser(add_help=False, prog='display',
description='''Displays the animation in a
window or in fullscreen.''')
display_parser.add_argument('-b', '--block', metavar='PATH',
help='''read flags and dislay group order from
specified file, ignore other flags''')
display_parser.add_argument('-f', '--fullscreen', action='store_true',
help='sets fullscreen mode, ESC to quit')
display_parser.add_argument('-p', '--priority', metavar='LEVEL',
help='''set priority while displaying,
higher priority results in
less dropped frames (choices:
0-3, low, normal, high,
realtime)''')
display_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly display specified display
groups N number of times''')
display_parser.add_argument('-pt', '--phototest', action='store_true',
help='''draw white test rectangle in topleft
corner of screen when groups become
visible for a photodiode to detect''')
display_parser.add_argument('-lt', '--logtime', action='store_true',
help='output frame timestamps to a log file')
display_parser.add_argument('-ld', '--logdur', action='store_true',
help='output frame durations to a log file')
display_parser.add_argument('-ss', '--sigser', action='store_true',
help='''send signals through the serial port
when shapes are being displayed''')
display_parser.add_argument('-sp', '--sigpar', action='store_true',
help='''send signals through the parallel port
when shapes are being displayed''')
display_parser.add_argument('-fpbs', metavar='N', type=int, default=0,
help='''unique signal corresponding to a
checkerboard is sent after the board
undergoes N color reversals (flips),
set to 0 to disable''')
display_parser.add_argument('-et', '--eyetrack', action='store_true',
help='''use eyetracking to ensure that subject
fixates on the cross in the center''')
display_parser.add_argument('-eu', '--etuser', action='store_true',
help='''allow user to select eyetracking video
source from a dialog''')
display_parser.add_argument('-ev', '--etvideo', metavar='path',
help='''path (with no spaces) to eyetracking
video file to be used as the source''')
display_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be displayed
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_display(self):
self.__class__.display_parser.print_help()
def do_display(self, line):
"""Displays the animation in a window or in fullscreen"""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.display_parser.parse_args(shlex.split(line))
except CmdParserError:
print "error:", str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
if args.block != None:
try:
blkdict = core.CkgProj.readblk(args.block)
flags = blkdict['flags']
try:
args = self.__class__.\
display_parser.parse_args(shlex.split(flags))
args.idlist = blkdict['idlist']
except CmdParserError:
print 'error: invalid flags stored in block file'
return
except IOError:
print "error:", str(sys.exc_value)
return
group_queue = []
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < -1:
print 'error: group', i, 'does not exist'
return
for i in args.idlist:
if i == -1:
group_queue.append(core.CkgWaitScreen())
else:
group_queue.append(self.cur_proj.groups[i])
else:
group_queue = list(self.cur_proj.groups)
if args.repeat != None:
group_queue = list(group_queue * args.repeat)
if args.priority != None:
if not priority.available:
print "error: setting priority not avaible on", sys.platform
print "continuing..."
else:
if args.priority.isdigit():
args.priority = int(args.priority)
try:
priority.set(args.priority)
except ValueError:
print "error:", str(sys.exc_value)
print "continuing..."
if args.eyetrack and eyetracking.available:
if not eyetracking.is_calibrated():
try:
self.do_calibrate('',True)
except eyetracking.EyetrackingError:
print "error:", str(sys.exc_value)
return
try:
self.cur_proj.display(fullscreen=args.fullscreen,
logtime=args.logtime,
logdur=args.logdur,
sigser=args.sigser,
sigpar=args.sigpar,
fpbs=args.fpbs,
phototest=args.phototest,
eyetrack=args.eyetrack,
etuser=args.etuser,
etvideo=args.etvideo,
group_queue=group_queue)
except (IOError, NotImplementedError, eyetracking.EyetrackingError):
print "error:", str(sys.exc_value)
return
if args.priority != None:
try:
priority.set('normal')
except:
pass
export_parser = CmdParser(add_help=False, prog='export',
description='''Exports animation as an image
sequence (in a folder) to the
specified directory.''')
# export_parser.add_argument('--fmt', dest='export_fmt',
# choices=core.EXPORT_FMTS,
# help='image format for export')
export_parser.add_argument('-n','--nofolder',
dest='folder', action='store_false',
help='''force images not to exported in
a containing folder''')
export_parser.add_argument('-r', '--repeat', metavar='N', type=int,
help='''repeatedly export specified display
groups N number of times''')
export_parser.add_argument('duration', nargs='?',
type=to_decimal, default='Infinity',
help='''number of seconds of the animation
that should be exported (default:
as long as the entire animation)''')
export_parser.add_argument('dir', nargs='?', default=os.getcwd(),
help='''destination directory for export
(default: current working directory)''')
export_parser.add_argument('idlist', nargs='*', metavar='id', type=int,
help='''list of display groups to be exported
in the specified order (default: order
by id, i.e. group 0 is first)''')
def help_export(self):
self.__class__.export_parser.print_help()
def do_export(self, line):
"""Exports animation an image sequence to the specified directory."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.export_parser.parse_args(shlex.split(line))
except CmdParserError:
print "error:", str(sys.exc_value)
self.__class__.export_parser.print_usage()
return
if len(args.idlist) > 0:
for i in set(args.idlist):
if i >= len(self.cur_proj.groups) or i < 0:
print 'error: group', i, 'does not exist'
return
group_queue = [self.cur_proj.groups[i] for i in args.idlist]
else:
group_queue = list(self.cur_proj.groups)
if args.repeat != None:
group_queue = list(group_queue * args.repeat)
try:
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
group_queue=group_queue,
folder=args.folder)
except IOError:
print "error:", str(sys.exc_value)
return
except core.FrameOverflowError:
print "warning:", str(sys.exc_value)
print "Are you sure you want to continue?"
while True:
try:
if self.__class__.yn_parse(raw_input()):
self.cur_proj.export(export_dir=args.dir,
export_duration=args.duration,
group_queue=group_queue,
export_fmt=None,
folder=args.folder,
force=True)
break
else:
return
except TypeError:
print str(sys.exc_value)
except EOFError:
return
print "Export done."
mkblks_parser = CmdParser(add_help=False, prog='mkblks',
description='''Generates randomized experimental
blocks from display groups and
saves each as a CSV file.''')
mkblks_parser.add_argument('-n','--nofolder',
dest='folder', action='store_false',
help='''force block files not to be saved in
a containing folder''')
mkblks_parser.add_argument('-d','--dir', default=os.getcwd(),
help='''where to save block files
(default: current working directory)''')
mkblks_parser.add_argument('length', type=int,
help='''no. of repeated trials in a block''')
mkblks_parser.add_argument('flags', nargs='?', default='',
help='''flags passed to the display command
that should be used when the block
file is run (enclose in quotes and use
'+' or '++' in place of '-' or '--')''')
def help_mkblks(self):
self.__class__.mkblks_parser.print_help()
def do_mkblks(self, line):
"""Generates randomized experimental blocks from display groups."""
if self.cur_proj == None:
print 'please create or open a project first'
return
try:
args = self.__class__.mkblks_parser.parse_args(shlex.split(line))
except CmdParserError:
print "error:", str(sys.exc_value)
self.__class__.mkblks_parser.print_usage()
return
args.flags = args.flags.replace('+','-')
try:
disp_args = self.__class__.display_parser.\
parse_args(shlex.split(args.flags))
except CmdParserError:
print "error: invalid flags to display command"
print str(sys.exc_value)
self.__class__.display_parser.print_usage()
return
try:
self.cur_proj.mkblks(args.length,
path=args.dir,
folder=args.folder,
flags=args.flags)
except IOError:
print "error:", str(sys.exc_value)
return
print "Experimental blocks generated."
def do_calibrate(self, line, query=False):
"""Calibrate subject for eyetracking, or load a calibration file."""
if not eyetracking.available:
print "error: eyetracking functionality not available"
return
if query:
print "path to calibration file (leave empty for GUI tool):"
try:
path = raw_input().strip().strip('"\'')
except EOFError:
msg = "calibration cancelled"
raise eyetracking.EyetrackingError(msg)
else:
path = line.strip().strip('"\'')
if len(path) == 0:
path = None
if not eyetracking.is_source_ready():
# Select default source if none has been selected
eyetracking.select_source()
try:
eyetracking.calibrate(path)
except eyetracking.EyetrackingError:
if query:
raise
else:
print "error:", str(sys.exc_value)
return
if len(path) > 0:
print "calibration file successfully loaded"
-
+
+ etsetup_parser = CmdParser(add_help=False, prog='etsetup',
+ description='''Set various eyetracking
+ parameters.''')
+ etsetup_parser.add_argument('-fp', '--fixperiod', type=int, metavar='MS',
+ help='''time in milliseconds subject
+ has to stare at the same spot
+ for fixation to be detected''')
+ etsetup_parser.add_argument('-fr', '--fixrange', type=float, metavar='MM',
+ help='''distance in mm beyond which the
+ eye position cannot change for
+ a fixation to be detected''')
+ etsetup_parser.add_argument('-s', '--size', metavar='WIDTH,HEIGHT',
+ action=store_tuple(2, ',', float),
+ help='physical screen dimensions in mm')
+ etsetup_parser.add_argument('-vd', '--viewdist', type=int, metavar='MM',
+ help='''viewing distance between subject's
+ eyes and the screen''')
+
+ def help_etsetup(self):
+ self.__class__.etsetup_parser.print_help()
+
+ def do_etsetup(self, line):
+ try:
+ args = self.__class__.etsetup_parser.parse_args(shlex.split(line))
+ except CmdParserError:
+ print "error:", str(sys.exc_value)
+ self.__class__.etsetup_parser.print_usage()
+ return
+ try:
+ eyetracking.setup(viewing_distance=args.viewdist,
+ screen_dims=args.size,
+ fixation_period=args.fixperiod,
+ fixation_range=args.fixrange)
+ except eyetracking.EyetrackingError:
+ print "error:", str(sys.exc_value)
+
def do_quit(self, line):
"""Quits the program."""
if self.save_check():
return
return True
def help_EOF(self):
print "Typing {0} issues this command, which quits the program."\
.format(CMD_EOF_STRING)
def do_EOF(self, line):
"""Typing Ctrl-D issues this command, which quits the program."""
print '\r'
if self.save_check():
return
return True
def help_help(self):
print 'Prints a list of commands.'
print "Type 'help <topic>' for more details on each command."
def default(self, line):
command = line.split()[0]
print \
"'{0}' is not a checkergen command.".format(command),\
"Type 'help' for a list of commands"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.