Skip to content

Mismatch Component Name in COSMO #2

Description

@swingg278
  1. The example does not work OTB, in the complist we have "full name" while in the "table_params" it is abbreviation.
  2. Code suggested is not very robust, please find below an updated version to ease step up.
  3. Cosmosac does not compile on Mac Book (Apple Silicon) - need to adapt Catch
    Find and replace:
    #define CATCH_TRAP() __asm__("int $3\n" : : ) to #define CATCH_TRAP() __builtin_trap()
import matplotlib.pyplot as plt
import cCOSMO
import os
from cosmopharm import SLE, COSMOSAC
from cosmopharm.utils import create_components, read_params

# Define all paths in one place
params_file = "data/sle/table_params.xlsx"
comp_list_path = "../../COSMOSAC/profiles/UD/complist.txt"
sigma3_path = "../../COSMOSAC/profiles/UD/sigma3/"

# Define components with mapping between abbreviated names (params) and full names (COSMO)
component_mapping = {
    'SIM': 'SIMVASTATINE',           # Mapping from params file to COSMO database
    'PLGA50': 'LACTIC_ACID',     # Example of mapping
}

# Abbreviated names used in the parameter file
params_names = ['SIM', 'PLGA50']

# Corresponding full names from the COSMO database
cosmo_names = [component_mapping[name] for name in params_names]

print(f"📋 Component mapping:")
for short, full in zip(params_names, cosmo_names):
    print(f"   {short} → {full}")

def verify_paths_exist(paths_dict):
    """Test function to verify that all required paths exist."""
    missing_paths = []
    for path_name, path in paths_dict.items():
        if not os.path.exists(path):
            missing_paths.append(f"{path_name}: {path}")
    
    if missing_paths:
        print("⚠️  Error: The following paths do not exist:")
        for missing_path in missing_paths:
            print(f"   - {missing_path}")
        return False
    else:
        print("✅ All required paths exist.")
        return True

# Verify paths before proceeding
print("Checking file paths...")
paths_to_check = {
    'params_file': params_file,
    'comp_list_path': comp_list_path,
    'sigma3_path': sigma3_path
}

if not verify_paths_exist(paths_to_check):
    print("Program stopped due to missing paths.")
    exit(1)

# Load parameters and create components
print("📋 Loading parameters...")
try:
    parameters = read_params(params_file)
    print(f"✅ Parameters successfully loaded from {params_file}")
    
    # Debug: show available components in parameters
    if hasattr(parameters, 'columns'):
        print("📊 Columns available in parameters:")
        for col in parameters.columns:
            print(f"   - {col}")
    
    if hasattr(parameters, 'index'):
        print("🧪 Components available in parameters:")
        for idx, comp in enumerate(parameters.index[:10]):  # Show the first 10
            print(f"   {idx+1}. {comp}")
        if len(parameters.index) > 10:
            print(f"   ... and {len(parameters.index) - 10} more")
    
    print(f"\n🔍 Attempting to create components: {params_names}")
    mixture = create_components(params_names, parameters)
    print("✅ Components successfully created")
    
except ValueError as e:
    print(f"❌ Error while creating components: {e}")
    print("\n💡 Suggestions:")
    print("1. Make sure the component names exactly match those in the parameter file")
    print("2. Check for case sensitivity (uppercase/lowercase)")
    print("3. Use component names that exist in the database")
    print("\nStopping the program.")
    exit(1)
except Exception as e:
    print(f"❌ Unexpected error while loading parameters: {e}")
    print("Stopping the program.")
    exit(1)

# Initialize COSMO-SAC model - replace paths with your local paths to COSMO profiles
db = cCOSMO.DelawareProfileDatabase(
    comp_list_path,
    sigma3_path)

# Debug: show a few available identifiers for diagnostics
print("🔍 Checking available identifiers in the database...")

# Try to normalize and add each component individually
for name in cosmo_names:
    try:
        print(f"Attempting to normalize identifier: '{name}'")
        iden = db.normalize_identifier(name)
        print(f"✅ Normalized identifier for '{name}': '{iden}'")
        db.add_profile(iden)
        print(f"✅ Profile added for '{name}'")
    except ValueError as e:
        print(f"❌ Error for '{name}': {e}")
        print(f"💡 Suggestion: Check that '{name}' exists in {comp_list_path}")
        # Show the first available identifiers for reference
        print("📋 Here are some available identifiers in the database:")
        with open(comp_list_path, 'r') as f:
            lines = f.readlines()[1:11]  # Skip header, show first 10
            for line in lines:
                if line.strip():
                    parts = line.strip().split()
                    if len(parts) >= 4:
                        print(f"   ID: {parts[0]}, Name: {parts[3]}")
        print("Stopping the program due to missing identifiers.")
        exit(1)

COSMO = cCOSMO.COSMO3(cosmo_names, db)

# Setup the COSMO-SAC model with components
actmodel = COSMOSAC(COSMO, mixture=mixture)

# Calculate solubility (SLE)
sle = SLE(actmodel=actmodel)
solubility = sle.solubility(mix='real')

# Output the solubility
print(solubility[['T', 'w', 'x']].to_string(index=False))

# Plot results
plt.plot(*solubility[['w','T']].values.T,'.-', label='Solubility (w)')

# Settings
plt.xlim(0,1)
plt.ylim(300,500)
# Adding title and labels
plt.title('Solubility vs. Temperature')
plt.ylabel("T / K")
xlabel = {'w':'Weight', 'x':'Mole'}
plt.xlabel(f"Weight fraction {mixture[0].name}")
plt.legend()
# Save the figure to a PNG or PDF file
plt.savefig('solubility_plot.png')  # Saves the plot as a PNG file
# plt.savefig('solubility_plot.pdf')  # Saves the plot as a PDF file
plt.show()

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions