holyhigh666 commited on
Commit
d6889ed
·
verified ·
1 Parent(s): d3e3413

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +202 -0
app.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ import plotly.graph_objects as go
4
+ from pymatgen.core import Structure
5
+ from pymatgen.analysis.diffraction.xrd import XRDCalculator
6
+ import tempfile # To create temporary files for download
7
+ import os
8
+ import traceback # For detailed error logging
9
+
10
+ # Define the core processing function
11
+ def generate_xrd_pattern(cif_file):
12
+ """
13
+ Processes an uploaded CIF file, calculates the XRD pattern,
14
+ and returns a Plotly figure, a Pandas DataFrame, and the path to a CSV file.
15
+
16
+ Args:
17
+ cif_file: A file object from Gradio's gr.File component.
18
+
19
+ Returns:
20
+ tuple: (plotly_fig, dataframe, csv_filepath) or (None, None, None) if processing fails.
21
+ plotly_fig: A Plotly figure object.
22
+ dataframe: A Pandas DataFrame containing the peak data.
23
+ csv_filepath: Path to the generated temporary CSV file.
24
+ """
25
+ if cif_file is None:
26
+ # Return None for all outputs if no file is uploaded
27
+ return None, None, None
28
+
29
+ try:
30
+ # Get the temporary path of the uploaded file
31
+ cif_filepath = cif_file.name
32
+
33
+ # 1. Load structure from CIF
34
+ structure = Structure.from_file(cif_filepath)
35
+
36
+ # 2. Calculate XRD pattern
37
+ calculator = XRDCalculator()
38
+ pattern = calculator.get_pattern(structure, two_theta_range=(10, 90)) # Adjust range if needed
39
+
40
+ # 3. Prepare data for DataFrame and Plot
41
+ miller_indices = []
42
+ for hkl_list in pattern.hkls:
43
+ if hkl_list:
44
+ # Format Miller indices: take the first set if multiple exist for a peak
45
+ #h, k, l = hkl_list[0]['hkl']
46
+ # Use standard tuple representation for display
47
+ miller_indices.append(str(tuple(hkl_list[0]['hkl'])))
48
+ # Alternative concise string: miller_indices.append(f"({h}{k}{l})")
49
+ else:
50
+ miller_indices.append("N/A")
51
+
52
+ # Round data for cleaner display
53
+ two_theta_rounded = [round(x, 3) for x in pattern.x]
54
+ intensity_rounded = [round(y, 3) for y in pattern.y]
55
+
56
+ data = pd.DataFrame({
57
+ "2θ (°)": two_theta_rounded,
58
+ "Intensity (norm)": intensity_rounded, # Assuming normalized intensity from pymatgen
59
+ "Miller Indices (hkl)": miller_indices
60
+ })
61
+
62
+ # --- Create Plotly Figure ---
63
+ fig = go.Figure()
64
+
65
+ fig.add_trace(go.Bar(
66
+ x=data["2θ (°)"],
67
+ y=data["Intensity (norm)"],
68
+ hovertext=[f"2θ: {t:.3f}<br>Intensity: {i:.1f}<br>hkl: {m}"
69
+ for t, i, m in zip(data["2θ (°)"], data["Intensity (norm)"], data["Miller Indices (hkl)"])],
70
+ hoverinfo="text", # Show only the custom hover text
71
+ width=0.1, # Slightly wider bars might look better
72
+ marker_color="#4682B4", # SteelBlue color
73
+ marker_line_width=0,
74
+ name='Peaks'
75
+ ))
76
+
77
+ # Customize Layout
78
+ max_intensity = data["Intensity (norm)"].max() if not data.empty else 100
79
+ min_2theta = data["2θ (°)"].min() if not data.empty else 10
80
+ max_2theta = data["2θ (°)"].max() if not data.empty else 90
81
+
82
+ fig.update_layout(
83
+ title=dict(text=f"Simulated XRD Pattern: {structure.formula}", x=0.5, xanchor='center'), # Centered title
84
+ xaxis_title="2θ (°)",
85
+ yaxis_title="Intensity (Arb. Unit)",
86
+ xaxis_title_font_size=16,
87
+ yaxis_title_font_size=16,
88
+ xaxis=dict(
89
+ range=[min_2theta - 2, max_2theta + 2], # Slightly tighter range
90
+ showline=True, linewidth=1.5, linecolor='black', mirror=True,
91
+ ticks='outside', tickwidth=1.5, tickcolor='black',
92
+ tickfont_size=12
93
+ ),
94
+ yaxis=dict(
95
+ range=[0, max_intensity * 1.05],
96
+ showline=True, linewidth=1.5, linecolor='black', mirror=True,
97
+ ticks='outside', tickwidth=1.5, tickcolor='black',
98
+ tickfont_size=12
99
+ ),
100
+ plot_bgcolor='white',
101
+ paper_bgcolor='white', # Ensure background outside plot is also white
102
+ bargap=0.9, # Adjust gap based on new width
103
+ font=dict(family="Arial, sans-serif", size=12, color="black"),
104
+ margin=dict(l=70, r=30, t=60, b=70),
105
+ # Adjust height/width as needed, None allows more flexibility
106
+ height=450,
107
+ # width=None # Let Gradio manage width for responsiveness
108
+ )
109
+ fig.update_xaxes(showgrid=False, zeroline=False)
110
+ fig.update_yaxes(showgrid=False, zeroline=False)
111
+
112
+
113
+ # --- Create CSV File ---
114
+ with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.csv', newline='', encoding='utf-8') as temp_csv:
115
+ data.to_csv(temp_csv.name, index=False)
116
+ csv_filepath_out = temp_csv.name
117
+
118
+ # Return figure, dataframe, and csv path
119
+ return fig, data, csv_filepath_out
120
+
121
+ except Exception as e:
122
+ print(f"Error processing file: {e}") # Log error to console
123
+ traceback.print_exc() # Print detailed traceback
124
+ # Raise a Gradio error to display it in the UI
125
+ raise gr.Error(f"Failed to process CIF file. Please ensure it's a valid CIF. Error: {str(e)}")
126
+ # return None, None, None # Alternative: clear outputs
127
+
128
+
129
+ # --- Build Gradio Interface ---
130
+ # Use a theme for better aesthetics
131
+ theme = gr.themes.Soft(
132
+ primary_hue="sky", # Adjust colors if desired
133
+ secondary_hue="blue",
134
+ neutral_hue="slate"
135
+ )
136
+
137
+ with gr.Blocks(theme=theme, title="XRD Pattern Generator") as demo:
138
+ gr.Markdown(
139
+ """
140
+ # XRD Pattern Simulator from CIF
141
+ Upload a Crystallographic Information File (.cif) to generate its simulated
142
+ X-ray Diffraction (XRD) pattern using pymatgen.
143
+ """
144
+ )
145
+
146
+ with gr.Row():
147
+ with gr.Column(scale=1): # Column for input
148
+ cif_input = gr.File(
149
+ label="Upload CIF File",
150
+ file_types=[".cif"],
151
+ type="filepath" # Use filepath directly
152
+ )
153
+ gr.Markdown("*(Example source: [Crystallography Open Database](http://crystallography.net/cod/))*")
154
+
155
+ with gr.Column(scale=3): # Column for outputs, make it wider
156
+ with gr.Tabs():
157
+ with gr.TabItem("📊 XRD Plot"):
158
+ # Wrap plot in a column/row to help with centering if needed,
159
+ # but Plotly's layout(title_x=0.5) is the primary centering method for the title.
160
+ # The plot component itself usually fills container width.
161
+ plot_output = gr.Plot(label="XRD Pattern") # Label might be redundant with Tab title
162
+
163
+ with gr.TabItem("📄 Peak Data Table"):
164
+ dataframe_output = gr.DataFrame(
165
+ label="Calculated Peak Data",
166
+ headers=["2θ (°)", "Intensity (norm)", "Miller Indices (hkl)"],
167
+ wrap=True, # Allow text wrapping for long indices
168
+ #max_rows=15, # Limit initial display height
169
+ #overflow_row_behaviour='paginate' # Add pagination if many rows
170
+ )
171
+
172
+ with gr.TabItem("⬇️ Download Data"):
173
+ csv_output = gr.File(label="Download Peak Data as CSV")
174
+ gr.Markdown("Click the link above to download the full data.")
175
+
176
+
177
+ # Clear outputs when input is cleared
178
+ cif_input.clear(
179
+ lambda: (None, None, None),
180
+ inputs=[],
181
+ outputs=[plot_output, dataframe_output, csv_output]
182
+ )
183
+
184
+ # Connect the input changes to the processing function
185
+ cif_input.change(
186
+ fn=generate_xrd_pattern,
187
+ inputs=cif_input,
188
+ outputs=[plot_output, dataframe_output, csv_output],
189
+ # show_progress="full" # Show progress indicator during calculation
190
+ )
191
+ examples = gr.Examples(
192
+ examples=[
193
+ ["example_cif/NaCl_1000041.cif"],
194
+ ["example_cif/Al2O3_1000017.cif"],
195
+ ],
196
+ inputs=[cif_input],
197
+ )
198
+
199
+ # --- Launch the App ---
200
+ if __name__ == "__main__":
201
+ demo.launch()
202
+ # Add share=True for a public link: demo.launch(share=True)