diff --git a/Source/OpenEPT.pro b/Source/OpenEPT.pro index 80685d2..f52b1a0 100644 --- a/Source/OpenEPT.pro +++ b/Source/OpenEPT.pro @@ -70,6 +70,7 @@ SOURCES += \ Windows/Device/configurationwnd.cpp \ Windows/Device/datastatistics.cpp \ Windows/Device/devicewnd.cpp \ + Windows/Device/profiletypedialog.cpp \ Windows/Device/energycontrolwnd.cpp \ Windows/Plot/plot.cpp \ Windows/Plot/plotdockwidget.cpp \ @@ -126,6 +127,7 @@ HEADERS += \ Windows/Device/configurationwnd.h \ Windows/Device/datastatistics.h \ Windows/Device/devicewnd.h \ + Windows/Device/profiletypedialog.h \ Windows/Device/energycontrolwnd.h \ Windows/Plot/plot.h \ Windows/Plot/plotdockwidget.h \ diff --git a/Source/Processing/batteryparamsextraction.cpp b/Source/Processing/batteryparamsextraction.cpp index 1fb0e48..4f2c446 100644 --- a/Source/Processing/batteryparamsextraction.cpp +++ b/Source/Processing/batteryparamsextraction.cpp @@ -1,8 +1,26 @@ #include "batteryparamsextraction.h" #include +#include #include +#if defined(Q_OS_LINUX) +#include +#endif + +void BatteryParamsExtraction::nameCurrentThread(unsigned int cycleIndex) +{ + QThread::currentThread()->setObjectName(QString("OpenEPT BA (Cycle %1)").arg(cycleIndex)); + +#if defined(Q_OS_LINUX) + /*The OS thread name htop shows is limited to 15 characters, so a compact name is + used there while the full name stays on the Qt object*/ + QString shortName = QString("BA Cyc %1").arg(cycleIndex); + if(shortName.size() > 15) shortName = shortName.left(15); + pthread_setname_np(pthread_self(), shortName.toLocal8Bit().constData()); +#endif +} + BatteryParamsExtraction::BatteryParamsExtraction(QObject *parent) : QObject{parent} { @@ -14,6 +32,7 @@ BatteryParamsExtraction::BatteryParamsExtraction(QObject *parent) samplingPeriod = 0; settings = settingsDefault(); analysisDeferred = false; + captureIncomplete = false; chargeTotal = 0; cycleActive = false; cycleCounter = 0; @@ -43,11 +62,12 @@ batteryparams_settings_t BatteryParamsExtraction::settingsDefault() defaults.model = BATTERYPARAMS_MODEL_SECOND_ORDER; defaults.fitEnd = BATTERYPARAMS_FIT_END_PAUSE; defaults.tauGridPoints = BATTERYPARAMS_TAU_GRID_POINTS; - defaults.tauRefinementNo = BATTERYPARAMS_TAU_REFINEMENT_NO; defaults.tauSeparation = BATTERYPARAMS_TAU_SEPARATION; defaults.capacity = 0; defaults.initialSoc = BATTERYPARAMS_INITIAL_SOC_DEFAULT; defaults.plotDecimation = BATTERYPARAMS_CYCLE_PLOT_DECIMATION_DEFAULT; + defaults.ocvWindow = BATTERYPARAMS_OCV_WINDOW_DEFAULT; + defaults.fitAverageWindow = BATTERYPARAMS_FIT_AVERAGE_WINDOW_DEFAULT; return defaults; } @@ -65,6 +85,37 @@ void BatteryParamsExtraction::setAnalysisDeferred(bool aDeferred) analysisDeferred = aDeferred; } +void BatteryParamsExtraction::setCaptureIncomplete(bool aCapture) +{ + captureIncomplete = aCapture; +} + +void BatteryParamsExtraction::finalizeIncompleteCycle(double pauseEndKey) +{ + if(!cycleActive) return; + + if(activeCycle.pulseStartKey <= 0 || keySamples.isEmpty()) + { + cycleActive = false; + return; + } + + activeCycle.pauseEndKey = pauseEndKey; + activeCycle.incomplete = true; + activeCycle.modelReason = "Incomplete cycle: the pulse/pause markers were not all captured, no model fitted"; + storeCycleSamples(); + cycles.append(activeCycle); + cycleActive = false; + emit sigCycleFinished(activeCycle); + trimSamples(pauseEndKey); +} + +void BatteryParamsExtraction::flushIncompleteCycle() +{ + if(!cycleActive || keySamples.isEmpty()) return; + finalizeIncompleteCycle(keySamples.last()); +} + batteryparams_settings_t BatteryParamsExtraction::getSettings() { return settings; @@ -113,91 +164,91 @@ static int prvBATTERYPARAMS_RelaxationPositionGet(const QVector &keys, c return -1; } -/*With the time constants fixed the relaxation curve is linear in its remaining - parameters, so the open circuit voltage the cell is heading to and the branch - amplitudes are obtained by least squares. Fitting the asymptote instead of - taking it from the last sample keeps the result usable even when the pause is - cut short*/ -static bool prvBATTERYPARAMS_RelaxationFit(const QVector &time, const QVector &voltage, - double tauFast, double tauSlow, bool secondOrder, - double *openCircuitVoltage, double *amplitudeFast, double *amplitudeSlow) +/*Fits a single decaying exponential value ~ amplitude * exp(-time / tau) over the + given index range. The time constant is searched on a logarithmic grid, the + amplitude is solved by least squares for every candidate, and the grid is narrowed + around the best value a few times. Used for peeling the slow and fast branches off + separate portions of the relaxation*/ +static bool prvBATTERYPARAMS_SingleExpFit(const QVector &time, const QVector &value, + int startIndex, int endIndex, + double tauLow, double tauHigh, + int gridPoints, int refinementNo, + double *bestTau, double *bestAmplitude) { - int size = secondOrder ? 3 : 2; - double matrix[3][4]; - - for(int row = 0; row < size; row++) - { - for(int column = 0; column < size + 1; column++) - { - matrix[row][column] = 0; - } - } - - for(int i = 0; i < time.size(); i++) + if((startIndex < 0) || (endIndex >= time.size()) || ((endIndex - startIndex) < 1)) return false; + if(gridPoints < 2) gridPoints = 2; + if(refinementNo < 1) refinementNo = 1; + if(tauLow <= 0) return false; + if(tauHigh <= tauLow) tauHigh = tauLow * 10.0; + + double low = tauLow; + double high = tauHigh; + double resultTau = 0; + double resultAmplitude = 0; + bool found = false; + + /*Sum of squares of the samples does not depend on tau, so it is computed once and + the fit error is obtained algebraically instead of a second exp() pass per tau: + error = sum(value^2) - amplitude * sum(value * basis)*/ + double sumValueSq = 0; + for(int i = startIndex; i <= endIndex; i++) sumValueSq += value[i] * value[i]; + + for(int refinement = 0; refinement < refinementNo; refinement++) { - double basis[3]; + double refineBestError = -1; + double refineBestTau = 0; + double refineBestAmplitude = 0; - basis[0] = 1.0; - basis[1] = exp(-time[i] / tauFast); - basis[2] = secondOrder ? exp(-time[i] / tauSlow) : 0; - - for(int row = 0; row < size; row++) + for(int step = 0; step < gridPoints; step++) { - for(int column = 0; column < size; column++) + double tau = low * pow(high / low, (double)step / (gridPoints - 1)); + double sumXe = 0; + double sumEe = 0; + + for(int i = startIndex; i <= endIndex; i++) { - matrix[row][column] += basis[row] * basis[column]; + double basis = exp(-time[i] / tau); + sumXe += value[i] * basis; + sumEe += basis * basis; } - matrix[row][size] += basis[row] * voltage[i]; - } - } - for(int column = 0; column < size; column++) - { - int pivot = column; + if(sumEe <= 0) continue; - for(int row = column + 1; row < size; row++) - { - if(fabs(matrix[row][column]) > fabs(matrix[pivot][column])) pivot = row; - } + double amplitude = sumXe / sumEe; + double error = sumValueSq - amplitude * sumXe; - if(fabs(matrix[pivot][column]) < 1e-18) return false; - - for(int i = 0; i < size + 1; i++) - { - double temporary = matrix[column][i]; - matrix[column][i] = matrix[pivot][i]; - matrix[pivot][i] = temporary; + if((refineBestError < 0) || (error < refineBestError)) + { + refineBestError = error; + refineBestTau = tau; + refineBestAmplitude = amplitude; + } } - for(int row = 0; row < size; row++) - { - double factor; + if(refineBestError < 0) break; - if(row == column) continue; + resultTau = refineBestTau; + resultAmplitude = refineBestAmplitude; + found = true; - factor = matrix[row][column] / matrix[column][column]; - - for(int i = column; i < size + 1; i++) - { - matrix[row][i] -= factor * matrix[column][i]; - } - } + low = refineBestTau / BATTERYPARAMS_TAU_REFINEMENT_SPAN; + high = refineBestTau * BATTERYPARAMS_TAU_REFINEMENT_SPAN; } - *openCircuitVoltage = matrix[0][size] / matrix[0][0]; - *amplitudeFast = -matrix[1][size] / matrix[1][1]; - *amplitudeSlow = secondOrder ? (-matrix[2][size] / matrix[2][2]) : 0; + if(!found) return false; + *bestTau = resultTau; + *bestAmplitude = resultAmplitude; return true; } -bool BatteryParamsExtraction::analyzeCycle(batteryparams_cycle_t *cycle, batteryparams_settings_t settings) +bool BatteryParamsExtraction::analyzeCycle(batteryparams_cycle_t *cycle, batteryparams_settings_t settings, + const std::function &progress) { batteryparams_model_t model = settings.model; int pauseStart = -1; int pauseEnd = -1; int relaxPosition; - int fastPosition; bool secondOrder = (model == BATTERYPARAMS_MODEL_SECOND_ORDER); double threshold = settings.relaxationThreshold / 1000.0; double window = settings.relaxationWindow * 1000.0; @@ -217,16 +268,23 @@ bool BatteryParamsExtraction::analyzeCycle(batteryparams_cycle_t *cycle, battery cycle->ocv = 0; cycle->model = model; cycle->modelValid = false; + cycle->modelReason = ""; cycle->tauFast = 0; cycle->tauSlow = 0; + cycle->fastPortionEndKey = 0; + cycle->fitEndKey = 0; cycle->r1 = 0; cycle->c1 = 0; cycle->r2 = 0; cycle->c2 = 0; + cycle->r1Valid = false; + cycle->r2Valid = false; cycle->fitRmse = 0; cycle->fitMaxError = 0; cycle->fitKeys.clear(); cycle->fitVoltage.clear(); + cycle->avgKeys.clear(); + cycle->avgVoltage.clear(); for(int i = 0; i < cycle->plotKeys.size(); i++) { @@ -234,7 +292,49 @@ bool BatteryParamsExtraction::analyzeCycle(batteryparams_cycle_t *cycle, battery if(cycle->plotKeys[i] <= cycle->pauseEndKey) pauseEnd = i; } - if((pauseStart < 0) || (pauseEnd <= pauseStart)) return false; + if((pauseStart < 0) || (pauseEnd <= pauseStart)) { cycle->modelReason = "Pause markers missing or out of order, no samples between pause start and pause end"; return false; } + + /*The RC fit runs on a moving average of the pause, the window is set in points. + A window of 1 keeps the raw samples. The average spans the whole pause and stays + aligned to the plotted keys: the window only shifts at the two ends so that the + pause start and the pause end are both inside their window and no offset is + introduced by the averaging*/ + if(progress) progress("averaging the pause"); + + int fitAvgWindow = (settings.fitAverageWindow > 1) ? settings.fitAverageWindow : 1; + int fitAvgHalf = (fitAvgWindow - 1) / 2; + QVector pauseAverage = cycle->plotVoltage; + + /*The averaged trace drawn in the cycle window is capped, so a long pause does not add + hundreds of thousands of points on top of the raw samples*/ + int pauseCount = pauseEnd - pauseStart + 1; + int avgStride = (pauseCount > BATTERYPARAMS_FIT_MAX_POINTS) ? (pauseCount / BATTERYPARAMS_FIT_MAX_POINTS) : 1; + + for(int i = pauseStart; i <= pauseEnd; i++) + { + /*Centered window that shrinks towards the two ends: it is a single point at the + pause start (so the first averaged point is exactly the pause start sample, with + no offset), grows symmetrically to the full window in the middle, and shrinks + back to a single point at the pause end*/ + int effHalf = fitAvgHalf; + if((i - pauseStart) < effHalf) effHalf = i - pauseStart; + if((pauseEnd - i) < effHalf) effHalf = pauseEnd - i; + + int lo = i - effHalf; + int hi = i + effHalf; + + double sum = 0; + int no = 0; + for(int k = lo; k <= hi; k++) { sum += cycle->plotVoltage[k]; no++; } + + pauseAverage[i] = (no > 0) ? (sum / no) : cycle->plotVoltage[i]; + + if((((i - pauseStart) % avgStride) == 0) || (i == pauseEnd)) + { + cycle->avgKeys.append(cycle->plotKeys[i]); + cycle->avgVoltage.append(pauseAverage[i]); + } + } /*Relaxation is searched over an evenly spaced series of averaged samples. The plotted waveform keeps the extremes of every bucket instead, and a time based @@ -252,38 +352,46 @@ bool BatteryParamsExtraction::analyzeCycle(batteryparams_cycle_t *cycle, battery if(searchKeys[i] <= cycle->pauseEndKey) searchEnd = i; } - if((searchStart < 0) || (searchEnd <= searchStart)) return false; + if((searchStart < 0) || (searchEnd <= searchStart)) { cycle->modelReason = "No samples found inside the pause for the relaxation search"; return false; } + + if(searchKeys.size() != searchVoltage.size()) { cycle->modelReason = "Relaxation sample series is inconsistent (key and voltage lengths differ)"; return false; } - if(searchKeys.size() != searchVoltage.size()) return false; + if(progress) progress("searching the relaxation point"); seriesSmooth(searchKeys, searchVoltage, settings.relaxationFilter, &smoothedVoltage); - if(smoothedVoltage.size() != searchKeys.size()) return false; + if(smoothedVoltage.size() != searchKeys.size()) { cycle->modelReason = "Relaxation smoothing failed"; return false; } relaxPosition = prvBATTERYPARAMS_RelaxationPositionGet(searchKeys, smoothedVoltage, searchStart, searchEnd, threshold, window); - if(relaxPosition < 0) return false; - - cycle->relaxationReached = true; - cycle->relaxationKey = searchKeys[relaxPosition]; - cycle->relaxationVoltage = searchVoltage[relaxPosition]; + if(relaxPosition >= 0) + { + cycle->relaxationReached = true; + cycle->relaxationKey = searchKeys[relaxPosition]; + cycle->relaxationVoltage = searchVoltage[relaxPosition]; - /*Fit works on the plotted waveform, so the relaxation point is taken back to it*/ - relaxPosition = pauseEnd; + /*Fit works on the plotted waveform, so the relaxation point is taken back to it*/ + relaxPosition = pauseEnd; - for(int i = pauseStart; i <= pauseEnd; i++) - { - if(cycle->plotKeys[i] >= cycle->relaxationKey) + for(int i = pauseStart; i <= pauseEnd; i++) { - relaxPosition = i; - break; + if(cycle->plotKeys[i] >= cycle->relaxationKey) + { + relaxPosition = i; + break; + } } } - - /*Cell is at rest once it relaxed, so the voltage measured there is its open - circuit voltage*/ - cycle->ocv = cycle->relaxationVoltage; + else + { + /*The relaxation point was not reached. Both fit intervals fall back to the pause + end: the OCV and the model are then taken from the pause end instead of being + dropped*/ + if(settings.fitEnd == BATTERYPARAMS_FIT_END_RELAXATION) + cycle->modelReason = "Relaxation point not reached within the pause, OCV and the fit fall back to the pause end"; + relaxPosition = pauseEnd; + } /*Overpotential left on the RC branches when the pulse ends, decaying to zero as the cell relaxes towards its open circuit voltage*/ @@ -292,157 +400,223 @@ bool BatteryParamsExtraction::analyzeCycle(batteryparams_cycle_t *cycle, battery cover the whole pause, so the two settings stay comparable*/ int fitEndPosition = (settings.fitEnd == BATTERYPARAMS_FIT_END_RELAXATION) ? relaxPosition : pauseEnd; - for(int i = pauseStart; i <= fitEndPosition; i++) + cycle->fitEndKey = cycle->plotKeys[fitEndPosition]; + + /*Open circuit voltage is the average of the last points of the fit interval: the + end is the relaxation point when the fit stops there, otherwise the pause end. + The window width is set in points, averaging the settled tail keeps a noisy + sample or the onset of the next pulse from pulling the value off*/ + { + int ocvWindow = (settings.ocvWindow > 1) ? settings.ocvWindow : 1; + int ocvStart = fitEndPosition - (ocvWindow - 1); + if(ocvStart < pauseStart) ocvStart = pauseStart; + + double ocvSum = 0; + int ocvNo = 0; + for(int i = ocvStart; i <= fitEndPosition; i++) + { + ocvSum += pauseAverage[i]; + ocvNo++; + } + cycle->ocv = (ocvNo > 0) ? (ocvSum / ocvNo) : pauseAverage[fitEndPosition]; + } + + /*The exponential fit is over determined, so for a long pause only a capped number + of evenly spaced points is fed to it. This keeps the grid search fast without + changing the fitted time constants. The last point is always kept so the interval + end is not lost*/ + int fitCount = fitEndPosition - pauseStart + 1; + int fitStride = (fitCount > BATTERYPARAMS_FIT_MAX_POINTS) ? (fitCount / BATTERYPARAMS_FIT_MAX_POINTS) : 1; + + for(int i = pauseStart; i <= fitEndPosition; i += fitStride) { relaxTime.append((cycle->plotKeys[i] - cycle->pauseStartKey) / 1000.0); - relaxValue.append(cycle->plotVoltage[i]); + relaxValue.append(pauseAverage[i]); } - if(relaxTime.size() < 4) return false; + if((fitStride > 1) && (((fitEndPosition - pauseStart) % fitStride) != 0)) + { + relaxTime.append((cycle->plotKeys[fitEndPosition] - cycle->pauseStartKey) / 1000.0); + relaxValue.append(pauseAverage[fitEndPosition]); + } + + if(relaxTime.size() < 4) { cycle->modelReason = "Too few samples in the fit interval (need at least 4)"; return false; } + + if(progress) progress("fitting the RC time constants"); + + /*The fit is anchored at both ends: the open circuit voltage is the relaxed + voltage, and the branch amplitudes sum to the overpotential present at the + pause start, so the drawn curve always starts exactly from the pause start + point and settles on the open circuit voltage. + The slow branch is peeled from the later portion of the relaxation, where the + fast branch has already settled, and the fast branch is then fitted on the + early residual, so it is clear which portion of the signal each time constant + comes from*/ + openCircuitVoltage = cycle->ocv; + + double overpotential = openCircuitVoltage - cycle->pauseStartVoltage; + + if(fabs(overpotential) < 1e-6) { cycle->modelReason = "Open circuit voltage equals the pause start voltage, no overpotential to fit (the cell barely moved during the pulse)"; return false; } - /*Time constants are searched for on a logarithmic grid, with the asymptote - and the amplitudes solved by least squares for every candidate. The grid is - then narrowed around the best pair a few times to refine the result. - Settling takes about five time constants, so nothing much longer than the - relaxation itself is worth trying*/ { + int sampleNo = relaxTime.size(); double relaxDuration = relaxTime.last(); - double tauFastLow = relaxTime[1] - relaxTime[0]; - double tauFastHigh = relaxDuration / BATTERYPARAMS_SETTLING_TAU_NO * 2.0; - double tauSlowLow; - double tauSlowHigh; - double bestError = -1; + QVector decay(sampleNo); - if(tauFastLow <= 0) tauFastLow = relaxDuration / 1000.0; - if(tauFastHigh <= tauFastLow) tauFastHigh = tauFastLow * 10.0; + for(int i = 0; i < sampleNo; i++) + { + decay[i] = openCircuitVoltage - relaxValue[i]; + } - tauSlowLow = tauFastLow; - tauSlowHigh = tauFastHigh; + double sampleStep = relaxTime[1] - relaxTime[0]; + if(sampleStep <= 0) sampleStep = relaxDuration / sampleNo; - for(int refinement = 0; refinement < settings.tauRefinementNo; refinement++) + int splitIndex = sampleNo - 1; + for(int i = 0; i < sampleNo; i++) { - double bestTauFast = 0; - double bestTauSlow = 0; - double bestAmplitudeFast = 0; - double bestAmplitudeSlow = 0; - double bestVoltage = 0; + if(relaxTime[i] >= relaxDuration * BATTERYPARAMS_PEEL_SPLIT) + { + splitIndex = i; + break; + } + } + if(splitIndex < 1) splitIndex = 1; + if(splitIndex > sampleNo - 2) splitIndex = sampleNo - 2; + + double tauSlowValue = 0; + double amplitudeSlowValue = 0; + bool slowOk = secondOrder && + prvBATTERYPARAMS_SingleExpFit(relaxTime, decay, splitIndex, sampleNo - 1, + sampleStep, relaxDuration, settings.tauGridPoints, BATTERYPARAMS_TAU_REFINEMENT_NO, + &tauSlowValue, &litudeSlowValue); - bestError = -1; + double tauFastValue = 0; + double amplitudeFastValue = 0; + bool fastOk; + + if(slowOk) + { + QVector residual(splitIndex); - for(int fastStep = 0; fastStep < settings.tauGridPoints; fastStep++) + for(int i = 0; i < splitIndex; i++) { - double tauFastCandidate = tauFastLow * pow(tauFastHigh / tauFastLow, - (double)fastStep / (settings.tauGridPoints - 1)); - int slowSteps = secondOrder ? settings.tauGridPoints : 1; - - for(int slowStep = 0; slowStep < slowSteps; slowStep++) - { - double tauSlowCandidate = 0; - double candidateFast = 0; - double candidateSlow = 0; - double candidateVoltage = 0; - double errorSum = 0; - - if(secondOrder) - { - tauSlowCandidate = tauSlowLow * pow(tauSlowHigh / tauSlowLow, - (double)slowStep / (settings.tauGridPoints - 1)); - - /*Branches have to be clearly separated, otherwise the two - exponentials describe the same thing*/ - if(tauSlowCandidate < tauFastCandidate * settings.tauSeparation) continue; - } - - if(!prvBATTERYPARAMS_RelaxationFit(relaxTime, relaxValue, tauFastCandidate, tauSlowCandidate, - secondOrder, &candidateVoltage, &candidateFast, &candidateSlow)) - { - continue; - } - - if(candidateFast < 0) continue; - if(secondOrder && (candidateSlow < 0)) continue; - - for(int i = 0; i < relaxTime.size(); i++) - { - double fitted = candidateVoltage - candidateFast * exp(-relaxTime[i] / tauFastCandidate); - double error; - - if(secondOrder) fitted -= candidateSlow * exp(-relaxTime[i] / tauSlowCandidate); - - error = relaxValue[i] - fitted; - errorSum += error * error; - } - - if((bestError < 0) || (errorSum < bestError)) - { - bestError = errorSum; - bestTauFast = tauFastCandidate; - bestTauSlow = tauSlowCandidate; - bestAmplitudeFast = candidateFast; - bestAmplitudeSlow = candidateSlow; - bestVoltage = candidateVoltage; - } - } + residual[i] = decay[i] - amplitudeSlowValue * exp(-relaxTime[i] / tauSlowValue); } - if(bestError < 0) return false; + fastOk = prvBATTERYPARAMS_SingleExpFit(relaxTime, residual, 0, splitIndex - 1, + sampleStep, tauSlowValue / settings.tauSeparation, + settings.tauGridPoints, BATTERYPARAMS_TAU_REFINEMENT_NO, + &tauFastValue, &litudeFastValue); + } + else + { + fastOk = prvBATTERYPARAMS_SingleExpFit(relaxTime, decay, 0, sampleNo - 1, + sampleStep, relaxDuration, settings.tauGridPoints, BATTERYPARAMS_TAU_REFINEMENT_NO, + &tauFastValue, &litudeFastValue); + secondOrder = false; + } + + (void)amplitudeFastValue; + + if(!fastOk) { cycle->modelReason = "Exponential fit of the fast branch did not converge"; return false; } + + if(secondOrder && (tauSlowValue <= tauFastValue)) + { + secondOrder = false; + } - cycle->tauFast = bestTauFast; - cycle->tauSlow = bestTauSlow; - amplitudeFast = bestAmplitudeFast; - amplitudeSlow = bestAmplitudeSlow; - openCircuitVoltage = bestVoltage; + cycle->tauFast = tauFastValue; + cycle->tauSlow = secondOrder ? tauSlowValue : 0; - tauFastLow = bestTauFast / BATTERYPARAMS_TAU_REFINEMENT_SPAN; - tauFastHigh = bestTauFast * BATTERYPARAMS_TAU_REFINEMENT_SPAN; + if(secondOrder) + { + /*Amplitudes are re-solved under the constraint that they sum to the + overpotential, so the curve is pinned to the pause start voltage*/ + double numerator = 0; + double denominator = 0; - if(secondOrder) + for(int i = 0; i < sampleNo; i++) { - tauSlowLow = bestTauSlow / BATTERYPARAMS_TAU_REFINEMENT_SPAN; - tauSlowHigh = bestTauSlow * BATTERYPARAMS_TAU_REFINEMENT_SPAN; + double basisFast = exp(-relaxTime[i] / cycle->tauFast); + double basisSlow = exp(-relaxTime[i] / cycle->tauSlow); + double difference = basisFast - basisSlow; + + numerator += (decay[i] - overpotential * basisSlow) * difference; + denominator += difference * difference; } + + amplitudeFast = (denominator > 0) ? (numerator / denominator) : overpotential; + + if((overpotential > 0) && (amplitudeFast < 0)) amplitudeFast = 0; + if((overpotential < 0) && (amplitudeFast > 0)) amplitudeFast = 0; + if(fabs(amplitudeFast) > fabs(overpotential)) amplitudeFast = overpotential; + + amplitudeSlow = overpotential - amplitudeFast; + } + else + { + amplitudeFast = overpotential; + amplitudeSlow = 0; } - } - if(secondOrder && (cycle->tauSlow <= cycle->tauFast)) - { - secondOrder = false; - cycle->model = BATTERYPARAMS_MODEL_FIRST_ORDER; - cycle->tauSlow = 0; - amplitudeSlow = 0; + double boundaryTime = BATTERYPARAMS_PEEL_BOUNDARY_TAU * cycle->tauFast; + + if(secondOrder && (boundaryTime > relaxTime[splitIndex])) boundaryTime = relaxTime[splitIndex]; + if(boundaryTime > relaxDuration) boundaryTime = relaxDuration; + + cycle->fastPortionEndKey = cycle->pauseStartKey + boundaryTime * 1000.0; } - /*Overpotential left on the RC branches when the pulse ends, decaying to zero - as the cell relaxes towards its open circuit voltage*/ + cycle->model = secondOrder ? BATTERYPARAMS_MODEL_SECOND_ORDER : BATTERYPARAMS_MODEL_FIRST_ORDER; + + /*During the pulse each branch charges towards I*R, so the amplitude seen at the + beginning of the relaxation is scaled by how far it got*/ pulseDuration = (cycle->pulseEndKey - cycle->pulseStartKey) / 1000.0; pulseCurrent = cycle->pulseEndCurrent / 1000.0; - if((pulseDuration <= 0) || (fabs(pulseCurrent) < 1e-9)) return false; + if((pulseDuration <= 0) || (fabs(pulseCurrent) < 1e-9)) { cycle->modelReason = "Pulse duration or pulse current is zero, R1/C1 cannot be scaled"; return false; } - /*During the pulse each branch charges towards I*R, so the amplitude seen at - the beginning of the relaxation is scaled by how far it got*/ double chargedFast = 1.0 - exp(-pulseDuration / cycle->tauFast); - if(chargedFast <= 0) return false; + if(chargedFast <= 0) { cycle->modelReason = "Fast time constant too large for the pulse length, R1/C1 cannot be scaled"; return false; } + + /*A branch is only reported when it actually carries part of the relaxation. If its + amplitude solved to (near) zero the branch could not be determined, so its R and C + are left empty instead of shown as zero*/ + double amplitudeEps = 1e-4 * fabs(overpotential); cycle->r1 = amplitudeFast / (pulseCurrent * chargedFast); cycle->c1 = (fabs(cycle->r1) > 1e-9) ? cycle->tauFast / cycle->r1 : 0; + cycle->r1Valid = (fabs(amplitudeFast) > amplitudeEps); if(secondOrder) { double chargedSlow = 1.0 - exp(-pulseDuration / cycle->tauSlow); - if(chargedSlow <= 0) return false; + if(chargedSlow <= 0) { cycle->modelReason = "Slow time constant too large for the pulse length, R2/C2 cannot be scaled"; return false; } cycle->r2 = amplitudeSlow / (pulseCurrent * chargedSlow); cycle->c2 = (fabs(cycle->r2) > 1e-9) ? cycle->tauSlow / cycle->r2 : 0; + cycle->r2Valid = (fabs(amplitudeSlow) > amplitudeEps); } + if(!cycle->r1Valid && cycle->r2Valid) + cycle->modelReason = "Fast RC branch (R1/C1) could not be determined: it had no amplitude, only the slow branch (R2/C2) was identified"; + else if(cycle->r1Valid && secondOrder && !cycle->r2Valid) + cycle->modelReason = "Slow RC branch (R2/C2) could not be determined: it had no amplitude, only the fast branch (R1/C1) was identified"; + + if(progress) progress("evaluating the fit error"); + double squareErrorSum = 0; int errorSampleNo = 0; - /*Evaluated over the whole pause no matter where the parameters came from*/ - for(int i = pauseStart; i <= pauseEnd; i++) + /*Evaluated over the whole pause no matter where the parameters came from. The drawn + curve and the error are sampled at the same capped rate as the fit, so a long pause + does not spend time evaluating exp() and drawing hundreds of thousands of points*/ + int errCount = pauseEnd - pauseStart + 1; + int errStride = (errCount > BATTERYPARAMS_FIT_MAX_POINTS) ? (errCount / BATTERYPARAMS_FIT_MAX_POINTS) : 1; + + for(int i = pauseStart; i <= pauseEnd; i += errStride) { double time = (cycle->plotKeys[i] - cycle->pauseStartKey) / 1000.0; double fitted = openCircuitVoltage - amplitudeFast * exp(-time / cycle->tauFast); @@ -453,7 +627,7 @@ bool BatteryParamsExtraction::analyzeCycle(batteryparams_cycle_t *cycle, battery fitted -= amplitudeSlow * exp(-time / cycle->tauSlow); } - error = cycle->plotVoltage[i] - fitted; + error = pauseAverage[i] - fitted; squareErrorSum += error * error; errorSampleNo++; @@ -463,11 +637,13 @@ bool BatteryParamsExtraction::analyzeCycle(batteryparams_cycle_t *cycle, battery cycle->fitVoltage.append(fitted); } - if(errorSampleNo == 0) return false; + if(errorSampleNo == 0) { cycle->modelReason = "No samples to evaluate the fit error"; return false; } cycle->fitRmse = sqrt(squareErrorSum / errorSampleNo); cycle->modelValid = true; + if(!secondOrder && cycle->modelReason.isEmpty()) cycle->modelReason = "First order model (single RC): R2/C2 not identified, the relaxation showed a single dominant time constant"; + return true; } @@ -496,12 +672,14 @@ void BatteryParamsExtraction::cycleReset() activeCycle.soc = 0; activeCycle.resistanceValid = false; activeCycle.socValid = false; + activeCycle.incomplete = false; activeCycle.relaxationReached = false; activeCycle.relaxationKey = 0; activeCycle.relaxationVoltage = 0; activeCycle.ocv = 0; activeCycle.model = settings.model; activeCycle.modelValid = false; + activeCycle.modelReason = ""; activeCycle.tauFast = 0; activeCycle.tauSlow = 0; activeCycle.r1 = 0; @@ -702,6 +880,43 @@ bool BatteryParamsExtraction::cyclePointsFit(batteryparams_cycle_t *cycle) return true; } +/*Moves the pause start onto the sample at or after the given key and recomputes the + series resistance from the new pause start. Pulse end stays where it is, so the + instantaneous step the resistance is read from is measured against the new pause + start. The RC fit is left to analyzeCycle, which reads the updated pause start*/ +bool BatteryParamsExtraction::setPauseStart(batteryparams_cycle_t *cycle, double pauseStartKey) +{ + int position = -1; + + if(cycle == NULL) return false; + if(cycle->plotKeys.size() != cycle->plotVoltage.size()) return false; + if(cycle->plotKeys.size() != cycle->plotCurrent.size()) return false; + + for(int i = 0; i < cycle->plotKeys.size(); i++) + { + if(cycle->plotKeys[i] >= pauseStartKey) + { + position = i; + break; + } + } + + if(position < 0) return false; + if(cycle->plotKeys[position] <= cycle->pulseEndKey) return false; + if(cycle->plotKeys[position] >= cycle->pauseEndKey) return false; + + cycle->pauseStartKey = cycle->plotKeys[position]; + cycle->pauseStartVoltage = cycle->plotVoltage[position]; + cycle->pauseStartCurrent = cycle->plotCurrent[position]; + + cycle->deltaVoltage = cycle->pauseStartVoltage - cycle->pulseEndVoltage; + cycle->deltaCurrent = cycle->pulseEndCurrent - cycle->pauseStartCurrent; + cycle->resistanceValid = fabs(cycle->deltaCurrent) > 0.000001; + cycle->resistance = cycle->resistanceValid ? cycle->deltaVoltage / (cycle->deltaCurrent / 1000.0) : 0; + + return true; +} + void BatteryParamsExtraction::seriesSmooth(const QVector &keys, const QVector &values, double window, QVector *smoothed) { @@ -847,10 +1062,9 @@ void BatteryParamsExtraction::processPendingMarkers() { double markerKey; - if(samplingPeriod <= 0) return; if(keySamples.isEmpty()) return; - markerKey = pendingMarkers.first().key * samplingPeriod; + markerKey = pendingMarkers.first().key; if(markerKey > keySamples.last()) return; @@ -877,6 +1091,7 @@ void BatteryParamsExtraction::processMarker(QString name, int position) if(name == pulseStartMarker) { + if(captureIncomplete && cycleActive) finalizeIncompleteCycle(key); cycleReset(); cycleActive = true; cycleCounter++; diff --git a/Source/Processing/batteryparamsextraction.h b/Source/Processing/batteryparamsextraction.h index 98ec8b3..012ed11 100644 --- a/Source/Processing/batteryparamsextraction.h +++ b/Source/Processing/batteryparamsextraction.h @@ -3,6 +3,7 @@ #include #include +#include #include #define BATTERYPARAMS_DEFAULT_PULSE_START_MARKER "Pulse Start" @@ -20,8 +21,15 @@ #define BATTERYPARAMS_TAU_SEPARATION 3.0 #define BATTERYPARAMS_TAU_REFINEMENT_NO 3 #define BATTERYPARAMS_TAU_REFINEMENT_SPAN 1.6 +#define BATTERYPARAMS_PEEL_SPLIT 0.4 +#define BATTERYPARAMS_PEEL_BOUNDARY_TAU 3.0 +#define BATTERYPARAMS_START_SWEEP_WINDOW 5000.0 +#define BATTERYPARAMS_START_SWEEP_MAX_STEPS 40 #define BATTERYPARAMS_INITIAL_SOC_DEFAULT 100.0 #define BATTERYPARAMS_CYCLE_PLOT_STEP_WINDOW 50.0 +#define BATTERYPARAMS_OCV_WINDOW_DEFAULT 10 +#define BATTERYPARAMS_FIT_AVERAGE_WINDOW_DEFAULT 1 +#define BATTERYPARAMS_FIT_MAX_POINTS 4000 typedef enum { @@ -43,11 +51,12 @@ typedef struct batteryparams_model_t model; batteryparams_fit_end_t fitEnd; int tauGridPoints; - int tauRefinementNo; double tauSeparation; double capacity; double initialSoc; int plotDecimation; + int ocvWindow; /*points averaged for the open circuit voltage*/ + int fitAverageWindow; /*points averaged before the RC fit, 1 keeps raw*/ }batteryparams_settings_t; typedef struct @@ -81,14 +90,21 @@ typedef struct double relaxationVoltage; double ocv; + bool incomplete; + batteryparams_model_t model; bool modelValid; + QString modelReason; double tauFast; double tauSlow; + double fastPortionEndKey; + double fitEndKey; double r1; double c1; double r2; double c2; + bool r1Valid; + bool r2Valid; double fitRmse; double fitMaxError; @@ -101,10 +117,23 @@ typedef struct QVector plotKeys; QVector plotVoltage; QVector plotCurrent; + + QVector avgKeys; + QVector avgVoltage; }batteryparams_cycle_t; Q_DECLARE_METATYPE(batteryparams_cycle_t); +typedef struct +{ + unsigned int index; + double startKey; + double endKey; + double capacity; +}batteryparams_charge_cycle_t; + +Q_DECLARE_METATYPE(batteryparams_charge_cycle_t); + class BatteryParamsExtraction : public QObject { Q_OBJECT @@ -115,13 +144,18 @@ class BatteryParamsExtraction : public QObject void setSamplingPeriod(double aSamplingPeriod); void setSettings(batteryparams_settings_t aSettings); void setAnalysisDeferred(bool aDeferred); + void setCaptureIncomplete(bool aCapture); + void flushIncompleteCycle(); batteryparams_settings_t getSettings(); static batteryparams_settings_t settingsDefault(); - static bool analyzeCycle(batteryparams_cycle_t *cycle, batteryparams_settings_t settings); + static void nameCurrentThread(unsigned int cycleIndex); + static bool analyzeCycle(batteryparams_cycle_t *cycle, batteryparams_settings_t settings, + const std::function &progress = std::function()); static int relaxationPositionGet(const QVector &keys, const QVector &voltage, int start, int end, double threshold, double window); static bool cyclePointsFit(batteryparams_cycle_t *cycle); + static bool setPauseStart(batteryparams_cycle_t *cycle, double pauseStartKey); static void seriesSmooth(const QVector &keys, const QVector &values, double window, QVector *smoothed); QVector getCycles(); @@ -153,6 +187,7 @@ public slots: double samplingPeriod; batteryparams_settings_t settings; bool analysisDeferred; + bool captureIncomplete; double chargeTotal; QVector pendingMarkers; @@ -167,6 +202,7 @@ public slots: void processMarker(QString name, int position); void trimSamples(double key); void storeCycleSamples(); + void finalizeIncompleteCycle(double pauseEndKey); void cycleReset(); }; diff --git a/Source/Processing/fileprocessing.cpp b/Source/Processing/fileprocessing.cpp index fb0bd35..28e2793 100644 --- a/Source/Processing/fileprocessing.cpp +++ b/Source/Processing/fileprocessing.cpp @@ -164,6 +164,7 @@ bool FileProcessing::appendSummaryFile(QString content) bool FileProcessing::appendSampleData(QVector* voltage, QVector* voltageKeys, QVector* current, QVector* currentKeys) { + if(samplesFile == NULL) return false; if(!samplesFile->isOpen()) { if(!samplesFile->open(QIODevice::WriteOnly | QIODevice::Text| QIODevice::Append)) return false; @@ -172,10 +173,10 @@ bool FileProcessing::appendSampleData(QVector* voltage, QVector* //TODO: Check QVectors sizes; for(unsigned int i = 0; i < voltage->size(); i++) { - out << QString::asprintf("%1.5f", voltage->at(i)) << ","; - out << QString::asprintf("%1.7f", voltageKeys->at(i)) << ","; - out << QString::asprintf("%1.5f", current->at(i)) << ","; - out << QString::asprintf("%1.7f", currentKeys->at(i)) << "\n"; + out << QString::asprintf("%1.5f", voltage->at(i)) << ","; + out << QString::asprintf("%1.7f", voltageKeys->at(i)) << ","; + out << QString::asprintf("%1.5f", current->at(i)) << ","; + out << QString::asprintf("%1.7f", currentKeys->at(i)) << "\n"; } samplesFile->close(); return true; @@ -183,6 +184,7 @@ bool FileProcessing::appendSampleData(QVector* voltage, QVector* bool FileProcessing::appendConsumptionData(QVector *consumption, QVector *consumptionKeys) { + if(consumptionFile == NULL) return false; if(!consumptionFile->isOpen()) { if(!consumptionFile->open(QIODevice::WriteOnly | QIODevice::Text| QIODevice::Append)) return false; @@ -200,6 +202,7 @@ bool FileProcessing::appendConsumptionData(QVector *consumption, QVector bool FileProcessing::appendEPData(QString name, int key) { + if(epFile == NULL) return false; if(!epFile->isOpen()) { if(!epFile->open(QIODevice::WriteOnly | QIODevice::Text| QIODevice::Append)) return false; diff --git a/Source/Processing/waveform.cpp b/Source/Processing/waveform.cpp index bf17776..1533abe 100644 --- a/Source/Processing/waveform.cpp +++ b/Source/Processing/waveform.cpp @@ -18,6 +18,12 @@ Waveform::Waveform() amplitude = 0; period = 0; points = 0; + batParam = false; + batCapacity = 0; + batRelaxAdaptive = false; + batRelaxThreshold = 0; + batRelaxWindow = 0; + batRelaxFilter = 0; } bool Waveform::isValid() @@ -367,6 +373,31 @@ QJsonObject Waveform::toJson() obj["amplitude"] = (int)amplitude; obj["period"] = (int)period; obj["points"] = (int)points; + obj["batParam"] = batParam; + if(batParam) + { + obj["batCapacity"] = batCapacity; + obj["batRelaxAdaptive"] = batRelaxAdaptive; + obj["batRelaxThreshold"] = batRelaxThreshold; + obj["batRelaxWindow"] = batRelaxWindow; + obj["batRelaxFilter"] = batRelaxFilter; + + QJsonArray regionsArray; + for(int i = 0; i < batRegions.size(); i++) + { + QJsonObject regionObj; + regionObj["socHigh"] = batRegions[i].socHigh; + regionObj["socLow"] = batRegions[i].socLow; + regionObj["accuracy"] = batRegions[i].accuracy; + regionObj["amplitude"] = batRegions[i].amplitude; + regionObj["pause"] = batRegions[i].pause; + regionObj["relaxThreshold"] = batRegions[i].relaxThreshold; + regionObj["relaxWindow"] = batRegions[i].relaxWindow; + regionObj["relaxFilter"] = batRegions[i].relaxFilter; + regionsArray.append(regionObj); + } + obj["batRegions"] = regionsArray; + } for(int i = 0; i < chunks.size(); i++) { QJsonObject chunkObj; @@ -395,6 +426,30 @@ bool Waveform::fromJson(QJsonObject obj) amplitude = obj["amplitude"].toInt(); period = obj["period"].toInt(); points = obj["points"].toInt(); + batParam = obj["batParam"].toBool(false); + batCapacity = obj["batCapacity"].toDouble(0); + batRelaxAdaptive = obj["batRelaxAdaptive"].toBool(false); + batRelaxThreshold = obj["batRelaxThreshold"].toDouble(0); + batRelaxWindow = obj["batRelaxWindow"].toDouble(0); + batRelaxFilter = obj["batRelaxFilter"].toDouble(0); + batRegions.clear(); + { + QJsonArray regionsArray = obj["batRegions"].toArray(); + for(int i = 0; i < regionsArray.size(); i++) + { + QJsonObject regionObj = regionsArray[i].toObject(); + waveform_batregion_t region; + region.socHigh = regionObj["socHigh"].toDouble(0); + region.socLow = regionObj["socLow"].toDouble(0); + region.accuracy = regionObj["accuracy"].toDouble(0); + region.amplitude = regionObj["amplitude"].toDouble(0); + region.pause = regionObj["pause"].toDouble(0); + region.relaxThreshold = regionObj["relaxThreshold"].toDouble(0); + region.relaxWindow = regionObj["relaxWindow"].toDouble(0); + region.relaxFilter = regionObj["relaxFilter"].toDouble(0); + batRegions.append(region); + } + } chunks.clear(); for(int i = 0; i < chunksArray.size(); i++) { diff --git a/Source/Processing/waveform.h b/Source/Processing/waveform.h index 81286d7..c1fb22f 100644 --- a/Source/Processing/waveform.h +++ b/Source/Processing/waveform.h @@ -39,6 +39,18 @@ typedef struct QString markerPos; }waveform_chunk_t; +typedef struct +{ + double socHigh; + double socLow; + double accuracy; + double amplitude; + double pause; + double relaxThreshold; + double relaxWindow; + double relaxFilter; +}waveform_batregion_t; + class Waveform { public: @@ -79,6 +91,14 @@ class Waveform unsigned int amplitude; unsigned int period; unsigned int points; + + bool batParam; + double batCapacity; + bool batRelaxAdaptive; + double batRelaxThreshold; + double batRelaxWindow; + double batRelaxFilter; + QList batRegions; }; class WaveformLibrary : public QObject diff --git a/Source/Windows/BatteryParams/batterycyclewnd.cpp b/Source/Windows/BatteryParams/batterycyclewnd.cpp index 2fccd7e..24d4783 100644 --- a/Source/Windows/BatteryParams/batterycyclewnd.cpp +++ b/Source/Windows/BatteryParams/batterycyclewnd.cpp @@ -2,10 +2,14 @@ #include #include +#include +#include +#include +#include #include -#define BATTERYCYCLE_PLOT_MIN_WIDTH 600 -#define BATTERYCYCLE_PLOT_MIN_HEIGHT 180 +#define BATTERYCYCLE_PLOT_MIN_WIDTH 500 +#define BATTERYCYCLE_PLOT_MIN_HEIGHT 140 #define BATTERYCYCLE_EDIT_WIDTH 100 #define BATTERYCYCLE_STEP_BUTTON_WIDTH 30 #define BATTERYCYCLE_BUTTON_WIDTH 90 @@ -22,10 +26,16 @@ BatteryCycleWnd::BatteryCycleWnd(QWidget *parent) : setFont(defaultFont); setWindowTitle("Battery cycle"); + fitSettings = BatteryParamsExtraction::settingsDefault(); + infoLabel = new QLabel(this); + infoLabel->setWordWrap(true); + infoLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred); mainLayout->addWidget(infoLabel); modelLabel = new QLabel(this); + modelLabel->setWordWrap(true); + modelLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred); mainLayout->addWidget(modelLabel); markerLayout->addLayout(createMarkerRow("Pulse Start", &pulseStartEdit)); @@ -72,13 +82,38 @@ BatteryCycleWnd::BatteryCycleWnd(QWidget *parent) : currentPlot->scatterAddGraph(); mainLayout->addWidget(currentPlot, 1); + /*With both plots locked, panning or zooming the X axis of one follows on the other, + so the voltage and the current stay aligned in time*/ + connect(voltagePlot, &Plot::sigXRangeChanged, this, [this](QCPRange range){ currentPlot->setXRangeSynced(range); }); + connect(currentPlot, &Plot::sigXRangeChanged, this, [this](QCPRange range){ voltagePlot->setXRangeSynced(range); }); + connect(fitButton, &QPushButton::clicked, this, &BatteryCycleWnd::onFitPoints); connect(restoreButton, &QPushButton::clicked, this, &BatteryCycleWnd::onRestore); connect(saveButton, &QPushButton::clicked, this, &BatteryCycleWnd::onSave); plotSettings = BATTERYPARAMSPLOT_SettingsDefault(); - resize(900, 650); + analysisEmit = false; + analysisGen = 0; + analysisRunGen = -1; + connect(&analysisWatcher, &QFutureWatcher::finished, + this, &BatteryCycleWnd::onAnalysisFinished); + + /*A normal top level window with minimize, maximize and close, so it can be resized + and maximized instead of opening larger than the screen*/ + setWindowFlags(Qt::Window | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint); + + int width = 900; + int height = 650; + + if(QGuiApplication::primaryScreen() != NULL) + { + QRect available = QGuiApplication::primaryScreen()->availableGeometry(); + if(width > available.width() - 40) width = available.width() - 40; + if(height > available.height() - 40) height = available.height() - 40; + } + + resize(width, height); } int BatteryCycleWnd::keyPositionGet(QVector keys, double key) @@ -208,13 +243,20 @@ void BatteryCycleWnd::refreshMarkerEdits() pauseEndEdit->setText(QString::number(cycle.pauseEndKey / timeScale(), 'f', timeDecimals())); } +void BatteryCycleWnd::setSettings(batteryparams_settings_t settings) +{ + fitSettings = settings; +} + void BatteryCycleWnd::onFitPoints() { if(!BatteryParamsExtraction::cyclePointsFit(&cycle)) return; + cycle.incomplete = false; + refreshMarkerEdits(); - updateInfo(); - updatePlots(); + + runAnalysis(true); } void BatteryCycleWnd::onRestore() @@ -256,8 +298,67 @@ void BatteryCycleWnd::applyMarkers() refreshMarkerEdits(); + runAnalysis(false); +} + +void BatteryCycleWnd::runAnalysis(bool emitWhenDone) +{ + /*The fit runs in a worker thread so moving the points never blocks the window. + analyzeCycle only reads the sample vectors and writes the fit and average vectors, + so the large input vectors are shared through copy on write (no deep copy, the + worker never writes them) and only the output vectors are given fresh empty storage + so the worker never shares a written container with the one the GUI thread draws. + If the points are moved again while a fit is running, setFuture drops the old one + and only the newest result reaches the GUI*/ + batteryparams_cycle_t snapshot = cycle; + + snapshot.fitKeys = QVector(); + snapshot.fitVoltage = QVector(); + snapshot.avgKeys = QVector(); + snapshot.avgVoltage = QVector(); + + analysisEmit = emitWhenDone; + analysisRunGen = ++analysisGen; + + modelLabel->setText("Calculating..."); + modelLabel->setStyleSheet("color: gray;"); + + int gen = analysisRunGen; + batteryparams_settings_t settings = fitSettings; + + analysisWatcher.setFuture(QtConcurrent::run([this, snapshot, settings, gen]() mutable -> batteryparams_cycle_t + { + BatteryParamsExtraction::nameCurrentThread(snapshot.index); + + /*Each stage reports its name. The label lives in the GUI thread, so the update is + posted there, and a stage from a superseded run is ignored by the generation*/ + auto progress = [this, gen](const QString &step) + { + QMetaObject::invokeMethod(this, [this, gen, step]() + { + if(gen == analysisGen) modelLabel->setText("Calculating: " + step + "..."); + }, Qt::QueuedConnection); + }; + + BatteryParamsExtraction::analyzeCycle(&snapshot, settings, progress); + return snapshot; + })); +} + +void BatteryCycleWnd::onAnalysisFinished() +{ + if(!analysisWatcher.future().isResultReadyAt(0)) return; + + /*A cycle opened in the meantime invalidates a result still coming from the old one*/ + if(analysisRunGen != analysisGen) return; + + cycle = analysisWatcher.result(); + + refreshMarkerEdits(); updateInfo(); - updatePlots(); + updatePlots(true); + + if(analysisEmit) emit sigCycleUpdated(cycle); } void BatteryCycleWnd::updateInfo() @@ -277,32 +378,45 @@ void BatteryCycleWnd::updateInfo() " | R0 " + (cycle.resistanceValid ? QString::number(cycle.resistance * 1000.0, 'f', 2) + " mOhm" : "-") + (moved ? " | markers moved, not saved" : "")); - if(!cycle.relaxationReached) + QString reasonSuffix = cycle.modelReason.isEmpty() ? QString() : (" | " + cycle.modelReason); + + if(!cycle.relaxationReached && !cycle.modelValid) { - modelLabel->setText("Relaxation not reached, RC model not calculated"); + modelLabel->setText("Relaxation not reached, RC model not calculated" + reasonSuffix); modelLabel->setStyleSheet("color: rgb(170, 130, 0);"); return; } if(!cycle.modelValid) { - modelLabel->setText("Relaxed at " + QString::number(cycle.relaxationKey / timeScale(), 'f', 1) + " " + timeSuffix() + ", RC model could not be fitted"); + modelLabel->setText("Relaxed at " + QString::number(cycle.relaxationKey / timeScale(), 'f', 1) + " " + timeSuffix() + ", RC model could not be fitted" + reasonSuffix); modelLabel->setStyleSheet("color: rgb(170, 130, 0);"); return; } + QString modelPrefix = cycle.relaxationReached + ? ("Relaxed at " + QString::number(cycle.relaxationKey / timeScale(), 'f', 1) + " " + timeSuffix()) + : "Fitted to pause end (relaxation not reached)"; + + QString fastText = cycle.r1Valid + ? (" | R1 " + QString::number(cycle.r1 * 1000.0, 'f', 2) + " mOhm" + + " C1 " + QString::number(cycle.c1, 'f', 1) + " F" + + " tau1 " + QString::number(cycle.tauFast, 'f', 2) + " s") + : " | R1 / C1 not determined"; + + QString slowText = cycle.r2Valid + ? (" | R2 " + QString::number(cycle.r2 * 1000.0, 'f', 2) + " mOhm" + + " C2 " + QString::number(cycle.c2, 'f', 1) + " F" + + " tau2 " + QString::number(cycle.tauSlow, 'f', 2) + " s") + : (cycle.model == BATTERYPARAMS_MODEL_SECOND_ORDER ? " | R2 / C2 not determined" : ""); + modelLabel->setStyleSheet("color: rgb(0, 120, 0);"); - modelLabel->setText("Relaxed at " + QString::number(cycle.relaxationKey / timeScale(), 'f', 1) + " " + timeSuffix() + " | " + + modelLabel->setText(modelPrefix + " | " + QString(cycle.model == BATTERYPARAMS_MODEL_SECOND_ORDER ? "2nd order" : "1st order") + - " | R1 " + QString::number(cycle.r1 * 1000.0, 'f', 2) + " mOhm" + - " C1 " + QString::number(cycle.c1, 'f', 1) + " F" + - " tau1 " + QString::number(cycle.tauFast, 'f', 2) + " s" + - (cycle.model == BATTERYPARAMS_MODEL_SECOND_ORDER ? - " | R2 " + QString::number(cycle.r2 * 1000.0, 'f', 2) + " mOhm" + - " C2 " + QString::number(cycle.c2, 'f', 1) + " F" + - " tau2 " + QString::number(cycle.tauSlow, 'f', 2) + " s" : "") + + fastText + slowText + " | RMSE " + QString::number(cycle.fitRmse * 1000.0, 'f', 3) + " mV" + - " max " + QString::number(cycle.fitMaxError * 1000.0, 'f', 3) + " mV"); + " max " + QString::number(cycle.fitMaxError * 1000.0, 'f', 3) + " mV" + + reasonSuffix); saveButton->setEnabled(moved); restoreButton->setEnabled(moved); @@ -333,13 +447,28 @@ void BatteryCycleWnd::setPlotSettings(batteryparams_plot_settings_t settings) } } -void BatteryCycleWnd::updatePlots() +void BatteryCycleWnd::updatePlots(bool keepView) { + /*When the view is kept, the current zoom is captured before the data is replaced and + restored afterwards, so a recalculation does not snap the plot back to the whole + cycle when the user has zoomed into a part of it*/ + QCPRange keepVoltageX, keepVoltageY, keepCurrentX, keepCurrentY; + + if(keepView) + { + keepVoltageX = voltagePlot->plotXRange(); + keepVoltageY = voltagePlot->plotYRange(); + keepCurrentX = currentPlot->plotXRange(); + keepCurrentY = currentPlot->plotYRange(); + } + voltagePlot->scatterClearMarkers(); currentPlot->scatterClearMarkers(); voltagePlot->markersAtKeyClear(); currentPlot->markersAtKeyClear(); voltagePlot->overlayClear(); + voltagePlot->shadeClear(); + voltagePlot->clearAverageData(); QVector scaledKeys; @@ -351,8 +480,19 @@ void BatteryCycleWnd::updatePlots() voltagePlot->setXLabel("[" + timeSuffix() + "]"); currentPlot->setXLabel("[" + timeSuffix() + "]"); - voltagePlot->setData(cycle.plotVoltage, scaledKeys); - currentPlot->setData(cycle.plotCurrent, scaledKeys); + voltagePlot->setData(cycle.plotVoltage, scaledKeys, !keepView); + currentPlot->setData(cycle.plotCurrent, scaledKeys, !keepView); + + /*Averaged pause voltage the RC fit actually used, shown so the effect of the fit + average window is visible. With a window of 1 it sits on top of the raw samples*/ + if(!cycle.avgVoltage.isEmpty() && (cycle.avgVoltage.size() == cycle.avgKeys.size())) + { + QVector scaledAvgKeys; + for(int i = 0; i < cycle.avgKeys.size(); i++) scaledAvgKeys.append(cycle.avgKeys[i] / timeScale()); + + voltagePlot->averageAddGraph(); + voltagePlot->appendAverageData(cycle.avgVoltage, scaledAvgKeys); + } addMarker(voltagePlot, cycle.plotVoltage, cycle.pulseStartKey, "Pulse Start"); addMarker(voltagePlot, cycle.plotVoltage, cycle.pulseEndKey, "Pulse End"); @@ -380,12 +520,38 @@ void BatteryCycleWnd::updatePlots() } voltagePlot->overlaySetData(cycle.fitVoltage, scaledFitKeys); + + /*Shade the portion of the relaxation each time constant was peeled from: + the early part feeds the fast branch, the later part the slow branch*/ + if((cycle.relaxationReached || cycle.modelValid) && (cycle.fastPortionEndKey > cycle.pauseStartKey)) + { + double fastStart = cycle.pauseStartKey / timeScale(); + double fastEnd = cycle.fastPortionEndKey / timeScale(); + double slowEnd = (cycle.fitEndKey > 0 ? cycle.fitEndKey : cycle.relaxationKey) / timeScale(); + + voltagePlot->shadeKeyRange(fastStart, fastEnd, QColor(80, 140, 255, 45)); + + if((cycle.model == BATTERYPARAMS_MODEL_SECOND_ORDER) && (slowEnd > fastEnd)) + { + voltagePlot->shadeKeyRange(fastEnd, slowEnd, QColor(255, 160, 60, 40)); + } + } } if(!cycle.plotKeys.isEmpty()) { - voltagePlot->zoomToKeyRange(scaledKeys.first(), scaledKeys.last()); - currentPlot->zoomToKeyRange(scaledKeys.first(), scaledKeys.last()); + if(keepView) + { + voltagePlot->setXRange(keepVoltageX.lower, keepVoltageX.upper); + voltagePlot->setYRange(keepVoltageY.lower, keepVoltageY.upper); + currentPlot->setXRange(keepCurrentX.lower, keepCurrentX.upper); + currentPlot->setYRange(keepCurrentY.lower, keepCurrentY.upper); + } + else + { + voltagePlot->zoomToKeyRange(scaledKeys.first(), scaledKeys.last()); + currentPlot->zoomToKeyRange(scaledKeys.first(), scaledKeys.last()); + } } applyPlotStyle(); @@ -393,6 +559,9 @@ void BatteryCycleWnd::updatePlots() void BatteryCycleWnd::setCycle(batteryparams_cycle_t aCycle) { + /*Invalidate a fit still running for the previous cycle so its result is dropped*/ + analysisGen++; + cycle = aCycle; originalCycle = aCycle; diff --git a/Source/Windows/BatteryParams/batterycyclewnd.h b/Source/Windows/BatteryParams/batterycyclewnd.h index a490a16..87361ed 100644 --- a/Source/Windows/BatteryParams/batterycyclewnd.h +++ b/Source/Windows/BatteryParams/batterycyclewnd.h @@ -8,6 +8,7 @@ #include #include #include +#include #include "Processing/batteryparamsextraction.h" #include "Windows/BatteryParams/batteryparamsplotsettings.h" @@ -22,6 +23,7 @@ class BatteryCycleWnd : public QWidget void setCycle(batteryparams_cycle_t aCycle); void setPlotSettings(batteryparams_plot_settings_t settings); + void setSettings(batteryparams_settings_t settings); signals: void sigCycleUpdated(batteryparams_cycle_t cycle); @@ -33,6 +35,7 @@ private slots: void onFitPoints(); void onRestore(); void onSave(); + void onAnalysisFinished(); private: QLabel *infoLabel; @@ -51,9 +54,16 @@ private slots: QStringList markerNames; batteryparams_plot_settings_t plotSettings; + batteryparams_settings_t fitSettings; batteryparams_cycle_t cycle; batteryparams_cycle_t originalCycle; + QFutureWatcher analysisWatcher; + bool analysisEmit; + int analysisGen; + int analysisRunGen; + + void runAnalysis(bool emitWhenDone); void addMarker(Plot *plot, QVector values, double key, QString name); int keyPositionGet(QVector keys, double key); QHBoxLayout* createMarkerRow(QString name, QLineEdit **edit); @@ -66,7 +76,7 @@ private slots: QString timeSuffix(); int timeDecimals(); void updateInfo(); - void updatePlots(); + void updatePlots(bool keepView = false); }; #endif // BATTERYCYCLEWND_H diff --git a/Source/Windows/BatteryParams/batteryparamssettingsdlg.cpp b/Source/Windows/BatteryParams/batteryparamssettingsdlg.cpp index 2e569ec..13bb8d4 100644 --- a/Source/Windows/BatteryParams/batteryparamssettingsdlg.cpp +++ b/Source/Windows/BatteryParams/batteryparamssettingsdlg.cpp @@ -66,10 +66,15 @@ BatteryParamsSettingsDlg::BatteryParamsSettingsDlg(QWidget *parent) : tauGridPointsEdit = createEntry(extractionLayout, 2, "Tau search points", "", "Number of candidate time constants tried per decade of the search range.\nMore points give a finer fit and take longer"); - tauRefinementEdit = createEntry(extractionLayout, 3, "Tau refinement steps", "", - "How many times the search range is narrowed around the best result"); - tauSeparationEdit = createEntry(extractionLayout, 4, "Tau separation", "x", + tauSeparationEdit = createEntry(extractionLayout, 3, "Tau separation", "x", "Smallest allowed ratio between the slow and the fast time constant.\nBranches closer than this describe the same effect"); + fitAverageWindowEdit = createEntry(extractionLayout, 4, "Fit average window", "pts", + "Points averaged over the pause before the RC model is fitted.\n" + "1 fits the raw samples, 10 fits a 10 point moving average.\n" + "The average spans the whole pause and stays aligned with the pause start and pause end"); + ocvWindowEdit = createEntry(extractionLayout, 5, "OCV window", "pts", + "Points averaged at the end of the fit interval (relaxation point or pause end) to obtain the open circuit voltage.\n" + "1 uses the single last point"); QTabWidget *tabWidget = new QTabWidget(this); QWidget *analysisTab = new QWidget(this); @@ -140,6 +145,16 @@ BatteryParamsSettingsDlg::BatteryParamsSettingsDlg(QWidget *parent) : setPlotSettings(BATTERYPARAMSPLOT_SettingsDefault()); } +void BatteryParamsSettingsDlg::setExtractionRunning(bool running) +{ + bool editable = !running; + + relaxationThresholdEdit->setEnabled(editable); + relaxationWindowEdit->setEnabled(editable); + relaxationFilterEdit->setEnabled(editable); + fitEndCombo->setEnabled(editable); +} + QLineEdit* BatteryParamsSettingsDlg::createEntry(QGridLayout *layout, int row, QString name, QString unit, QString tooltip) { QLabel *label = new QLabel(name, this); @@ -168,8 +183,9 @@ void BatteryParamsSettingsDlg::setSettings(batteryparams_settings_t settings) modelCombo->setCurrentIndex(settings.model == BATTERYPARAMS_MODEL_FIRST_ORDER ? 0 : 1); fitEndCombo->setCurrentIndex(settings.fitEnd == BATTERYPARAMS_FIT_END_RELAXATION ? 0 : 1); tauGridPointsEdit->setText(QString::number(settings.tauGridPoints)); - tauRefinementEdit->setText(QString::number(settings.tauRefinementNo)); tauSeparationEdit->setText(QString::number(settings.tauSeparation)); + fitAverageWindowEdit->setText(QString::number(settings.fitAverageWindow)); + ocvWindowEdit->setText(QString::number(settings.ocvWindow)); } void BatteryParamsSettingsDlg::setPlotSettings(batteryparams_plot_settings_t settings) @@ -222,8 +238,9 @@ batteryparams_settings_t BatteryParamsSettingsDlg::getSettings() if(relaxationFilterEdit->text().toDouble() >= 0) settings.relaxationFilter = relaxationFilterEdit->text().toDouble(); if(plotDecimationEdit->text().toInt() > 0) settings.plotDecimation = plotDecimationEdit->text().toInt(); if(tauGridPointsEdit->text().toInt() > 1) settings.tauGridPoints = tauGridPointsEdit->text().toInt(); - if(tauRefinementEdit->text().toInt() > 0) settings.tauRefinementNo = tauRefinementEdit->text().toInt(); if(tauSeparationEdit->text().toDouble() > 1) settings.tauSeparation = tauSeparationEdit->text().toDouble(); + if(fitAverageWindowEdit->text().toInt() > 0) settings.fitAverageWindow = fitAverageWindowEdit->text().toInt(); + if(ocvWindowEdit->text().toInt() > 0) settings.ocvWindow = ocvWindowEdit->text().toInt(); settings.model = (modelCombo->currentIndex() == 0) ? BATTERYPARAMS_MODEL_FIRST_ORDER : BATTERYPARAMS_MODEL_SECOND_ORDER; settings.fitEnd = (fitEndCombo->currentIndex() == 0) ? BATTERYPARAMS_FIT_END_RELAXATION : BATTERYPARAMS_FIT_END_PAUSE; diff --git a/Source/Windows/BatteryParams/batteryparamssettingsdlg.h b/Source/Windows/BatteryParams/batteryparamssettingsdlg.h index 1697a52..76bdae7 100644 --- a/Source/Windows/BatteryParams/batteryparamssettingsdlg.h +++ b/Source/Windows/BatteryParams/batteryparamssettingsdlg.h @@ -25,6 +25,8 @@ class BatteryParamsSettingsDlg : public QDialog void setPlotSettings(batteryparams_plot_settings_t settings); batteryparams_plot_settings_t getPlotSettings(); + void setExtractionRunning(bool running); + private: QLineEdit *capacityEdit; QLineEdit *initialSocEdit; @@ -35,8 +37,9 @@ class BatteryParamsSettingsDlg : public QDialog QComboBox *modelCombo; QComboBox *fitEndCombo; QLineEdit *tauGridPointsEdit; - QLineEdit *tauRefinementEdit; QLineEdit *tauSeparationEdit; + QLineEdit *ocvWindowEdit; + QLineEdit *fitAverageWindowEdit; QFontComboBox *plotFontCombo; QLineEdit *plotLabelSizeEdit; diff --git a/Source/Windows/BatteryParams/batteryparamstrendwnd.cpp b/Source/Windows/BatteryParams/batteryparamstrendwnd.cpp index 3cc5648..fc135d4 100644 --- a/Source/Windows/BatteryParams/batteryparamstrendwnd.cpp +++ b/Source/Windows/BatteryParams/batteryparamstrendwnd.cpp @@ -1,20 +1,13 @@ #include "batteryparamstrendwnd.h" -#include -#include -#include -#include #include -#define BATTERYPARAMSTREND_MARKER_SIZE 7 - BatteryParamsTrendWnd::BatteryParamsTrendWnd(QWidget *parent) : QWidget(parent) { QFont defaultFont("Arial", 10); QVBoxLayout *mainLayout = new QVBoxLayout(this); QHBoxLayout *controlLayout = new QHBoxLayout(); - QPushButton *saveButton = new QPushButton("Save image", this); setFont(defaultFont); setWindowTitle("Battery parameters trend"); @@ -22,21 +15,13 @@ BatteryParamsTrendWnd::BatteryParamsTrendWnd(QWidget *parent) : seriesLayout = new QHBoxLayout(); controlLayout->addLayout(seriesLayout); controlLayout->addStretch(); - controlLayout->addWidget(saveButton); mainLayout->addLayout(controlLayout); - plot = new QCustomPlot(this); - plot->setInteraction(QCP::iRangeDrag, true); - plot->setInteraction(QCP::iRangeZoom, true); - plot->legend->setVisible(true); - plot->legend->setFont(defaultFont); - plot->axisRect()->insetLayout()->setInsetAlignment(0, Qt::AlignTop | Qt::AlignRight); - plot->xAxis->setLabel("SoC [%]"); - plot->xAxis->setRangeReversed(true); + plot = new Plot(400, 220, false, this); + plot->setXLabel("SoC [%]"); + plot->setXReversed(true); mainLayout->addWidget(plot, 1); - connect(saveButton, &QPushButton::clicked, this, &BatteryParamsTrendWnd::onSaveImage); - plotSettings = BATTERYPARAMSPLOT_SettingsDefault(); resize(900, 550); @@ -52,20 +37,19 @@ void BatteryParamsTrendWnd::setTrends(QString title, QString yLabel, QVectordeleteLater(); } seriesCheckBoxes.clear(); - plot->clearGraphs(); + seriesGraphs.clear(); + plot->seriesClear(); - plot->yAxis->setLabel(yLabel); + plot->setTitle(title); + plot->setYLabel(yLabel); + plot->setXReversed(true); for(int i = 0; i < trends.size(); i++) { - QCPGraph *graph = plot->addGraph(); + QCPGraph *graph = plot->seriesAdd(trends[i].name, trends[i].color, trends[i].soc, trends[i].value); QCheckBox *checkBox = new QCheckBox(trends[i].name, this); - graph->setName(trends[i].name); - graph->setPen(QPen(trends[i].color, 2)); - graph->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, trends[i].color, - trends[i].color, BATTERYPARAMSTREND_MARKER_SIZE)); - graph->setData(trends[i].soc, trends[i].value, true); + seriesGraphs.append(graph); checkBox->setChecked(true); checkBox->setStyleSheet("color: " + trends[i].color.name() + ";"); @@ -75,50 +59,20 @@ void BatteryParamsTrendWnd::setTrends(QString title, QString yLabel, QVectorseriesRescale(); } void BatteryParamsTrendWnd::setPlotSettings(batteryparams_plot_settings_t settings) { plotSettings = settings; - BATTERYPARAMSPLOT_Apply(plot, plotSettings); + plot->applyStyle(plotSettings.fontFamily, plotSettings.labelFontSize, plotSettings.tickFontSize, + plotSettings.lineWidth, plotSettings.gridVisible, plotSettings.minorGridVisible); } void BatteryParamsTrendWnd::onSeriesToggled() { - for(int i = 0; i < seriesCheckBoxes.size() && i < plot->graphCount(); i++) + for(int i = 0; i < seriesCheckBoxes.size() && i < seriesGraphs.size(); i++) { - plot->graph(i)->setVisible(seriesCheckBoxes[i]->isChecked()); - plot->graph(i)->removeFromLegend(); - if(seriesCheckBoxes[i]->isChecked()) plot->graph(i)->addToLegend(); + plot->seriesSetVisible(seriesGraphs[i], seriesCheckBoxes[i]->isChecked()); } - - rescale(); -} - -void BatteryParamsTrendWnd::rescale() -{ - bool firstVisible = true; - - plot->xAxis->rescale(); - - for(int i = 0; i < plot->graphCount(); i++) - { - if(!plot->graph(i)->visible()) continue; - plot->graph(i)->rescaleValueAxis(!firstVisible); - firstVisible = false; - } - - if(!firstVisible) - { - QCPRange range = plot->yAxis->range(); - plot->yAxis->setRange(range.lower - range.size() * 0.1, range.upper + range.size() * 0.1); - } - - plot->replot(); -} - -void BatteryParamsTrendWnd::onSaveImage() -{ - BATTERYPARAMSPLOT_Save(plot, this, windowTitle().toLower().replace(' ', '_')); } diff --git a/Source/Windows/BatteryParams/batteryparamstrendwnd.h b/Source/Windows/BatteryParams/batteryparamstrendwnd.h index a306e3a..400f984 100644 --- a/Source/Windows/BatteryParams/batteryparamstrendwnd.h +++ b/Source/Windows/BatteryParams/batteryparamstrendwnd.h @@ -3,11 +3,13 @@ #include #include +#include #include #include #include #include "Chart/qcustomplot.h" +#include "Windows/Plot/plot.h" #include "batteryparamsplotsettings.h" typedef struct @@ -30,15 +32,13 @@ class BatteryParamsTrendWnd : public QWidget private slots: void onSeriesToggled(); - void onSaveImage(); private: - QCustomPlot *plot; + Plot *plot; QHBoxLayout *seriesLayout; QVector seriesCheckBoxes; + QVector seriesGraphs; batteryparams_plot_settings_t plotSettings; - - void rescale(); }; #endif // BATTERYPARAMSTRENDWND_H diff --git a/Source/Windows/BatteryParams/batteryparamswnd.cpp b/Source/Windows/BatteryParams/batteryparamswnd.cpp index 316e3c5..a5e6039 100644 --- a/Source/Windows/BatteryParams/batteryparamswnd.cpp +++ b/Source/Windows/BatteryParams/batteryparamswnd.cpp @@ -5,15 +5,34 @@ #include #include #include +#include #include #include +#include +#include +#include +#include +#include #include + +#include "Chart/qcustomplot.h" #include #include #include #include - -#define BATTERYPARAMS_COLUMN_NO 21 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define BATTERYPARAMS_COLUMN_NO 23 #define BATTERYPARAMS_SETTINGS_EDIT_WIDTH 80 #define BATTERYPARAMS_SETTINGS_ROW_HEIGHT 28 #define BATTERYPARAMS_AUTO_RESIZE_ROW_NO 10 @@ -34,13 +53,17 @@ BatteryParamsWnd::BatteryParamsWnd(QWidget *parent) : statusLabel = new QLabel("Waiting for the first cycle...", this); topLayout->addWidget(statusLabel); topLayout->addStretch(); - mainLayout->addLayout(topLayout); - QHBoxLayout *settingsLayout = new QHBoxLayout(); + liveStatusLabel = new QLabel(this); + liveStatusLabel->setStyleSheet("QLabel { background-color: #eef3fb; border: 1px solid #b7c7e0; border-radius: 4px; padding: 6px; }"); + liveStatusLabel->setTextFormat(Qt::RichText); + liveStatusLabel->hide(); settings = BatteryParamsExtraction::settingsDefault(); parallelAnswer = -1; settingsDlg = NULL; + extractionRunning = false; + fitInProgress = false; resistanceTrendWnd = NULL; capacitanceTrendWnd = NULL; ocvTrendWnd = NULL; @@ -51,81 +74,86 @@ BatteryParamsWnd::BatteryParamsWnd(QWidget *parent) : connectedToFitIntervalWnd = false; plotSettings = BATTERYPARAMSPLOT_SettingsDefault(); - settingsButton = new QPushButton("Settings", this); - settingsButton->setFixedHeight(BATTERYPARAMS_SETTINGS_ROW_HEIGHT); - settingsButton->setToolTip("Battery capacity, initial state of charge, relaxation and extraction settings"); - - resistanceTrendButton = new QPushButton("R vs SoC", this); - resistanceTrendButton->setFixedHeight(BATTERYPARAMS_SETTINGS_ROW_HEIGHT); - resistanceTrendButton->setToolTip("Show R0, R1 and R2 against the state of charge"); - - capacitanceTrendButton = new QPushButton("C vs SoC", this); - capacitanceTrendButton->setFixedHeight(BATTERYPARAMS_SETTINGS_ROW_HEIGHT); - capacitanceTrendButton->setToolTip("Show C1 and C2 against the state of charge"); - - ocvTrendButton = new QPushButton("OCV vs SoC", this); - ocvTrendButton->setFixedHeight(BATTERYPARAMS_SETTINGS_ROW_HEIGHT); - ocvTrendButton->setToolTip("Show the open circuit voltage against the state of charge"); - - ocvAnalysisButton = new QPushButton("OCV analysis", this); - ocvAnalysisButton->setFixedHeight(BATTERYPARAMS_SETTINGS_ROW_HEIGHT); - ocvAnalysisButton->setToolTip("State of charge against the open circuit voltage, its sensitivity and the effect of measurement noise"); - - fitQualityButton = new QPushButton("Estimation quality", this); - fitQualityButton->setFixedHeight(BATTERYPARAMS_SETTINGS_ROW_HEIGHT); - fitQualityButton->setToolTip("Compare how well the first and the second order model describe every cycle"); - - relaxationTimeButton = new QPushButton("Relaxation time", this); - relaxationTimeButton->setFixedHeight(BATTERYPARAMS_SETTINGS_ROW_HEIGHT); - relaxationTimeButton->setToolTip("Time every cycle needed from the beginning of the pause until the battery relaxed"); - - fitIntervalButton = new QPushButton("Fit interval", this); - fitIntervalButton->setFixedHeight(BATTERYPARAMS_SETTINGS_ROW_HEIGHT); - fitIntervalButton->setToolTip("Compare the parameters and the errors obtained by fitting up to the relaxation point and up to the end of the pause"); - - fitPointsButton = new QPushButton("Fit cycle points", this); - fitPointsButton->setFixedHeight(BATTERYPARAMS_SETTINGS_ROW_HEIGHT); - fitPointsButton->setToolTip("Check every cycle and move Pulse End and Pause Start onto the settled levels around the current step.\nCycles that had to be corrected are opened for review"); - - fitPointsSaveButton = new QPushButton("Save new points", this); - fitPointsSaveButton->setFixedHeight(BATTERYPARAMS_SETTINGS_ROW_HEIGHT); - fitPointsSaveButton->setToolTip("Keep the fitted points on every corrected cycle and clear the marks"); - - fitPointsRestoreButton = new QPushButton("Restore old points", this); - fitPointsRestoreButton->setFixedHeight(BATTERYPARAMS_SETTINGS_ROW_HEIGHT); - fitPointsRestoreButton->setToolTip("Return every corrected cycle to the points reported by the device"); + graphWnd = NULL; + graphResistance = NULL; + graphCapacitance = NULL; + graphOcv = NULL; + graphRelaxation = NULL; + analysisWnd = NULL; + + QToolBar *toolBar = new QToolBar(this); + toolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); + toolBar->setIconSize(QSize(20, 20)); + toolBar->setMovable(false); + toolBar->setFloatable(false); + + configAction = toolBar->addAction(QIcon(":/images/NewSet/setting.png"), "Analysis configuration"); + configAction->setToolTip("Battery capacity, initial state of charge, relaxation and extraction settings"); + + statisticsAction = toolBar->addAction(QIcon(":/images/NewSet/analysis.png"), "Statistics"); + statisticsAction->setToolTip("Charge and discharge capacity and other summary figures"); + + toolBar->addSeparator(); + + graphAction = toolBar->addAction(QIcon(":/images/NewSet/tracking_graph.png"), "Graph"); + graphAction->setToolTip("R, C and OCV against the state of charge, each a zoomable and exportable plot"); + + analysisAction = toolBar->addAction(QIcon(":/images/NewSet/process.png"), "Do Analysis"); + analysisAction->setToolTip("OCV analysis, estimation quality, relaxation time and fit interval"); + + toolBar->addSeparator(); + + /*The cycle operations are grouped under one tool button with a drop down menu*/ + QToolButton *cyclesButton = new QToolButton(this); + cyclesButton->setText("Cycles"); + cyclesButton->setIcon(QIcon(":/images/NewSet/reload.png")); + cyclesButton->setPopupMode(QToolButton::InstantPopup); + cyclesButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); + QMenu *cyclesMenu = new QMenu(cyclesButton); + + fitPointsAction = cyclesMenu->addAction("Fit cycle points"); + fitPointsAction->setToolTip("Check every cycle and move Pulse End and Pause Start onto the settled levels around the current step.\nCycles that had to be corrected are opened for review"); + fitPointsSaveAction = cyclesMenu->addAction("Save new points"); + fitPointsSaveAction->setToolTip("Keep the fitted points on every corrected cycle and clear the marks"); + fitPointsRestoreAction = cyclesMenu->addAction("Restore old points"); + fitPointsRestoreAction->setToolTip("Return every corrected cycle to the points reported by the device"); + fitPointsFindStartAction = cyclesMenu->addAction("Find new start point"); + fitPointsFindStartAction->setToolTip("Sweep the pause start of every cycle over a short window and show the\nminimum RMSE and the minimum maximum error reachable.\nThen apply the pause start by the chosen criterion to all cycles"); + cyclesMenu->addSeparator(); + recalcAction = cyclesMenu->addAction("Recalculate"); + recalcAction->setToolTip("Force a fresh re-analysis of every cycle with the current settings and points"); + + cyclesButton->setMenu(cyclesMenu); + toolBar->addWidget(cyclesButton); + + /*Column visibility is a checkable menu, every column can be shown or hidden*/ + QToolButton *columnsButton = new QToolButton(this); + columnsButton->setText("Columns"); + columnsButton->setIcon(QIcon(":/images/NewSet/format.png")); + columnsButton->setPopupMode(QToolButton::InstantPopup); + columnsButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); + columnsMenu = new QMenu(columnsButton); + columnsButton->setMenu(columnsMenu); + toolBar->addWidget(columnsButton); + + mainLayout->addWidget(toolBar); settingsLabel = new QLabel(this); settingsLabel->setStyleSheet("color: gray;"); + mainLayout->addWidget(settingsLabel); - settingsLayout->addWidget(settingsButton); - settingsLayout->addSpacing(15); - settingsLayout->addWidget(resistanceTrendButton); - settingsLayout->addWidget(capacitanceTrendButton); - settingsLayout->addWidget(ocvTrendButton); - settingsLayout->addWidget(ocvAnalysisButton); - settingsLayout->addWidget(fitQualityButton); - settingsLayout->addWidget(relaxationTimeButton); - settingsLayout->addWidget(fitIntervalButton); - settingsLayout->addSpacing(15); - settingsLayout->addWidget(fitPointsButton); - settingsLayout->addWidget(fitPointsSaveButton); - settingsLayout->addWidget(fitPointsRestoreButton); - settingsLayout->addSpacing(15); - settingsLayout->addWidget(settingsLabel, 1); - mainLayout->addLayout(settingsLayout); - - connect(settingsButton, &QPushButton::clicked, this, &BatteryParamsWnd::onSettings); - connect(resistanceTrendButton, &QPushButton::clicked, this, &BatteryParamsWnd::onResistanceTrend); - connect(capacitanceTrendButton, &QPushButton::clicked, this, &BatteryParamsWnd::onCapacitanceTrend); - connect(ocvTrendButton, &QPushButton::clicked, this, &BatteryParamsWnd::onOcvTrend); - connect(ocvAnalysisButton, &QPushButton::clicked, this, &BatteryParamsWnd::onOcvAnalysis); - connect(fitQualityButton, &QPushButton::clicked, this, &BatteryParamsWnd::onFitQuality); - connect(relaxationTimeButton, &QPushButton::clicked, this, &BatteryParamsWnd::onRelaxationTime); - connect(fitIntervalButton, &QPushButton::clicked, this, &BatteryParamsWnd::onFitInterval); - connect(fitPointsButton, &QPushButton::clicked, this, &BatteryParamsWnd::onFitCyclePoints); - connect(fitPointsSaveButton, &QPushButton::clicked, this, &BatteryParamsWnd::onFitPointsSave); - connect(fitPointsRestoreButton, &QPushButton::clicked, this, &BatteryParamsWnd::onFitPointsRestore); + mainLayout->addLayout(topLayout); + mainLayout->addWidget(liveStatusLabel); + + connect(configAction, &QAction::triggered, this, &BatteryParamsWnd::onSettings); + connect(statisticsAction, &QAction::triggered, this, &BatteryParamsWnd::onStatistics); + connect(graphAction, &QAction::triggered, this, &BatteryParamsWnd::onGraph); + connect(analysisAction, &QAction::triggered, this, &BatteryParamsWnd::onAnalysisWindow); + connect(fitPointsAction, &QAction::triggered, this, &BatteryParamsWnd::onFitCyclePoints); + connect(fitPointsSaveAction, &QAction::triggered, this, &BatteryParamsWnd::onFitPointsSave); + connect(fitPointsRestoreAction, &QAction::triggered, this, &BatteryParamsWnd::onFitPointsRestore); + connect(fitPointsFindStartAction, &QAction::triggered, this, &BatteryParamsWnd::onFindNewStartPoint); + connect(recalcAction, &QAction::triggered, this, &BatteryParamsWnd::recalculate); updateSettingsLabel(); updateFitPointsButtons(); @@ -136,10 +164,20 @@ BatteryParamsWnd::BatteryParamsWnd(QWidget *parent) : << "I pulse end [mA]" << "I pause start [mA]" << "dI [mA]" << "R0 [mOhm]" << "R1 [mOhm]" << "C1 [F]" << "R2 [mOhm]" << "C2 [F]" - << "RMSE [mV]" << "Max err [mV]"; + << "RMSE [mV]" << "Max err [mV]" << "Rtotal [mOhm]" << "Status"; cyclesTable = new QTableWidget(0, BATTERYPARAMS_COLUMN_NO, this); cyclesTable->setHorizontalHeaderLabels(header); + + for(int i = 0; i < header.size(); i++) + { + QAction *columnAction = columnsMenu->addAction(header[i]); + columnAction->setCheckable(true); + columnAction->setChecked(true); + columnAction->setData(i); + columnActions.append(columnAction); + connect(columnAction, &QAction::toggled, this, &BatteryParamsWnd::onColumnToggled); + } cyclesTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive); cyclesTable->horizontalHeader()->setSectionsMovable(true); cyclesTable->horizontalHeader()->setStretchLastSection(true); @@ -150,26 +188,53 @@ BatteryParamsWnd::BatteryParamsWnd(QWidget *parent) : cyclesTable->setSelectionBehavior(QAbstractItemView::SelectRows); cyclesTable->setEditTriggers(QAbstractItemView::NoEditTriggers); cyclesTable->setMinimumHeight(200); - mainLayout->addWidget(cyclesTable, 1); + + QStringList chargeHeader; + chargeHeader << "Charge cycle" << "Start [ms]" << "End [ms]" << "Capacity [mAh]"; + chargeCyclesTable = new QTableWidget(0, chargeHeader.size(), this); + chargeCyclesTable->setHorizontalHeaderLabels(chargeHeader); + chargeCyclesTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive); + chargeCyclesTable->horizontalHeader()->setStretchLastSection(true); + chargeCyclesTable->horizontalHeader()->setMinimumSectionSize(40); + chargeCyclesTable->resizeColumnsToContents(); + chargeCyclesTable->verticalHeader()->setVisible(false); + chargeCyclesTable->verticalHeader()->setDefaultSectionSize(22); + chargeCyclesTable->setSelectionBehavior(QAbstractItemView::SelectRows); + chargeCyclesTable->setEditTriggers(QAbstractItemView::NoEditTriggers); + chargeCyclesTable->setMinimumHeight(200); + + cycleTabs = new QTabWidget(this); + cycleTabs->addTab(cyclesTable, "Discharge"); + cycleTabs->addTab(chargeCyclesTable, "Charge"); + mainLayout->addWidget(cycleTabs, 1); summaryLabel = new QLabel(this); summaryLabel->setStyleSheet("color: gray;"); bottomLayout->addWidget(summaryLabel, 1); + saveCyclesButton = new QPushButton("Save New Cycles", this); + saveCyclesButton->setToolTip("Remove the deleted cycles from the table and update ep.csv so the removal, fitted points and new cycles are saved (voltage and current recording is kept)"); + storeCyclesButton = new QPushButton("Store New Points", this); + storeCyclesButton->setToolTip("Write the current pulse/pause points of every cycle into ep.csv and refresh the main plot (offline profile)"); exportButton = new QPushButton("Export CSV", this); clearButton = new QPushButton("Clear", this); + bottomLayout->addWidget(saveCyclesButton); + bottomLayout->addWidget(storeCyclesButton); bottomLayout->addWidget(exportButton); bottomLayout->addWidget(clearButton); mainLayout->addLayout(bottomLayout); - cyclesTable->setToolTip("Click a cycle to show its waveform.\nColumns can be resized and reordered by dragging the header"); + cyclesTable->setToolTip("Right-click a cycle for options (show data, delete, fit points).\nColumns can be resized and reordered by dragging the header"); cycleWnd = NULL; fittedPositions.clear(); fittedOriginals.clear(); connectedToCycleWnd = false; - connect(cyclesTable, &QTableWidget::cellClicked, this, &BatteryParamsWnd::onCycleSelected); + cyclesTable->setContextMenuPolicy(Qt::CustomContextMenu); + connect(cyclesTable, &QTableWidget::customContextMenuRequested, this, &BatteryParamsWnd::onCycleContextMenu); + connect(saveCyclesButton, &QPushButton::clicked, this, &BatteryParamsWnd::onSaveNewCycles); + connect(storeCyclesButton, &QPushButton::clicked, this, &BatteryParamsWnd::onStoreNewPoints); connect(exportButton, &QPushButton::clicked, this, &BatteryParamsWnd::onExport); connect(clearButton, &QPushButton::clicked, this, &BatteryParamsWnd::onClear); @@ -192,14 +257,17 @@ QTableWidgetItem* BatteryParamsWnd::createItem(QString text) void BatteryParamsWnd::fillCycleRow(int row, batteryparams_cycle_t cycle) { - cyclesTable->setItem(row, 0, createItem(QString::number(cycle.index) + (fittedPositions.contains(row) ? " *" : ""))); + QString cycleText = QString::number(cycle.index); + if(cycle.incomplete) cycleText += " (inc)"; + if(fittedPositions.contains(row)) cycleText += " *"; + cyclesTable->setItem(row, 0, createItem(cycleText)); cyclesTable->setItem(row, 1, createItem(QString::number(cycle.pulseStartKey, 'f', 3))); cyclesTable->setItem(row, 2, createItem(QString::number(cycle.pauseEndKey, 'f', 3))); cyclesTable->setItem(row, 3, createItem(QString::number(cycle.charge, 'f', 3))); cyclesTable->setItem(row, 4, createItem(QString::number(cycle.chargeTotal, 'f', 3))); cyclesTable->setItem(row, 5, createItem(cycle.socValid ? QString::number(cycle.socUsed, 'f', 2) : "-")); cyclesTable->setItem(row, 6, createItem(cycle.socValid ? QString::number(cycle.soc, 'f', 2) : "-")); - cyclesTable->setItem(row, 7, createItem(cycle.relaxationReached ? QString::number(cycle.ocv, 'f', 4) : "-")); + cyclesTable->setItem(row, 7, createItem((cycle.relaxationReached || cycle.modelValid) ? QString::number(cycle.ocv, 'f', 4) : "-")); cyclesTable->setItem(row, 8, createItem(QString::number(cycle.pulseEndVoltage, 'f', 4))); cyclesTable->setItem(row, 9, createItem(QString::number(cycle.pauseStartVoltage, 'f', 4))); cyclesTable->setItem(row, 10, createItem(QString::number(cycle.deltaVoltage * 1000.0, 'f', 2))); @@ -207,16 +275,32 @@ void BatteryParamsWnd::fillCycleRow(int row, batteryparams_cycle_t cycle) cyclesTable->setItem(row, 12, createItem(QString::number(cycle.pauseStartCurrent, 'f', 2))); cyclesTable->setItem(row, 13, createItem(QString::number(cycle.deltaCurrent, 'f', 2))); cyclesTable->setItem(row, 14, createItem(cycle.resistanceValid ? QString::number(cycle.resistance * 1000.0, 'f', 2) : "-")); - cyclesTable->setItem(row, 15, createItem(cycle.modelValid ? QString::number(cycle.r1 * 1000.0, 'f', 2) : "-")); - cyclesTable->setItem(row, 16, createItem(cycle.modelValid ? QString::number(cycle.c1, 'f', 1) : "-")); - cyclesTable->setItem(row, 17, createItem((cycle.modelValid && (cycle.model == BATTERYPARAMS_MODEL_SECOND_ORDER)) ? QString::number(cycle.r2 * 1000.0, 'f', 2) : "-")); - cyclesTable->setItem(row, 18, createItem((cycle.modelValid && (cycle.model == BATTERYPARAMS_MODEL_SECOND_ORDER)) ? QString::number(cycle.c2, 'f', 1) : "-")); + cyclesTable->setItem(row, 15, createItem((cycle.modelValid && cycle.r1Valid) ? QString::number(cycle.r1 * 1000.0, 'f', 2) : "-")); + cyclesTable->setItem(row, 16, createItem((cycle.modelValid && cycle.r1Valid) ? QString::number(cycle.c1, 'f', 1) : "-")); + cyclesTable->setItem(row, 17, createItem((cycle.modelValid && cycle.r2Valid) ? QString::number(cycle.r2 * 1000.0, 'f', 2) : "-")); + cyclesTable->setItem(row, 18, createItem((cycle.modelValid && cycle.r2Valid) ? QString::number(cycle.c2, 'f', 1) : "-")); cyclesTable->setItem(row, 19, createItem(cycle.modelValid ? QString::number(cycle.fitRmse * 1000.0, 'f', 3) : "-")); cyclesTable->setItem(row, 20, createItem(cycle.modelValid ? QString::number(cycle.fitMaxError * 1000.0, 'f', 3) : "-")); - /*Green marks a cycle where the cell relaxed and the model could be fitted, - yellow one where it did not*/ - QColor rowColor = cycle.relaxationReached ? QColor(200, 240, 200) : QColor(255, 245, 190); + double rTotal = cycle.resistance + (cycle.modelValid ? ((cycle.r1Valid ? cycle.r1 : 0.0) + (cycle.r2Valid ? cycle.r2 : 0.0)) : 0.0); + cyclesTable->setItem(row, 21, createItem((cycle.resistanceValid && cycle.modelValid) ? QString::number(rTotal * 1000.0, 'f', 2) : "-")); + + QString statusText = cycle.modelReason; + if(statusText.isEmpty()) statusText = cycle.modelValid ? "Second order model fitted (R0, R1, C1, R2, C2)" : "Model not fitted"; + cyclesTable->setItem(row, 22, createItem(statusText)); + + /*The reason a parameter could not be determined is shown in the last column and + repeated as a tooltip on every cell, so it is visible wherever the row is read*/ + for(int column = 0; column < BATTERYPARAMS_COLUMN_NO; column++) + { + if(cyclesTable->item(row, column) != NULL) cyclesTable->item(row, column)->setToolTip(statusText); + } + + /*Light purple marks a discharge cycle where the cell relaxed and the model + could be fitted, yellow one where it did not, light red an incomplete cycle*/ + QColor rowColor; + if(cycle.incomplete) rowColor = QColor(255, 210, 210); + else rowColor = (cycle.relaxationReached || cycle.modelValid) ? QColor(226, 212, 240) : QColor(255, 245, 190); for(int column = 0; column < BATTERYPARAMS_COLUMN_NO; column++) { @@ -245,9 +329,14 @@ void BatteryParamsWnd::updateSummary() { double sum = 0; int validNo = 0; + double totalCharge = 0; + + if((graphWnd != NULL) && graphWnd->isVisible()) refreshGraphs(); for(int i = 0; i < cycles.size(); i++) { + totalCharge += cycles[i].charge; + if(!cycles[i].resistanceValid) continue; sum += cycles[i].resistance; validNo++; @@ -255,12 +344,13 @@ void BatteryParamsWnd::updateSummary() if(validNo == 0) { - summaryLabel->setText(QString::number(cycles.size()) + " cycles, no resistance calculated yet"); + summaryLabel->setText(QString::number(cycles.size()) + " cycles, " + + QString::number(totalCharge, 'f', 3) + " mAh extracted, no resistance calculated yet"); return; } summaryLabel->setText(QString::number(cycles.size()) + " cycles, " + - QString::number(cycles.last().chargeTotal, 'f', 3) + " mAh extracted" + + QString::number(totalCharge, 'f', 3) + " mAh extracted" + (cycles.last().socValid ? ", " + QString::number(cycles.last().socUsed, 'f', 2) + " % SoC used" : "") + ", average resistance " + QString::number(sum / validNo * 1000.0, 'f', 2) + " mOhm"); } @@ -279,22 +369,109 @@ void BatteryParamsWnd::addCycles(QVector newCycles, QProg void BatteryParamsWnd::onCycleStarted(unsigned int index, double key) { + if(fitInProgress) return; statusLabel->setText("Cycle " + QString::number(index) + " ongoing (started at " + QString::number(key, 'f', 3) + " ms)"); } void BatteryParamsWnd::onCycleFinished(batteryparams_cycle_t cycle) { + if(fitInProgress) + { + pendingCycles.append(cycle); + return; + } + cycles.append(cycle); addCycleRow(cycle); updateSummary(); statusLabel->setText("Cycle " + QString::number(cycle.index) + " done, waiting for the next one..."); } +void BatteryParamsWnd::addChargeCycleRow(batteryparams_charge_cycle_t cycle) +{ + int row = chargeCyclesTable->rowCount(); + + chargeCyclesTable->insertRow(row); + chargeCyclesTable->setItem(row, 0, createItem(QString::number(cycle.index))); + chargeCyclesTable->setItem(row, 1, createItem(QString::number(cycle.startKey, 'f', 3))); + chargeCyclesTable->setItem(row, 2, createItem(QString::number(cycle.endKey, 'f', 3))); + chargeCyclesTable->setItem(row, 3, createItem(QString::number(cycle.capacity, 'f', 3))); + + QColor rowColor(200, 240, 200); + for(int c = 0; c < chargeCyclesTable->columnCount(); c++) + if(chargeCyclesTable->item(row, c) != NULL) chargeCyclesTable->item(row, c)->setBackground(rowColor); + + chargeCyclesTable->scrollToBottom(); +} + +void BatteryParamsWnd::onChargeCycleFinished(batteryparams_charge_cycle_t cycle) +{ + chargeCycles.append(cycle); + addChargeCycleRow(cycle); +} + +void BatteryParamsWnd::addChargeCycles(QVector newCharges) +{ + for(int i = 0; i < newCharges.size(); i++) onChargeCycleFinished(newCharges[i]); +} + +void BatteryParamsWnd::onStatistics() +{ + double dischargeCapacity = 0; + double chargeCapacity = 0; + double resistanceSum = 0; + int resistanceNo = 0; + int dischargeValid = 0; + + for(int i = 0; i < cycles.size(); i++) + { + dischargeCapacity += cycles[i].charge; + if(cycles[i].resistanceValid) + { + resistanceSum += cycles[i].resistance; + resistanceNo++; + } + if(cycles[i].pulseStartKey > 0) dischargeValid++; + } + + for(int i = 0; i < chargeCycles.size(); i++) chargeCapacity += chargeCycles[i].capacity; + + QDialog dialog(this); + dialog.setWindowTitle("Battery statistics"); + + QFormLayout *form = new QFormLayout(&dialog); + + form->addRow("Discharge cycles:", new QLabel(QString::number(dischargeValid), &dialog)); + form->addRow("Discharge capacity [mAh]:", new QLabel(QString::number(dischargeCapacity, 'f', 3), &dialog)); + form->addRow("Charge cycles:", new QLabel(QString::number(chargeCycles.size()), &dialog)); + form->addRow("Charge capacity [mAh]:", new QLabel(QString::number(chargeCapacity, 'f', 3), &dialog)); + + if(chargeCapacity > 0) + form->addRow("Coulombic efficiency [%]:", new QLabel(QString::number(dischargeCapacity / chargeCapacity * 100.0, 'f', 2), &dialog)); + + if(resistanceNo > 0) + form->addRow("Average R0 [mOhm]:", new QLabel(QString::number(resistanceSum / resistanceNo * 1000.0, 'f', 2), &dialog)); + + if(!cycles.isEmpty() && cycles.last().socValid) + form->addRow("SoC used [%]:", new QLabel(QString::number(cycles.last().socUsed, 'f', 2), &dialog)); + + QDialogButtonBox *box = new QDialogButtonBox(QDialogButtonBox::Close, &dialog); + connect(box, &QDialogButtonBox::rejected, &dialog, &QDialog::reject); + connect(box, &QDialogButtonBox::accepted, &dialog, &QDialog::accept); + form->addRow(box); + + dialog.exec(); +} + void BatteryParamsWnd::onCycleSelected(int row, int column) { Q_UNUSED(column); + openCycleData(row); +} +void BatteryParamsWnd::openCycleData(int row) +{ if(row < 0 || row >= cycles.size()) return; if(cycleWnd == NULL) @@ -310,6 +487,7 @@ void BatteryParamsWnd::onCycleSelected(int row, int column) } cycleWnd->setPlotSettings(plotSettings); + cycleWnd->setSettings(settings); cycleWnd->setCycle(cycles[row]); cycleWnd->show(); cycleWnd->raise(); @@ -318,20 +496,53 @@ void BatteryParamsWnd::onCycleSelected(int row, int column) void BatteryParamsWnd::updateFitPointsButtons() { - fitPointsSaveButton->setEnabled(!fittedPositions.isEmpty()); - fitPointsRestoreButton->setEnabled(!fittedPositions.isEmpty()); + fitPointsAction->setEnabled(!extractionRunning); + recalcAction->setEnabled(!extractionRunning); + fitPointsSaveAction->setEnabled(!extractionRunning && !fittedPositions.isEmpty()); + fitPointsRestoreAction->setEnabled(!extractionRunning && !fittedPositions.isEmpty()); + fitPointsFindStartAction->setEnabled(!extractionRunning && !cycles.isEmpty()); +} + +void BatteryParamsWnd::endFit() +{ + fitInProgress = false; + + QVector deferred = pendingCycles; + pendingCycles.clear(); + for(int i = 0; i < deferred.size(); i++) onCycleFinished(deferred[i]); } void BatteryParamsWnd::onFitCyclePoints() { + if(extractionRunning) return; + if(cycles.isEmpty()) return; + QVector working = cycles; QVector changed; - QProgressDialog progressDialog("Fitting cycle points...", QString(), 0, cycles.size(), this); + QProgressDialog progressDialog("Fitting cycle points...", "Cancel", 0, cycles.size(), this); batteryparams_settings_t usedSettings = settings; int cycleNo = cycles.size(); int fittedNo = 0; - if(cycles.isEmpty()) return; + analyzeCancel.storeRelease(0); + QAtomicInt *cancelPtr = &analyzeCancel; + + /*Each cycle carries its own sample vectors, which are implicitly shared with the + ones in "cycles". The parallel tasks write into them, so the shared data is + detached into independent copies here before the tasks start, otherwise live + cycles arriving during processEvents would race with the worker threads*/ + for(int i = 0; i < working.size(); i++) + { + working[i].plotKeys = QVector(working[i].plotKeys.constBegin(), working[i].plotKeys.constEnd()); + working[i].plotVoltage = QVector(working[i].plotVoltage.constBegin(), working[i].plotVoltage.constEnd()); + working[i].plotCurrent = QVector(working[i].plotCurrent.constBegin(), working[i].plotCurrent.constEnd()); + working[i].fitKeys = QVector(working[i].fitKeys.constBegin(), working[i].fitKeys.constEnd()); + working[i].fitVoltage = QVector(working[i].fitVoltage.constBegin(), working[i].fitVoltage.constEnd()); + working[i].relaxKeys = QVector(working[i].relaxKeys.constBegin(), working[i].relaxKeys.constEnd()); + working[i].relaxVoltage = QVector(working[i].relaxVoltage.constBegin(), working[i].relaxVoltage.constEnd()); + } + + fitInProgress = true; changed.fill(0, cycleNo); @@ -350,8 +561,11 @@ void BatteryParamsWnd::onFitCyclePoints() progressDialog.setValue(i); QApplication::processEvents(); + if(progressDialog.wasCanceled()) { analyzeCancel.storeRelease(1); endFit(); return; } + if(!BatteryParamsExtraction::cyclePointsFit(&working[i])) continue; + working[i].incomplete = false; BatteryParamsExtraction::analyzeCycle(&working[i], usedSettings); changed[i] = 1; } @@ -370,10 +584,13 @@ void BatteryParamsWnd::onFitCyclePoints() /*Every cycle is fitted and analysed on its own entry of the working copy, so the tasks never touch the same data*/ - QFuture future = QtConcurrent::map(positions, [workingData, changedData, usedSettings](int position) + QFuture future = QtConcurrent::map(positions, [workingData, changedData, usedSettings, cancelPtr](int position) { + BatteryParamsExtraction::nameCurrentThread(workingData[position].index); + if(cancelPtr->loadAcquire()) return; if(!BatteryParamsExtraction::cyclePointsFit(&workingData[position])) return; + workingData[position].incomplete = false; BatteryParamsExtraction::analyzeCycle(&workingData[position], usedSettings); changedData[position] = 1; }); @@ -389,6 +606,15 @@ void BatteryParamsWnd::onFitCyclePoints() progressDialog.setValue(watcher.progressValue()); QApplication::processEvents(); QThread::msleep(20); + + if(progressDialog.wasCanceled()) + { + analyzeCancel.storeRelease(1); + future.cancel(); + future.waitForFinished(); + endFit(); + return; + } } } @@ -411,6 +637,8 @@ void BatteryParamsWnd::onFitCyclePoints() fittedNo++; } + endFit(); + updateSummary(); updateFitPointsButtons(); @@ -470,6 +698,332 @@ void BatteryParamsWnd::onFitPointsRestore() statusLabel->setText("Points reported by the device restored on " + QString::number(no) + " cycles"); } +void BatteryParamsWnd::onFindNewStartPoint() +{ + if(extractionRunning) return; + if(cycles.isEmpty()) return; + + /*Ask how far to the right the pause start may move and with how many points*/ + double windowSeconds = 5.0; + int pointNo = 40; + + { + QDialog paramDialog(this); + paramDialog.setWindowTitle("Find new start point"); + + QFormLayout *form = new QFormLayout(¶mDialog); + + QDoubleSpinBox *windowSpin = new QDoubleSpinBox(¶mDialog); + windowSpin->setRange(0.1, 600.0); + windowSpin->setDecimals(2); + windowSpin->setValue(windowSeconds); + windowSpin->setSuffix(" s"); + + QSpinBox *pointSpin = new QSpinBox(¶mDialog); + pointSpin->setRange(2, 500); + pointSpin->setValue(pointNo); + + QDialogButtonBox *box = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, ¶mDialog); + + form->addRow("Move pause start right by:", windowSpin); + form->addRow("Number of points:", pointSpin); + form->addRow(box); + + connect(box, &QDialogButtonBox::accepted, ¶mDialog, &QDialog::accept); + connect(box, &QDialogButtonBox::rejected, ¶mDialog, &QDialog::reject); + + if(paramDialog.exec() != QDialog::Accepted) return; + + windowSeconds = windowSpin->value(); + pointNo = pointSpin->value(); + } + + int cycleNo = cycles.size(); + double windowMs = windowSeconds * 1000.0; + batteryparams_settings_t usedSettings = settings; + + QVector> shiftSeries(cycleNo); + QVector> rmseSeries(cycleNo); + QVector> maxSeries(cycleNo); + QVector bestRmseKey(cycleNo, 0); + QVector bestVmaxKey(cycleNo, 0); + QVector found(cycleNo, 0); + + /*Each cycle carries its own sample vectors, implicitly shared with the ones in + "cycles". The tasks read them, so a fully detached copy is made here before the + sweep starts so the workers never share a Qt container with the live cycles*/ + QProgressDialog progressDialog("Preparing...", "Cancel", 0, cycleNo * pointNo, this); + progressDialog.setWindowModality(Qt::WindowModal); + progressDialog.setWindowTitle("Find new start point"); + progressDialog.setMinimumDuration(0); + progressDialog.setValue(0); + QApplication::processEvents(); + + QVector work = cycles; + for(int i = 0; i < work.size(); i++) + { + work[i].plotKeys = QVector(work[i].plotKeys.constBegin(), work[i].plotKeys.constEnd()); + work[i].plotVoltage = QVector(work[i].plotVoltage.constBegin(), work[i].plotVoltage.constEnd()); + work[i].plotCurrent = QVector(work[i].plotCurrent.constBegin(), work[i].plotCurrent.constEnd()); + work[i].fitKeys = QVector(work[i].fitKeys.constBegin(), work[i].fitKeys.constEnd()); + work[i].fitVoltage = QVector(work[i].fitVoltage.constBegin(), work[i].fitVoltage.constEnd()); + work[i].relaxKeys = QVector(work[i].relaxKeys.constBegin(), work[i].relaxKeys.constEnd()); + work[i].relaxVoltage = QVector(work[i].relaxVoltage.constBegin(), work[i].relaxVoltage.constEnd()); + + if(progressDialog.wasCanceled()) { endFit(); return; } + } + + bool parallel = parallelGet(cycleNo); + + fitInProgress = true; + + QAtomicInt progressCounter(0); + QAtomicInt cancelFlag(0); + QAtomicInt *progressPtr = &progressCounter; + QAtomicInt *cancelPtr = &cancelFlag; + + batteryparams_cycle_t *workData = work.data(); + QVector *shiftData = shiftSeries.data(); + QVector *rmseData = rmseSeries.data(); + QVector *maxData = maxSeries.data(); + double *bestRmseData = bestRmseKey.data(); + double *bestVmaxData = bestVmaxKey.data(); + int *foundData = found.data(); + + auto sweepCycle = [=](int i) + { + BatteryParamsExtraction::nameCurrentThread(workData[i].index); + const batteryparams_cycle_t &original = workData[i]; + double minRmse = -1; + double minVmax = -1; + double lastKey = -1; + + for(int p = 0; p < pointNo; p++) + { + if(cancelPtr->loadAcquire()) return; + progressPtr->fetchAndAddOrdered(1); + + double targetKey = original.pauseStartKey + windowMs * (double)p / (double)(pointNo - 1); + batteryparams_cycle_t working = original; + + if(!BatteryParamsExtraction::setPauseStart(&working, targetKey)) continue; + if(working.pauseStartKey == lastKey) continue; + lastKey = working.pauseStartKey; + + BatteryParamsExtraction::analyzeCycle(&working, usedSettings); + if(!working.modelValid) continue; + + double shift = (working.pauseStartKey - original.pauseStartKey) / 1000.0; + double rmseMv = working.fitRmse * 1000.0; + double maxMv = working.fitMaxError * 1000.0; + + shiftData[i].append(shift); + rmseData[i].append(rmseMv); + maxData[i].append(maxMv); + + if((minRmse < 0) || (rmseMv < minRmse)) { minRmse = rmseMv; bestRmseData[i] = working.pauseStartKey; } + if((minVmax < 0) || (maxMv < minVmax)) { minVmax = maxMv; bestVmaxData[i] = working.pauseStartKey; } + } + + if(minRmse >= 0) foundData[i] = 1; + }; + + if(!parallel) + { + for(int i = 0; i < cycleNo; i++) + { + progressDialog.setLabelText(QString("Sweeping cycle %1 of %2...").arg(i + 1).arg(cycleNo)); + sweepCycle(i); + progressDialog.setValue(progressCounter.loadAcquire()); + QApplication::processEvents(); + + if(progressDialog.wasCanceled()) { cancelFlag.storeRelease(1); endFit(); return; } + } + } + else + { + QVector positions; + for(int i = 0; i < cycleNo; i++) positions.append(i); + + QFutureWatcher watcher; + QFuture future = QtConcurrent::map(positions, sweepCycle); + watcher.setFuture(future); + + while(!watcher.isFinished()) + { + progressDialog.setLabelText(QString("Sweeping %1 cycles on %2 cores...") + .arg(cycleNo).arg(QThread::idealThreadCount())); + progressDialog.setValue(progressCounter.loadAcquire()); + QApplication::processEvents(); + QThread::msleep(20); + + if(progressDialog.wasCanceled()) + { + cancelFlag.storeRelease(1); + future.cancel(); + future.waitForFinished(); + endFit(); + return; + } + } + } + + progressDialog.setValue(cycleNo * pointNo); + + endFit(); + + bool anyFound = false; + for(int i = 0; i < cycleNo; i++) if(found[i]) { anyFound = true; break; } + + if(!anyFound) + { + QMessageBox::information(this, "Find new start point", + "No cycle could be fitted while sweeping the pause start."); + return; + } + + /*Results dialog: one curve per cycle, RMSE and max error over the pause start shift*/ + QDialog dialog(this); + dialog.setWindowTitle("Find new start point"); + + QVBoxLayout *dialogLayout = new QVBoxLayout(&dialog); + + QCustomPlot *rmsePlot = new QCustomPlot(&dialog); + rmsePlot->xAxis->setLabel("Pause start shift [s]"); + rmsePlot->yAxis->setLabel("RMSE [mV]"); + rmsePlot->legend->setVisible(true); + rmsePlot->legend->setFont(QFont("Arial", 7)); + rmsePlot->legend->setWrap(8); + rmsePlot->legend->setFillOrder(QCPLegend::foColumnsFirst); + rmsePlot->axisRect()->insetLayout()->setInsetAlignment(0, Qt::AlignTop | Qt::AlignRight); + + QCustomPlot *maxPlot = new QCustomPlot(&dialog); + maxPlot->xAxis->setLabel("Pause start shift [s]"); + maxPlot->yAxis->setLabel("Max error [mV]"); + maxPlot->legend->setVisible(true); + maxPlot->legend->setFont(QFont("Arial", 7)); + maxPlot->legend->setWrap(8); + maxPlot->legend->setFillOrder(QCPLegend::foColumnsFirst); + maxPlot->axisRect()->insetLayout()->setInsetAlignment(0, Qt::AlignTop | Qt::AlignRight); + + for(int i = 0; i < cycleNo; i++) + { + if(!found[i] || shiftSeries[i].isEmpty()) continue; + + QColor color = QColor::fromHsv((i * 47) % 360, 200, 220); + QString name = "Cycle " + QString::number(cycles[i].index); + + QCPGraph *rmseGraph = rmsePlot->addGraph(); + rmseGraph->setData(shiftSeries[i], rmseSeries[i]); + rmseGraph->setPen(QPen(color, 1.5)); + rmseGraph->setName(name); + + QCPGraph *maxGraph = maxPlot->addGraph(); + maxGraph->setData(shiftSeries[i], maxSeries[i]); + maxGraph->setPen(QPen(color, 1.5)); + maxGraph->setName(name); + + /*Mark the point that would be chosen: the minimum of each metric for this + cycle. That is the pause start applied when the matching button is pressed*/ + int rmseMinIndex = 0; + int maxMinIndex = 0; + + for(int k = 1; k < rmseSeries[i].size(); k++) + { + if(rmseSeries[i][k] < rmseSeries[i][rmseMinIndex]) rmseMinIndex = k; + if(maxSeries[i][k] < maxSeries[i][maxMinIndex]) maxMinIndex = k; + } + + QCPGraph *rmseDot = rmsePlot->addGraph(); + rmseDot->setData(QVector{shiftSeries[i][rmseMinIndex]}, QVector{rmseSeries[i][rmseMinIndex]}); + rmseDot->setLineStyle(QCPGraph::lsNone); + rmseDot->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssDisc, color, 7)); + rmseDot->removeFromLegend(); + + QCPGraph *maxDot = maxPlot->addGraph(); + maxDot->setData(QVector{shiftSeries[i][maxMinIndex]}, QVector{maxSeries[i][maxMinIndex]}); + maxDot->setLineStyle(QCPGraph::lsNone); + maxDot->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssDisc, color, 7)); + maxDot->removeFromLegend(); + } + + rmsePlot->rescaleAxes(); + rmsePlot->replot(); + maxPlot->rescaleAxes(); + maxPlot->replot(); + + dialogLayout->addWidget(rmsePlot, 1); + dialogLayout->addWidget(maxPlot, 1); + + QHBoxLayout *buttonLayout = new QHBoxLayout(); + QPushButton *applyRmseButton = new QPushButton("Apply by RMSE", &dialog); + QPushButton *applyVmaxButton = new QPushButton("Apply by max error", &dialog); + QPushButton *cancelButton = new QPushButton("Cancel", &dialog); + + buttonLayout->addStretch(); + buttonLayout->addWidget(applyRmseButton); + buttonLayout->addWidget(applyVmaxButton); + buttonLayout->addWidget(cancelButton); + dialogLayout->addLayout(buttonLayout); + + int choice = 0; + + connect(applyRmseButton, &QPushButton::clicked, &dialog, [&choice, &dialog]() { choice = 1; dialog.accept(); }); + connect(applyVmaxButton, &QPushButton::clicked, &dialog, [&choice, &dialog]() { choice = 2; dialog.accept(); }); + connect(cancelButton, &QPushButton::clicked, &dialog, &QDialog::reject); + + dialog.resize(820, 680); + + if((dialog.exec() != QDialog::Accepted) || (choice == 0)) return; + + int appliedNo = 0; + int processedNo = 0; + + int toApply = 0; + for(int i = 0; i < cycleNo; i++) if(found[i]) toApply++; + + QProgressDialog applyProgress("Applying the new pause start and recalculating...", "Cancel", 0, toApply, this); + applyProgress.setWindowModality(Qt::WindowModal); + applyProgress.setWindowTitle("Find new start point"); + applyProgress.setMinimumDuration(0); + applyProgress.setValue(0); + + for(int i = 0; i < cycleNo; i++) + { + if(!found[i]) continue; + + applyProgress.setValue(processedNo++); + QApplication::processEvents(); + + if(applyProgress.wasCanceled()) break; + + double key = (choice == 1) ? bestRmseKey[i] : bestVmaxKey[i]; + batteryparams_cycle_t working = cycles[i]; + + if(!BatteryParamsExtraction::setPauseStart(&working, key)) continue; + + BatteryParamsExtraction::analyzeCycle(&working, usedSettings); + + if(!fittedPositions.contains(i)) + { + fittedPositions.append(i); + fittedOriginals.append(cycles[i]); + } + + cycles[i] = working; + fillCycleRow(i, cycles[i]); + appliedNo++; + } + + applyProgress.setValue(toApply); + + updateSummary(); + updateFitPointsButtons(); + + statusLabel->setText("Pause start set by " + QString(choice == 1 ? "RMSE" : "max error") + + " on " + QString::number(appliedNo) + " cycles, marked with * and not confirmed yet"); +} + void BatteryParamsWnd::onCycleUpdated(batteryparams_cycle_t cycle) { for(int i = 0; i < cycles.size(); i++) @@ -484,14 +1038,223 @@ void BatteryParamsWnd::onCycleUpdated(batteryparams_cycle_t cycle) } } +void BatteryParamsWnd::deleteCycleAt(int row) +{ + if(row < 0 || row >= cycles.size()) return; + + batteryparams_cycle_t &cycle = cycles[row]; + + if(cycle.pulseStartKey > 0) removedMarkerKeys.append(cycle.pulseStartKey); + if(cycle.pulseEndKey > 0) removedMarkerKeys.append(cycle.pulseEndKey); + if(cycle.pauseStartKey > 0) removedMarkerKeys.append(cycle.pauseStartKey); + if(cycle.pauseEndKey > 0) removedMarkerKeys.append(cycle.pauseEndKey); + + cycle.pulseStartKey = 0; + cycle.pulseEndKey = 0; + cycle.pauseStartKey = 0; + cycle.pauseEndKey = 0; + cycle.pulseEndVoltage = 0; + cycle.pulseEndCurrent = 0; + cycle.pauseStartVoltage = 0; + cycle.pauseStartCurrent = 0; + cycle.deltaVoltage = 0; + cycle.deltaCurrent = 0; + cycle.resistance = 0; + cycle.charge = 0; + cycle.chargeTotal = 0; + cycle.socUsed = 0; + cycle.soc = 0; + cycle.resistanceValid = false; + cycle.socValid = false; + cycle.relaxationReached = false; + cycle.relaxationKey = 0; + cycle.relaxationVoltage = 0; + cycle.ocv = 0; + cycle.modelValid = false; + cycle.tauFast = 0; + cycle.tauSlow = 0; + cycle.fastPortionEndKey = 0; + cycle.r1 = 0; + cycle.c1 = 0; + cycle.r2 = 0; + cycle.c2 = 0; + cycle.fitRmse = 0; + cycle.fitMaxError = 0; + cycle.fitKeys.clear(); + cycle.fitVoltage.clear(); + cycle.relaxKeys.clear(); + cycle.relaxVoltage.clear(); + + int fitIndex = fittedPositions.indexOf(row); + if(fitIndex >= 0) + { + fittedPositions.remove(fitIndex); + fittedOriginals.remove(fitIndex); + } + + deletedCycleRows.insert(row); + + fillCycleRow(row, cycle); +} + +void BatteryParamsWnd::onDeleteCycle() +{ + QVector rows; + QModelIndexList selected = cyclesTable->selectionModel()->selectedRows(); + + for(int i = 0; i < selected.size(); i++) rows.append(selected[i].row()); + + if(rows.isEmpty()) + { + int current = cyclesTable->currentRow(); + if(current >= 0) rows.append(current); + } + + if(rows.isEmpty()) return; + + for(int i = 0; i < rows.size(); i++) deleteCycleAt(rows[i]); + + updateSummary(); + updateFitPointsButtons(); +} + +void BatteryParamsWnd::fitCycleAt(int row) +{ + if(extractionRunning) return; + if(row < 0 || row >= cycles.size()) return; + + batteryparams_cycle_t working = cycles[row]; + + if(!BatteryParamsExtraction::cyclePointsFit(&working)) + { + statusLabel->setText("Cycle " + QString::number(cycles[row].index) + " already sits on the settled levels"); + return; + } + + BatteryParamsExtraction::analyzeCycle(&working, settings); + + if(!fittedPositions.contains(row)) + { + fittedPositions.append(row); + fittedOriginals.append(cycles[row]); + } + + cycles[row] = working; + fillCycleRow(row, cycles[row]); + updateSummary(); + updateFitPointsButtons(); + statusLabel->setText("Cycle points fitted on cycle " + QString::number(cycles[row].index) + ", marked with * and not confirmed yet"); +} + +void BatteryParamsWnd::onCycleContextMenu(const QPoint &pos) +{ + int row = cyclesTable->rowAt(pos.y()); + if(row < 0 || row >= cycles.size()) return; + + cyclesTable->selectRow(row); + + QMenu menu(this); + QAction *showAction = menu.addAction("Show cycle data"); + QAction *deleteAction = menu.addAction("Delete cycle"); + QAction *fitAction = menu.addAction("Fit cycle points"); + + fitAction->setEnabled(!extractionRunning); + + QAction *chosen = menu.exec(cyclesTable->viewport()->mapToGlobal(pos)); + + if(chosen == showAction) openCycleData(row); + else if(chosen == deleteAction) + { + deleteCycleAt(row); + updateSummary(); + updateFitPointsButtons(); + } + else if(chosen == fitAction) fitCycleAt(row); +} + +void BatteryParamsWnd::onSaveNewCycles() +{ + if(deletedCycleRows.isEmpty()) return; + + QVector rows; + for(QSet::const_iterator it = deletedCycleRows.constBegin(); it != deletedCycleRows.constEnd(); ++it) + rows.append(*it); + std::sort(rows.begin(), rows.end()); + + for(int i = rows.size() - 1; i >= 0; i--) + { + int row = rows[i]; + if(row < 0 || row >= cycles.size()) continue; + + int fitIndex = fittedPositions.indexOf(row); + if(fitIndex >= 0) + { + fittedPositions.remove(fitIndex); + fittedOriginals.remove(fitIndex); + } + for(int j = 0; j < fittedPositions.size(); j++) + if(fittedPositions[j] > row) fittedPositions[j] -= 1; + + cycles.remove(row); + cyclesTable->removeRow(row); + } + + int no = deletedCycleRows.size(); + deletedCycleRows.clear(); + removedMarkerKeys.clear(); + + fittedPositions.clear(); + fittedOriginals.clear(); + for(int i = 0; i < cycles.size(); i++) fillCycleRow(i, cycles[i]); + + emit sigPointsStored(collectCycleMarkers()); + + if(cycles.isEmpty()) statusLabel->setText("Waiting for the first cycle..."); + else statusLabel->setText(QString::number(no) + " deleted cycles removed, ep.csv updated"); + + updateSummary(); + updateFitPointsButtons(); +} + +QVector> BatteryParamsWnd::collectCycleMarkers() +{ + QVector> markers; + + for(int i = 0; i < cycles.size(); i++) + { + if(cycles[i].pulseStartKey > 0) markers.append(qMakePair(QString(BATTERYPARAMS_DEFAULT_PULSE_START_MARKER), cycles[i].pulseStartKey)); + if(cycles[i].pulseEndKey > 0) markers.append(qMakePair(QString(BATTERYPARAMS_DEFAULT_PULSE_END_MARKER), cycles[i].pulseEndKey)); + if(cycles[i].pauseStartKey > 0) markers.append(qMakePair(QString(BATTERYPARAMS_DEFAULT_PAUSE_START_MARKER), cycles[i].pauseStartKey)); + if(cycles[i].pauseEndKey > 0) markers.append(qMakePair(QString(BATTERYPARAMS_DEFAULT_PAUSE_END_MARKER), cycles[i].pauseEndKey)); + } + + return markers; +} + +void BatteryParamsWnd::onStoreNewPoints() +{ + fittedPositions.clear(); + fittedOriginals.clear(); + for(int i = 0; i < cycles.size(); i++) fillCycleRow(i, cycles[i]); + + emit sigPointsStored(collectCycleMarkers()); + + updateFitPointsButtons(); + statusLabel->setText("Points stored to ep.csv"); +} + void BatteryParamsWnd::onClear() { fittedPositions.clear(); fittedOriginals.clear(); + deletedCycleRows.clear(); + removedMarkerKeys.clear(); updateFitPointsButtons(); cycles.clear(); cyclesTable->setRowCount(0); + chargeCycles.clear(); + chargeCyclesTable->setRowCount(0); statusLabel->setText("Waiting for the first cycle..."); updateSummary(); } @@ -503,6 +1266,38 @@ void BatteryParamsWnd::setSettings(batteryparams_settings_t aSettings) if(settingsDlg != NULL) settingsDlg->setSettings(settings); } +void BatteryParamsWnd::setExtractionRunning(bool running) +{ + extractionRunning = running; + if(settingsDlg != NULL) settingsDlg->setExtractionRunning(running); + updateFitPointsButtons(); + + if(!running) clearLiveStatus(); +} + +void BatteryParamsWnd::setLiveStatus(double amplitude, double pauseMs, bool dvdt, + double socHigh, double socLow, double soc, QString nextText) +{ + QString text; + + text = "Active pass   "; + text += "SoC " + QString::number(soc, 'f', 1) + " % (region " + + QString::number(socHigh, 'f', 0) + "-" + QString::number(socLow, 'f', 0) + " %)"; + text += "  |  amplitude " + QString::number(amplitude, 'f', 0) + " mA"; + text += "  |  pause " + QString::number(pauseMs / 1000.0, 'f', 1) + " s"; + text += "  |  pause ends on " + QString(dvdt ? "dV/dt (relaxation)" : "fixed duration"); + text += "
Next   " + nextText; + + liveStatusLabel->setText(text); + liveStatusLabel->show(); +} + +void BatteryParamsWnd::clearLiveStatus() +{ + liveStatusLabel->clear(); + liveStatusLabel->hide(); +} + void BatteryParamsWnd::updateSettingsLabel() { settingsLabel->setText(QString(settings.model == BATTERYPARAMS_MODEL_SECOND_ORDER ? "2nd order" : "1st order") + @@ -523,6 +1318,7 @@ void BatteryParamsWnd::onSettings() settingsDlg->setSettings(settings); settingsDlg->setPlotSettings(plotSettings); + settingsDlg->setExtractionRunning(extractionRunning); if(settingsDlg->exec() != QDialog::Accepted) return; @@ -574,6 +1370,9 @@ void BatteryParamsWnd::analyzeCycles(QVector *target, QPr { int cycleNo = target->size(); + analyzeCancel.storeRelease(0); + QAtomicInt *cancelPtr = &analyzeCancel; + if(!parallel) { for(int i = 0; i < cycleNo; i++) @@ -584,8 +1383,11 @@ void BatteryParamsWnd::analyzeCycles(QVector *target, QPr .arg(cycleNo).arg(i + 1)); progressDialog->setValue(i); QApplication::processEvents(); + + if(progressDialog->wasCanceled()) { analyzeCancel.storeRelease(1); return; } } + if((*target)[i].incomplete) continue; BatteryParamsExtraction::analyzeCycle(&(*target)[i], usedSettings); } @@ -594,8 +1396,11 @@ void BatteryParamsWnd::analyzeCycles(QVector *target, QPr } QFutureWatcher watcher; - QFuture future = QtConcurrent::map(*target, [usedSettings](batteryparams_cycle_t &cycle) + QFuture future = QtConcurrent::map(*target, [usedSettings, cancelPtr](batteryparams_cycle_t &cycle) { + BatteryParamsExtraction::nameCurrentThread(cycle.index); + if(cancelPtr->loadAcquire()) return; + if(cycle.incomplete) return; BatteryParamsExtraction::analyzeCycle(&cycle, usedSettings); }); @@ -610,6 +1415,14 @@ void BatteryParamsWnd::analyzeCycles(QVector *target, QPr .arg(QThread::idealThreadCount()) .arg(watcher.progressValue())); progressDialog->setValue(watcher.progressValue()); + + if(progressDialog->wasCanceled()) + { + analyzeCancel.storeRelease(1); + future.cancel(); + future.waitForFinished(); + return; + } } QApplication::processEvents(); QThread::msleep(20); @@ -623,10 +1436,11 @@ void BatteryParamsWnd::recalculate() /*Already collected cycles keep their samples, so changed settings are applied to them as well instead of only to the cycles still to come. Fitting takes a moment per cycle, so the progress is shown*/ + if(extractionRunning) return; if(cycles.isEmpty()) return; QProgressDialog progressDialog(QString("%1 cycles detected\nRecalculating battery parameters...").arg(cycles.size()), - QString(), 0, cycles.size(), this); + "Cancel", 0, cycles.size(), this); progressDialog.setWindowModality(Qt::WindowModal); progressDialog.setMinimumDuration(0); @@ -636,6 +1450,8 @@ void BatteryParamsWnd::recalculate() progressDialog.setWindowTitle("Battery parameters"); progressDialog.setMinimumWidth(320); progressDialog.setValue(0); + + fitInProgress = true; QApplication::processEvents(); for(int i = 0; i < cycles.size(); i++) @@ -656,6 +1472,8 @@ void BatteryParamsWnd::recalculate() progressDialog.close(); + endFit(); + updateSummary(); } @@ -700,12 +1518,13 @@ void BatteryParamsWnd::trendShow(BatteryParamsTrendWnd **window, QString title, (*window)->activateWindow(); } -void BatteryParamsWnd::onResistanceTrend() +QVector BatteryParamsWnd::buildResistanceTrends() { QVector trends; batteryparams_trend_t r0 = trendCreate("R0", QColor(200, 60, 20)); batteryparams_trend_t r1 = trendCreate("R1", QColor(30, 110, 200)); batteryparams_trend_t r2 = trendCreate("R2", QColor(30, 150, 60)); + batteryparams_trend_t rTotal = trendCreate("Rtotal", QColor(130, 60, 170)); for(int i = 0; i < cycles.size(); i++) { @@ -719,20 +1538,37 @@ void BatteryParamsWnd::onResistanceTrend() if(!cycles[i].modelValid) continue; - r1.soc.append(cycles[i].soc); - r1.value.append(cycles[i].r1 * 1000.0); + if(cycles[i].r1Valid) + { + r1.soc.append(cycles[i].soc); + r1.value.append(cycles[i].r1 * 1000.0); + } + + if(cycles[i].resistanceValid) + { + double total = cycles[i].resistance; + if(cycles[i].r1Valid) total += cycles[i].r1; + if(cycles[i].r2Valid) total += cycles[i].r2; + rTotal.soc.append(cycles[i].soc); + rTotal.value.append(total * 1000.0); + } - if(cycles[i].model != BATTERYPARAMS_MODEL_SECOND_ORDER) continue; + if(!cycles[i].r2Valid) continue; r2.soc.append(cycles[i].soc); r2.value.append(cycles[i].r2 * 1000.0); } - trends << r0 << r1 << r2; - trendShow(&resistanceTrendWnd, "Resistance vs SoC", "R [mOhm]", trends); + trends << r0 << r1 << r2 << rTotal; + return trends; } -void BatteryParamsWnd::onCapacitanceTrend() +void BatteryParamsWnd::onResistanceTrend() +{ + trendShow(&resistanceTrendWnd, "Resistance vs SoC", "R [mOhm]", buildResistanceTrends()); +} + +QVector BatteryParamsWnd::buildCapacitanceTrends() { QVector trends; batteryparams_trend_t c1 = trendCreate("C1", QColor(30, 110, 200)); @@ -743,20 +1579,28 @@ void BatteryParamsWnd::onCapacitanceTrend() if(!cycles[i].socValid) continue; if(!cycles[i].modelValid) continue; - c1.soc.append(cycles[i].soc); - c1.value.append(cycles[i].c1); + if(cycles[i].r1Valid) + { + c1.soc.append(cycles[i].soc); + c1.value.append(cycles[i].c1); + } - if(cycles[i].model != BATTERYPARAMS_MODEL_SECOND_ORDER) continue; + if(!cycles[i].r2Valid) continue; c2.soc.append(cycles[i].soc); c2.value.append(cycles[i].c2); } trends << c1 << c2; - trendShow(&capacitanceTrendWnd, "Capacitance vs SoC", "C [F]", trends); + return trends; } -void BatteryParamsWnd::onOcvTrend() +void BatteryParamsWnd::onCapacitanceTrend() +{ + trendShow(&capacitanceTrendWnd, "Capacitance vs SoC", "C [F]", buildCapacitanceTrends()); +} + +QVector BatteryParamsWnd::buildOcvTrends() { QVector trends; batteryparams_trend_t ocv = trendCreate("OCV", QColor(120, 60, 180)); @@ -764,14 +1608,138 @@ void BatteryParamsWnd::onOcvTrend() for(int i = 0; i < cycles.size(); i++) { if(!cycles[i].socValid) continue; - if(!cycles[i].relaxationReached) continue; + /*OCV is available whenever the model was fitted, also when the fit stops at the + pause end without the relaxation being reached (the late, low SoC cycles)*/ + if(!cycles[i].relaxationReached && !cycles[i].modelValid) continue; ocv.soc.append(cycles[i].soc); ocv.value.append(cycles[i].ocv); } trends << ocv; - trendShow(&ocvTrendWnd, "OCV vs SoC", "OCV [V]", trends); + return trends; +} + +void BatteryParamsWnd::onOcvTrend() +{ + trendShow(&ocvTrendWnd, "OCV vs SoC", "OCV [V]", buildOcvTrends()); +} + +void BatteryParamsWnd::onGraph() +{ + if(graphWnd == NULL) + { + /*Each graph is its own dock widget, tabbed together, so they can be viewed one at + a time, torn off, floated or arranged side by side*/ + QMainWindow *graphMain = new QMainWindow(); + graphMain->setAttribute(Qt::WA_QuitOnClose, false); + graphMain->setWindowTitle(profileName.isEmpty() ? "Battery parameters graphs" : "Battery parameters graphs - " + profileName); + graphMain->setDockNestingEnabled(true); + + graphResistance = new BatteryParamsTrendWnd(); + graphCapacitance = new BatteryParamsTrendWnd(); + graphOcv = new BatteryParamsTrendWnd(); + graphRelaxation = new BatteryParamsTrendWnd(); + + BatteryParamsTrendWnd *widgets[4] = {graphResistance, graphCapacitance, graphOcv, graphRelaxation}; + QString titles[4] = {"Resistance", "Capacitance", "OCV", "Relaxation time"}; + QDockWidget *docks[4]; + + for(int i = 0; i < 4; i++) + { + docks[i] = new QDockWidget(titles[i], graphMain); + docks[i]->setWidget(widgets[i]); + docks[i]->setAllowedAreas(Qt::AllDockWidgetAreas); + docks[i]->setFeatures(QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable); + graphMain->addDockWidget(Qt::LeftDockWidgetArea, docks[i]); + if(i > 0) graphMain->tabifyDockWidget(docks[0], docks[i]); + } + + docks[0]->raise(); + graphMain->resize(900, 620); + graphWnd = graphMain; + } + + refreshGraphs(); + + graphWnd->show(); + graphWnd->raise(); + graphWnd->activateWindow(); +} + +void BatteryParamsWnd::refreshGraphs() +{ + if(graphWnd == NULL) return; + + graphResistance->setPlotSettings(plotSettings); + graphCapacitance->setPlotSettings(plotSettings); + graphOcv->setPlotSettings(plotSettings); + graphRelaxation->setPlotSettings(plotSettings); + + graphResistance->setTrends("Resistance vs SoC", "R [mOhm]", buildResistanceTrends()); + graphCapacitance->setTrends("Capacitance vs SoC", "C [F]", buildCapacitanceTrends()); + graphOcv->setTrends("OCV vs SoC", "OCV [V]", buildOcvTrends()); + graphRelaxation->setTrends("Relaxation time vs SoC", "t [s]", buildRelaxationTrends()); +} + +QVector BatteryParamsWnd::buildRelaxationTrends() +{ + QVector trends; + batteryparams_trend_t relaxation = trendCreate("Relaxation time", QColor(210, 120, 20)); + + for(int i = 0; i < cycles.size(); i++) + { + if(!cycles[i].socValid) continue; + if(!cycles[i].relaxationReached) continue; + + relaxation.soc.append(cycles[i].soc); + relaxation.value.append((cycles[i].relaxationKey - cycles[i].pauseStartKey) / 1000.0); + } + + trends << relaxation; + return trends; +} + +void BatteryParamsWnd::onAnalysisWindow() +{ + if(analysisWnd == NULL) + { + analysisWnd = new QWidget(); + analysisWnd->setAttribute(Qt::WA_QuitOnClose, false); + analysisWnd->setWindowTitle("Do Analysis"); + + QVBoxLayout *analysisLayout = new QVBoxLayout(analysisWnd); + + QPushButton *ocvAnalysisButton = new QPushButton("OCV analysis", analysisWnd); + ocvAnalysisButton->setToolTip("State of charge against the open circuit voltage, its sensitivity and the effect of measurement noise"); + QPushButton *fitQualityButton = new QPushButton("Estimation quality", analysisWnd); + fitQualityButton->setToolTip("Compare how well the first and the second order model describe every cycle"); + QPushButton *fitIntervalButton = new QPushButton("Fit interval", analysisWnd); + fitIntervalButton->setToolTip("Compare the parameters and the errors obtained by fitting up to the relaxation point and up to the end of the pause"); + + analysisLayout->addWidget(ocvAnalysisButton); + analysisLayout->addWidget(fitQualityButton); + analysisLayout->addWidget(fitIntervalButton); + analysisLayout->addStretch(); + + connect(ocvAnalysisButton, &QPushButton::clicked, this, &BatteryParamsWnd::onOcvAnalysis); + connect(fitQualityButton, &QPushButton::clicked, this, &BatteryParamsWnd::onFitQuality); + connect(fitIntervalButton, &QPushButton::clicked, this, &BatteryParamsWnd::onFitInterval); + + analysisWnd->resize(260, 180); + } + + analysisWnd->show(); + analysisWnd->raise(); + analysisWnd->activateWindow(); +} + +void BatteryParamsWnd::onColumnToggled() +{ + for(int i = 0; i < columnActions.size(); i++) + { + cyclesTable->setColumnHidden(columnActions[i]->data().toInt(), !columnActions[i]->isChecked()); + } } void BatteryParamsWnd::onOcvAnalysis() @@ -838,7 +1806,7 @@ void BatteryParamsWnd::onFitQuality() parallel = parallelGet(firstOrder.size() * 2); QProgressDialog progressDialog(QString("%1 cycles detected\nFitting the first order model...").arg(firstOrder.size()), - QString(), 0, firstOrder.size(), this); + "Cancel", 0, firstOrder.size(), this); progressDialog.setWindowModality(Qt::WindowModal); progressDialog.setMinimumDuration(0); @@ -853,12 +1821,14 @@ void BatteryParamsWnd::onFitQuality() /*Both models are fitted over the same cycles, so their errors can be put side by side*/ analyzeCycles(&firstOrder, &progressDialog, parallel, firstSettings); + if(analyzeCancel.loadAcquire()) { progressDialog.close(); return; } progressDialog.setLabelText(QString("%1 cycles detected\nFitting the second order model...").arg(secondOrder.size())); progressDialog.setValue(0); QApplication::processEvents(); analyzeCycles(&secondOrder, &progressDialog, parallel, secondSettings); + if(analyzeCancel.loadAcquire()) { progressDialog.close(); return; } progressDialog.close(); @@ -953,7 +1923,7 @@ void BatteryParamsWnd::onFitInterval() parallel = parallelGet(relaxationFit.size() * 2); QProgressDialog progressDialog(QString("%1 cycles detected\nFitting up to the relaxation point...").arg(relaxationFit.size()), - QString(), 0, relaxationFit.size(), this); + "Cancel", 0, relaxationFit.size(), this); progressDialog.setWindowModality(Qt::WindowModal); progressDialog.setMinimumDuration(0); @@ -966,12 +1936,14 @@ void BatteryParamsWnd::onFitInterval() QApplication::processEvents(); analyzeCycles(&relaxationFit, &progressDialog, parallel, relaxationSettings); + if(analyzeCancel.loadAcquire()) { progressDialog.close(); return; } progressDialog.setLabelText(QString("%1 cycles detected\nFitting up to the end of the pause...").arg(pauseFit.size())); progressDialog.setValue(0); QApplication::processEvents(); analyzeCycles(&pauseFit, &progressDialog, parallel, pauseSettings); + if(analyzeCancel.loadAcquire()) { progressDialog.close(); return; } progressDialog.close(); @@ -1059,7 +2031,7 @@ void BatteryParamsWnd::onSweepRequested(batteryfitinterval_sweep_t mode, double parallel = parallelGet(source.size() * steps); QProgressDialog progressDialog(QString("Sweeping the relaxation criterion over %1 points...").arg(steps), - QString(), 0, steps + (compare ? 1 : 0), this); + "Cancel", 0, steps + (compare ? 1 : 0), this); progressDialog.setWindowModality(Qt::WindowModal); progressDialog.setMinimumDuration(0); @@ -1073,6 +2045,8 @@ void BatteryParamsWnd::onSweepRequested(batteryfitinterval_sweep_t mode, double for(int step = 0; step < steps; step++) { + if(progressDialog.wasCanceled()) { progressDialog.close(); return; } + QVector target = source; batteryparams_settings_t stepSettings = settings; double value = from + (to - from) * (double)step / (steps - 1); diff --git a/Source/Windows/BatteryParams/batteryparamswnd.h b/Source/Windows/BatteryParams/batteryparamswnd.h index d0826cc..2fa43ad 100644 --- a/Source/Windows/BatteryParams/batteryparamswnd.h +++ b/Source/Windows/BatteryParams/batteryparamswnd.h @@ -8,7 +8,14 @@ #include #include #include +#include +#include +#include +#include #include +#include +#include +#include #include "Processing/batteryparamsextraction.h" #include "batterycyclewnd.h" @@ -28,19 +35,32 @@ class BatteryParamsWnd : public QWidget void setProfileName(QString name); void setSettings(batteryparams_settings_t settings); + void setExtractionRunning(bool running); + void setLiveStatus(double amplitude, double pauseMs, bool dvdt, + double socHigh, double socLow, double soc, QString nextText); + void clearLiveStatus(); void addCycles(QVector newCycles, QProgressDialog *progressDialog); + void addChargeCycles(QVector newCharges); signals: void sigSettingsChanged(batteryparams_settings_t settings); + void sigPointsStored(QVector> markers); public slots: void onCycleStarted(unsigned int index, double key); void onCycleFinished(batteryparams_cycle_t cycle); + void onChargeCycleFinished(batteryparams_charge_cycle_t cycle); void onClear(); private slots: void onExport(); + void onDeleteCycle(); + void onStatistics(); + void onStoreNewPoints(); void onSettings(); + void onGraph(); + void onAnalysisWindow(); + void onColumnToggled(); void onResistanceTrend(); void onCapacitanceTrend(); void onOcvTrend(); @@ -51,24 +71,38 @@ private slots: void onFitCyclePoints(); void onFitPointsSave(); void onFitPointsRestore(); + void onFindNewStartPoint(); void onSweepRequested(batteryfitinterval_sweep_t mode, double fixedValue, double from, double to, int steps, bool compare); void onCycleSelected(int row, int column); + void onCycleContextMenu(const QPoint &pos); + void onSaveNewCycles(); void onCycleUpdated(batteryparams_cycle_t cycle); private: QLabel *statusLabel; - QPushButton *settingsButton; - QPushButton *resistanceTrendButton; - QPushButton *capacitanceTrendButton; - QPushButton *ocvTrendButton; - QPushButton *ocvAnalysisButton; - QPushButton *fitQualityButton; - QPushButton *relaxationTimeButton; - QPushButton *fitIntervalButton; - QPushButton *fitPointsButton; - QPushButton *fitPointsSaveButton; - QPushButton *fitPointsRestoreButton; + QLabel *liveStatusLabel; + + QAction *configAction; + QAction *statisticsAction; + QAction *graphAction; + QAction *analysisAction; + QAction *fitPointsAction; + QAction *fitPointsSaveAction; + QAction *fitPointsRestoreAction; + QAction *fitPointsFindStartAction; + QAction *recalcAction; + QMenu *columnsMenu; + QVector columnActions; + + QWidget *graphWnd; + BatteryParamsTrendWnd *graphResistance; + BatteryParamsTrendWnd *graphCapacitance; + BatteryParamsTrendWnd *graphOcv; + BatteryParamsTrendWnd *graphRelaxation; + + QWidget *analysisWnd; + QLabel *settingsLabel; BatteryParamsSettingsDlg *settingsDlg; @@ -81,17 +115,33 @@ private slots: BatteryFitIntervalWnd *fitIntervalWnd; batteryparams_settings_t settings; + bool extractionRunning; batteryparams_plot_settings_t plotSettings; int parallelAnswer; QLabel *summaryLabel; + QTabWidget *cycleTabs; QTableWidget *cyclesTable; + QTableWidget *chargeCyclesTable; + QVector chargeCycles; QPushButton *clearButton; QPushButton *exportButton; + QPushButton *saveCyclesButton; + QPushButton *storeCyclesButton; + QSet deletedCycleRows; + QVector removedMarkerKeys; + bool fitInProgress; + QAtomicInt analyzeCancel; + QVector pendingCycles; BatteryCycleWnd *cycleWnd; QVector fittedPositions; QVector fittedOriginals; void updateFitPointsButtons(); + void refreshGraphs(); + QVector buildResistanceTrends(); + QVector buildCapacitanceTrends(); + QVector buildOcvTrends(); + QVector buildRelaxationTrends(); bool connectedToCycleWnd; bool connectedToFitIntervalWnd; @@ -100,6 +150,12 @@ private slots: QTableWidgetItem* createItem(QString text); void addCycleRow(batteryparams_cycle_t cycle); + void addChargeCycleRow(batteryparams_charge_cycle_t cycle); + void openCycleData(int row); + void deleteCycleAt(int row); + void fitCycleAt(int row); + void endFit(); + QVector> collectCycleMarkers(); void fillCycleRow(int row, batteryparams_cycle_t cycle); void updateSummary(); void recalculate(); diff --git a/Source/Windows/DataAnalyzer/dataanalyzer.cpp b/Source/Windows/DataAnalyzer/dataanalyzer.cpp index 720aab0..371522e 100644 --- a/Source/Windows/DataAnalyzer/dataanalyzer.cpp +++ b/Source/Windows/DataAnalyzer/dataanalyzer.cpp @@ -4,11 +4,17 @@ #include #include #include +#include +#include +#include #include #include #include #include #include +#include +#include +#include #include DataAnalyzer::DataAnalyzer(QWidget *parent, QString aWsDirPath) : @@ -125,6 +131,12 @@ QStringList DataAnalyzer::listConsumptionProfiles() listConsumptionProfilesInDir(dir, "", profileList, 0); + std::sort(profileList.begin(), profileList.end(), [this](const QString &a, const QString &b){ + QDateTime ta = QFileInfo(QDir(wsDirPath).filePath(a)).lastModified(); + QDateTime tb = QFileInfo(QDir(wsDirPath).filePath(b)).lastModified(); + return ta > tb; + }); + return profileList; } @@ -160,12 +172,47 @@ void DataAnalyzer::realoadConsumptionProfiles() } else { - consumptionProfilesCB->addItems(consumptionProfilesName); + /*Each profile is tagged by its analysis type: a battery icon for a battery + profile, the OpenEPT logo for a consumption profile, and no icon for other*/ + for(int i = 0; i < consumptionProfilesName.size(); i++) + { + QString type = profileAnalysisType(consumptionProfilesName[i]); + + if(type == "Battery") + consumptionProfilesCB->addItem(QIcon(":/images/NewSet/battery.png"), consumptionProfilesName[i]); + else if(type == "Consumption") + consumptionProfilesCB->addItem(QIcon(":/images/main.png"), consumptionProfilesName[i]); + else + consumptionProfilesCB->addItem(consumptionProfilesName[i]); + } + detectedProfilesLabe->setText("Select one consumption profile"); consumptionProfilesCB->setEnabled(true); } } +QString DataAnalyzer::profileAnalysisType(const QString &profilePath) +{ + QFile file(wsDirPath + "/" + profilePath + "/OpenEPT.txt"); + QString type; + + if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) return type; + + QTextStream in(&file); + while(!in.atEnd()) + { + QString line = in.readLine().trimmed(); + if(line.startsWith("Analysis Type:")) + { + type = line.section(':', 1).trimmed(); + break; + } + } + + file.close(); + return type; +} + void DataAnalyzer::onRealoadConsumptionProfiles() { realoadConsumptionProfiles(); @@ -181,6 +228,7 @@ void DataAnalyzer::attachProfile(DataAnalyzerProfile *profile, QString title) QMdiSubWindow *subWindow = mdiArea->addSubWindow(profile); subWindow->setWindowTitle(title); + if(!profile->windowIcon().isNull()) subWindow->setWindowIcon(profile->windowIcon()); subWindow->setAttribute(Qt::WA_DeleteOnClose); subWindow->showMaximized(); mdiArea->setActiveSubWindow(subWindow); @@ -209,6 +257,12 @@ void DataAnalyzer::onLoadConsumptionProfileData() profile = new DataAnalyzerProfile(wsDirPath, selectedConsumptionProfile); profiles.append(profile); + /*The tab icon follows the profile type: battery, OpenEPT for consumption, and the + default icon is kept for an other/untyped profile*/ + QString profileType = profileAnalysisType(selectedConsumptionProfile); + if(profileType == "Battery") profile->setWindowIcon(QIcon(":/images/NewSet/battery.png")); + else if(profileType == "Consumption") profile->setWindowIcon(QIcon(":/images/main.png")); + connect(profile, SIGNAL(sigDockStateToggleRequested()), this, SLOT(onProfileDockStateToggleRequested())); connect(profile, SIGNAL(destroyed(QObject*)), this, SLOT(onProfileDestroyed(QObject*))); @@ -381,6 +435,7 @@ bool DataAnalyzerWorker::setLimits(int limitsNumber) consumptionDataProcessingStartPercentage = 55; epDataProcessingStartPercentage = 0; range = 45; + epEnabled = false; return true; } if(limitsNumber == 3 ) @@ -390,30 +445,63 @@ bool DataAnalyzerWorker::setLimits(int limitsNumber) consumptionDataProcessingStartPercentage = 40; epDataProcessingStartPercentage = 70; range = 30; + epEnabled = true; return true; } + return false; } -void DataAnalyzerWorker::processVoltCurConData(const QString &wsDirPath, const QString &selectedConsumptionProfile) +void DataAnalyzerWorker::reportProgress(int which, int localPercent) { - // Simulating heavy processing - qDebug() << "Processing started in thread:" << QThread::currentThread(); + if(which == 0) vcProgress.storeRelease(localPercent); + else if(which == 1) consProgress.storeRelease(localPercent); + else epProgress.storeRelease(localPercent); + + int global; + if(epEnabled) + global = (vcProgress.loadAcquire() + consProgress.loadAcquire() + epProgress.loadAcquire()) / 3; + else + global = (vcProgress.loadAcquire() + consProgress.loadAcquire()) / 2; + + emit progressUpdated(global); +} +void DataAnalyzerWorker::processVoltCurConData(const QString &wsDirPath, const QString &selectedConsumptionProfile) +{ QString voltageCurrentPath = wsDirPath + "/" + selectedConsumptionProfile + "/vc.csv"; QString consPath = wsDirPath + "/" + selectedConsumptionProfile + "/cons.csv"; QString epPath = wsDirPath + "/" + selectedConsumptionProfile + "/ep.csv"; - emit progressUpdated(vcDataProcessingStartPercentage); - emit updateProgressText("Load Voltage and Current Data"); - QVector > vcData = parseVCData(voltageCurrentPath); + vcProgress.storeRelease(0); + consProgress.storeRelease(0); + epProgress.storeRelease(0); + + emit updateProgressText(epEnabled ? "Loading voltage, current, consumption and points" + : "Loading voltage, current and consumption"); + emit progressUpdated(0); + + /*Voltage/current, consumption and the energy points are independent files, so they + are parsed concurrently instead of one after another*/ + QFuture > > vcFuture = + QtConcurrent::run(this, &DataAnalyzerWorker::parseVCData, voltageCurrentPath); + QFuture > > consFuture = + QtConcurrent::run(this, &DataAnalyzerWorker::parseConsumptionData, consPath); + QFuture > > epFuture; + + if(epEnabled) epFuture = QtConcurrent::run(this, &DataAnalyzerWorker::parseEPFile, epPath); - emit progressUpdated(consumptionDataProcessingStartPercentage); - emit updateProgressText("Load Consumption Data"); + vcFuture.waitForFinished(); + consFuture.waitForFinished(); - QVector > consData = parseConsumptionData(consPath); + emit processingVolCurConFinished(vcFuture.result(), consFuture.result()); + + if(epEnabled) + { + epFuture.waitForFinished(); + emit processingEPFinished(epFuture.result()); + } - // Emit a signal when processing is complete - emit processingVolCurConFinished(vcData, consData); + emit progressUpdated(100); } void DataAnalyzerWorker::processEPData(const QString &wsDirPath, const QString &selectedConsumptionProfile) @@ -539,11 +627,11 @@ QVector > DataAnalyzerWorker::parseVCData(const QString &filePat { skipped++; } - int percent = (int)((file.pos() * (qint64)range) / limit); + int percent = (int)((file.pos() * (qint64)100) / limit); if(percent != lastPercent) { lastPercent = percent; - emit progressUpdated(vcDataProcessingStartPercentage + percent); + reportProgress(0, percent); } } if(skipped > 0) qWarning() << "vc.csv: skipped" << skipped << "malformed lines"; @@ -589,11 +677,11 @@ QVector > DataAnalyzerWorker::parseVCData(const QString &filePat { skipped++; } - int percent = (int)((file.pos() * (qint64)range) / limit); + int percent = (int)((file.pos() * (qint64)100) / limit); if(percent != lastPercent) { lastPercent = percent; - emit progressUpdated(consumptionDataProcessingStartPercentage + percent); + reportProgress(1, percent); } } if(skipped > 0) qWarning() << "cons.csv: skipped" << skipped << "malformed lines"; @@ -643,11 +731,11 @@ QVector > DataAnalyzerWorker::parseEPFile(const QString &fil { skipped++; } - int percent = (int)((file.pos() * (qint64)range) / limit); + int percent = (int)((file.pos() * (qint64)100) / limit); if(percent != lastPercent) { lastPercent = percent; - emit progressUpdated(epDataProcessingStartPercentage + percent); + reportProgress(2, percent); } } if(skipped > 0) qWarning() << "ep.csv: skipped" << skipped << "malformed lines"; diff --git a/Source/Windows/DataAnalyzer/dataanalyzer.h b/Source/Windows/DataAnalyzer/dataanalyzer.h index 8e06aa5..de3c68f 100644 --- a/Source/Windows/DataAnalyzer/dataanalyzer.h +++ b/Source/Windows/DataAnalyzer/dataanalyzer.h @@ -63,6 +63,7 @@ public slots: QStringList listConsumptionProfiles(); void listConsumptionProfilesInDir(QDir dir, QString relativePath, QStringList& profiles, int depth); void realoadConsumptionProfiles(); + QString profileAnalysisType(const QString &profilePath); QMdiSubWindow* subWindowFor(DataAnalyzerProfile *profile); void attachProfile(DataAnalyzerProfile *profile, QString title); void toggleProfileDockState(DataAnalyzerProfile *profile); diff --git a/Source/Windows/DataAnalyzer/dataanalyzerprofile.cpp b/Source/Windows/DataAnalyzer/dataanalyzerprofile.cpp index 26220f5..ee93bda 100644 --- a/Source/Windows/DataAnalyzer/dataanalyzerprofile.cpp +++ b/Source/Windows/DataAnalyzer/dataanalyzerprofile.cpp @@ -1,4 +1,5 @@ #include "dataanalyzerprofile.h" +#include "Windows/Device/profiletypedialog.h" #include #include @@ -10,6 +11,9 @@ #include #include #include +#include +#include +#include #define PLOT_MINIMUM_SIZE_HEIGHT 100 #define PLOT_MINIMUM_SIZE_WIDTH 500 @@ -30,17 +34,40 @@ DataAnalyzerProfile::DataAnalyzerProfile(QString aWsDirPath, QString aProfileNam progressDialog = NULL; statisticsProgressDialog = NULL; + QString analysisType = getValueForKey(parseSummaryFile(wsDirPath + "/" + profileName + "/OpenEPT.txt"), "Analysis Type"); + bool isBattery = (analysisType == "Battery"); + bool isConsumption = (analysisType == "Consumption"); + bool typed = isBattery || isConsumption; + plotsToolBar = new QToolBar(this); plotsToolBar->setIconSize(QSize(24, 24)); + + /*Save and the profile type (gear) stay on the left*/ QAction *saveAllPlotsAction = plotsToolBar->addAction(QIcon(QPixmap(":/images/NewSet/save.png")), "Save all plots"); saveAllPlotsAction->setToolTip("Save Voltage, Current and Consumption plots (current view) to a folder"); connect(saveAllPlotsAction, SIGNAL(triggered(bool)), this, SLOT(onSaveAllPlots())); - QAction *genStatisticsAction = plotsToolBar->addAction(QIcon(QPixmap(":/images/NewSet/analysis.png")), "Gen statistics"); + + QAction *profileTypeAction = plotsToolBar->addAction(QIcon(QPixmap(":/images/NewSet/setting.png")), "Profile type"); + profileTypeAction->setToolTip("Edit the analysis type of this profile (Battery / Consumption / Other) and the battery name and capacity"); + connect(profileTypeAction, SIGNAL(triggered(bool)), this, SLOT(onEditProfileType())); + + /*Spacer pushes the analysis specific icon to the right*/ + QWidget *toolBarSpacer = new QWidget(plotsToolBar); + toolBarSpacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); + plotsToolBar->addWidget(toolBarSpacer); + + /*Only the icon matching the profile type is shown: the battery analyzer for a battery + profile, the consumption statistics for a consumption profile, both for an untyped one*/ + QAction *genStatisticsAction = plotsToolBar->addAction(QIcon(QPixmap(":/images/main.png")), "Gen statistics"); genStatisticsAction->setToolTip("Generate consumption statistics for segments between \" Start\" and \" Stop\" markers"); + genStatisticsAction->setVisible(!typed || isConsumption); connect(genStatisticsAction, SIGNAL(triggered(bool)), this, SLOT(onGenerateStatistics())); - QAction *batteryAnalyzerAction = plotsToolBar->addAction(QIcon(QPixmap(":/images/NewSet/loadProfiler.png")), "Battery analyzer"); + + QAction *batteryAnalyzerAction = plotsToolBar->addAction(QIcon(QPixmap(":/images/NewSet/battery.png")), "Battery analyzer"); batteryAnalyzerAction->setToolTip("Extract battery parameters from \"Pulse Start / Pulse End / Pause Start / Pause End\" marker cycles"); + batteryAnalyzerAction->setVisible(!typed || isBattery); connect(batteryAnalyzerAction, SIGNAL(triggered(bool)), this, SLOT(onBatteryAnalyzer())); + detachAction = plotsToolBar->addAction(QIcon(QPixmap(":/images/NewSet/expand.png")), "Attach"); detachAction->setToolTip("Show this profile back as a tab of the Data Analyzer"); detachAction->setVisible(false); @@ -250,14 +277,199 @@ void DataAnalyzerProfile::processingVolCurConDone(QVector > vc, graphLoad = true; - if(epEnabledFlag) + /*The energy points are parsed in parallel with the voltage, current and consumption, + so they are not requested again here. When they are enabled the EP finished handler + closes the dialog, otherwise it is closed now*/ + if(!epEnabledFlag) { - emit processEPRequest(wsDirPath, profileName); + if(progressDialog) progressDialog->close(); } - else +} + +void DataAnalyzerProfile::saveBatterySettings(const batteryparams_settings_t &settings) +{ + QJsonObject obj; + obj["relaxationThreshold"] = settings.relaxationThreshold; + obj["relaxationWindow"] = settings.relaxationWindow; + obj["relaxationFilter"] = settings.relaxationFilter; + obj["model"] = (int)settings.model; + obj["fitEnd"] = (int)settings.fitEnd; + obj["tauGridPoints"] = settings.tauGridPoints; + obj["tauSeparation"] = settings.tauSeparation; + obj["capacity"] = settings.capacity; + obj["initialSoc"] = settings.initialSoc; + obj["plotDecimation"] = settings.plotDecimation; + obj["ocvWindow"] = settings.ocvWindow; + obj["fitAverageWindow"] = settings.fitAverageWindow; + + QFile file(wsDirPath + "/" + profileName + "/batteryparams.json"); + if(file.open(QIODevice::WriteOnly | QIODevice::Truncate)) { - if(progressDialog) progressDialog->close(); + file.write(QJsonDocument(obj).toJson(QJsonDocument::Indented)); + file.close(); + } +} + +bool DataAnalyzerProfile::loadBatterySettings(batteryparams_settings_t *settings) +{ + if(settings == NULL) return false; + + QFile file(wsDirPath + "/" + profileName + "/batteryparams.json"); + if(!file.open(QIODevice::ReadOnly)) return false; + + QByteArray data = file.readAll(); + file.close(); + + QJsonParseError error; + QJsonDocument doc = QJsonDocument::fromJson(data, &error); + if(error.error != QJsonParseError::NoError || !doc.isObject()) return false; + + QJsonObject obj = doc.object(); + batteryparams_settings_t loaded = BatteryParamsExtraction::settingsDefault(); + + loaded.relaxationThreshold = obj.value("relaxationThreshold").toDouble(loaded.relaxationThreshold); + loaded.relaxationWindow = obj.value("relaxationWindow").toDouble(loaded.relaxationWindow); + loaded.relaxationFilter = obj.value("relaxationFilter").toDouble(loaded.relaxationFilter); + loaded.model = (batteryparams_model_t)obj.value("model").toInt((int)loaded.model); + loaded.fitEnd = (batteryparams_fit_end_t)obj.value("fitEnd").toInt((int)loaded.fitEnd); + loaded.tauGridPoints = obj.value("tauGridPoints").toInt(loaded.tauGridPoints); + loaded.tauSeparation = obj.value("tauSeparation").toDouble(loaded.tauSeparation); + loaded.capacity = obj.value("capacity").toDouble(loaded.capacity); + loaded.initialSoc = obj.value("initialSoc").toDouble(loaded.initialSoc); + loaded.plotDecimation = obj.value("plotDecimation").toInt(loaded.plotDecimation); + loaded.ocvWindow = obj.value("ocvWindow").toInt(loaded.ocvWindow); + loaded.fitAverageWindow = obj.value("fitAverageWindow").toInt(loaded.fitAverageWindow); + + *settings = loaded; + return true; +} + +void DataAnalyzerProfile::onBatterySettingsChanged(batteryparams_settings_t settings) +{ + saveBatterySettings(settings); + + /*Keep the declared capacity in the profile in sync with the one used for the analysis*/ + if(settings.capacity > 0) setDeclaredCapacity(settings.capacity); +} + +void DataAnalyzerProfile::setDeclaredCapacity(double capacity) +{ + QString summaryPath = wsDirPath + "/" + profileName + "/OpenEPT.txt"; + QFile file(summaryPath); + QStringList lines; + + if(file.open(QIODevice::ReadOnly | QIODevice::Text)) + { + QTextStream in(&file); + while(!in.atEnd()) lines << in.readLine(); + file.close(); + } + + QString capacityLine = "Battery capacity [mAh]: " + QString::number(capacity); + bool replaced = false; + + for(int i = 0; i < lines.size(); i++) + { + if(lines[i].trimmed().startsWith("Battery capacity [mAh]:")) + { + lines[i] = capacityLine; + replaced = true; + break; + } + } + + /*If the profile had no declared capacity yet, it is added together with the type block*/ + if(!replaced) + { + bool hasType = false; + for(int i = 0; i < lines.size(); i++) + if(lines[i].trimmed().startsWith("Analysis Type:")) { hasType = true; break; } + + while(!lines.isEmpty() && lines.last().trimmed().isEmpty()) lines.removeLast(); + + if(!hasType) + { + lines << "-------"; + lines << "Analysis Type: Battery"; + } + lines << capacityLine; + } + + if(file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) + { + QTextStream out(&file); + for(const QString &line : lines) out << line << "\n"; + file.close(); + } +} + +void DataAnalyzerProfile::onBatteryPointsStored(QVector> cycleMarkers) +{ + /*Every pulse/pause marker is replaced with the current set reported by the + battery parameters window, so moved points, newly completed cycles and removed + cycles are all reflected. Markers that do not belong to a cycle (for example the + charge markers) are kept as they were*/ + QVector> rebuilt; + + for(int i = 0; i < loadedMarkers.size(); i++) + { + QString name = loadedMarkers[i].first.trimmed(); + if(name == BATTERYPARAMS_DEFAULT_PULSE_START_MARKER || + name == BATTERYPARAMS_DEFAULT_PULSE_END_MARKER || + name == BATTERYPARAMS_DEFAULT_PAUSE_START_MARKER || + name == BATTERYPARAMS_DEFAULT_PAUSE_END_MARKER) continue; + rebuilt.append(loadedMarkers[i]); + } + + for(int i = 0; i < cycleMarkers.size(); i++) + rebuilt.append(qMakePair(cycleMarkers[i].first, (int)qRound(cycleMarkers[i].second))); + + std::sort(rebuilt.begin(), rebuilt.end(), [](const QPair &a, const QPair &b){ + return a.second < b.second; + }); + + loadedMarkers = rebuilt; + + QString epPath = wsDirPath + "/" + profileName + "/ep.csv"; + QStringList headerLines; + QFile in(epPath); + + if(in.open(QIODevice::ReadOnly | QIODevice::Text)) + { + while(!in.atEnd()) + { + QString line = QString::fromUtf8(in.readLine()); + QString trimmed = line.trimmed(); + int comma = trimmed.lastIndexOf(','); + bool isData = false; + + if(comma >= 0) + { + bool ok; + trimmed.mid(comma + 1).trimmed().toInt(&ok); + isData = ok; + } + + if(isData) break; + + while(line.endsWith('\n') || line.endsWith('\r')) line.chop(1); + headerLines.append(line); + } + in.close(); + } + + if(headerLines.isEmpty()) headerLines.append("Energy point info"); + + QFile out(epPath); + if(out.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text)) + { + QTextStream ts(&out); + for(int i = 0; i < headerLines.size(); i++) ts << headerLines[i] << "\n"; + for(int i = 0; i < loadedMarkers.size(); i++) ts << loadedMarkers[i].first << "," << loadedMarkers[i].second << "\n"; + out.close(); } + + applyMarkersToPlots(loadedMarkers); } void DataAnalyzerProfile::processingEPDone(QVector > epData) @@ -351,23 +563,31 @@ void DataAnalyzerProfile::onBatteryAnalyzer() } /*Capacity is stored with the profile, so the offline analysis can show the - used state of charge the same way the live one does*/ + used state of charge the same way the live one does. If a saved battery + parameters configuration exists for this profile, it is used as is so the + capacity, relaxation and extraction settings do not have to be set again*/ { QVector> summaryInfo = parseSummaryFile(wsDirPath + "/" + profileName + "/OpenEPT.txt"); double capacity = getValueForKey(summaryInfo, "Battery capacity [mAh]").toDouble(); batteryparams_settings_t settings = extraction.getSettings(); - if(capacity > 0) - { - settings.capacity = capacity; - extraction.setSettings(settings); - } + batteryparams_settings_t saved; + if(loadBatterySettings(&saved)) settings = saved; + + /*The declared capacity from the profile is the single source of truth, so it wins + over the saved value. Editing it in the battery params settings writes it back to + the profile, so the two stay in sync*/ + if(capacity > 0) settings.capacity = capacity; + + extraction.setSettings(settings); } if(batteryParamsWnd == NULL) { batteryParamsWnd = new BatteryParamsWnd(); batteryParamsWnd->setAttribute(Qt::WA_QuitOnClose, false); + connect(batteryParamsWnd, &BatteryParamsWnd::sigPointsStored, this, &DataAnalyzerProfile::onBatteryPointsStored); + connect(batteryParamsWnd, &BatteryParamsWnd::sigSettingsChanged, this, &DataAnalyzerProfile::onBatterySettingsChanged); } batteryParamsWnd->setProfileName(profileName); @@ -400,6 +620,8 @@ void DataAnalyzerProfile::onBatteryAnalyzer() progressDialog.setValue(0); QApplication::processEvents(); + extraction.onReset(); + extraction.setCaptureIncomplete(true); extraction.onNewSamplesReceived(loadedVoltage, loadedCurrent, loadedVoltageKeys, loadedCurrentKeys); progressDialog.setValue(1); @@ -423,6 +645,8 @@ void DataAnalyzerProfile::onBatteryAnalyzer() QApplication::processEvents(); } + extraction.flushIncompleteCycle(); + cycleNo = extraction.getCycles().size(); if(cycleNo == 0) @@ -439,6 +663,45 @@ void DataAnalyzerProfile::onBatteryAnalyzer() progressDialog.close(); + { + QVector chargeCycles; + unsigned int chargeIndex = 0; + double chargeStartKey = -1; + + for(int i = 0; i < loadedMarkers.size(); i++) + { + QString name = loadedMarkers[i].first.trimmed(); + + if(name == "Charge Start") + { + chargeStartKey = loadedMarkers[i].second; + } + else if(name == "Charge End" && chargeStartKey >= 0) + { + double chargeEndKey = loadedMarkers[i].second; + double capacity = 0; + + for(int s = 1; s < loadedCurrentKeys.size() && s < loadedCurrent.size(); s++) + { + if(loadedCurrentKeys[s] < chargeStartKey) continue; + if(loadedCurrentKeys[s] > chargeEndKey) break; + capacity += loadedCurrent[s] * (loadedCurrentKeys[s] - loadedCurrentKeys[s - 1]) / 3600000.0; + } + + batteryparams_charge_cycle_t chargeCycle; + chargeIndex++; + chargeCycle.index = chargeIndex; + chargeCycle.startKey = chargeStartKey; + chargeCycle.endKey = chargeEndKey; + chargeCycle.capacity = qAbs(capacity); + chargeCycles.append(chargeCycle); + chargeStartKey = -1; + } + } + + if(!chargeCycles.isEmpty()) batteryParamsWnd->addChargeCycles(chargeCycles); + } + batteryParamsWnd->show(); batteryParamsWnd->raise(); batteryParamsWnd->activateWindow(); @@ -575,6 +838,86 @@ void DataAnalyzerProfile::onSaveAllPlots() } } +void DataAnalyzerProfile::onEditProfileType() +{ + QString summaryPath = wsDirPath + "/" + profileName + "/OpenEPT.txt"; + QVector> info = parseSummaryFile(summaryPath); + + ProfileTypeDialog dialog(this); + dialog.setValues(getValueForKey(info, "Analysis Type"), + getValueForKey(info, "Battery"), + getValueForKey(info, "Battery capacity [mAh]")); + + if(dialog.exec() != QDialog::Accepted) return; + + QFile file(summaryPath); + QStringList lines; + + if(file.open(QIODevice::ReadOnly | QIODevice::Text)) + { + QTextStream in(&file); + while(!in.atEnd()) lines << in.readLine(); + file.close(); + } + + /*Only the existing analysis type block (its separator and its lines) is dropped, the + acquisition info and its header separator above are left untouched, then a fresh block + is appended below*/ + int blockStart = -1; + for(int i = 0; i < lines.size(); i++) + { + if(lines[i].trimmed().startsWith("Analysis Type:")) { blockStart = i; break; } + } + + QStringList kept = lines; + if(blockStart >= 0) + { + /*Include the separator line right before the block if there is one*/ + QString before = (blockStart > 0) ? lines[blockStart - 1].trimmed() : QString(); + if(!before.isEmpty() && (before.count('-') == before.size())) blockStart--; + + while(kept.size() > blockStart) kept.removeLast(); + } + + while(!kept.isEmpty() && kept.last().trimmed().isEmpty()) kept.removeLast(); + + kept << "-------"; + kept << "Analysis Type: " + dialog.analysisType(); + if(dialog.analysisType() == "Battery") + { + kept << "Battery: " + dialog.batteryName(); + kept << "Battery capacity [mAh]: " + dialog.batteryCapacity(); + } + + if(file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) + { + QTextStream out(&file); + for(const QString &line : kept) out << line << "\n"; + file.close(); + + /*The declared capacity is kept in sync with the battery parameters settings*/ + if(dialog.analysisType() == "Battery") + { + bool ok; + double capacity = dialog.batteryCapacity().toDouble(&ok); + if(ok && (capacity > 0)) + { + batteryparams_settings_t settings; + if(!loadBatterySettings(&settings)) settings = BatteryParamsExtraction::settingsDefault(); + settings.capacity = capacity; + saveBatterySettings(settings); + if(batteryParamsWnd != NULL) batteryParamsWnd->setSettings(settings); + } + } + + QMessageBox::information(this, "Profile type", "Profile type updated"); + } + else + { + QMessageBox::warning(this, "Profile type", "Unable to write OpenEPT.txt"); + } +} + QString DataAnalyzerProfile::getValueForKey(const QVector> &parsedData, const QString &key) { for(const auto &pair : parsedData) diff --git a/Source/Windows/DataAnalyzer/dataanalyzerprofile.h b/Source/Windows/DataAnalyzer/dataanalyzerprofile.h index 60e67a6..3c8c08e 100644 --- a/Source/Windows/DataAnalyzer/dataanalyzerprofile.h +++ b/Source/Windows/DataAnalyzer/dataanalyzerprofile.h @@ -40,6 +40,7 @@ class DataAnalyzerProfile : public QWidget public slots: void onGenerateStatistics(); void onBatteryAnalyzer(); + void onEditProfileType(); void onStatisticsProgress(int percentage, QString text); void onStatisticsFinished(QVector stats, QVector points, dataanalyzer_segment_stat_t total, QStringList warnings); void onStatisticsSegmentSelected(QString name, int startIndex, int endIndex); @@ -49,6 +50,8 @@ public slots: void onDetachClicked(); void processingVolCurConDone(QVector > vc, QVector> cons); void processingEPDone(QVector> epData); + void onBatteryPointsStored(QVector> cycleMarkers); + void onBatterySettingsChanged(batteryparams_settings_t settings); void updateProgress(int percentage); void updateProgressText(QString text); @@ -57,8 +60,11 @@ public slots: void createCurrentSubWin(); void createConsumptionSubWin(); void applyMarkersToPlots(QVector> markers); + void saveBatterySettings(const batteryparams_settings_t &settings); + bool loadBatterySettings(batteryparams_settings_t *settings); QVector> parseSummaryFile(const QString &filePath); QString getValueForKey(const QVector > &parsedData, const QString &key); + void setDeclaredCapacity(double capacity); QMainWindow *mainWindow; QToolBar *plotsToolBar; diff --git a/Source/Windows/DataAnalyzer/dataanalyzerworker.h b/Source/Windows/DataAnalyzer/dataanalyzerworker.h index 524e69a..3731a10 100644 --- a/Source/Windows/DataAnalyzer/dataanalyzerworker.h +++ b/Source/Windows/DataAnalyzer/dataanalyzerworker.h @@ -5,6 +5,7 @@ #include #include #include +#include class DataAnalyzerWorker : public QObject { @@ -29,10 +30,16 @@ public slots: QVector> parseConsumptionData(const QString &filePath); QVector> parseEPFile(const QString &filePath); + void reportProgress(int which, int localPercent); + int vcDataProcessingStartPercentage; int consumptionDataProcessingStartPercentage; int epDataProcessingStartPercentage; double range; + bool epEnabled; + QAtomicInt vcProgress; + QAtomicInt consProgress; + QAtomicInt epProgress; }; #endif // DATAANALYZERWORKER_H diff --git a/Source/Windows/Device/devicewnd.cpp b/Source/Windows/Device/devicewnd.cpp index 8c8ed5a..99f0697 100644 --- a/Source/Windows/Device/devicewnd.cpp +++ b/Source/Windows/Device/devicewnd.cpp @@ -1,6 +1,7 @@ #include "devicewnd.h" #include "ui_devicewnd.h" #include "Windows/Console/consolewnd.h" +#include "Windows/Device/profiletypedialog.h" #include #include #include @@ -60,8 +61,11 @@ DeviceWnd::DeviceWnd(QWidget *parent) : connect(energyControlWnd, &EnergyControlWnd::sigLoadWaveChanged, this, &DeviceWnd::onLoadWaveChanged); connect(energyControlWnd, &EnergyControlWnd::sigLoadWaveStatusChanged, this, &DeviceWnd::onLoadWaveStatusChanged); connect(energyControlWnd, &EnergyControlWnd::sigBatParamViewRequested, this, &DeviceWnd::sigBatParamViewRequested); + connect(energyControlWnd, &EnergyControlWnd::sigBatParamProcedureActive, this, &DeviceWnd::sigBatParamProcedureActive); connect(energyControlWnd, &EnergyControlWnd::sigBatParamCapacityChanged, this, &DeviceWnd::sigBatParamCapacityChanged); connect(energyControlWnd, &EnergyControlWnd::sigBatParamRelaxationChanged, this, &DeviceWnd::sigBatParamRelaxationChanged); + connect(energyControlWnd, &EnergyControlWnd::sigBatParamExtractionRunning, this, &DeviceWnd::sigBatParamExtractionRunning); + connect(energyControlWnd, &EnergyControlWnd::sigChargeMarkersEnabled, this, &DeviceWnd::sigChargeMarkersEnabled); connect(energyControlWnd, &EnergyControlWnd::sigLoadWaveClear, this, &DeviceWnd::sigLoadWaveClear); connect(energyControlWnd, SIGNAL(sigChargingCurrentStatusChanged(bool)), this, SLOT(onChargingCurrentStatusChanged(bool))); connect(energyControlWnd, SIGNAL(sigChargingCurrentChanged(unsigned int)), this, SLOT(onChargingCurrentChanged(unsigned int))); @@ -128,6 +132,7 @@ DeviceWnd::DeviceWnd(QWidget *parent) : connect(ui->refreshPusb, SIGNAL(clicked(bool)), this, SLOT(onRefreshAcquisiton())); connect(ui->ConsolePusb, SIGNAL(clicked(bool)), this, SLOT(onConsolePressed())); connect(ui->DataStatisticsPushb, SIGNAL(clicked(bool)), this, SLOT(onDataAnalyzerPressed())); + connect(ui->BatteryParamsPushb, &QPushButton::clicked, this, &DeviceWnd::sigBatParamViewRequested); connect(ui->samplingPeriodLine, SIGNAL(returnPressed()), this, SLOT(onSamplingPeriodChanged())); connect(ui->streamServerInterfComb, SIGNAL(currentTextChanged(QString)), this, SLOT(onInterfaceChanged(QString))); @@ -177,7 +182,14 @@ void DeviceWnd::onCalibrationStoreRequest() void DeviceWnd::onSetConsumptionName() { - emit sigConsumptionProfileNameChanged(ui->consNameLine->text()); + QString name = ui->consNameLine->text().trimmed(); + if(name.isEmpty()) return; + + ProfileTypeDialog dialog(this); + if(dialog.exec() != QDialog::Accepted) return; + + emit sigConsumptionProfileNameChanged(name); + emit sigProfileAnalysisTypeChanged(dialog.analysisType(), dialog.batteryName(), dialog.batteryCapacity()); } void DeviceWnd::onInterfaceChanged(QString interfaceInfo) diff --git a/Source/Windows/Device/devicewnd.h b/Source/Windows/Device/devicewnd.h index c5b3b6c..6ca2b20 100644 --- a/Source/Windows/Device/devicewnd.h +++ b/Source/Windows/Device/devicewnd.h @@ -190,6 +190,7 @@ class DeviceWnd : public QWidget void sigStopAcquisition(); void sigRefreshAcquisition(); void sigConsumptionProfileNameChanged(QString newName); + void sigProfileAnalysisTypeChanged(QString analysisType, QString batteryName, QString batteryCapacity); void sigNewControlMessageRcvd(const QString &response); void sigAdvConfigurationReqested(); void sigAdvConfigurationChanged(QVariant newConfig); @@ -204,8 +205,11 @@ class DeviceWnd : public QWidget void sigLoadWaveChanged(Waveform wave); void sigLoadWaveStatusChanged(bool newState); void sigBatParamViewRequested(); + void sigBatParamProcedureActive(bool active); void sigBatParamCapacityChanged(double capacity); void sigBatParamRelaxationChanged(bool enabled, double thresholdMv, double windowS, double filterMs); + void sigBatParamExtractionRunning(bool running); + void sigChargeMarkersEnabled(bool enabled); void sigLoadWaveClear(); void sigChargingCurrentChanged(unsigned int current); void sigChargingTermCurrentChanged(unsigned int current); diff --git a/Source/Windows/Device/devicewnd.ui b/Source/Windows/Device/devicewnd.ui index 1c7ce3c..95d0c22 100644 --- a/Source/Windows/Device/devicewnd.ui +++ b/Source/Windows/Device/devicewnd.ui @@ -1260,6 +1260,65 @@ + + + + + + + Arial + 10 + + + + Battery params + + + + + + + + 30 + 30 + + + + + 30 + 30 + + + + Open the battery parameters view (available while the battery parameter extraction runs) + + + + + + + :/images/NewSet/battery.png:/images/NewSet/battery.png + + + + + + + Qt::Horizontal + + + QSizePolicy::Minimum + + + + 40 + 20 + + + + + + diff --git a/Source/Windows/Device/energycontrolwnd.cpp b/Source/Windows/Device/energycontrolwnd.cpp index 9efd0f7..0c18023 100644 --- a/Source/Windows/Device/energycontrolwnd.cpp +++ b/Source/Windows/Device/energycontrolwnd.cpp @@ -178,10 +178,22 @@ EnergyControlWnd::EnergyControlWnd(QWidget *parent) : QVBoxLayout *batParamLayout = new QVBoxLayout(batParamWidget); batParamLayout->setContentsMargins(0, 0, 0, 0); + QHBoxLayout *batParamLibRow = new QHBoxLayout(); + QLabel *batParamLibLabel = new QLabel("Library", this); + batParamLibLabel->setFixedSize(ENTRY_LABEL_WIDTH, ENTRY_ROW_HEIGHT); + batParamLibraryCombo = new QComboBox(this); + batParamLibraryCombo->setFixedHeight(ENTRY_ROW_HEIGHT); + batParamLibraryCombo->setMinimumWidth(ENTRY_EDIT_WIDTH + ENTRY_UNIT_WIDTH); + batParamLibraryCombo->setToolTip("Saved battery parameter waves. Select one to load its settings back into the fields and the region table."); + batParamLibRow->addWidget(batParamLibLabel); + batParamLibRow->addWidget(batParamLibraryCombo, 1); + batParamLibraryDeleteButton = createSmallButton("Delete", batParamLibRow); + batParamLayout->addLayout(batParamLibRow); + + connect(batParamLibraryCombo, QOverload::of(&QComboBox::activated), this, &EnergyControlWnd::onBatParamLibrarySelected); + connect(batParamLibraryDeleteButton, &QPushButton::clicked, this, &EnergyControlWnd::onBatParamLibraryDelete); + batParamLayout->addLayout(createEntryRow("Battery Capacity", "mAh", loadEntryEdits)); - batParamLayout->addLayout(createEntryRow("Extraction Accuracy", "%", loadEntryEdits)); - batParamLayout->addLayout(createEntryRow("Maximum Current", "mA", loadEntryEdits)); - batParamLayout->addLayout(createEntryRow("Pause Duration", "ms", loadEntryEdits)); batParamLayout->addLayout(createEntryRow("Marker Guard", "ms", loadEntryEdits)); QHBoxLayout *batParamRelaxRow = new QHBoxLayout(); @@ -197,25 +209,10 @@ EnergyControlWnd::EnergyControlWnd(QWidget *parent) : batParamRelaxRow->addStretch(); batParamLayout->addLayout(batParamRelaxRow); - batParamLayout->addLayout(createEntryRow("Relax Threshold", "mV", loadEntryEdits)); - batParamLayout->addLayout(createEntryRow("Relax Window", "s", loadEntryEdits)); - batParamLayout->addLayout(createEntryRow("Relax Filter", "ms", loadEntryEdits)); loadEntryEdits["Battery Capacity"]->setText("500"); - loadEntryEdits["Extraction Accuracy"]->setText("1"); - loadEntryEdits["Maximum Current"]->setText("1000"); - loadEntryEdits["Pause Duration"]->setText("1000"); loadEntryEdits["Marker Guard"]->setText("1"); - loadEntryEdits["Relax Threshold"]->setText("5"); - loadEntryEdits["Relax Window"]->setText("60"); - loadEntryEdits["Relax Filter"]->setText("1000"); loadEntryEdits["Battery Capacity"]->setToolTip("Nominal battery capacity"); - loadEntryEdits["Extraction Accuracy"]->setToolTip("Charge extracted by a single pulse, in percent of the battery capacity"); - loadEntryEdits["Maximum Current"]->setToolTip("Pulse amplitude, pause is always 0 mA"); - loadEntryEdits["Pause Duration"]->setToolTip("Relaxation time between two pulses"); loadEntryEdits["Marker Guard"]->setToolTip("Distance between a current step and the marker that follows it.\nKeeps every marker inside a settled level instead of on the step itself.\nMust cover the load response time, a few sample periods at least"); - loadEntryEdits["Relax Threshold"]->setToolTip("Voltage span allowed inside the relaxation window, the pause ends when the battery stays within it"); - loadEntryEdits["Relax Window"]->setToolTip("Time window the voltage has to stay inside the threshold before the pause is ended"); - loadEntryEdits["Relax Filter"]->setToolTip("Voltage is averaged over this window, in milliseconds, before it is compared with the threshold.\nThe averaged voltage is drawn over the live voltage plot.\n0 turns the filter off"); batParamInfoLabel = new QLabel(this); batParamInfoLabel->setStyleSheet("color: gray;"); @@ -224,26 +221,44 @@ EnergyControlWnd::EnergyControlWnd(QWidget *parent) : batParamSaveWaveButton->setToolTip("Save generated wave to library for later use"); loadButtons.insert("SaveBatParamWave", batParamSaveWaveButton); batParamSaveRow->addWidget(batParamInfoLabel, 1); + batParamAddRegionButton = createSmallButton("Add Region", batParamSaveRow); + batParamRemoveRegionButton = createSmallButton("Remove Region", batParamSaveRow); + batParamClearRegionButton = createSmallButton("Clear", batParamSaveRow); batParamLayout->addLayout(batParamSaveRow); connect(batParamSaveWaveButton, &QPushButton::clicked, this, &EnergyControlWnd::onLoadWaveSave); - - batParamTable = createWaveTable(false); + connect(batParamAddRegionButton, &QPushButton::clicked, this, &EnergyControlWnd::onBatParamAddRegion); + connect(batParamRemoveRegionButton, &QPushButton::clicked, this, &EnergyControlWnd::onBatParamRemoveRegion); + connect(batParamClearRegionButton, &QPushButton::clicked, this, &EnergyControlWnd::onBatParamClearRegions); + + batParamTable = new QTableWidget(0, 8, this); + QStringList batParamRegionHeader; + batParamRegionHeader << "SoC hi [%]" << "SoC lo [%]" << "Acc [%]" << "Amp [mA]" + << "Pause [ms]" << "R thr [mV]" << "R win [s]" << "R filt [ms]"; + batParamTable->setHorizontalHeaderLabels(batParamRegionHeader); + batParamTable->horizontalHeader()->setMinimumSectionSize(40); + batParamTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); + batParamTable->horizontalHeader()->setStretchLastSection(true); + batParamTable->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + batParamTable->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); + batParamTable->verticalHeader()->setDefaultSectionSize(22); + batParamTable->setSelectionBehavior(QAbstractItemView::SelectRows); + batParamTable->setMinimumHeight(140); + batParamTable->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + batParamTable->setToolTip("Extraction regions over the state of charge. Each row is a SoC range with its own accuracy, amplitude, pause and relaxation.\nThe region matching the current state of charge is used for the next pulse.\nColumns: SoC high %, SoC low %, accuracy %, amplitude mA, pause ms, relax threshold mV, relax window s, relax filter ms."); batParamLayout->addWidget(batParamTable, 1); + batParamRegionsInit(); + batParamWidget->setVisible(false); loadTopLayout->addWidget(batParamWidget); connect(loadEntryEdits["Battery Capacity"], &QLineEdit::textChanged, this, &EnergyControlWnd::onBatParamChanged); - connect(loadEntryEdits["Extraction Accuracy"], &QLineEdit::textChanged, this, &EnergyControlWnd::onBatParamChanged); - connect(loadEntryEdits["Maximum Current"], &QLineEdit::textChanged, this, &EnergyControlWnd::onBatParamChanged); - connect(loadEntryEdits["Pause Duration"], &QLineEdit::textChanged, this, &EnergyControlWnd::onBatParamChanged); connect(loadEntryEdits["Marker Guard"], &QLineEdit::textChanged, this, &EnergyControlWnd::onBatParamChanged); - connect(loadEntryEdits["Relax Threshold"], &QLineEdit::textChanged, this, &EnergyControlWnd::onBatParamChanged); - connect(loadEntryEdits["Relax Window"], &QLineEdit::textChanged, this, &EnergyControlWnd::onBatParamChanged); - connect(loadEntryEdits["Relax Filter"], &QLineEdit::textChanged, this, &EnergyControlWnd::onBatParamChanged); + connect(batParamTable, &QTableWidget::cellChanged, this, &EnergyControlWnd::onBatParamChanged); connect(batParamRelaxCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(onBatParamChanged())); refreshCustomWaveLibraryCombo(); + refreshBatParamLibraryCombo(); updateStdWaveInfo(); updateCustomWaveInfo(); updateBatParamInfo(); @@ -331,7 +346,21 @@ EnergyControlWnd::EnergyControlWnd(QWidget *parent) : chargerTopLayout->addLayout(createSectionHeader("Parameters")); chargerTopLayout->addLayout(createEntryRow("Current", "mA", chargerEntryEdits)); chargerTopLayout->addLayout(createEntryRow("Term Voltage", "V", chargerEntryEdits)); - chargerTopLayout->addLayout(createEntryRow("Term Current", "%", chargerEntryEdits)); + QHBoxLayout *termCurrentRow = new QHBoxLayout(); + QLabel *termCurrentLabel = new QLabel("Term Current", this); + termCurrentLabel->setObjectName("Term CurrentLabel"); + termCurrentLabel->setFixedSize(ENTRY_LABEL_WIDTH, ENTRY_ROW_HEIGHT); + chargerTermCurrentCombo = new QComboBox(this); + chargerTermCurrentCombo->setObjectName("Term CurrentComboBox"); + chargerTermCurrentCombo->setFixedSize(ENTRY_EDIT_WIDTH + ENTRY_UNIT_WIDTH, ENTRY_ROW_HEIGHT); + chargerTermCurrentCombo->addItem("Disabled", 0); + chargerTermCurrentCombo->addItem("5 %", 5); + chargerTermCurrentCombo->addItem("10 %", 10); + chargerTermCurrentCombo->addItem("20 %", 20); + termCurrentRow->addWidget(termCurrentLabel); + termCurrentRow->addWidget(chargerTermCurrentCombo); + termCurrentRow->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Minimum)); + chargerTopLayout->addLayout(termCurrentRow); chargerTopLayout->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding)); chargerTopLayout->addLayout(createButtonRow("Set", "Set", chargerButtons)); chargerTopLayout->addLayout(createButtonRow("StartStop", "Start", chargerButtons)); @@ -342,12 +371,12 @@ EnergyControlWnd::EnergyControlWnd(QWidget *parent) : connect(chargerEntryEdits["Current"], &QLineEdit::textChanged, this, &EnergyControlWnd::onChargerEntryChanged); connect(chargerEntryEdits["Term Voltage"], &QLineEdit::textChanged, this, &EnergyControlWnd::onChargerEntryChanged); - connect(chargerEntryEdits["Term Current"], &QLineEdit::textChanged, this, &EnergyControlWnd::onChargerEntryChanged); + chargerTermCurrentChanged = false; + connect(chargerTermCurrentCombo, QOverload::of(&QComboBox::currentIndexChanged), this, [this](int){ chargerTermCurrentChanged = true; }); // Initialize all entries as "not changed" chargerEntryChanged["Current"] = false; chargerEntryChanged["Term Voltage"] = false; - chargerEntryChanged["Term Current"] = false; connect(chargerButtons["Set"], &QPushButton::clicked, this, &EnergyControlWnd::onChargingConfigSet); connect(chargerButtons["StartStop"], &QPushButton::clicked, this, &EnergyControlWnd::onChargingStartStop); @@ -423,6 +452,7 @@ EnergyControlWnd::EnergyControlWnd(QWidget *parent) : paramLeftLayout->addLayout(createEntryRow("Charge Current", "mA", chdischEntryEdits)); paramLeftLayout->addLayout(createTimeEntryRow("Charge Relax Time", chdischTimeEdits)); paramLeftLayout->addLayout(createEntryRow("Cycles", "", chdischEntryEdits)); + chdischEntryEdits["Cycles"]->setText("1"); // --- Right side: radio buttons ("Start with") --- QVBoxLayout *paramRightLayout = new QVBoxLayout(); @@ -430,8 +460,13 @@ EnergyControlWnd::EnergyControlWnd(QWidget *parent) : QStringList radioNames = {"Discharge", "Charge"}; paramRightLayout->addLayout(createRadioButtonRow("Start with", 2, radioNames, chdischDirectionGroups)); paramRightLayout->addLayout(createCheckButtonRow("Write To File", chdischCheckBox)); + paramRightLayout->addLayout(createCheckButtonRow("Charge Markers", chdischCheckBox)); + chdischCheckBox["Charge Markers"]->setToolTip("Place Charge Start / Charge End markers and report the mAh charged into the battery between them"); paramRightLayout->addStretch(); + connect(chdischCheckBox["Charge Markers"], &QCheckBox::toggled, + this, &EnergyControlWnd::sigChargeMarkersEnabled); + connect(chdischDirectionGroups["Start with"], QOverload::of(&QButtonGroup::buttonClicked), this, &EnergyControlWnd::onChdischDirectionChanged); connect(chdischCheckBox["Write To File"], &QCheckBox::toggled, @@ -987,6 +1022,9 @@ void EnergyControlWnd::chDischStartDischargeRelaxTimeout() connect(chdischDischargeRelaxTimer, &QTimer::timeout, this, &EnergyControlWnd::onChDschDischargeRelaxTick); } + chdischDischargeRelaxRemaining = chdischTimeEdits["Discharge Relax Time"]->time(); + chdischTimeEdits["Discharge Relax Timeout"]->setTime(chdischDischargeRelaxRemaining); + chdischDischargeRelaxTimer->start(); } @@ -1003,6 +1041,9 @@ void EnergyControlWnd::chDischStartChargeRelaxTimeout() connect(chdischChargeRelaxTimer, &QTimer::timeout, this, &EnergyControlWnd::onChDschChargeRelaxTick); } + chdischChargeRelaxRemaining = chdischTimeEdits["Charge Relax Time"]->time(); + chdischTimeEdits["Charge Relax Timeout"]->setTime(chdischChargeRelaxRemaining); + chdischChargeRelaxTimer->start(); } @@ -1158,7 +1199,6 @@ bool EnergyControlWnd::chdischDoneCurrentStep() bool EnergyControlWnd::chdischMoveToNextStep() { - QTime now = QTime::currentTime(); if(chdischCycleSteps[chdischCurrentStepIndex].status != StepDone) return false; chdischCurrentStepIndex += 1; if(chdischCurrentStepIndex == 4) @@ -1166,7 +1206,15 @@ bool EnergyControlWnd::chdischMoveToNextStep() chdischCycleCompleted(); return true; } - else + chdischStartStep(); + chdischCycleSteps[chdischCurrentStepIndex].status = StepOngoing; + chdischUpdateCycleStatusSteps(chdischCycleSteps); + return true; +} + +void EnergyControlWnd::chdischStartStep() +{ + QTime now = QTime::currentTime(); { if(chdischCycleSteps[chdischCurrentStepIndex].state == ChDschCharge) { @@ -1237,13 +1285,23 @@ bool EnergyControlWnd::chdischMoveToNextStep() chDischStartDischargeRelaxTimeout(); } } - chdischCycleSteps[chdischCurrentStepIndex].status = StepOngoing; - chdischUpdateCycleStatusSteps(chdischCycleSteps); - return true; } void EnergyControlWnd::chdischCycleCompleted() { + chdischCyclesDone += 1; + if(chdischCyclesDone < chdischCyclesTotal) + { + for(int i = 0; i < 4; i++) + { + chdischCycleSteps[i].status = StepUnknown; + } + chdischCurrentStepIndex = 0; + chdischStartStep(); + chdischCycleSteps[chdischCurrentStepIndex].status = StepOngoing; + chdischUpdateCycleStatusSteps(chdischCycleSteps); + return; + } chdischStartStatusSet(false, ChDschUnknown); if(chdischCheckBox["Write To File"]->isChecked()) { @@ -1285,7 +1343,7 @@ void EnergyControlWnd::underVoltageStatusSet(bool enabled) break; break; case ModeChDisch: - if(chdischStartStopStatus && uVoltage) + if(chdischStartStopStatus && uVoltage && chdischCycleSteps[chdischCurrentStepIndex].state == ChDschDischarge) { chdischDoneCurrentStep(); chdischMoveToNextStep(); @@ -1425,6 +1483,7 @@ bool EnergyControlWnd::loadCurrentStatusSet(bool status) } loadStartStopStatus = status; loadButtons["Set"]->setEnabled(!loadStartStopStatus); + emit sigBatParamExtractionRunning(status && (loadModeGet() == LoadModeBatParamExtraction)); if(loadStartStopStatus) { loadButtons["StartStop"]->setText("Stop"); @@ -1507,9 +1566,10 @@ void EnergyControlWnd::chargerTermVoltageSet(float voltage) void EnergyControlWnd::chargerTermCurrentSet(int current) { - chargerEntryEdits["Term Current"]->blockSignals(true); - chargerEntryEdits["Term Current"]->setText(QString::number(current)); - chargerEntryEdits["Term Current"]->blockSignals(false); + chargerTermCurrentCombo->blockSignals(true); + int idx = chargerTermCurrentCombo->findData(current); + if(idx >= 0) chargerTermCurrentCombo->setCurrentIndex(idx); + chargerTermCurrentCombo->blockSignals(false); } bool EnergyControlWnd::chargerCurrentStatusSet(bool status) @@ -1533,7 +1593,7 @@ bool EnergyControlWnd::chargerCurrentStatusSet(bool status) chargerTimeEdits["Charging Stop Time"]->setEnabled(false); chargerEntryEdits["Current"]->setEnabled(false); chargerEntryEdits["Term Voltage"]->setEnabled(false); - chargerEntryEdits["Term Current"]->setEnabled(false); + chargerTermCurrentCombo->setEnabled(false); statusControlButtons["LoadDisable"]->setEnabled(false); statusControlButtons["PPathDisable"]->setEnabled(false); @@ -1554,7 +1614,7 @@ bool EnergyControlWnd::chargerCurrentStatusSet(bool status) chargerTimeEdits["Charging Stop Time"]->setTime(now); chargerEntryEdits["Current"]->setEnabled(true); chargerEntryEdits["Term Voltage"]->setEnabled(true); - chargerEntryEdits["Term Current"]->setEnabled(true); + chargerTermCurrentCombo->setEnabled(true); statusControlButtons["LoadDisable"]->setEnabled(true); statusControlButtons["PPathDisable"]->setEnabled(true); @@ -1585,12 +1645,12 @@ void EnergyControlWnd::chargingDone() QMessageBox *msgBox = new QMessageBox(this); switch(mode){ case ModeCharge: - msgBox->setIcon(QMessageBox::Warning); - msgBox->setWindowTitle("Warning"); + msgBox->setIcon(QMessageBox::Information); + msgBox->setWindowTitle("Charging"); + msgBox->setText("Charging completed"); if(chargingStartStopStatus) { emit sigChargingCurrentStatusChanged(false); - msgBox->setText("Charging completed"); } msgBox->setStandardButtons(QMessageBox::Ok); msgBox->show(); @@ -1598,7 +1658,7 @@ void EnergyControlWnd::chargingDone() break; break; case ModeChDisch: - if(chdischStartStopStatus) + if(chdischStartStopStatus && chdischCycleSteps[chdischCurrentStepIndex].state == ChDschCharge) { chdischDoneCurrentStep(); chdischMoveToNextStep(); @@ -1737,10 +1797,17 @@ bool EnergyControlWnd::chdischStartStatusSet(bool status, ChDschState state) chdischEntryEdits["Charge Current"]->setEnabled(false); chdischEntryEdits["Cycles"]->setEnabled(false); + chdischCyclesTotal = chdischEntryEdits["Cycles"]->text().toInt(); + if(chdischCyclesTotal < 1) chdischCyclesTotal = 1; + chdischCyclesDone = 0; + statusControlButtons["LoadDisable"]->setEnabled(false); statusControlButtons["PPathDisable"]->setEnabled(false); statusControlButtons["BatteryDisable"]->setEnabled(false); + if(chdischChargeRelaxTimer) chdischChargeRelaxTimer->stop(); + if(chdischDischargeRelaxTimer) chdischDischargeRelaxTimer->stop(); + chdischDischargeRelaxRemaining = chdischTimeEdits["Discharge Relax Time"]->time(); chdischTimeEdits["Discharge Relax Timeout"]->setTime(chdischDischargeRelaxRemaining); @@ -1755,6 +1822,13 @@ bool EnergyControlWnd::chdischStartStatusSet(bool status, ChDschState state) setTabControlsEnabled(loadTab, false); setTabControlsEnabled(chargerTab, false); + if(chdischDischargeIsBatParam()) + { + batParamViewButton->setVisible(false); + batParamViewButton->setEnabled(true); + emit sigBatParamProcedureActive(true); + } + chdischCycleSteps[chdischCurrentStepIndex].status = StepOngoing; chdischUpdateCycleStatusSteps(chdischCycleSteps); } @@ -1775,14 +1849,14 @@ bool EnergyControlWnd::chdischStartStatusSet(bool status, ChDschState state) chdischTimeEdits["Discharge Stop Time"]->setTime(now); chdischDischargeStop(); } - if(chdischCycleStartStep.state == ChDschChargeRelax) - { - chdischChargeRelaxTimer->stop(); - } - if(chdischCycleStartStep.state == ChDschDischargeRelax) - { - chdischDischargeRelaxTimer->stop(); - } + if(chdischChargeRelaxTimer) chdischChargeRelaxTimer->stop(); + if(chdischDischargeRelaxTimer) chdischDischargeRelaxTimer->stop(); + + chdischChargeRelaxRemaining = chdischTimeEdits["Charge Relax Time"]->time(); + chdischTimeEdits["Charge Relax Timeout"]->setTime(chdischChargeRelaxRemaining); + chdischDischargeRelaxRemaining = chdischTimeEdits["Discharge Relax Time"]->time(); + chdischTimeEdits["Discharge Relax Timeout"]->setTime(chdischDischargeRelaxRemaining); + chdischTimeEdits["Discharge Relax Time"]->setEnabled(true); chdischTimeEdits["Charge Relax Time"]->setEnabled(true); chdischComboBoxEdits["Discharge Profile"]->setEnabled(true); @@ -1799,6 +1873,11 @@ bool EnergyControlWnd::chdischStartStatusSet(bool status, ChDschState state) setTabControlsEnabled(loadTab, true); setTabControlsEnabled(chargerTab, true); + + batParamViewButton->setEnabled(false); + batParamViewButton->setVisible(false); + emit sigBatParamProcedureActive(false); + if(chdischCurrentStepIndex < 4) { chdischCycleSteps[chdischCurrentStepIndex].status = StepDone; @@ -1886,7 +1965,7 @@ void EnergyControlWnd::onLoadModeChanged(const QString &mode) standardWaveWidget->setVisible(mode == "Standard Wave"); customWaveWidget->setVisible(mode == "Custom Wave"); batParamWidget->setVisible(mode == "Bat Param Extraction"); - batParamViewButton->setVisible(mode == "Bat Param Extraction"); + batParamViewButton->setVisible(false); } LoadMode EnergyControlWnd::loadModeGet() @@ -1983,9 +2062,103 @@ QString EnergyControlWnd::getCustomWaveLibraryName(int index) void EnergyControlWnd::onWaveLibraryChanged() { refreshCustomWaveLibraryCombo(); + refreshBatParamLibraryCombo(); chdischRefreshLibraryCombo(); } +void EnergyControlWnd::refreshBatParamLibraryCombo() +{ + QString current = batParamLibraryCombo->currentText(); + QList waves = WaveformLibrary::instance().getWaves(); + int index; + + batParamLibraryCombo->blockSignals(true); + batParamLibraryCombo->clear(); + batParamLibraryCombo->addItem("