Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /sustainability-software-lab_ca-biositing /analysis /composition /proximate_distribution_viz.py
| # --- | |
| # jupyter: | |
| # jupytext: | |
| # text_representation: | |
| # extension: .py | |
| # format_name: light | |
| # format_version: '1.5' | |
| # jupytext_version: 1.16.1 | |
| # kernelspec: | |
| # display_name: Python 3 | |
| # language: python | |
| # name: python3 | |
| # --- | |
| # # Aim Record Distribution Visualization (Altair Dashboard) | |
| # This script visualizes the distribution of individual data points for Proximate Analysis. | |
| # | |
| # **Multi-Selection Instructions:** | |
| # - Click bars in sidebars to filter. | |
| # - Shift-Click to select multiple items in a single sidebar. | |
| # - Click background of a sidebar to clear that filter. | |
| import os | |
| import pandas as pd | |
| import altair as alt | |
| from sqlalchemy import text | |
| # Force localhost for local database access | |
| os.environ["POSTGRES_HOST"] = "localhost" | |
| from ca_biositing.datamodels.database import get_engine | |
| from ca_biositing.visualization.theme import LBNL_PALETTE | |
| def main(): | |
| # 1. Query Data | |
| engine = get_engine() | |
| EXCLUDED_PROVIDERS = ["jaguar"] | |
| EXCLUDED_RESOURCES = [ | |
| "sargassum", "#n/a", "lab media", "alfalfa", | |
| "almond hulls and shells mix", "almond shells and hulls mix", "almond woodchips" | |
| ] | |
| query = text(""" | |
| WITH all_records AS ( | |
| SELECT record_id, resource_id, experiment_id, prepared_sample_id, qc_pass, note FROM proximate_record | |
| UNION ALL SELECT record_id, resource_id, experiment_id, prepared_sample_id, qc_pass, note FROM compositional_record | |
| UNION ALL SELECT record_id, resource_id, experiment_id, prepared_sample_id, qc_pass, note FROM ultimate_record | |
| UNION ALL SELECT record_id, resource_id, experiment_id, prepared_sample_id, qc_pass, note FROM icp_record | |
| UNION ALL SELECT record_id, resource_id, experiment_id, prepared_sample_id, qc_pass, note FROM xrf_record | |
| UNION ALL SELECT record_id, resource_id, experiment_id, prepared_sample_id, qc_pass, note FROM calorimetry_record | |
| UNION ALL SELECT record_id, resource_id, experiment_id, prepared_sample_id, qc_pass, note FROM xrd_record | |
| UNION ALL SELECT record_id, resource_id, experiment_id, prepared_sample_id, qc_pass, note FROM ftnir_record | |
| UNION ALL SELECT record_id, resource_id, experiment_id, prepared_sample_id, qc_pass, note FROM rgb_record | |
| UNION ALL SELECT record_id, resource_id, experiment_id, prepared_sample_id, qc_pass, note FROM fermentation_record | |
| UNION ALL SELECT record_id, resource_id, experiment_id, prepared_sample_id, qc_pass, note FROM pretreatment_record | |
| UNION ALL SELECT record_id, resource_id, experiment_id, prepared_sample_id, qc_pass, note FROM gasification_record | |
| ), | |
| proximate_sums AS ( | |
| SELECT | |
| r.resource_id, | |
| r.experiment_id, | |
| ( | |
| COALESCE(AVG(CASE WHEN p.name = 'moisture' THEN o.value END), 0) + | |
| COALESCE(AVG(CASE WHEN p.name = 'ash' OR p.name = 'ash solids' THEN o.value END), 0) + | |
| COALESCE( | |
| AVG(CASE WHEN p.name = 'volatile solids' THEN o.value END), | |
| 100 - COALESCE(AVG(CASE WHEN p.name = 'fixed carbon' THEN o.value END), 0) | |
| ) | |
| ) as prox_sum | |
| FROM observation o | |
| JOIN all_records r ON o.record_id = r.record_id | |
| JOIN parameter p ON o.parameter_id = p.id | |
| WHERE o.record_type = 'proximate analysis' | |
| GROUP BY r.resource_id, r.experiment_id | |
| ) | |
| SELECT | |
| obs.record_id, | |
| res.name as resource_name, | |
| pap.name as primary_ag_product, | |
| psam.name as prepared_sample_name, | |
| prov.codename as provider_code, | |
| param.name as analysis_param, | |
| obs.value, | |
| rec.qc_pass, | |
| ps.prox_sum, | |
| CASE | |
| WHEN LOWER(res.name) IN :excluded THEN 'Raw' | |
| WHEN LOWER(prov.codename) IN :excluded_providers THEN 'Raw' | |
| WHEN rec.qc_pass = 'fail' THEN 'Raw' | |
| WHEN ps.prox_sum != 0 AND (ps.prox_sum < 95 OR ps.prox_sum > 105) THEN 'Raw' | |
| ELSE 'Portal Compliant' | |
| END as data_status | |
| FROM observation obs | |
| JOIN all_records rec ON obs.record_id = rec.record_id | |
| LEFT JOIN resource res ON rec.resource_id = res.id | |
| LEFT JOIN primary_ag_product pap ON res.primary_ag_product_id = pap.id | |
| LEFT JOIN prepared_sample psam ON rec.prepared_sample_id = psam.id | |
| LEFT JOIN field_sample fs ON psam.field_sample_id = fs.id | |
| LEFT JOIN provider prov ON fs.provider_id = prov.id | |
| LEFT JOIN parameter param ON obs.parameter_id = param.id | |
| LEFT JOIN proximate_sums ps ON rec.resource_id = ps.resource_id AND COALESCE(rec.experiment_id, -1) = COALESCE(ps.experiment_id, -1) | |
| WHERE obs.record_type = 'proximate analysis' | |
| """) | |
| with engine.connect() as conn: | |
| df = pd.read_sql(query, conn, params={"excluded": tuple(EXCLUDED_RESOURCES), "excluded_providers": tuple(EXCLUDED_PROVIDERS)}) | |
| if df.empty: | |
| print("No Proximate Analysis data found.") | |
| return | |
| # Data Cleaning | |
| df['value'] = pd.to_numeric(df['value'], errors='coerce') | |
| df = df.dropna(subset=['value']).copy() | |
| df['qc_pass'] = df['qc_pass'].fillna('unknown') | |
| df['provider_code'] = df['provider_code'].fillna('unknown') | |
| df['primary_ag_product'] = df['primary_ag_product'].fillna('unknown') | |
| # 2. Build Altair Dashboard | |
| # Selections | |
| status_sel = alt.selection_point(name='status_selector', fields=['data_status'], toggle=True) | |
| res_sel = alt.selection_point(name='res_selector', fields=['resource_name'], toggle=True) | |
| prod_sel = alt.selection_point(name='prod_selector', fields=['primary_ag_product'], toggle=True) | |
| prov_sel = alt.selection_point(name='prov_selector', fields=['provider_code'], toggle=True) | |
| qc_sel = alt.selection_point(name='qc_selector', fields=['qc_pass'], toggle=True) | |
| # Combined filters | |
| all_filters = status_sel & res_sel & prod_sel & prov_sel & qc_sel | |
| # Base Chart | |
| base = alt.Chart(df) | |
| # Main Chart with Layering: Boxplot (Stats) + Circle (Points) | |
| # Applying filter at the layer level | |
| main_base = base.transform_filter(all_filters) | |
| boxplot = main_base.mark_boxplot(extent='min-max', size=30, color='#00313C', opacity=0.3).encode( | |
| x=alt.X('analysis_param:N', title='Analysis Parameter', axis=alt.Axis(labelAngle=0)), | |
| y=alt.Y('value:Q', title='Measured Value') | |
| ) | |
| points = main_base.mark_circle(size=60, opacity=0.7).encode( | |
| x=alt.X('analysis_param:N'), | |
| y=alt.Y('value:Q'), | |
| xOffset='jitter:Q', | |
| color=alt.Color('resource_name:N', scale=alt.Scale(range=LBNL_PALETTE), legend=None), | |
| tooltip=['record_id', 'prepared_sample_name', 'resource_name', 'primary_ag_product', 'provider_code', 'data_status', 'qc_pass', 'value', 'prox_sum'] | |
| ).transform_calculate( | |
| jitter='sqrt(-2*log(random()))*cos(2*PI*random())' | |
| ) | |
| main_chart = (boxplot + points).properties( | |
| width=600, | |
| height=600, | |
| title='Proximate Analysis Distribution (Individual Points + Summary Stats)' | |
| ) | |
| # Sidebar Filter Factory | |
| def make_filter_bar(field, title, selection): | |
| return base.mark_bar().encode( | |
| y=alt.Y(f'{field}:N', sort='-x', title=None), | |
| x=alt.X('count():Q', title=None, axis=alt.Axis(labels=False, ticks=False)), | |
| color=alt.condition(selection, alt.value('#00B5E2'), alt.value('lightgray')), | |
| tooltip=[alt.Tooltip(field, title=title), alt.Tooltip('count()', title='Count')] | |
| ).add_params(selection).properties( | |
| width=180, | |
| height=alt.Step(20), | |
| title=alt.TitleParams(text=title, fontSize=13, anchor='start') | |
| ) | |
| # All requested sidebars | |
| sidebar = alt.vconcat( | |
| make_filter_bar('data_status', 'Data Status', status_sel), | |
| make_filter_bar('resource_name', 'Resource Name', res_sel), | |
| make_filter_bar('primary_ag_product', 'Ag Product', prod_sel), | |
| make_filter_bar('provider_code', 'Provider Code', prov_sel), | |
| make_filter_bar('qc_pass', 'QC Pass Status', qc_sel) | |
| ).resolve_scale(y='independent') | |
| # Final Assembly | |
| dashboard = alt.hconcat( | |
| sidebar, | |
| main_chart | |
| ).resolve_scale( | |
| color='independent' | |
| ).configure_view( | |
| stroke=None | |
| ).configure_title( | |
| anchor='start', | |
| fontSize=18 | |
| ) | |
| # 4. Save | |
| os.makedirs("exports/plots/composition", exist_ok=True) | |
| export_path = "exports/plots/composition/proximate_distribution.html" | |
| # Using the built-in save with default options is most reliable | |
| dashboard.save(export_path) | |
| # Also save to the "dashboard" named file for safety | |
| dashboard.save("exports/plots/composition/proximate_distribution_dashboard.html") | |
| print(f"Dashboard saved to {export_path}") | |
| if __name__ == "__main__": | |
| main() | |
Xet Storage Details
- Size:
- 8.83 kB
- Xet hash:
- 5e255f337b0679dae8b1372027c925625d03bf6d7a3514412dd3fe33a39fe204
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.