Skip to content

Commit

Permalink
issue with plot when stopping Unity
Browse files Browse the repository at this point in the history
  • Loading branch information
BenoitGeslain committed Feb 23, 2024
1 parent 7bec35a commit ffd7aea
Show file tree
Hide file tree
Showing 5 changed files with 125 additions and 80 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1144,6 +1144,9 @@ PrefabInstance:
- targetCorrespondingSourceObject: {fileID: 200869264966477082, guid: 7e46c8eb8c13fdb429130703b04c8216, type: 3}
insertIndex: -1
addedObject: {fileID: 358983254}
- targetCorrespondingSourceObject: {fileID: 200869264966477082, guid: 7e46c8eb8c13fdb429130703b04c8216, type: 3}
insertIndex: -1
addedObject: {fileID: 358983261}
m_SourcePrefab: {fileID: 100100000, guid: 7e46c8eb8c13fdb429130703b04c8216, type: 3}
--- !u!1 &358983253 stripped
GameObject:
Expand Down Expand Up @@ -1184,6 +1187,20 @@ MonoBehaviour:
m_Script: {fileID: 11500000, guid: bb5310432868de244b86ddcc9c3aa8c1, type: 3}
m_Name:
m_EditorClassIdentifier:
--- !u!114 &358983261
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 358983253}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 51d618b1b4dddf44a8b914838ac6e9b6, type: 3}
m_Name:
m_EditorClassIdentifier:
pathToFile: LoggedData\
fileNamePrefix:
--- !u!1 &398215666
GameObject:
m_ObjectHideFlags: 0
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Globalization;

using CsvHelper;
using CsvHelper.Configuration;

using UnityEngine;

using VHToolkit.Redirection;
using Newtonsoft.Json;

namespace VHToolkit.Logging
{
public class JsonLogging : MonoBehaviour
{

public string pathToFile = "LoggedData\\";
[SerializeField] private string fileNamePrefix;
private string fileName;
private readonly int bufferSize = 10; // number of records kept before writing to disk

private List<RedirectionData> records = new();

private Interaction script;

private void Start()
{
CreateNewFile();
script = GetComponent<Interaction>();
}

private void Update()
{
void writeRecords<Data, DataMap>(List<Data> records) where DataMap : ClassMap<Data>
{
if (records.Count > bufferSize)
{
using var writer = new StreamWriter(fileName, append: true);
foreach (var record in records) {
// writer.WriteLine(JsonConvert.SerializeObject(record));
}
records.Clear();
}
}

records.Add(new RedirectionData(script));
writeRecords<RedirectionData, RedirectionDataMap>(records);
}

public void CreateNewFile()
{
fileName = $"{pathToFile}{fileNamePrefix}{DateTime.Now:yyyy-MM-dd_HH-mm-ss}.json";
using StreamWriter writer = new(fileName);
using CsvWriter csv = new(writer, CultureInfo.InvariantCulture);
records = new List<RedirectionData>();
}
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,12 @@
using VHToolkit.Redirection;
using VHToolkit.Redirection.BodyRedirection;
using VHToolkit.Redirection.WorldRedirection;
using Newtonsoft.Json;

namespace VHToolkit.Logging
{
/// <summary>
/// Class specifying loggable data for a redirection scene.
/// </summary>
/// <summary>
/// Class specifying loggable data for a redirection scene.
/// </summary>
public record RedirectionData {
public DateTime timeStamp = DateTime.Now;
public string Technique => script switch {
Expand Down Expand Up @@ -121,51 +120,4 @@ void writeHeaders<Data, DataMap>(out List<Data> records) where DataMap : ClassMa
writeHeaders<RedirectionData, RedirectionDataMap>(out records);
}
}

public class JsonLogging : MonoBehaviour
{

public string pathToFile = "LoggedData\\";
[SerializeField] private string fileNamePrefix;
private string fileName;
private readonly int bufferSize = 10; // number of records kept before writing to disk

private List<RedirectionData> records = new();
private readonly CsvConfiguration config = new(CultureInfo.InvariantCulture) { HasHeaderRecord = false, MemberTypes = MemberTypes.Fields };

private Interaction script;

private void Start()
{
CreateNewFile();
script = GetComponent<Interaction>();
}

private void Update()
{
void writeRecords<Data, DataMap>(List<Data> records) where DataMap : ClassMap<Data>
{
if (records.Count > bufferSize)
{
using var writer = new StreamWriter(fileName, append: true);
using var csv = new CsvWriter(writer, config);
foreach (var record in records) {
writer.WriteLine(JsonConvert.SerializeObject(record));
}
records.Clear();
}
}

records.Add(new RedirectionData(script));
writeRecords<RedirectionData, RedirectionDataMap>(records);
}

public void CreateNewFile()
{
fileName = $"{pathToFile}{fileNamePrefix}{DateTime.Now:yyyy-MM-dd_HH-mm-ss}.json";
using StreamWriter writer = new(fileName);
using CsvWriter csv = new(writer, CultureInfo.InvariantCulture);
records = new List<RedirectionData>();
}
}
}
63 changes: 34 additions & 29 deletions python/RedirectionPlotter.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,39 +30,44 @@
serversocket.listen(5)

while True:
print("Waiting for socket")
clientsocket, _ = serversocket.accept()
while clientsocket:
chunk = clientsocket.recv(4096).decode()
print(chunk)
for m in re.finditer(r'\{[^}]*}', chunk):
d = json.loads(m[0])
otrs.append(d["overTime"])
rs.append(d["rotational"])
cs.append(d["curvature"])
hybrid.append(d["hybrid"])
tots.append(d["total"])
ys.append(d["time"])
with clientsocket:
while True:
try:
chunk = clientsocket.recv(4096).decode()
except ConnectionResetError:
print('Should close')
break
for m in re.finditer(r'\{[^}]*}', chunk):
d = json.loads(m[0])
otrs.append(d["overTime"])
rs.append(d["rotational"])
cs.append(d["curvature"])
hybrid.append(d["hybrid"])
tots.append(d["total"])
ys.append(d["time"])

ax1.clear()
ax2.clear()
ax1.clear()
ax2.clear()

ax1.set_xticks(list(map(int, ys[::10])))
ax1.set_xlim((ys[-1] - 30, ys[-1]))
ax1.set_title('Redirection amounts over time')
ax1.set_ylabel('Redirection per second (degrees)')
for series, color, label in zip((otrs[-60:], rs[-60:], cs[-60:]), 'rgy', ('Over time\nrotation', 'Rotational', 'Curvature')):
ax1.plot(ys[-60:], series, color=color, label=label, linewidth=0.5, linestyle="dashed")
ax1.fill_between(ys[-60:], hybrid[-60:], color='b', alpha=0.2)
ax1.plot(ys[-60:], hybrid[-60:], color='b', label='Hybrid', linewidth=0.5)
ax1.set_xticks(list(map(int, ys[::10])))
ax1.set_xlim((ys[-1] - 30, ys[-1]))
ax1.set_title('Redirection amounts over time')
ax1.set_ylabel('Redirection per second (degrees)')
for series, color, label in zip((otrs, rs, cs), 'rgy', ('Over time\nrotation', 'Rotational', 'Curvature')):
ax1.plot(ys[-60:], series[-60:], color=color, label=label, linewidth=0.5, linestyle="dashed")
ax1.fill_between(ys[-60:], hybrid[-60:], color='b', alpha=0.2)
ax1.plot(ys[-60:], hybrid[-60:], color='b', label='Hybrid', linewidth=0.5)

ax2.set_xticks(list(map(int, ys[::10])))
ax2.set_xlim((ys[-1] - 30, ys[-1]))
ax2.set_xlabel('Time from start (seconds)', loc='right')
ax2.set_ylabel('Redirection amount (degrees)')
ax2.plot(ys[-60:], tots[-60:], color='m', label='Total\nredirection', linewidth=1)
ax2.set_xticks(list(map(int, ys[::10])))
ax2.set_xlim((ys[-1] - 30, ys[-1]))
ax2.set_xlabel('Time from start (seconds)', loc='right')
ax2.set_ylabel('Redirection amount (degrees)')
ax2.plot(ys[-60:], tots[-60:], color='m', label='Total\nredirection', linewidth=1)

ax1.legend(loc='center left', bbox_to_anchor=(1, 0.5))
ax2.legend(loc='center left', bbox_to_anchor=(1, 0.5))
ax1.legend(loc='center left', bbox_to_anchor=(1, 0.5))
ax2.legend(loc='center left', bbox_to_anchor=(1, 0.5))

plt.pause(0.05)
plt.pause(0.05)
plt.ioff()

0 comments on commit ffd7aea

Please sign in to comment.