Beispiel #1
0
        public static string Instructions(this TrialState state)
        {
            switch (state)
            {
            case TrialState.Starting:     return("<size=60>Verbal Stroop\nTask\n\nFor each trial,\nyou will see\na word written\nin a color.</size>");

            case TrialState.Instruction1: return("<size=60>The word and\ncolor will change\neach trial.\nAdditionally, you will\nhear the teacher\nsay a color.</size>");

            case TrialState.Instruction2: return("<size=60>Your goal is\nto let the\nteacher know if\nshe read the\nink color correctly.</size>");

            case TrialState.Instruction3: return("<size=60>If she is\ncorrect press <b>up</b>.\nIf she is\nincorrect press <b>down</b></size>");

            case TrialState.Instruction4: return("<size=60>You must respond\nbefore the next\nword appears.</size>");

            case TrialState.Ready:        return("<size=60><b>Remember:\npress up if\nshe is correct\nand press down if\nshe is incorrect.</b></size>\n\n<size=30><b>Coordinator begin task.</b></size>");

            case TrialState.Correct:      return("<size=60>Correct!</size>\n\n<size=30><i>Press any key to continue.</i></size>");

            case TrialState.Incorrect:    return("<size=60>Incorrect.\nTry again!</size>\n\n<size=30><i>Press any key to continue.</i></size>");

            case TrialState.Slow:         return("<size=60><b>Too slow!</b>\nYou must respond\nbefore the next\nword appears.</size>\n\n<size=30><i>Press any key to continue.</i></size>");

            default:                      return("");
            }
        }
Beispiel #2
0
        public static string Instructions(this TrialState state, Textures textures)
        {
            switch (state)
            {
            case TrialState.Starting:     return("<size=60>AX-CPT Task\n\nFor each trial,\nyou will see\na series of\npictures with\ntext below.</size>");

            case TrialState.Instruction1: return("<size=60>Your job will be\nto decide whether\nyou have seen\nthe target sequence.</size>");

            case TrialState.Instruction2: return("<size=60>You will often\nsee <i>" + textures.a_group [0].name + "</i>\nfollowed by <color=blue><i>" + textures.x_group [0].name + "</i></color>.</size>");

            case TrialState.Instruction3: return("<size=60>If you see <i>" + textures.a_group [0].name + "</i>,\npress <b>up</b>.\nThen if you\nsee <color=blue><i>" + textures.x_group [0].name + "</i></color>,\npress <b>down</b>\nbecause you saw\nthe target sequence.</size>");

            case TrialState.Instruction4: return("<size=60>Sometimes you will\nsee other sequences.\n Press <b>up</b> for all\n other pictures.</size>");

            case TrialState.Instruction5: return("<size=60>You must respond\nbefore the next\npicture appears.</size>");

            case TrialState.Ready:        return("<size=60><b>Remember: <i>" + textures.a_group [0].name + "</i>\nbefore <color=blue><i>" + textures.x_group [0].name + "</i></color>.</b></size>\n\n<size=30><i>Coordinator begin task.</i></size>");

            case TrialState.Correct:      return("<size=60>Correct!</size>\n\n<size=30><i>Press any button to continue.</i></size>");

            case TrialState.Incorrect:    return("<size=60>Incorrect.\nTry again!</size>\n\n<size=30><i>Press any button to continue.</i></size>");

            case TrialState.Slow:         return("<size=60><b>Too slow!</b>\nYou must respond\nbefore the next\npair appears.</size>\n\n<size=30><i>Press any button to continue.</i></size>");

            case TrialState.Ending:       return("<size=60>Note: in the\nreal task,\nyou will se\ndifferent objects\ninstead of shapes.</size>\n\n<size=30><i>Press any button to continue.</i></size>");

            default:                      return("");
            }
        }
Beispiel #3
0
        public static TrialState Next(this TrialState state)
        {
            switch (state)
            {
            case TrialState.Starting:     return(TrialState.Instruction1);

            case TrialState.Instruction1: return(TrialState.Instruction2);

            case TrialState.Instruction2: return(TrialState.Instruction3);

            case TrialState.Instruction3: return(TrialState.Instruction4);

            case TrialState.Instruction4: return(TrialState.Ready);

            case TrialState.Ready:        return(TrialState.ITI);

            case TrialState.Word:         return(TrialState.ITI);

            case TrialState.ITI:          return(TrialState.Word);

            case TrialState.Slow:         return(TrialState.ITI);

            case TrialState.Incorrect:    return(TrialState.ITI);

            case TrialState.Correct:      return(TrialState.ITI);

            default:                      return(TrialState.Ending);
            }
        }
Beispiel #4
0
 //when the task has been successfully finished
 protected void TrialFinish()
 {
     OnTrialFinished();
     SendTrialStateChanged(TrialState.Finished);
     TrialState = TrialState.Finished;
     AfterTrialFinished();
 }
        //start the trial
        public void Start()
        {
            if (_state != TrialState.NotStarted)
            {
                return;
            }
            _startChrono = -1;
            _success     = true;

            if (MExp.Inst.SaveData)//write head
            {
                _stream = new StreamWriter(Filename);
                foreach (KeyValuePair <string, string> pair in _variables)
                {
                    _stream.WriteLine(pair.Key + "\t" + pair.Value);
                }
                _stream.Write("SessionTime\tTrialTime");
                foreach (string key in MExp.Inst.Data._values.Keys)
                {
                    _stream.Write("\t" + key);
                }
                _stream.WriteLine();
            }
            _state = TrialState.Running;
            if (onTrialStarted != null)
            {
                onTrialStarted();
            }
        }
Beispiel #6
0
 //called when new trial is prepaired
 protected void TrialSetup()
 {
     OnTrialSetup();
     SendTrialStateChanged(TrialState.WaitingToStart);
     TrialState = TrialState.WaitingToStart;
     AfterTrialSetup();
 }
Beispiel #7
0
 //called when the trial is actually started
 protected void TrialStart()
 {
     OnTrialStart();
     SendTrialStateChanged(TrialState.Running);
     TrialState = TrialState.Running;
     AfterTrialStart();
 }
Beispiel #8
0
        void UpdateTrialState()
        {
            if (_currentState == TrialState.SweepAway)
            {
                _currentState = TrialState.MansFight;
            }
            else if (_currentState == TrialState.MansFight)
            {
                _currentState = TrialState.WomansFight;
            }
            else if (_currentState == TrialState.WomansFight)
            {
                _currentState = TrialState.TwoDevil;
            }
            else if (_currentState == TrialState.TwoDevil)
            {
                _currentState = TrialState.StormEye;
            }
            else if (_currentState == TrialState.StormEye)
            {
                _currentState = TrialState.Bloody;
            }
            else if (_currentState == TrialState.Bloody)
            {
                _currentState = TrialState.Finished;
            }

            Console.WriteLine("Current state : [" + _currentState + "] ##########################################");
        }
Beispiel #9
0
    /// <summary>
    /// During the trial, waits for the specified amount of time then ends the trial
    /// and cleans up trial objects and object lists.
    /// </summary>
    void Update()
    {
        if (State == TrialState.Trial)
        {
            TrialTimer += Time.deltaTime;

            if (TrialTimer >= Settings.TrialDuration)
            {
                ///Trial is over!
                State = TrialState.Questionnaire;
                Questionnaire.ShowQuestionnaire();

                foreach (UnusualObject unusual in UnusualObjects)
                {
                    Destroy(unusual.gameObject);
                }
                UnusualObjects.Clear();
                foreach (BouncingObject bouncing in BouncingObjects)
                {
                    Destroy(bouncing.gameObject);
                }
                BouncingObjects.Clear();
            }
        }
    }
Beispiel #10
0
    /// <summary>
    /// Initializes the BasicTrialManager with the passed in data. The passed in data should be a serialized
    /// BasicTrialSettings in JSON format, which is used to initialize trial settings.
    /// </summary>
    /// <param name="trialSettings">A JSON string containing a BasicTrialSettings struct.</param>
    public override void InitializeTrials(TrialData trialSettings)
    {
        Settings = (BasicTrialSettings)trialSettings;

        //Displays the tracked object on the pre-trial UI, and shows UI.
        InstructionsUI.InitializeUI(this, Settings.BouncingObjects);
        InstructionsUI.gameObject.SetActive(true);
        State = TrialState.InstructionsUI;

        Camera.backgroundColor = Settings.CameraBackgroundColor.GetColor();
        TrialIteration         = 0;
        BouncingObjects        = new List <BouncingObject> ();
        UnusualObjects         = new List <UnusualObject> ();
        Questionnaire.SetQuestions(Settings.Questionnaire);

        //Set up array used to determine whether the current trial is an unusual one.
        UnusualTrials = new bool [Settings.NumberOfTrials];
        int numUnusual = 0, random;

        while (numUnusual < Settings.NumberOfUnusualTrials)
        {
            random = Random.Range(0, UnusualTrials.Length);
            if (UnusualTrials [random] == false)
            {
                UnusualTrials [random] = true;
                numUnusual++;
            }
        }

        Results = new List <TrialResults> ();
    }
Beispiel #11
0
        /**
         * Initiate next trial.
         * We do it in two steps:
         * Step 1. We first retrieve the network coordinate state of the remote node.
         * Step 2. We take one or more latency samples.
         * Sometimes NATs are first on the first packet sent after a long time.
         * This is why the second step gets the latency sample.
         */
        protected void GetNextSample(object node, EventArgs args)
        {
            DateTime now = DateTime.UtcNow;

            lock (_sync) {
                TimeSpan elapsed = now - _last_sample_instant;
                //
                // Check if it is too early to get a sample.
                //
                if (elapsed.TotalSeconds < SAMPLE_INTERVAL)
                {
                    return;
                }
                _last_sample_instant = now;
            }

            try {
                TrialState new_trial = new TrialState(_node, TrialComplete);
                _current_trial = new_trial;
                new_trial.Start();

                /** The trial object will not get garbage collected while it is active. It will be registered
                 *  with the queues during the course of its activity.
                 */
            } catch (Exception
#if NC_DEBUG
                     x) {    //This silliness is so the compiler doesn't complain about x being unsed
                Console.Error.WriteLine("[NCService] {0}, {1}", _node.Address, x.Message);
Beispiel #12
0
 public bool CheckResponse(TrialState state, string buttonPressed)
 {
     if (state == TrialState.ISI)
     {
         if (buttonPressed == "Button1")
         {
             return(true);
         }
         else
         {
             return(false);
         }
     }
     if (cue == TrialItem.A && probe == TrialItem.X)
     {
         if (buttonPressed == "Button2")
         {
             return(true);
         }
         else
         {
             return(false);
         }
     }
     if (buttonPressed == "Button1")
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
Beispiel #13
0
 //called before new trial is set up
 protected void CloseTrial()
 {
     OnTrialClosed();
     SendTrialStateChanged(TrialState.Closed);
     TrialState = TrialState.Closed;
     AfterTrialClosed();
 }
Beispiel #14
0
        public static bool isInstruction(this TrialState state)
        {
            var beforeReady        = state < TrialState.Ready;
            var isPracticeFeedback = state == TrialState.Correct || state == TrialState.Incorrect || state == TrialState.Slow;

            return(beforeReady || isPracticeFeedback);
        }
 //end the trial
 public void End(bool success)
 {
     if (_state != TrialState.Running)
     {
         return;
     }
     if (MExp.Inst.SaveData)
     {
         _stream.Write(Time.realtimeSinceStartup + "\t" + (Time.realtimeSinceStartup - _startChrono).ToString());
         foreach (string key in MExp.Inst.Data._values.Keys)
         {
             _stream.Write("\t" + MExp.Inst.Data._values[key]);
         }
         _stream.WriteLine();
         _stream.Close();
     }
     _state   = TrialState.Ended;
     _success = success;
     if (!_success)
     {
         MarkAsFailed();
     }
     if (onTrialEnded != null)
     {
         onTrialEnded(_success);
     }
 }
Beispiel #16
0
    /// <summary>
    /// Starts the trial. Spawns all the BouncingObjects, and starts Co-routine to
    /// spawn the UnusualObjects on the correct timer.
    /// </summary>
    public void BeginTrial()
    {
        State      = TrialState.Trial;
        TrialTimer = 0;
        BouncingObject.ResetBounces();

        //Spawns BouncingObjects
        foreach (BouncingObjectSettings settings in Settings.BouncingObjects)
        {
            for (int i = 0; i < settings.NumberToSpawn; i++)
            {
                BouncingObject bouncingObject = GameObject.Instantiate <BouncingObject> (BouncingObjectPrefab);
                bouncingObject.SetObjectSettings(settings, Camera);
                BouncingObjects.Add(bouncingObject);
            }
        }

        //Starts Co-routine to spawn UnusualObject if this trial is an unusual one.
        if (UnusualTrials [TrialIteration])
        {
            foreach (UnusualObjectSettings settings in Settings.UnusualObjects)
            {
                StartCoroutine(SpawnUnusualObject(settings));
            }
        }
    }
Beispiel #17
0
 public TrialOutput(int num, TrialType type, TrialState state, string stimulusName, List <RecordResponses.Response> response)
 {
     this.num          = num;
     this.type         = type;
     this.state        = state;
     this.stimulusName = stimulusName;
     this.response     = response;
 }
Beispiel #18
0
 void OnEnable()
 {
     base.OnEnable();
     currentTrial  = -1;            // Start at -1 because we start the trial into ITI which will increment currentTrial
     trialState    = TrialState.Starting;
     timer         = new CountdownTimer(-1);
     recordResults = CSVWriter.NewOutputFile(subject, "axcpt_results");
     recordResults.WriteRow("trial_number,trial_type,stimulus_type,stimulus_name,button_pressed,reaction_time");
 }
Beispiel #19
0
 private void SendTrialStateChanged(TrialState toState)
 {
     if (TrialStateChanged != null)
     {
         TrialStateChanged(this, new TrialStateArgs {
             Experiment = this, FromState = TrialState.ToString(), ToState = toState.ToString()
         });
     }
 }
Beispiel #20
0
 void OnEnable()
 {
     base.OnEnable();
     currentTrial  = -1;            // Start at -1 because we start the trial into ITI which will increment currentTrial
     trialState    = TrialState.Starting;
     this.timer    = new CountdownTimer(-1);
     recordResults = CSVWriter.NewOutputFile(subject, "verbal_stroop_results");
     recordResults.WriteRow("trial_number,trial_properties,button_pressed,reaction_time");
     avatar = GetComponent <AvatarController> ();
 }
Beispiel #21
0
        public static Texture GetTexture(this TrialState state, BlockType type, Textures textures)
        {
            switch (state)
            {
            case TrialState.Problem: return(textures.Get(type));

            case TrialState.ITI:     return(textures.iti);

            default:                 return(null);
            }
        }
Beispiel #22
0
 //called before new trial is set up
 protected void TrialClose()
 {
     OnTrialClosed();
     SendTrialStateChanged(TrialState.Closed);
     TrialState = TrialState.Closed;
     if (CheckForEnd())
     {
         StopingSequence();
     }
     AfterTrialClosed();
 }
Beispiel #23
0
        public static float Duration(this TrialState state)
        {
            switch (state)
            {
            case TrialState.Problem: return(30.0f);

            case TrialState.ITI:     return(2.0f);

            default:                 return(-1.0f);
            }
        }
Beispiel #24
0
 /// <summary>
 /// Shows the pre-trial UI displaying the object to track before the trial begins.
 /// </summary>
 public void ShowPreTrialUI()
 {
     State = TrialState.PreTrialUI;
     foreach (BouncingObjectSettings objectSettings in Settings.BouncingObjects)
     {
         if (objectSettings.bTrackedObject)
         {
             PreTrialUI.SetUI(objectSettings);
             break;
         }
     }
 }
Beispiel #25
0
 //called when the trial is actually started
 protected void StartTrial()
 {
     //Should be checking if no trial is being run
     //check if it is not finishing again!
     if (TrialState != TrialState.WaitingToStart)
     {
         Debug.LogWarning("Trial not in waiting to start state, can't start", this);
         return;
     }
     OnTrialStart();
     SendTrialStateChanged(TrialState.Running);
     TrialState = TrialState.Running;
     AfterTrialStart();
 }
Beispiel #26
0
 //called when new trial is prepaired
 protected void SetupTrial()
 {
     //Should be checking if no trial is being run
     //check if it is not finishing again!
     if (TrialState > TrialState.Closed)
     {
         Debug.LogWarning("Trial not in closed state, can't setup", this);
         return;
     }
     OnTrialSetup();
     SendTrialStateChanged(TrialState.WaitingToStart);
     TrialState = TrialState.WaitingToStart;
     AfterTrialSetup();
 }
Beispiel #27
0
        public static TrialState Next(this TrialState state)
        {
            switch (state)
            {
            case TrialState.ISI:          return(TrialState.Probe);

            case TrialState.Probe:        return(TrialState.PreCueITI);

            case TrialState.Slow:         return(TrialState.PreCueITI);

            case TrialState.Incorrect:    return(TrialState.PreCueITI);

            default:                      return((TrialState)((int)state + 1));
            }
        }
Beispiel #28
0
 void OnEnable()
 {
     base.OnEnable();
     currentTrial  = -1;            // Start at -1 because we start the trial into ITI which will increment currentTrial
     currentBlock  = 0;
     type          = BlockType.Easy;
     trialState    = TrialState.Starting;
     trialTimer    = new CountdownTimer(-1);
     blockTimer    = new CountdownTimer(BlockTime);
     recordResults = CSVWriter.NewOutputFile(subject, "math_results");
     recordResults.WriteRow("trial_number,block_number,trial_item,button_pressed,reaction_time");
     if (practice != null)
     {
         practice.SetProblemChecker(checker);
     }
 }
Beispiel #29
0
        public static float Duration(this TrialState state)
        {
            switch (state)
            {
            case TrialState.Cue:         return(1.0f);

            case TrialState.ISI:         return(2.0f);

            case TrialState.Probe:       return(0.5f);

            case TrialState.PreCueITI:   return(1.2f);

            case TrialState.PreProbeITI: return(1.2f);

            default:                     return(-1.0f);
            }
        }
Beispiel #30
0
        public static Texture GetTexture(this TrialState state, TrialType type, Textures textures)
        {
            switch (state)
            {
            case TrialState.Cue:         return(textures.Get(type.cue));

            case TrialState.ISI:         return(textures.isi);

            case TrialState.Probe:       return(textures.Get(type.probe));

            case TrialState.PreCueITI:   return(textures.iti);

            case TrialState.PreProbeITI: return(textures.iti);

            default:                     return(null);
            }
        }
Beispiel #31
0
	public TrialData(string line, string path) {

		///////////////////////////////////////////////////////////////////////
		// PARSE TRIAL SUMMARY LINE
		///////////////////////////////////////////////////////////////////////
		string[] cells = line.Split('\t');
		try {
			trialNum = Int32.Parse(cells[0]);
	
			// Scene Object properties
			float oPosX = Single.Parse(cells[1]);
			float oPosY = Single.Parse(cells[2]);
			float oPosZ = Single.Parse(cells[3]);
			float oRotX = Single.Parse(cells[4]);
			float oRotY = Single.Parse(cells[5]);
			float oRotZ = Single.Parse(cells[6]);
			float oRotW = Single.Parse(cells[7]);
			oPos = new    Vector3(oPosX, oPosY, oPosZ);
			oRot = new Quaternion(oRotX, oRotY, oRotZ, oRotW);
	
			// Scene Target properties
			float tPosX = Single.Parse(cells[ 8]);
			float tPosY = Single.Parse(cells[ 9]);
			float tPosZ = Single.Parse(cells[10]);
			float tRotX = Single.Parse(cells[11]);
			float tRotY = Single.Parse(cells[12]);
			float tRotZ = Single.Parse(cells[13]);
			float tRotW = Single.Parse(cells[14]);
			tPos = new    Vector3(tPosX, tPosY, tPosZ);
			tRot = new Quaternion(tRotX, tRotY, tRotZ, tRotW);
	
			// Hoop properties
			float hPosX = Single.Parse(cells[15]);
			float hPosY = Single.Parse(cells[16]);
			float hPosZ = Single.Parse(cells[17]);
			float hRotX = Single.Parse(cells[18]);
			float hRotY = Single.Parse(cells[19]);
			float hRotZ = Single.Parse(cells[20]);
			float hRotW = Single.Parse(cells[21]);
			hPos = new    Vector3(hPosX, hPosY, hPosZ);
			hRot = new Quaternion(hRotX, hRotY, hRotZ, hRotW);
	
			// Important times
			timeToGrab = Single.Parse(cells[22]);
			timeToHoop = Single.Parse(cells[23]);
			timeToTarg = Single.Parse(cells[24]);
	
			// Distances
			distToHoop = Single.Parse(cells[25]);
			distToTarg = Single.Parse(cells[26]);
	
			// Red Frames
			red = Single.Parse(cells[27]);
	
			// Forward vector stuff
			float oForwardX = Single.Parse(cells[28]);
			float oForwardY = Single.Parse(cells[29]);
			float oForwardZ = Single.Parse(cells[30]);
			float tForwardX = Single.Parse(cells[31]);
			float tForwardY = Single.Parse(cells[32]);
			float tForwardZ = Single.Parse(cells[33]);
			fAngle          = Single.Parse(cells[34]);
			oForward = new Vector3(oForwardX, oForwardY, oForwardZ);
			tForward = new Vector3(tForwardX, tForwardY, tForwardZ);

			// Up vector stuff
			float oUpX   = Single.Parse(cells[35]);
			float oUpY   = Single.Parse(cells[36]);
			float oUpZ   = Single.Parse(cells[37]);
			float tUpX   = Single.Parse(cells[38]);
			float tUpY   = Single.Parse(cells[39]);
			float tUpZ   = Single.Parse(cells[40]);
			uAngle       = Single.Parse(cells[41]);
			oUp = new Vector3(oUpX, oUpY, oUpZ);
			tUp = new Vector3(tUpX, tUpY, tUpZ);
	
			if (float.IsNaN(uAngle)) {
				Debug.Log(line);
			}

			// Max angle
			mAngle = Single.Parse(cells[42]);
		}
		catch {
			Debug.Log("Line ignored: " + path + "\n" + line);
			initialized = false;
			return;
		}

		///////////////////////////////////////////////////////////////////////
		// PARSE RAW TRIAL DATA
		///////////////////////////////////////////////////////////////////////
		string[] lines;
		string trialPath = path + "/Trial_" + trialNum + ".tsv";
		try {
			lines = File.ReadAllLines(trialPath);

			for (int i = 1; i < lines.Length; i++) {
				TrialState s = new TrialState(lines[i]);
				if (s.initialized) {
					states.Add(s);
				}
			}
		}
		catch {
			Debug.Log("File not found:\n" + trialPath);
			initialized = false;
		}

		///////////////////////////////////////////////////////////////////////
		// GET INITIAL HANDSTREAM POSITION
		///////////////////////////////////////////////////////////////////////
		initHSPos = states[0].hsPos;


		///////////////////////////////////////////////////////////////////////
		// LOOK FOR LAST HOOP ATTEMPT (FINAL LOCAL MINIMA)
		///////////////////////////////////////////////////////////////////////	
		for (int i = states.Count - 2; i >= 1; i--) {
			float d0 = Vector3.Distance(states[i - 1].oPos, hPos);
			float d1 = Vector3.Distance(states[i    ].oPos, hPos);
			float d2 = Vector3.Distance(states[i + 1].oPos, hPos);
			if (d1 <= d0 && d1 <= d2 && d1 < 3f) {
				lastHoopAttempt  = states[i].time;
				lastHoopDistance = d1; 
				break;
			}
		}

		initialized = true;
	}
Beispiel #32
0
 public TrialEventArgs(TrialState state, int trial_count)
 {
     State = state;
     TrialCount = trial_count;
 }
Beispiel #33
0
    /** 
     * Initiate next trial. 
     * We do it in two steps:
     * Step 1. We first retrieve the network coordinate state of the remote node. 
     * Step 2. We take one or more latency samples.
     * Sometimes NATs are first on the first packet sent after a long time. 
     * This is why the second step gets the latency sample. 
     */
    protected void GetNextSample(object node, EventArgs args) {
      DateTime now = DateTime.UtcNow;
      lock(_sync) {
        TimeSpan elapsed = now - _last_sample_instant;
        //
        // Check if it is too early to get a sample. 
        //
        if (elapsed.TotalSeconds < SAMPLE_INTERVAL) {
          return;
        }
        _last_sample_instant = now;
      }

      try {
        TrialState new_trial = new TrialState(_node, TrialComplete); 
        _current_trial = new_trial; 
        new_trial.Start();  
       /** The trial object will not get garbage collected while it is active. It will be registered
        *  with the queues during the course of its activity. 
        */
      } catch(Exception x) {
#if NC_DEBUG
        Console.Error.WriteLine("[NCService] {0}, {1}", _node.Address, x.Message);
#endif        
      }
    }
Beispiel #34
0
    protected void TrialComplete(TrialState trial, DateTime instant, Address target_address, 
                                 Hashtable state_result, double latency) {
#if NC_DEBUG
      Console.Error.WriteLine("[NCService] {0} Trial complete to: {1}.", _node.Address, target_address);
#endif
      if (_current_trial != trial) {
#if NC_DEBUG
        Console.Error.WriteLine("[NCService] {0} Too late now: {1}.", _node.Address, target_address);
#endif
        return;
      }
      
      Hashtable ht_position = (Hashtable) state_result["position"];
      Point position = 
        new Point((double[]) ((ArrayList) ht_position["side"]).ToArray(typeof(double)), (double) ht_position["height"]);
      double weighted_error = (double) state_result["error"];
      string host = (string) state_result["hostname"];
#if NC_DEBUG
      Console.Error.WriteLine("[NCService] {0} Trial result at: {1}, from: {2} {3}, position: {4}, error: {5}, latency: {6}", 
                              _node.Address, instant.Ticks, host, target_address, position, weighted_error, latency);
#endif
      ProcessSample(instant, host, target_address, position, weighted_error, latency);
    }
Beispiel #35
0
      public TrialState(Node n, TrialState.TrialFinishedCallback cb) {
        _node = n;
        _callback = cb;
        ArrayList con_list = new ArrayList();
        foreach (Connection con in _node.ConnectionTable.GetConnections(ConnectionType.Structured))
        {
          if (con.Edge is Tunnel.TunnelEdge) {
            continue;
          }
          con_list.Add(con);
        }

        if (con_list.Count == 0) {
          throw new Exception("Cannot initialize a trial state (No usable structured connections).");
        }
        
        Connection target = (Connection) con_list[_rand.Next(con_list.Count)];
        _target_address = target.Address;
        _target_edge = target.Edge;
        _state_result = new WriteOnce<Hashtable>();
        _num_samples = 0;
        _started = 0;
      }
Beispiel #36
0
    /** 
     * Initiate next trial. 
     * We do it in two steps:
     * Step 1. We first retrieve the network coordinate state of the remote node. 
     * Step 2. We take one or more latency samples.
     * Sometimes NATs are first on the first packet sent after a long time. 
     * This is why the second step gets the latency sample. 
     */
    protected void GetNextSample(object node, EventArgs args) {
      DateTime now = DateTime.UtcNow;
      lock(_sync) {
        TimeSpan elapsed = now - _last_sample_instant;
        //
        // Check if it is too early to get a sample. 
        //
        if (elapsed.TotalSeconds < SAMPLE_INTERVAL) {
          return;
        }
        _last_sample_instant = now;
      }

      try {
        TrialState new_trial = new TrialState(_node, TrialComplete); 
        _current_trial = new_trial; 
        new_trial.Start();  
       /** The trial object will not get garbage collected while it is active. It will be registered
        *  with the queues during the course of its activity. 
        */
      } catch(Exception
#if NC_DEBUG
                        x) { //This silliness is so the compiler doesn't complain about x being unsed
        Console.Error.WriteLine("[NCService] {0}, {1}", _node.Address, x.Message);
#else 
                         ) {
#endif        
      }
    }
    
    protected void TrialComplete(TrialState trial, DateTime instant, Address target_address, 
                                 Hashtable state_result, double latency) {
#if NC_DEBUG
      Console.Error.WriteLine("[NCService] {0} Trial complete to: {1}.", _node.Address, target_address);
#endif
      if (_current_trial != trial) {
#if NC_DEBUG
        Console.Error.WriteLine("[NCService] {0} Too late now: {1}.", _node.Address, target_address);
#endif
        return;
      }
      
      Hashtable ht_position = (Hashtable) state_result["position"];
      Point position = 
        new Point((double[]) ((ArrayList) ht_position["side"]).ToArray(typeof(double)), (double) ht_position["height"]);
      double weighted_error = (double) state_result["error"];
      string host = (string) state_result["hostname"];
#if NC_DEBUG
      Console.Error.WriteLine("[NCService] {0} Trial result at: {1}, from: {2} {3}, position: {4}, error: {5}, latency: {6}", 
                              _node.Address, instant.Ticks, host, target_address, position, weighted_error, latency);
#endif
      ProcessSample(instant, host, target_address, position, weighted_error, latency);
    }