|
""" |
|
Analyze Results | New York |
|
Copyright (c) 2024 Cannlytics |
|
|
|
Authors: Keegan Skeate <https://github.com/keeganskeate> |
|
Created: 6/26/2024 |
|
Updated: 6/26/2024 |
|
License: MIT License <https://github.com/cannlytics/cannabis-data-science/blob/main/LICENSE> |
|
""" |
|
|
|
import base64 |
|
from datetime import datetime |
|
import json |
|
import os |
|
import shutil |
|
import tempfile |
|
from typing import List, Optional |
|
|
|
|
|
from cannlytics.data.cache import Bogart |
|
from cannlytics.data.coas import CoADoc |
|
from cannlytics.data.coas import standardize_results |
|
from cannlytics.data.coas.parsing import get_coa_files, parse_coa_pdfs |
|
from cannlytics.firebase import initialize_firebase |
|
from cannlytics.compounds import cannabinoids, terpenes |
|
from dotenv import dotenv_values |
|
import pandas as pd |
|
import pdfplumber |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
pdf_dir = 'D://data/new-york' |
|
|
|
|
|
pdfs = get_coa_files(pdf_dir) |
|
pdfs.sort(key=os.path.getmtime) |
|
print('Found %i PDFs.' % len(pdfs)) |
|
|
|
|
|
parser = CoADoc() |
|
cache = Bogart('D://data/.cache/results-ny.jsonl') |
|
verbose = True |
|
all_results = [] |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
extracted_data = [] |
|
for pdf_file in pdfs: |
|
try: |
|
with pdfplumber.open(pdf_file) as pdf: |
|
text = pdf.pages[0].extract_text() + '\n' |
|
extracted_data.append({'file': pdf_file, 'text': text}) |
|
except: |
|
pass |
|
|
|
|
|
coas = {} |
|
unidentified_coas = [] |
|
labs = [ |
|
'Phyto-farma Labs', |
|
'Phyto-Farma Labs', |
|
'Kaycha Labs', |
|
'Keystone State Testing', |
|
'Green Analytics', |
|
] |
|
for data in extracted_data: |
|
for lab in labs: |
|
if lab in data['text']: |
|
lab_coas = coas.get(lab, []) |
|
lab_coas.append(data['file']) |
|
coas[lab] = lab_coas |
|
break |
|
else: |
|
unidentified_coas.append(data['file']) |
|
print('Number of unidentified COAs:', len(unidentified_coas)) |
|
|
|
|
|
if unidentified_coas: |
|
pdf = pdfplumber.open(unidentified_coas[0]) |
|
page = pdf.pages[0] |
|
im = page.to_image(resolution=300) |
|
im.debug_tablefinder() |
|
|
|
|
|
for lab, lab_coas in coas.items(): |
|
print(lab, len(lab_coas)) |
|
|
|
|
|
|
|
|
|
|
|
|
|
from cannlytics.data.coas.algorithms.kaycha import parse_kaycha_coa |
|
|
|
|
|
lab_coas = coas['Kaycha Labs'] |
|
for pdf in lab_coas: |
|
if not os.path.exists(pdf): |
|
if verbose: print(f'PDF not found: {pdf}') |
|
continue |
|
pdf_hash = cache.hash_file(pdf) |
|
if cache is not None: |
|
if cache.get(pdf_hash): |
|
if verbose: print('Cached:', pdf) |
|
all_results.append(cache.get(pdf_hash)) |
|
continue |
|
try: |
|
coa_data = parse_kaycha_coa(parser, pdf) |
|
all_results.append(coa_data) |
|
if cache is not None: cache.set(pdf_hash, coa_data) |
|
print('Parsed:', pdf) |
|
except: |
|
print('Error:', pdf) |
|
|
|
|
|
|
|
|
|
|
|
|
|
from cannlytics.data.coas.algorithms.keystone import parse_keystone_coa |
|
|
|
lab_coas = coas['Keystone State Testing'] |
|
for pdf in lab_coas: |
|
pdf_hash = cache.hash_file(pdf) |
|
if cache is not None: |
|
if cache.get(pdf_hash): |
|
if verbose: print('Cached:', pdf) |
|
all_results.append(cache.get(pdf_hash)) |
|
continue |
|
try: |
|
coa_data = parse_keystone_coa(parser, pdf) |
|
all_results.append(coa_data) |
|
if cache is not None: cache.set(pdf_hash, coa_data) |
|
print('Parsed:', pdf) |
|
except Exception as e: |
|
print('Error:', pdf) |
|
print(e) |
|
|
|
|
|
|
|
|
|
|
|
|
|
from cannlytics.data.coas.algorithms.phytofarma import parse_phyto_farma_coa |
|
|
|
|
|
lab_coas = coas['Phyto-Farma Labs'] + coas['Phyto-farma Labs'] |
|
for pdf in lab_coas: |
|
pdf_hash = cache.hash_file(pdf) |
|
if cache is not None: |
|
if cache.get(pdf_hash): |
|
if verbose: print('Cached:', pdf) |
|
all_results.append(cache.get(pdf_hash)) |
|
continue |
|
try: |
|
coa_data = parse_phyto_farma_coa(parser, pdf) |
|
all_results.append(coa_data) |
|
if cache is not None: cache.set(pdf_hash, coa_data) |
|
print('Parsed:', pdf) |
|
except Exception as e: |
|
print('Error:', pdf) |
|
print(e) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
lab_coas = [ |
|
'D://data/new-york\\NYSCannabis\\pdfs\\1c3sh5h-coa-1.pdf', |
|
'D://data/new-york\\NYSCannabis\\pdfs\\1cp4tdr-coa-1.pdf', |
|
'D://data/new-york\\NYSCannabis\\pdfs\\1c91onw-coa-1.pdf' |
|
] |
|
|
|
|
|
|
|
|
|
|
|
|
|
def encode_image(image_path): |
|
"""Encode an image as a base64 string.""" |
|
with open(image_path, 'rb') as image_file: |
|
return base64.b64encode(image_file.read()).decode('utf-8') |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
from cannlytics.data.coas import standardize_results |
|
from cannlytics.compounds import cannabinoids, terpenes |
|
import matplotlib.pyplot as plt |
|
from matplotlib.dates import MonthLocator, DateFormatter |
|
import seaborn as sns |
|
|
|
|
|
assets_dir = r'C:\Users\keega\Documents\cannlytics\cannabis-data-science\season-4\165-labels\presentation\images\figures' |
|
plt.style.use('seaborn-v0_8-whitegrid') |
|
plt.rcParams.update({ |
|
'font.family': 'Times New Roman', |
|
'font.size': 24, |
|
}) |
|
|
|
|
|
def format_date(x, pos): |
|
try: |
|
return pd.to_datetime(x).strftime('%b %d, %Y') |
|
except ValueError: |
|
return '' |
|
|
|
|
|
|
|
cache = Bogart('D://data/.cache/results-ny.jsonl') |
|
results = cache.to_df() |
|
print('Number of results:', len(results)) |
|
|
|
|
|
compounds = list(cannabinoids.keys()) + list(terpenes.keys()) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
results['date'] = pd.to_datetime(results['date_tested'], format='mixed') |
|
results['week'] = results['date'].dt.to_period('W').astype(str) |
|
results['month'] = results['date'].dt.to_period('M').astype(str) |
|
results = standardize_results(results, compounds) |
|
|
|
|
|
results = results.sort_values('date') |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
sample = results.dropna(subset=['date']) |
|
plt.figure(figsize=(18, 8)) |
|
ax = sns.countplot(data=sample, x='week', hue='lab', palette='tab10') |
|
plt.title('Number of Lab Results by Lab', pad=10) |
|
plt.xlabel('') |
|
plt.ylabel('Number of Results') |
|
plt.xticks(rotation=45) |
|
ticks = ax.get_xticks() |
|
ax.set_xticks(ticks[::4]) |
|
ax.set_xticklabels([format_date(item.get_text(), None) for item in ax.get_xticklabels()]) |
|
plt.legend(loc='upper right') |
|
plt.tight_layout() |
|
plt.savefig(os.path.join(assets_dir, 'lab-timeseries.png')) |
|
plt.show() |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
producer_names = { |
|
'Hudson Valley Cannabis LLC': 'Hudson Cannabis', |
|
'MFNY Processor LLC': 'MFNY', |
|
'': 'Unknown', |
|
'Hepworth Ag, INC': 'Hepworth Ag', |
|
'Processing': 'Unknown', |
|
'MFNY PROCESSOR LLC': 'MFNY', |
|
'Hudson Valley Hemp Company': 'Hudson Cannabis', |
|
'Hepworth Ag, Inc.': 'Hepworth Ag', |
|
'NYHO Labs LLC': 'NYHO Labs', |
|
'Hudson Valley Hemp Company, LLC': 'Hudson Cannabis', |
|
'Cirona Labs': 'Cirona Labs', |
|
'Hudson Cannabis c/o Hudson Valley Hemp Company, LLC': 'Hudson Cannabis', |
|
'Milton, NY, 12547, US': 'Unknown', |
|
} |
|
results['producer_dba'] = results['producer'].map(producer_names) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
sample = results.dropna(subset=['date']) |
|
plt.figure(figsize=(18, 8)) |
|
ax = sns.countplot(data=sample, x='week', hue='producer_dba', palette='tab10') |
|
plt.title('Number of Lab Results by Producer', pad=10) |
|
plt.xlabel('') |
|
plt.ylabel('Number of Results') |
|
plt.xticks(rotation=45) |
|
ticks = ax.get_xticks() |
|
ax.set_xticks(ticks[::4]) |
|
ax.set_xticklabels([format_date(item.get_text(), None) for item in ax.get_xticklabels()]) |
|
plt.legend(loc='upper right') |
|
plt.tight_layout() |
|
plt.savefig(os.path.join(assets_dir, 'producer-timeseries.png')) |
|
plt.show() |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
flower_types = [ |
|
'Plant, Flower - Cured', |
|
'Flower', |
|
] |
|
preroll_types = [ |
|
'Plant, Preroll', |
|
] |
|
infused_preroll_types = [ |
|
'Plant, Enhanced Preroll', |
|
] |
|
concentrate_types = [ |
|
'Concentrate', |
|
'Derivative', |
|
'Concentrates & Extract, Vape Cartridge', |
|
'Concentrates & Extract, Live Rosin', |
|
'Concentrates & Extract, Concentrate', |
|
'Concentrates & Extract, Rosin', |
|
'Concentrates & Extract, Distillate' |
|
] |
|
edible_types = [ |
|
'Edible', |
|
'Ingestible, Gummy', |
|
'Ingestible, Edibles', |
|
] |
|
|
|
|
|
def assign_product_type(x): |
|
if x in flower_types: |
|
return 'Flower' |
|
if x in concentrate_types: |
|
return 'Concentrate' |
|
if x in edible_types: |
|
return 'Edible' |
|
if x in preroll_types: |
|
return 'Preroll' |
|
if x in infused_preroll_types: |
|
return 'Infused Preroll' |
|
return 'Other' |
|
|
|
|
|
|
|
results['standard_product_type'] = results['product_type'].apply(assign_product_type) |
|
|
|
|
|
product_type_palette = { |
|
'Flower': '#2ca02c', |
|
'Concentrate': '#ff7f0e', |
|
'Edible': '#8c564b', |
|
'Preroll': '#1f77b4', |
|
'Infused Preroll': '#9467bd', |
|
'Other': '#d62728' |
|
} |
|
|
|
|
|
sample = results.dropna(subset=['date']) |
|
sample.sort_values('date', inplace=True) |
|
plt.figure(figsize=(18, 8)) |
|
ax = sns.countplot(data=sample, x='week', hue='standard_product_type', palette=product_type_palette) |
|
plt.title('Number of Lab Results by Product Type', pad=10) |
|
plt.xlabel('') |
|
plt.ylabel('Number of Results') |
|
plt.xticks(rotation=45) |
|
ticks = ax.get_xticks() |
|
ax.set_xticks(ticks[::4]) |
|
|
|
ax.set_xticklabels([format_date(item.get_text(), None) for item in ax.get_xticklabels()]) |
|
plt.legend(loc='upper right') |
|
plt.tight_layout() |
|
plt.savefig(os.path.join(assets_dir, 'product-type-timeseries.png')) |
|
plt.show() |
|
|
|
|
|
plt.figure(figsize=(12, 12)) |
|
results['standard_product_type'].value_counts().plot.pie( |
|
autopct='%1.1f%%', |
|
startangle=90, |
|
colors=[product_type_palette[key] for key in results['standard_product_type'].value_counts().index] |
|
) |
|
plt.title('Proportions of Product Types') |
|
plt.ylabel('') |
|
plt.tight_layout() |
|
plt.savefig(os.path.join(assets_dir, 'product-type-pie.png')) |
|
plt.show() |
|
|
|
|
|
sample = results.loc[results['standard_product_type'] != 'Other'] |
|
plt.figure(figsize=(18, 8)) |
|
ax = sns.scatterplot( |
|
data=sample, |
|
y='total_cannabinoids', |
|
x='total_terpenes', |
|
hue='standard_product_type', |
|
palette=product_type_palette, |
|
s=200 |
|
) |
|
plt.title('Total Cannabinoids to Total Terpenes', pad=10) |
|
plt.ylabel('Total Cannabinoids (%)') |
|
plt.xlabel('Total Terpenes (%)') |
|
plt.xlim(0, 10.5) |
|
plt.ylim(0, 100) |
|
legend = ax.legend(title='Product Type', bbox_to_anchor=(1.05, 1), loc='upper left') |
|
for leg_entry in legend.legendHandles: |
|
leg_entry.set_sizes([200]) |
|
plt.tight_layout() |
|
plt.savefig(os.path.join(assets_dir, 'cannabinoids-to-terpenes.png')) |
|
plt.show() |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
import statsmodels.api as sm |
|
|
|
|
|
compound = 'thca' |
|
sample = results[results['standard_product_type'] == 'Flower'] |
|
avg = results.groupby(['month', 'standard_product_type'])[compound].mean().reset_index() |
|
avg['month'] = pd.to_datetime(avg['month'], errors='coerce') |
|
flower_data = avg[avg['standard_product_type'] == 'Flower'] |
|
flower_data = flower_data.dropna(subset=[compound, 'month']) |
|
flower_data['month_num'] = range(len(flower_data)) |
|
X = sm.add_constant(flower_data['month_num']) |
|
y = flower_data[compound] |
|
model = sm.OLS(y, X).fit() |
|
slope = model.params['month_num'] |
|
direction = '+' if slope > 0 else '-' |
|
plt.figure(figsize=(13, 8)) |
|
plt.plot(flower_data['month'], flower_data[compound], 'bo-', label='Avg. THCA by month', linewidth=2) |
|
plt.plot(flower_data['month'], model.predict(X), 'r-', label=f'Trend: {direction}{slope:.2f}% per month', linewidth=2) |
|
plt.scatter(sample['date'], sample[compound], color='lightblue', s=80) |
|
plt.title('Trend of THCA in Flower in New York', pad=10) |
|
plt.xlabel('') |
|
plt.ylabel('THCA') |
|
plt.legend() |
|
plt.xticks(rotation=45) |
|
plt.tight_layout() |
|
plt.savefig(os.path.join(assets_dir, 'average-thca-by-month.png')) |
|
plt.show() |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def create_scatter_plot(x_col, y_col, title, x_label, y_label, filename): |
|
plt.figure(figsize=(18, 8)) |
|
ax = sns.scatterplot( |
|
data=results, |
|
x=x_col, |
|
y=y_col, |
|
hue='standard_product_type', |
|
palette=product_type_palette, |
|
s=200 |
|
) |
|
plt.title(title, pad=10) |
|
plt.xlabel(x_label) |
|
plt.ylabel(y_label) |
|
legend = ax.legend(title='Product Type', bbox_to_anchor=(1.05, 1), loc='upper left') |
|
for leg_entry in legend.legendHandles: |
|
leg_entry.set_sizes([200]) |
|
plt.tight_layout() |
|
plt.savefig(os.path.join(assets_dir, filename)) |
|
plt.show() |
|
|
|
|
|
|
|
create_scatter_plot( |
|
y_col='alpha_humulene', |
|
x_col='beta_caryophyllene', |
|
title='Ratio of Alpha-Humulene to Beta-Caryophyllene by Product Type', |
|
y_label='Alpha-Humulene', |
|
x_label='Beta-Caryophyllene', |
|
filename='alpha_humulene_to_beta_caryophyllene.png' |
|
) |
|
|
|
|
|
create_scatter_plot( |
|
y_col='beta_pinene', |
|
x_col='d_limonene', |
|
title='Ratio of Beta-Pinene to D-Limonene by Product Type', |
|
y_label='Beta-Pinene', |
|
x_label='D-Limonene', |
|
filename='beta_pinene_to_d_limonene.png' |
|
) |
|
|
|
|
|
|
|
|
|
|
|
|
|
from patsy import dmatrices |
|
|
|
|
|
compound = 'thca' |
|
product_type = 'Flower' |
|
sample = results[results['standard_product_type'] == product_type] |
|
sample['month'] = pd.to_datetime(sample['month'], errors='coerce') |
|
sample = sample.dropna(subset=['month']) |
|
sample['month_num'] = sample['month'].rank(method='dense').astype(int) - 1 |
|
y, X = dmatrices('thca ~ month_num + C(lab) + C(dba)', data=sample, return_type='dataframe') |
|
model = sm.OLS(y, X).fit() |
|
print(model.summary().as_latex()) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
last_test_date = results['date'].max().strftime('%Y-%m-%d') |
|
outfile = f'D://data/new-york/ny-results-{last_test_date}.xlsx' |
|
results.to_excel(outfile, index=False) |
|
print('Saved:', outfile) |
|
|