Skip to content

Commit

Permalink
Merge pull request #4 from konradoberwimmer/improvements/provide-repr…
Browse files Browse the repository at this point in the history
…oducible-R-session-code

provide reproducible R session code
  • Loading branch information
konradoberwimmer authored Jul 17, 2024
2 parents 7fc973b + e14d5ab commit 48032bd
Show file tree
Hide file tree
Showing 9 changed files with 97 additions and 20 deletions.
1 change: 0 additions & 1 deletion LSAnalyzer/README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# ToDo-List
Test and debug!

* update and fix session log to provide reproducible R code of the whole session
* split application core and UI in separate assemblies to possibly switch to AvaloniaUI
* refactoring of data table creation and management OR switch from BIFIEsurvey to a specialized R package for LSAnalyzer

Expand Down
18 changes: 14 additions & 4 deletions LSAnalyzer/Services/Logging.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,21 @@ namespace LSAnalyzer.Services
public class Logging
{
private List<LogEntry> _logEntries = new();
public List<LogEntry> LogEntries { get => _logEntries; }

public void AddEntry(LogEntry logEntry)
{
_logEntries.Add(logEntry);
}

public string Stringify()
public string GetRcode()
{
return String.Join("\n", _logEntries.ConvertAll<string>(logEntry => logEntry.Stringify()).ToArray());
return String.Join("\n", _logEntries.ConvertAll<string>(logEntry => logEntry.Rcode).ToArray());
}

public string GetFullText()
{
return String.Join("\n", _logEntries.ConvertAll<string>(logEntry => logEntry.ToFullText()).ToArray());
}
}

Expand All @@ -26,15 +32,19 @@ public class LogEntry
public DateTime When { get; set; }
public string? AnalysisName { get; set; }
public string Rcode { get; set; }
public bool OneLiner { get; set; }

public string RcodeForTableCell => (OneLiner && Rcode.Contains('\n')) ? Rcode.Substring(0, Rcode.IndexOf('\n')) + "\n..." : Rcode;

public LogEntry(DateTime when, string rcode, string? analysisName = null)
public LogEntry(DateTime when, string rcode, string? analysisName = null, bool oneLiner = false)
{
When = when;
Rcode = rcode;
AnalysisName = analysisName;
OneLiner = oneLiner;
}

public string Stringify()
public string ToFullText()
{
return When.ToString() + " - " + AnalysisName + " - " + Rcode;
}
Expand Down
6 changes: 3 additions & 3 deletions LSAnalyzer/Services/Rservice.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public Rservice(Logging logger)

private SymbolicExpression EvaluateAndLog(string what, string? analysisName = null, bool oneLiner = false)
{
_logger.AddEntry(new LogEntry(DateTime.Now, (oneLiner && what.Contains("\n")) ? what.Substring(0, what.IndexOf("\n")) : what, analysisName));
_logger.AddEntry(new LogEntry(DateTime.Now, what, analysisName, oneLiner));
return _engine!.Evaluate(what);
}

Expand Down Expand Up @@ -1354,11 +1354,11 @@ public bool PrepareForAnalysis(Analysis analysis, List<string>? additionalVariab
}
}

public virtual bool Execute(string rCode)
public virtual bool Execute(string rCode, bool oneLiner = false)
{
try
{
EvaluateAndLog(rCode, null, true);
EvaluateAndLog(rCode, null, oneLiner);
return true;
} catch
{
Expand Down
27 changes: 24 additions & 3 deletions LSAnalyzer/ViewModels/SystemSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,9 @@ public string? BifieSurveyVersion
}
}

public string? SessionLog
public Logging SessionLog
{
get => _logger.Stringify();
get => _logger;
}

[ExcludeFromCodeCoverage]
Expand Down Expand Up @@ -175,7 +175,28 @@ private void SaveSessionLog(string? filename)
}

using StreamWriter streamWriter = new(filename, false);
streamWriter.Write(_logger.Stringify());
streamWriter.Write(_logger.GetFullText());
}

private RelayCommand<string?> _saveSessionRcodeCommand = null!;
public ICommand SaveSessionRcodeCommand
{
get
{
_saveSessionRcodeCommand ??= new RelayCommand<string?>(this.SaveSessionRcode);
return _saveSessionRcodeCommand;
}
}

private void SaveSessionRcode(string? filename)
{
if (filename == null)
{
return;
}

using StreamWriter streamWriter = new(filename, false);
streamWriter.Write(_logger.GetRcode());
}
}

Expand Down
15 changes: 11 additions & 4 deletions LSAnalyzer/Views/SystemSettings.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,17 @@
<RowDefinition/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ScrollViewer Grid.Row="0" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
<TextBlock Text="{Binding SessionLog}" TextWrapping="NoWrap"/>
</ScrollViewer>
<Button x:Name="buttomSaveSessionLog" Grid.Row="1" Margin="0,5,0,0" HorizontalAlignment="Right" Content="Save ..." Height="22" Width="80" Click="ButtonSaveSessionLog_Click"/>
<DataGrid Grid.Row="0" ItemsSource="{Binding SessionLog.LogEntries}" AutoGenerateColumns="False" IsReadOnly="True">
<DataGrid.Columns>
<DataGridTextColumn Header="Time" Binding="{Binding When}"/>
<DataGridTextColumn Header="Analysis" Binding="{Binding AnalysisName}"/>
<DataGridTextColumn Header="R code" Binding="{Binding RcodeForTableCell}"/>
</DataGrid.Columns>
</DataGrid>
<StackPanel Grid.Row="1" Margin="0,5,0,0" Orientation="Horizontal" HorizontalAlignment="Right">
<Button x:Name="buttomSaveSessionRcode" Content="Save R code (.R) ..." Height="22" Width="100" Margin="0,0,10,0" Click="ButtonSaveSessionRcode_Click"/>
<Button x:Name="buttomSaveSessionLog" Content="Save All (.txt) ..." Height="22" Width="100" Click="ButtonSaveSessionLog_Click"/>
</StackPanel>
</Grid>
</GroupBox>
</Grid>
Expand Down
20 changes: 20 additions & 0 deletions LSAnalyzer/Views/SystemSettings.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,26 @@ private void HyperLinkGPL3_RequestNavigate(object sender, System.Windows.Navigat
System.Diagnostics.Process.Start(sInfo);
}

private void ButtonSaveSessionRcode_Click(object sender, RoutedEventArgs e)
{
if (sender is not Button button || DataContext is not ViewModels.SystemSettings systemSettingsViewModel)
{
return;
}

SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "R Script File (*.R)|*.R";
saveFileDialog.InitialDirectory = Properties.Settings.Default.lastResultOutFileLocation ?? Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var wantsSave = saveFileDialog.ShowDialog(this);

if (wantsSave == true)
{
Properties.Settings.Default.lastResultOutFileLocation = Path.GetDirectoryName(saveFileDialog.FileName);
Properties.Settings.Default.Save();
systemSettingsViewModel.SaveSessionRcodeCommand.Execute(saveFileDialog.FileName);
}
}

private void ButtonSaveSessionLog_Click(object sender, RoutedEventArgs e)
{
if (sender is not Button button || DataContext is not ViewModels.SystemSettings systemSettingsViewModel)
Expand Down
6 changes: 3 additions & 3 deletions TestLSAnalyzer/ViewModels/DataProvider/TestDataverse.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public async Task TestTestFileAccess()
.Returns(false)
.Returns(true)
.Returns(true);
rserviceMock.SetupSequence(rservice => rservice.Execute(It.IsAny<string>()))
rserviceMock.SetupSequence(rservice => rservice.Execute(It.IsAny<string>(), It.IsAny<bool>()))
.Returns(false)
.Returns(true).Returns(true).Returns(true);

Expand Down Expand Up @@ -75,7 +75,7 @@ public void TestLoadDataTemporarilyAndGetVariables()
configuration.ApiToken = "token";

var rserviceMock = new Mock<Rservice>();
rserviceMock.SetupSequence(rservice => rservice.Execute(It.IsAny<string>()))
rserviceMock.SetupSequence(rservice => rservice.Execute(It.IsAny<string>(), It.IsAny<bool>()))
.Returns(true).Returns(false)
.Returns(true).Returns(true).Returns(true).Returns(true)
.Returns(true).Returns(true).Returns(true).Returns(true);
Expand Down Expand Up @@ -109,7 +109,7 @@ public void TestLoadDataForUsage()
configuration.ApiToken = "token";

var rserviceMock = new Mock<Rservice>();
rserviceMock.SetupSequence(rservice => rservice.Execute(It.IsAny<string>()))
rserviceMock.SetupSequence(rservice => rservice.Execute(It.IsAny<string>(), It.IsAny<bool>()))
.Returns(true).Returns(false)
.Returns(true).Returns(true).Returns(true).Returns(true).Returns(true);

Expand Down
2 changes: 1 addition & 1 deletion TestLSAnalyzer/ViewModels/TestDataProviders.cs
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ public void TestTestDataProvider()

var RServiceMock = new Mock<Rservice>();
RServiceMock.Setup(rservice => rservice.CheckNecessaryRPackages(It.IsAny<string>())).Returns(true);
RServiceMock.Setup(rservice => rservice.Execute(It.IsAny<string>())).Returns(true);
RServiceMock.Setup(rservice => rservice.Execute(It.IsAny<string>(), It.IsAny<bool>())).Returns(true);

ServiceCollection services = new();
services.AddSingleton(RServiceMock.Object);
Expand Down
22 changes: 21 additions & 1 deletion TestLSAnalyzer/ViewModels/TestSystemSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,26 @@ namespace TestLSAnalyzer.ViewModels
[Collection("Sequential")]
public class TestSystemSettings
{
[Fact]
public void TestSaveSessionRcodeCommand()
{
Logging logger = new();
Configuration configuration = new("");
Rservice rservice = new(logger);

Assert.True(rservice.Connect(), "R must also be available for tests");
Assert.True(rservice.InjectAppFunctions());

SystemSettings systemSettingsViewModel = new(rservice, configuration, logger);

var filename = Path.GetTempFileName();
systemSettingsViewModel.SaveSessionRcodeCommand.Execute(filename);

var savedLog = File.ReadAllText(filename);
Assert.Contains("lsanalyzer_func_quantile <- function(", savedLog);
Assert.DoesNotContain("- lsanalyzer_func_quantile <- function(", savedLog);
}

[Fact]
public void TestSaveSessionLogCommand()
{
Expand All @@ -28,7 +48,7 @@ public void TestSaveSessionLogCommand()
systemSettingsViewModel.SaveSessionLogCommand.Execute(filename);

var savedLog = File.ReadAllText(filename);
Assert.Contains("lsanalyzer_func_quantile <- function(", savedLog);
Assert.Contains("- lsanalyzer_func_quantile <- function(", savedLog);
}

[Fact]
Expand Down

0 comments on commit 48032bd

Please sign in to comment.