-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
196 lines (169 loc) · 6.5 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
import dash
from dash import dcc, html
from dash.dependencies import Input, Output, State
import dash_bootstrap_components as dbc
import base64
import io
import pandas as pd
import numpy as np
import plotly.graph_objects as go
import os
import plotly.io as pio
# Initialize the Dash app
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
server = app.server
# App layout
app.layout = html.Div([
dcc.Upload(
id='upload-data',
children=html.Div(['Drag and Drop or ', html.A('Select Files')]),
style={
'width': '100%',
'height': '60px',
'lineHeight': '60px',
'borderWidth': '1px',
'borderStyle': 'dashed',
'borderRadius': '5px',
'textAlign': 'center',
'margin': '10px'
},
multiple=False
),
html.Div(id='output-data-upload'),
html.Div(
dcc.Graph(id='plot-display', style={'height': '80vh'}),
style={
'display': 'flex',
'justifyContent': 'center',
'alignItems': 'center',
'height': '80vh'
}
),
html.Button('Save Plot', id='save-plot-button'),
html.Div(id='save-output')
], style={'textAlign': 'center'})
@app.callback(
Output('output-data-upload', 'children'),
Output('plot-display', 'figure'),
[Input('upload-data', 'contents')],
State('upload-data', 'filename')
)
def update_output(contents, filename):
if contents is None:
return None, {}
content_type, content_string = contents.split(',')
decoded = base64.b64decode(content_string)
try:
if 'txt' in filename:
# Define the column names
columns = ["cycle number", "Q discharge/mA.h", "Q charge/mA.h", "Ewe/V", "(-Qo)/mA.h", "time/s", "<I>/mA", "Capacity/mA.h", "Efficiency/%"]
# Read the data, specifying the delimiter as a tab
data = pd.read_csv(io.StringIO(decoded.decode('utf-8')), sep='\t', skiprows=1, header=None, names=columns, engine='python')
# Convert the comma to a dot
# data = data.applymap(lambda x: float(x.replace(',', '.')) if isinstance(x, str) else x)
# Convert the comma to a dot if the numbers are in the European format
data = data.apply(lambda x: x.str.replace(',', '.') if x.dtype == "object" else x).astype(float)
# List of cycle numbers to plot
cycles_to_plot = [2,3,4,5,6,7,8,9]
# Define a colormap to get different colors for each cycle
colors = [
"blue",
"green",
"red",
"cyan",
"magenta",
"yellow",
"black",
"purple",
"pink",
]
fig = go.Figure()
for index, cycle_number in enumerate(cycles_to_plot):
cycle_data = data[data['cycle number'] == cycle_number]
if cycle_data.empty:
print(f"No data available for cycle number {cycle_number}.")
continue
max_charge = np.max(cycle_data['Q charge/mA.h'].values[:-945])
SoC_charge = cycle_data['Q charge/mA.h'].values[:-945] / max_charge
max_discharge = np.max(cycle_data['Q discharge/mA.h'].values[500:-5])
SoC_discharge = cycle_data['Q discharge/mA.h'].values[500:-5] / max_discharge
Ewe_V_charge = cycle_data['Ewe/V'].to_numpy()[:-945]
Ewe_V_discharge = cycle_data['Ewe/V'].to_numpy()[500:-5]
fig.add_trace(go.Scatter(x=SoC_charge, y=Ewe_V_charge, mode='lines', line=dict(color=colors[index], width=2, dash='dash'), name=f'Cycle {cycle_number} Charge'))
fig.add_trace(go.Scatter(x=SoC_discharge, y=Ewe_V_discharge, mode='lines', line=dict(color=colors[index], width=2), name=f'Cycle {cycle_number} Discharge'))
# Customizing the figure
fig.update_layout(
title="Potential vs. SoC for Multiple Cycles",
xaxis_title="State of Charge (SoC)",
yaxis_title="Ewe/V",
height=400,
width=600,
font=dict(
family="Arial",
size=13,
color="black"
),
xaxis=dict(
showline=True,
linewidth=2,
linecolor='black',
mirror=True,
showgrid=False,
tickfont=dict(
family="serif",
size=14
),
title_font=dict(
size=16
),
ticks="outside",
tickwidth=2,
tickcolor="black",
ticklen=5,
title_standoff=15
),
yaxis=dict(
showline=True,
linewidth=2,
linecolor='black',
mirror=True,
showgrid=False,
tickfont=dict(
family="serif",
size=14
),
title_font=dict(
size=16
),
ticks="outside",
tickwidth=2,
tickcolor="black",
ticklen=5,
title_standoff=15
),
plot_bgcolor="white",
paper_bgcolor="white",
showlegend=True
)
return f'File "{filename}" processed and plotted.', fig
else:
return 'Unsupported File Type', {}
except Exception as e:
print(e)
return f'Error processing "{filename}".', {}
@app.callback(
Output('save-output', 'children'),
[Input('save-plot-button', 'n_clicks')],
[State('plot-display', 'figure')]
)
def save_plot(n_clicks, current_figure):
if n_clicks is not None:
if not os.path.exists('saved_plots'):
os.mkdir('saved_plots')
path = os.path.join("saved_plots", f"saved_plot_{n_clicks}.png")
pio.write_image(current_figure, path)
return html.Div(f'Plot saved as {path}')
# if __name__ == '__main__':
# app.run_server(debug=False, port=os.environ.get('PORT', 8050))
if __name__ == '__main__':
app.run_server(debug=True)