quick-pp 0.2.76__tar.gz → 0.2.77__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. {quick_pp-0.2.76 → quick_pp-0.2.77}/PKG-INFO +1 -1
  2. {quick_pp-0.2.76 → quick_pp-0.2.77}/pyproject.toml +1 -1
  3. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/__init__.py +1 -1
  4. quick_pp-0.2.76/quick_pp/core_calibration.py → quick_pp-0.2.77/quick_pp/core_analysis.py +498 -74
  5. {quick_pp-0.2.76 → quick_pp-0.2.77}/.gitignore +0 -0
  6. {quick_pp-0.2.76 → quick_pp-0.2.77}/LICENSE +0 -0
  7. {quick_pp-0.2.76 → quick_pp-0.2.77}/README.md +0 -0
  8. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/api/__init__.py +0 -0
  9. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/api/exceptions.py +0 -0
  10. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/api/fastapi_mlflow/__init__.py +0 -0
  11. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/api/fastapi_mlflow/_mlflow_types.py +0 -0
  12. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/api/fastapi_mlflow/applications.py +0 -0
  13. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/api/fastapi_mlflow/exceptions.py +0 -0
  14. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/api/fastapi_mlflow/predictors.py +0 -0
  15. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/api/main.py +0 -0
  16. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/api/mlflow_model_deployment.py +0 -0
  17. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/api/router.py +0 -0
  18. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/api/schemas/lithology_hc_correction.py +0 -0
  19. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/api/schemas/lithology_ssc.py +0 -0
  20. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/api/schemas/lithology_vsh_gr.py +0 -0
  21. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/api/schemas/permeability_choo.py +0 -0
  22. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/api/schemas/permeability_others.py +0 -0
  23. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/api/schemas/porosity.py +0 -0
  24. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/api/schemas/ressum.py +0 -0
  25. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/api/schemas/saturation_archie.py +0 -0
  26. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/api/schemas/saturation_b.py +0 -0
  27. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/api/schemas/saturation_qv.py +0 -0
  28. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/api/schemas/saturation_rw.py +0 -0
  29. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/api/schemas/saturation_temp_grad.py +0 -0
  30. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/api/schemas/saturation_waxman_smits.py +0 -0
  31. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/api/services/chat.py +0 -0
  32. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/api/services/las_handler.py +0 -0
  33. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/api/services/lithology.py +0 -0
  34. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/api/services/permeability.py +0 -0
  35. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/api/services/porosity.py +0 -0
  36. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/api/services/reservoir_summary.py +0 -0
  37. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/api/services/saturation.py +0 -0
  38. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/api/static/favicon.ico +0 -0
  39. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/api/static/logo.png +0 -0
  40. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/api/template/chat.html +0 -0
  41. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/api/template/home.html +0 -0
  42. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/cli.py +0 -0
  43. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/config.py +0 -0
  44. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/database/__init__.py +0 -0
  45. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/database/db_connector.py +0 -0
  46. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/database/models.py +0 -0
  47. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/database/objects.py +0 -0
  48. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/database/setup_postgresql_db.sql +0 -0
  49. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/database/setup_sqlite_db.sql +0 -0
  50. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/fluid_type.py +0 -0
  51. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/las_handler.py +0 -0
  52. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/lithology/__init__.py +0 -0
  53. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/lithology/carbonate.py +0 -0
  54. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/lithology/multi_mineral.py +0 -0
  55. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/lithology/sand_shale.py +0 -0
  56. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/lithology/sand_silt_clay.py +0 -0
  57. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/lithology/thin_beds.py +0 -0
  58. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/machine_learning/__init__.py +0 -0
  59. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/machine_learning/config.py +0 -0
  60. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/machine_learning/feature_engineering.py +0 -0
  61. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/machine_learning/mock_data/mock_data.parquet +0 -0
  62. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/machine_learning/predict_pipeline.py +0 -0
  63. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/machine_learning/train_pipeline.py +0 -0
  64. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/machine_learning/utils.py +0 -0
  65. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/permeability.py +0 -0
  66. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/plotter/__init__.py +0 -0
  67. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/plotter/plotter.py +0 -0
  68. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/plotter/well_log.py +0 -0
  69. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/plotter/well_log_config.py +0 -0
  70. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/porosity.py +0 -0
  71. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/qaqc.py +0 -0
  72. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/ressum.py +0 -0
  73. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/rock_physics/__init__.py +0 -0
  74. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/rock_physics/geomechanics.py +0 -0
  75. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/rock_physics/geophysics.py +0 -0
  76. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/rock_physics/rpm.py +0 -0
  77. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/rock_type.py +0 -0
  78. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/saturation.py +0 -0
  79. {quick_pp-0.2.76 → quick_pp-0.2.77}/quick_pp/utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: quick-pp
3
- Version: 0.2.76
3
+ Version: 0.2.77
4
4
  Summary: Python package to assist in providing quick-look preliminary petrophysical estimation.
5
5
  Project-URL: Homepage, https://github.com/imranfadhil/quick_pp
6
6
  Author-email: Imran Fadhil <imranfadhil@gmail.com>
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "quick-pp"
7
- version = "0.2.76"
7
+ version = "0.2.77"
8
8
  description = "Python package to assist in providing quick-look preliminary petrophysical estimation."
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -20,4 +20,4 @@ logging.getLogger("mlflow").setLevel(logging.WARNING)
20
20
 
21
21
  __author__ = """Imran Fadhil"""
22
22
  __email__ = "imranfadhil@gmail.com"
23
- __version__ = "0.2.76" # Need to be updated manually when releasing a new version/ change in pyproject.toml
23
+ __version__ = "0.2.77" # Need to be updated manually when releasing a new version/ change in pyproject.toml
@@ -489,33 +489,58 @@ def sw_shf_choo(perm, phit, phie, depth, fwl, ift, theta, gw, ghc, b0=0.4):
489
489
 
490
490
 
491
491
  def autocorrelate_core_depth(df):
492
- """Automatically shift core depths to match log depths using Dynamic Time Warping (DTW).
493
-
494
- This function aligns core porosity (CPORE) with log porosity (PHIT) to correct for
495
- depth discrepancies between core and wireline log measurements. It processes the data
496
- on a per-well basis.
492
+ """
493
+ Automatically shift core depths to match log depths.
494
+
495
+ This function aligns core porosity (CPORE) with log porosity (PHIT) for each
496
+ well in the DataFrame. It uses a hybrid approach combining Dynamic Time Warping
497
+ (DTW) for alignment and machine learning models for correction.
498
+
499
+ The process is as follows:
500
+ 1. **Segmentation**: Core data is clustered by depth proximity using DBSCAN to
501
+ identify continuous segments.
502
+ 2. **Interpolation & Smoothing**: Within each segment, sparse core porosity is
503
+ interpolated to match log data resolution. Both core and log porosity
504
+ signals are then smoothed to focus on trends.
505
+ 3. **Weighted DTW Alignment**: A weighted Dynamic Time Warping (DTW) is used
506
+ to find the optimal alignment path between the two porosity signals. The
507
+ weighting is achieved by adding a second feature channel that identifies
508
+ peaks and troughs, guiding the alignment.
509
+ 4. **Filtered Model Training**: A RandomForestRegressor model is trained on the
510
+ DTW alignment path. The training data is filtered to include only points
511
+ where the proposed shift is within a plausible window, preventing the
512
+ model from learning from extreme outliers.
513
+ 5. **Correction & Post-processing**: The model predicts the corrected depths.
514
+ This shift is clipped to the window size. A spacing correction ensures
515
+ that core samples are not artificially compressed.
516
+ 6. **Finalization**: Isotonic regression is applied across all corrected depths
517
+ for the well to enforce strict monotonicity.
497
518
 
498
519
  Args:
499
520
  df (pd.DataFrame): DataFrame containing well log and core data. Must include
500
521
  'WELL_NAME', 'DEPTH', 'PHIT', 'CPORE', 'CPERM', and 'CORE_ID'.
501
-
502
522
  Returns:
503
523
  tuple[pd.DataFrame, pd.DataFrame]:
504
- - A DataFrame with the original data merged with the depth-corrected core
505
- data. New columns include 'DEPTH_CORRECTED', 'CORE_ID_SHIFTED',
506
- 'CPORE_SHIFTED', and 'CPERM_SHIFTED'.
507
- - A summary DataFrame detailing the depth shifts for each core sample,
508
- including 'WELL_NAME', 'CORE_ID', 'ORIGINAL_DEPTH', 'DEPTH_CORRECTED',
509
- and 'DEPTH_SHIFT'.
524
+ - A DataFrame with the original data merged with the depth-corrected core data.
525
+ - A summary DataFrame detailing the depth shifts for each core sample.
510
526
  """
511
527
  from dtw import dtw
512
528
  from sklearn.preprocessing import minmax_scale
529
+ from sklearn.ensemble import RandomForestRegressor
530
+ from sklearn.isotonic import IsotonicRegression
531
+ from sklearn.cluster import DBSCAN
532
+ from scipy.signal import find_peaks
533
+ from scipy.interpolate import interp1d
513
534
 
514
535
  required_cols = ["WELL_NAME", "DEPTH", "PHIT", "CPORE", "CPERM", "CORE_ID"]
515
536
  for col in required_cols:
516
537
  if col not in df.columns:
517
538
  raise AssertionError(f"Missing required column: {col}")
518
539
 
540
+ df = df.copy()
541
+ # Ensure porosity and permeability columns are numeric, coercing errors.
542
+ df["CPERM"] = pd.to_numeric(df["CPERM"], errors="coerce")
543
+ df["PHIT"] = pd.to_numeric(df["PHIT"], errors="coerce")
519
544
  all_wells_data = []
520
545
  shift_summaries = []
521
546
 
@@ -538,48 +563,203 @@ def autocorrelate_core_depth(df):
538
563
  f"Processing {well}: {len(core_data)} core data and {len(log_data)} log data"
539
564
  )
540
565
 
541
- # Create a window of log data around core points to speed up DTW
542
- core_indices_in_log = np.searchsorted(
543
- log_data.DEPTH, core_data.DEPTH, side="left"
544
- )
545
- window = 50 # Increased window size to allow for larger shifts
546
- window_indices = core_indices_in_log[:, None] + np.arange(-window, window + 1)
547
- window_indices = np.clip(window_indices, 0, len(log_data) - 1)
548
- unique_indices = np.unique(window_indices.flatten())
549
- log_data_subset = log_data.iloc[unique_indices].reset_index(drop=True)
550
-
551
- # Extract numpy arrays for DTW
552
- phit_vals = minmax_scale(log_data_subset["PHIT"].values)
553
- cpore_vals = minmax_scale(core_data["CPORE"].values)
554
-
555
- alignment = dtw(
556
- cpore_vals, phit_vals, keep_internals=True, step_pattern="symmetric2"
566
+ # Cluster core data into segments based on depth proximity.
567
+ depth_clusters = DBSCAN(eps=0.01, min_samples=3).fit(
568
+ minmax_scale(core_data["DEPTH"].values.reshape(-1, 1))
557
569
  )
570
+ core_data = core_data.assign(cluster=depth_clusters.labels_)
558
571
 
559
- # Map alignment indices back to original data
560
- core_indices = alignment.index1
561
- log_subset_indices = alignment.index2
572
+ all_alignments = []
573
+ final_corrected_depths = np.zeros(len(core_data))
562
574
 
563
- original_depths = core_data.loc[core_indices, "DEPTH"].values
564
- corrected_depths = log_data_subset.loc[log_subset_indices, "DEPTH"].values
575
+ # Process each core data segment (cluster) independently.
576
+ for cluster_id in np.unique(core_data["cluster"]):
577
+ cluster_core_data = core_data[core_data["cluster"] == cluster_id]
578
+ core_indices_in_cluster = cluster_core_data.index
565
579
 
566
- # Calculate the shift for each point in the DTW path
567
- depth_shifts = corrected_depths - original_depths
580
+ # Create a window of log data around the current core segment
581
+ min_depth, max_depth = (
582
+ cluster_core_data["DEPTH"].min(),
583
+ cluster_core_data["DEPTH"].max(),
584
+ )
585
+ window = 5 # Window size in depth units for log data subset.
586
+ log_subset = log_data[
587
+ (log_data["DEPTH"] >= min_depth - window)
588
+ & (log_data["DEPTH"] <= max_depth + window)
589
+ ].reset_index(drop=True)
590
+
591
+ if log_subset.empty:
592
+ # If no log data is found in the window, keep original depths.
593
+ final_corrected_depths[core_indices_in_cluster] = cluster_core_data[
594
+ "DEPTH"
595
+ ].values
596
+ continue
597
+
598
+ # Smooth the log data to focus on trends rather than high-frequency noise.
599
+ log_phit_smooth = (
600
+ log_subset["PHIT"]
601
+ .rolling(window=window, center=True, min_periods=1)
602
+ .mean()
603
+ )
568
604
 
569
- # Determine the single best shift for the entire core sequence (using the median for robustness)
570
- if len(depth_shifts) > 0:
571
- best_shift = round(np.median(depth_shifts), 4)
572
- else:
573
- best_shift = 0.0
605
+ # Interpolate sparse core data to create a dense signal for DTW.
606
+ core_depths = cluster_core_data["DEPTH"].values
607
+ core_poro = cluster_core_data["CPORE"].values
608
+
609
+ # Use cubic interpolation if possible for a smoother curve.
610
+ interp_kind = "cubic" if len(core_depths) >= 4 else "linear"
611
+ interp_func = interp1d(
612
+ core_depths,
613
+ core_poro,
614
+ kind=interp_kind,
615
+ bounds_error=False,
616
+ fill_value="extrapolate",
617
+ )
574
618
 
575
- tqdm.write(f"Determined best shift for {well}: {best_shift:.2f}")
619
+ dense_core_depths = np.linspace(
620
+ core_depths.min(), core_depths.max(), num=len(log_subset)
621
+ )
622
+ dense_core_poro = interp_func(dense_core_depths)
576
623
 
577
- # Apply the consistent shift to all original core data for this well
624
+ # Smooth the interpolated core data to match the smoothing of log data.
625
+ dense_core_poro_smooth = (
626
+ pd.Series(dense_core_poro)
627
+ .rolling(window=window, center=True, min_periods=1)
628
+ .mean()
629
+ )
630
+
631
+ # Scale both signals to a [0, 1] range for DTW.
632
+ cpore_vals = minmax_scale(dense_core_poro_smooth)
633
+ phit_vals = minmax_scale(log_phit_smooth.values)
634
+
635
+ # Identify peaks and troughs in both signals to act as anchor points.
636
+ # This creates a second feature channel to guide the DTW alignment.
637
+ peaks, _ = find_peaks(phit_vals, prominence=0.1, distance=2)
638
+ troughs, _ = find_peaks(-phit_vals, prominence=0.1, distance=2)
639
+ anchor_indices = np.concatenate([peaks, troughs])
640
+
641
+ phit_anchor_channel = np.zeros_like(phit_vals)
642
+ if len(anchor_indices) > 0:
643
+ phit_anchor_channel[anchor_indices] = 1.0
644
+
645
+ # Repeat for the core porosity signal.
646
+ peaks, _ = find_peaks(cpore_vals, prominence=0.1, distance=2)
647
+ troughs, _ = find_peaks(-cpore_vals, prominence=0.1, distance=2)
648
+ anchor_indices = np.concatenate([peaks, troughs])
649
+ cpore_anchor_channel = np.zeros_like(cpore_vals)
650
+ if len(anchor_indices) > 0:
651
+ cpore_anchor_channel[anchor_indices] = 1.0
652
+
653
+ # Stack signals and anchor channels for 2D DTW.
654
+ weight_factor = 5.0
655
+ cpore_2d = np.vstack([cpore_vals, cpore_anchor_channel * weight_factor]).T
656
+ phit_2d = np.vstack([phit_vals, phit_anchor_channel * weight_factor]).T
657
+
658
+ # 5. Run DTW on the augmented 2D data.
659
+ alignment = dtw(
660
+ cpore_2d,
661
+ phit_2d,
662
+ keep_internals=True,
663
+ step_pattern="symmetric2",
664
+ )
665
+
666
+ cluster_alignment = pd.DataFrame(
667
+ {
668
+ "original_depth": dense_core_depths[
669
+ alignment.index1
670
+ ], # Interpolated depths
671
+ "log_idx": log_subset.index[alignment.index2],
672
+ }
673
+ )
674
+ cluster_alignment["aligned_depth"] = log_subset.loc[
675
+ cluster_alignment["log_idx"], "DEPTH"
676
+ ].values
677
+ cluster_alignment["cluster"] = cluster_id
678
+ all_alignments.append(cluster_alignment)
679
+
680
+ # Filter the DTW path to create a reliable training set for the model,
681
+ # excluding alignments that suggest an impossibly large shift.
682
+ cluster_alignment["shift"] = (
683
+ cluster_alignment["aligned_depth"] - cluster_alignment["original_depth"]
684
+ )
685
+ training_alignment = cluster_alignment[
686
+ cluster_alignment["shift"].abs() <= window
687
+ ]
688
+
689
+ # If filtering removes all points, the alignment is unreliable; skip this cluster.
690
+ if training_alignment.empty:
691
+ tqdm.write(
692
+ f"Well {well}, Cluster {cluster_id}: No reliable alignment found within window. "
693
+ f"Skipping shift for this segment."
694
+ )
695
+ final_corrected_depths[core_indices_in_cluster] = cluster_core_data[
696
+ "DEPTH"
697
+ ].values
698
+ continue
699
+
700
+ # Train a model on the filtered, reliable alignment points.
701
+ X_fit = training_alignment["original_depth"].values.reshape(-1, 1)
702
+ y_fit = training_alignment["aligned_depth"].values
703
+
704
+ rf = RandomForestRegressor(random_state=42)
705
+ rf.fit(X_fit, y_fit)
706
+
707
+ # Predict the corrected depths for the original core points.
708
+ original_depths = cluster_core_data["DEPTH"].values
709
+ corrected_depths_for_cluster = rf.predict(original_depths.reshape(-1, 1))
710
+
711
+ # Post-process the predicted depths for this cluster.
712
+ # 1. Clip the shift to the maximum allowed window size.
713
+ shift = corrected_depths_for_cluster - original_depths
714
+ clipped_shift = np.clip(shift, -window, window)
715
+ corrected_depths_for_cluster = original_depths + clipped_shift
716
+
717
+ # 2. Ensure the spacing between points is not less than original spacing.
718
+ if len(corrected_depths_for_cluster) > 1:
719
+ original_diffs = cluster_core_data["DEPTH"].diff().to_numpy()
720
+ for i in range(1, len(corrected_depths_for_cluster)):
721
+ current_position = (
722
+ corrected_depths_for_cluster[i] - original_depths[i]
723
+ )
724
+ min_spacing = (
725
+ original_diffs[i]
726
+ if current_position < 0
727
+ else -original_diffs[i]
728
+ )
729
+ current_spacing = (
730
+ corrected_depths_for_cluster[i]
731
+ - corrected_depths_for_cluster[i - 1]
732
+ )
733
+ if current_spacing < min_spacing:
734
+ corrected_depths_for_cluster[i] = (
735
+ corrected_depths_for_cluster[i - 1] + min_spacing
736
+ ) # Enforce minimum spacing
737
+
738
+ final_corrected_depths[core_indices_in_cluster] = (
739
+ corrected_depths_for_cluster
740
+ )
741
+
742
+ # Combine alignment results from all clusters for this well.
743
+ alignment_df = (
744
+ pd.concat(all_alignments, ignore_index=True)
745
+ if all_alignments
746
+ else pd.DataFrame()
747
+ )
748
+
749
+ # Enforce strict monotonicity across all corrected depths for the well.
750
+ # This ensures no depth inversions occur between different clusters.
751
+ ir = IsotonicRegression(out_of_bounds="clip")
752
+ final_corrected_depths = ir.fit_transform(
753
+ core_data["DEPTH"], final_corrected_depths
754
+ )
755
+
756
+ # Create shifted core data and summary
578
757
  shifted_core_data = core_data.copy()
579
- shifted_core_data["DEPTH_CORRECTED"] = shifted_core_data["DEPTH"] + best_shift
580
- shifted_core_data["DEPTH_SHIFT"] = best_shift
758
+ shifted_core_data["DEPTH_CORRECTED"] = final_corrected_depths
759
+ shifted_core_data["DEPTH_SHIFT"] = (
760
+ final_corrected_depths - shifted_core_data["DEPTH"]
761
+ )
581
762
 
582
- # Create summary for this well
583
763
  summary = shifted_core_data[
584
764
  ["CORE_ID", "DEPTH", "DEPTH_CORRECTED", "DEPTH_SHIFT"]
585
765
  ].copy()
@@ -589,45 +769,53 @@ def autocorrelate_core_depth(df):
589
769
  ["WELL_NAME", "CORE_ID", "ORIGINAL_DEPTH", "DEPTH_CORRECTED", "DEPTH_SHIFT"]
590
770
  ]
591
771
  shift_summaries.append(summary)
592
-
593
- # Prepare shifted data for merging
594
- final_shifted = shifted_core_data.rename(
595
- columns={
596
- "CPORE": "CPORE_SHIFTED",
597
- "CPERM": "CPERM_SHIFTED",
598
- "CORE_ID": "CORE_ID_SHIFTED",
599
- }
772
+ tqdm.write(
773
+ f"Well {well}: Applied segmented correction. Mean shift: {summary['DEPTH_SHIFT'].mean():.2f}m"
600
774
  )
601
775
 
602
- # Prepare the log data: keep only necessary columns and set DEPTH as index
603
- log_df_to_merge = data.set_index("DEPTH")
776
+ # Reconstruct the well's DataFrame with the newly corrected core depths.
777
+ log_only_data = data.loc[data["CORE_ID"].isna()].copy()
778
+ log_only_data["WELL_NAME"] = well
604
779
 
605
- # Prepare the shifted core data: keep shifted values and set corrected depth as index
606
- core_df_to_merge = final_shifted[
607
- ["DEPTH_CORRECTED", "CPORE_SHIFTED", "CPERM_SHIFTED", "CORE_ID_SHIFTED"]
608
- ].set_index("DEPTH_CORRECTED")
780
+ corrected_core_df = shifted_core_data.copy()
781
+ corrected_core_df.rename(columns={"DEPTH": "ORIGINAL_DEPTH"}, inplace=True)
782
+ corrected_core_df.rename(columns={"DEPTH_CORRECTED": "DEPTH"}, inplace=True)
609
783
 
610
- # Merge the two dataframes on their indices (which are the depths)
611
- well_corrected_df = pd.merge(
612
- log_df_to_merge,
613
- core_df_to_merge,
614
- left_index=True,
615
- right_index=True,
616
- how="outer",
617
- ).reset_index()
784
+ corrected_core_df["REMARKS"] = corrected_core_df.apply(
785
+ lambda row: f"Corrected from {row['ORIGINAL_DEPTH']:.2f} (Shift: {row['DEPTH_SHIFT']:.2f})",
786
+ axis=1,
787
+ )
618
788
 
619
- # The merged 'index' column is the unified depth column, so rename it
620
- well_corrected_df.rename(columns={"index": "DEPTH"}, inplace=True)
789
+ corrected_core_df.drop(columns=["ORIGINAL_DEPTH", "DEPTH_SHIFT"], inplace=True)
790
+ corrected_core_df["WELL_NAME"] = well
791
+
792
+ # 3. Combine the log-only data with the newly depth-corrected core data
793
+ data.sort_values("DEPTH", inplace=True)
794
+ corrected_core_df.sort_values("DEPTH", inplace=True)
795
+ core_cols_to_merge = ["DEPTH", "CPORE", "CPERM", "CORE_ID", "REMARKS"]
796
+ well_corrected_df = pd.merge_asof(
797
+ data,
798
+ corrected_core_df[core_cols_to_merge],
799
+ on="DEPTH",
800
+ direction="nearest",
801
+ tolerance=1e-2,
802
+ suffixes=("_ORI", ""),
803
+ )
621
804
 
622
- # Sort by the final unified depth
623
805
  well_corrected_df.sort_values("DEPTH", inplace=True)
624
806
 
625
- # Add well name back if lost during merge
626
- well_corrected_df["WELL_NAME"] = well
627
- all_wells_data.append(well_corrected_df)
807
+ all_wells_data.append(well_corrected_df.reset_index(drop=True))
808
+
809
+ _plot_autocorrelation_results(
810
+ well, log_data, core_data, shifted_core_data, alignment_df
811
+ )
628
812
 
629
- # Combine all processed well data and summaries
813
+ # Combine data from all processed wells into the final return DataFrames.
630
814
  return_df = pd.concat(all_wells_data, ignore_index=True)
815
+
816
+ # Plot xplot comparing the original and shifted data points together with R2 score and RMSE
817
+ _plot_correction_xplot(return_df)
818
+
631
819
  final_summary_df = (
632
820
  pd.concat(shift_summaries, ignore_index=True)
633
821
  if shift_summaries
@@ -637,6 +825,242 @@ def autocorrelate_core_depth(df):
637
825
  return return_df, final_summary_df
638
826
 
639
827
 
828
+ def _plot_correction_xplot(df):
829
+ """
830
+ Plots a crossplot comparing log porosity (PHIT) with original and corrected
831
+ core porosity (CPORE), showing R-squared and RMSE for both.
832
+
833
+ Args:
834
+ df (pd.DataFrame): DataFrame containing 'PHIT', 'CPORE', 'CPORE_ORI', and 'CORE_ID'.
835
+ """
836
+ from sklearn.metrics import r2_score, root_mean_squared_error
837
+
838
+ # Prepare data by dropping NaNs
839
+ plot_df = df[["PHIT", "CPORE_ORI", "CPORE", "CORE_ID"]].dropna().copy()
840
+
841
+ # Calculate metrics for original data
842
+ r2_original = r2_score(plot_df["PHIT"], plot_df["CPORE_ORI"])
843
+ rmse_original = root_mean_squared_error(plot_df["PHIT"], plot_df["CPORE_ORI"])
844
+
845
+ # Calculate metrics for corrected data
846
+ r2_corrected = r2_score(plot_df["PHIT"], plot_df["CPORE"])
847
+ rmse_corrected = root_mean_squared_error(plot_df["PHIT"], plot_df["CPORE"])
848
+
849
+ # Create the plot
850
+ fig, ax = plt.subplots(figsize=(8, 8))
851
+
852
+ # Scatter plot for original and corrected data
853
+ ax.scatter(
854
+ plot_df["PHIT"],
855
+ plot_df["CPORE_ORI"],
856
+ alpha=0.5,
857
+ label=f"Original (R2={r2_original:.2f}, RMSE={rmse_original:.3f})",
858
+ marker="x",
859
+ )
860
+ ax.scatter(
861
+ plot_df["PHIT"],
862
+ plot_df["CPORE"],
863
+ alpha=0.5,
864
+ label=f"Corrected (R2={r2_corrected:.2f}, RMSE={rmse_corrected:.3f})",
865
+ marker="o",
866
+ )
867
+
868
+ # Add lines and annotations connecting original to corrected points
869
+ for _, row in plot_df.iterrows():
870
+ # Add a line from the original point to the corrected point
871
+ ax.plot(
872
+ [row["PHIT"], row["PHIT"]],
873
+ [row["CPORE_ORI"], row["CPORE"]],
874
+ color="gray",
875
+ linestyle="--",
876
+ linewidth=0.8,
877
+ alpha=0.7,
878
+ )
879
+ # Annotate the CORE_ID near the corrected point
880
+ ax.text(
881
+ row["PHIT"] * 1.01, row["CPORE"], str(row["CORE_ID"]), fontsize=7, alpha=0.8
882
+ )
883
+
884
+ # Add 1:1 line for reference
885
+ lims = [
886
+ min(ax.get_xlim()[0], ax.get_ylim()[0]),
887
+ max(ax.get_xlim()[1], ax.get_ylim()[1]),
888
+ ]
889
+ ax.plot(lims, lims, "k--", alpha=0.75, zorder=0, label="1:1 Line")
890
+
891
+ # Formatting
892
+ ax.set_xlabel("Log Porosity (PHIT)")
893
+ ax.set_ylabel("Core Porosity (CPORE)")
894
+ ax.set_title("Core vs. Log Porosity Before and After Depth Correction")
895
+ ax.legend()
896
+ ax.grid(True)
897
+ ax.set_aspect("equal", adjustable="box")
898
+ ax.set_xlim(lims)
899
+ ax.set_ylim(lims)
900
+
901
+ plt.tight_layout()
902
+ plt.show()
903
+
904
+
905
+ def _plot_autocorrelation_results(
906
+ well_name, log_data, original_core, corrected_core, alignment_df
907
+ ):
908
+ """
909
+ Visualize the results of the core depth correction using Plotly.
910
+
911
+ This helper function generates a two-panel plot for quality control:
912
+ 1. **Porosity Alignment**: Shows log porosity, original core porosity, and
913
+ depth-corrected core porosity versus depth. Lines connect original to
914
+ corrected points to visualize the shifts.
915
+ 2. **DTW Alignment**: Plots the DTW path, showing how original core depths
916
+ were mapped to log depths. A 1:1 line indicates no shift.
917
+
918
+ Args:
919
+ well_name (str): The name of the well being plotted.
920
+ log_data (pd.DataFrame): DataFrame with log data ('DEPTH', 'PHIT').
921
+ original_core (pd.DataFrame): DataFrame with original core data.
922
+ corrected_core (pd.DataFrame): DataFrame with depth-corrected core data.
923
+ alignment_df (pd.DataFrame): DataFrame containing the DTW alignment path.
924
+ """
925
+ from plotly.subplots import make_subplots
926
+ import plotly.graph_objects as go
927
+
928
+ fig = make_subplots(
929
+ rows=1,
930
+ cols=2,
931
+ subplot_titles=("Porosity Alignment", "DTW Alignment & Shift Clusters"),
932
+ shared_yaxes=True,
933
+ )
934
+
935
+ # Panel 1: Porosity Alignment Plot
936
+ fig.add_trace(
937
+ go.Scatter(
938
+ x=log_data["PHIT"],
939
+ y=log_data["DEPTH"],
940
+ name="Log PHIT",
941
+ mode="lines",
942
+ line=dict(color="black", width=1),
943
+ ),
944
+ row=1,
945
+ col=1,
946
+ )
947
+ fig.add_trace(
948
+ go.Scatter(
949
+ x=original_core["CPORE"],
950
+ y=original_core["DEPTH"],
951
+ name="Original CPORE",
952
+ mode="lines+markers",
953
+ line=dict(color="red"),
954
+ marker=dict(symbol="circle-open"),
955
+ text=[f"Core ID: {c}" for c in original_core["CORE_ID"]],
956
+ hoverinfo="x+y+text",
957
+ ),
958
+ row=1,
959
+ col=1,
960
+ )
961
+ fig.add_trace(
962
+ go.Scatter(
963
+ x=corrected_core["CPORE"],
964
+ y=corrected_core["DEPTH_CORRECTED"],
965
+ name="Corrected CPORE",
966
+ mode="lines+markers",
967
+ line=dict(color="blue"),
968
+ text=[f"Core ID: {c}" for c in corrected_core["CORE_ID"]],
969
+ hoverinfo="x+y+text",
970
+ ),
971
+ row=1,
972
+ col=1,
973
+ )
974
+
975
+ # Add lines connecting original to corrected points to show the shift.
976
+ x_lines, y_lines = [], []
977
+ for _, row in corrected_core.iterrows():
978
+ x_lines.extend([row["CPORE"], row["CPORE"], None])
979
+ y_lines.extend([row["DEPTH"], row["DEPTH_CORRECTED"], None])
980
+ fig.add_trace(
981
+ go.Scatter(
982
+ x=x_lines,
983
+ y=y_lines,
984
+ name="Depth Shift",
985
+ mode="lines",
986
+ line=dict(color="gray", dash="dot", width=1),
987
+ showlegend=False,
988
+ ),
989
+ row=1,
990
+ col=1,
991
+ )
992
+
993
+ # Panel 2: DTW Path and Cluster Visualization
994
+ fig.add_trace(
995
+ go.Scatter(
996
+ x=alignment_df["original_depth"],
997
+ y=alignment_df["aligned_depth"],
998
+ name="DTW Path",
999
+ mode="lines",
1000
+ line=dict(color="lightgray"),
1001
+ ),
1002
+ row=1,
1003
+ col=2,
1004
+ )
1005
+
1006
+ fig.add_trace(
1007
+ go.Scatter(
1008
+ x=alignment_df["original_depth"],
1009
+ y=alignment_df["aligned_depth"],
1010
+ name="Clusters",
1011
+ mode="markers",
1012
+ marker=dict(
1013
+ color=alignment_df["cluster"],
1014
+ colorscale="Viridis",
1015
+ showscale=False,
1016
+ colorbar=dict(title="Cluster ID"),
1017
+ cmin=0,
1018
+ cmid=alignment_df["cluster"].max() / 2
1019
+ if alignment_df["cluster"].max() > 0
1020
+ else 0.5,
1021
+ ),
1022
+ text=[f"Cluster: {c}" for c in alignment_df["cluster"].values],
1023
+ hoverinfo="x+y+text",
1024
+ ),
1025
+ row=1,
1026
+ col=2,
1027
+ )
1028
+
1029
+ # Add a 1:1 line to represent no depth shift.
1030
+ lim_min = min(
1031
+ alignment_df["original_depth"].min(), alignment_df["aligned_depth"].min()
1032
+ )
1033
+ lim_max = max(
1034
+ alignment_df["original_depth"].max(), alignment_df["aligned_depth"].max()
1035
+ )
1036
+ fig.add_shape(
1037
+ type="line",
1038
+ x0=lim_min,
1039
+ y0=lim_min,
1040
+ x1=lim_max,
1041
+ y1=lim_max,
1042
+ line=dict(color="black", width=2, dash="dash"),
1043
+ row=1,
1044
+ col=2,
1045
+ )
1046
+
1047
+ fig.update_layout(
1048
+ title_text=f"Core Depth Autocorrelation Results for Well: {well_name}",
1049
+ legend_title_text="Data",
1050
+ height=700,
1051
+ width=1200,
1052
+ )
1053
+ fig.update_yaxes(autorange="reversed")
1054
+ fig.update_xaxes(title_text="Porosity (frac)", row=1, col=1)
1055
+ fig.update_yaxes(title_text="Depth", row=1, col=1)
1056
+ fig.update_xaxes(title_text="Original Core Depth", row=1, col=2)
1057
+ fig.update_yaxes(title_text="DTW Aligned Log Depth", row=1, col=2)
1058
+
1059
+ fig.update_xaxes(fixedrange=True)
1060
+
1061
+ fig.show()
1062
+
1063
+
640
1064
  def restructure_scal_data(df_wide):
641
1065
  """
642
1066
  Restructures a SCAL dataset from a wide format (multiple Pc/Sw columns per depth)
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes