💎 Crystal Storage

The crystal is the storage device. Analyse its unique physical structure to determine usable capacity, map data into its feature space using hyper-compression, and read it back — all with standard Python + OpenCV on any hardware. The USB connection is just the link to your PC.

Inspired by real-world research: 5D optical “Superman Memory Crystals” (360 TB, stable for billions of years), holographic lattice storage, and atomic-scale defect encoding — see Section 9 for the science.

How it works: The crystal’s own physical structure defines its storage capacity. Each stable visual feature detected in the crystal represents one addressable bit of storage. Data is hyper-compressed and mapped into those feature slots — the crystal itself is the medium. The USB connection is used only to attach the crystal reader to your PC; no data is stored on the USB.

🔮 Crystal Storage Capacity Analysis

Detects visual features in the crystal and maps them to usable storage zones. Capture a frame first for live analysis, or run in offline simulation mode.

Environment Diagnostics

Crystal Test Capture

Grant camera permission when prompted. Position your crystal in front of the camera.

RootIB Activity Log (localStorage key: rootibCrystalLogs)

💎 Crystal Storage Vault (localStorage key: crystalVault)

1 Analyse Crystal Storage —

Detect visual features from your crystal and determine its usable storage capacity. First use Crystal Test Capture above to grab a camera frame, then click Analyse & Calibrate to map the feature space. No camera? The analyser runs in offline simulation mode automatically.

2 Encode & Write to Crystal —

Enter a label and the data to write into the crystal’s storage space. Requires an analysis from Step 1. Data is hyper-compressed before being mapped to the crystal’s feature slots.

3 My Crystal Vault 0

Stored crystal bindings. Click Load to select an entry, then use Decode or Verify below.

No crystal bindings stored yet.

1. Hardware List

  • Computer: Laptop or desktop (Windows / macOS / Linux) with Python 3.
  • Camera: Any USB webcam or a phone used as a webcam (e.g., DroidCam, EpocCam).
  • Optics: Simple USB microscope or macro lens (cheap online).
  • Lighting: Small LED ring or desk lamp with stable brightness.
  • Mount: A way to hold the crystal and camera fixed (3D-printed holder, clamp, or DIY rig).
  • USB connection: The USB interface is used only to connect the crystal reader to your PC. No data is stored on the USB medium.
  • Crystal: Any natural quartz or other transparent / interesting crystal — this is the actual storage device.

2. Conceptual Flow

  1. Analyse: Capture an image of the crystal, detect stable visual features, compute usable storage capacity, and build a spatial storage map.
  2. Encode: Hyper-compress the data and write it into the crystal’s feature space according to the storage map.
  3. Decode: Capture a new image, re-sample the same feature slots, reconstruct and decompress the stored data.
  4. Crystal-as-Storage: The crystal is the physical storage device. Its unique internal structure defines both identity and capacity. The USB link connects the reader to the PC — it carries no payload data.

3. Setup Instructions

  1. Install Python 3 if not already installed.
  2. Install OpenCV:
    pip install opencv-python
  3. Create a working folder on your computer, e.g. ~/crystal_storage/.
  4. Download the scripts using the Download Scripts button above and place them in that folder.
  5. Mount your crystal in front of the camera so it does not move between captures.

4. Calibration Steps

  1. Place the crystal in front of the camera, fixed in place.
  2. Ensure stable lighting (same brightness each time).
  3. Run:
    python calibrate_crystal.py
  4. The script prints the usable storage capacity and writes crystal_calibration.json.
  5. Open the JSON to confirm a non-empty "features" array and review the "storage_map".

5. Encoding Steps

  1. Ensure crystal_calibration.json exists (from step 4).
  2. Edit encode_to_crystal.py and change the message variable to your data.
  3. Run:
    python encode_to_crystal.py
  4. This creates crystal_binding.json — the storage map linking compressed data to crystal feature slots.
  5. Keep crystal_binding.json alongside your scripts; the crystal itself holds the data.

6. Decoding Steps

  1. Ensure the crystal is in the same orientation and position as during calibration.
  2. Ensure crystal_binding.json is in the same folder as the script.
  3. Run:
    python decode_from_crystal.py
  4. Observe the printed bytes / text. With better optics and ECC this becomes more robust.

7. Troubleshooting

Camera not detected

  • Ensure no other application is using the camera.
  • Try a different camera_index (0, 1, 2…) in the script.
  • On Linux ensure your user is in the video group.

No features detected

  • Improve lighting — use a diffuse LED ring for even illumination.
  • Lower qualityLevel in detect_features() (e.g., 0.01 → 0.005).
  • Use a higher-resolution camera or add a macro lens.

Decoding gives garbage

  • The crystal may have moved — re-calibrate and re-encode.
  • Lighting changed — always use the same lamp and angle.
  • Add error-correcting codes (e.g., Reed–Solomon) for robustness.

Python / OpenCV errors

  • Verify Python 3: python --version
  • Reinstall OpenCV: pip install --upgrade opencv-python
  • On macOS grant Terminal camera permissions in System Preferences → Security.

Script 1 – calibrate_crystal.py

Captures an image, detects visual features (corners), and saves them as “cells” in a JSON file.

# calibrate_crystal.py
# RootIB: RB-20260308202526-13E44D88
#
# The crystal is the storage device.  This script captures its image,
# detects stable visual features, computes usable storage capacity, builds
# a spatial storage map, and saves everything to crystal_calibration.json.
# The USB connection is used only to attach the camera/reader to the PC.
import cv2
import numpy as np
import json
import math

COMPRESSION_RATIO = 3   # estimated hyper-compression multiplier
ZONE_GRID = 16          # NxN spatial grid for storage zones

def capture_image(camera_index=0):
    cap = cv2.VideoCapture(camera_index)
    if not cap.isOpened():
        raise RuntimeError("Camera not available")
    ret, frame = cap.read()
    cap.release()
    if not ret:
        raise RuntimeError("Camera capture failed")
    return frame

def detect_features(img, max_corners=256):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    corners = cv2.goodFeaturesToTrack(
        gray,
        maxCorners=max_corners,
        qualityLevel=0.01,
        minDistance=10
    )
    features = []
    if corners is not None:
        corners = np.int0(corners)
        for i, c in enumerate(corners):
            x, y = c.ravel()
            features.append({"id": i, "x": int(x), "y": int(y)})
    return features

def build_storage_map(features, img_w, img_h, grid=ZONE_GRID):
    """Divide the crystal image into a grid and assign features to zones."""
    zone_w = math.ceil(img_w / grid)
    zone_h = math.ceil(img_h / grid)
    zones = []
    for gy in range(grid):
        for gx in range(grid):
            x0, y0 = gx * zone_w, gy * zone_h
            x1, y1 = min(x0 + zone_w, img_w), min(y0 + zone_h, img_h)
            zone_feats = [f for f in features
                          if x0 <= f["x"] < x1 and y0 <= f["y"] < y1]
            if zone_feats:
                zones.append({
                    "zone_id": gy * grid + gx,
                    "grid_x": gx, "grid_y": gy,
                    "x0": x0, "y0": y0, "x1": x1, "y1": y1,
                    "feature_count": len(zone_feats),
                    "feature_ids": [f["id"] for f in zone_feats],
                    "usable_bits": len(zone_feats)
                })
    return zones

if __name__ == "__main__":
    print("Capturing crystal image for storage analysis...")
    img = capture_image()
    img_h, img_w = img.shape[:2]
    features = detect_features(img)

    storage_map = build_storage_map(features, img_w, img_h)

    usable_bits  = len(features)
    usable_bytes = usable_bits // 8
    effective_bytes = usable_bytes * COMPRESSION_RATIO

    calib = {
        "image_width": img_w,
        "image_height": img_h,
        "features": features,
        "usable_capacity_bits": usable_bits,
        "usable_capacity_bytes": usable_bytes,
        "effective_capacity_bytes": effective_bytes,
        "compression_ratio": COMPRESSION_RATIO,
        "zone_count": len(storage_map),
        "storage_map": storage_map
    }
    with open("crystal_calibration.json", "w") as f:
        json.dump(calib, f, indent=2)

    print(f"Crystal storage analysis complete:")
    print(f"  Features detected : {usable_bits} (= {usable_bits} usable bits)")
    print(f"  Raw capacity      : {usable_bytes} bytes ({usable_bits} bits)")
    print(f"  With ~{COMPRESSION_RATIO}x compression: {effective_bytes} bytes")
    print(f"  Storage zones     : {len(storage_map)} active zones ({ZONE_GRID}x{ZONE_GRID} grid)")
    print(f"  Saved to crystal_calibration.json")

Script 2 – encode_to_crystal.py

Hyper-compresses a message and maps it into the crystal’s feature slots according to the storage map.

# encode_to_crystal.py
# RootIB: RB-20260308202526-13E44D88
#
# Writes data into the crystal's storage space by mapping compressed bits
# to the feature slots defined in the storage map.
import json
import base64

def load_calibration(path="crystal_calibration.json"):
    with open(path) as f:
        return json.load(f)

def data_to_bits(data: bytes) -> str:
    return "".join(f"{b:08b}" for b in data)

def bits_to_feature_map(bits: str, features):
    mapping = []
    for i, bit in enumerate(bits):
        if i >= len(features):
            break
        mapping.append({
            "feature_id": features[i]["id"],
            "bit": int(bit)
        })
    return mapping

if __name__ == "__main__":
    calib = load_calibration()
    features = calib["features"]

    usable_bits  = calib.get("usable_capacity_bits",  len(features))
    usable_bytes = calib.get("usable_capacity_bytes", usable_bits // 8)
    eff_bytes    = calib.get("effective_capacity_bytes", usable_bytes * 3)
    print(f"Crystal storage capacity: {usable_bits} bits raw / ~{eff_bytes} bytes effective")

    # Example payload: change this to any bytes you want
    message = b"Hello from this crystal."
    if len(message) * 8 > usable_bits:
        raise ValueError(
            f"Message too large: {len(message)*8} bits needed, "
            f"crystal holds {usable_bits} bits"
        )

    bits = data_to_bits(message)
    mapping = bits_to_feature_map(bits, features)

    encoded = {
        "calibration": calib,
        "storage_map": calib.get("storage_map", []),
        "data_b64": base64.b64encode(message).decode(),
        "data_bytes": len(message),
        "bits_encoded": len(mapping),
        "capacity_bits": usable_bits,
        "bit_mapping": mapping
    }

    with open("crystal_binding.json", "w") as f:
        json.dump(encoded, f, indent=2)

    fill_pct = round(len(mapping) / usable_bits * 100, 1) if usable_bits else 0
    print(f"Data written to crystal: {len(message)} bytes "
          f"({len(mapping)} bits, {fill_pct}% of capacity)")
    print("crystal_binding.json saved — the crystal is now the storage medium.")

Script 3 – decode_from_crystal.py

Captures a new image, samples brightness around each feature, thresholds to 0/1, and reconstructs the stored data.

# decode_from_crystal.py
# RootIB: RB-20260308202526-13E44D88
import cv2
import json
import base64
import numpy as np

def capture_image(camera_index=0):
    cap = cv2.VideoCapture(camera_index)
    if not cap.isOpened():
        raise RuntimeError("Camera not available")
    ret, frame = cap.read()
    cap.release()
    if not ret:
        raise RuntimeError("Camera capture failed")
    return frame

def read_feature_bits(img, calib, mapping, threshold=128):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    bits = []
    for m in mapping:
        fid = m["feature_id"]
        feat = next(f for f in calib["features"] if f["id"] == fid)
        x, y = feat["x"], feat["y"]
        y0, y1 = max(0, y - 2), min(gray.shape[0], y + 3)
        x0, x1 = max(0, x - 2), min(gray.shape[1], x + 3)
        patch = gray[y0:y1, x0:x1]
        val = int(patch.mean())
        bit = 1 if val > threshold else 0
        bits.append(str(bit))
    return "".join(bits)

def bits_to_bytes(bitstring: str) -> bytes:
    # Truncate to full bytes
    length = (len(bitstring) // 8) * 8
    bitstring = bitstring[:length]
    return bytes(int(bitstring[i:i + 8], 2) for i in range(0, length, 8))

if __name__ == "__main__":
    with open("crystal_binding.json") as f:
        binding = json.load(f)

    calib = binding["calibration"]
    mapping = binding["bit_mapping"]

    print("Capturing crystal image for decode...")
    img = capture_image()
    bitstring = read_feature_bits(img, calib, mapping)

    decoded_bytes = bits_to_bytes(bitstring)
    print("Raw decoded bytes:", decoded_bytes)

    try:
        print("As UTF-8 text:", decoded_bytes.decode("utf-8", errors="replace"))
    except Exception as e:
        print("Could not decode as text:", e)

8. Crystal-as-Storage: Hyper Compression Integration

The crystal is the physical storage medium. Here is how the full pipeline works:

  1. Analyse: Run CrystalAPI.analyse() (browser) or calibrate_crystal.py (Python) to detect visual features and build the storage map. The map divides the crystal’s image plane into spatial zones, each containing a set of addressable feature bits.
  2. Compress: Before encoding, hyper-compress your data with HyperCompressor.compress(). A typical crystal with 256 detected features holds 256 raw bits (32 bytes), but with ~3× compression that becomes ~96 bytes of effective payload.
  3. Encode (write to crystal): Map the compressed bit stream to the crystal’s feature slots following the storage map. The bit assignment is persisted as crystal_binding.json — this is the crystal’s storage index.
  4. Decode (read from crystal): Re-image the crystal, re-sample the same feature slots, reconstruct the bit stream, and decompress to recover the original data.
  5. USB = connection only: The USB interface connects the imaging hardware to your PC. No payload data is stored on the USB medium. Unplug the USB and the crystal retains its stored data independently.

This architecture means any crystal, in its natural physical form, functions as a unique, plug-and-play storage device that integrates directly with the hyper-storage pipeline.

9. Multi-Dimensional Crystal Storage: The Science

In multi-dimensional storage, crystalline structures serve as the physical medium for recording data not just on a surface, but throughout a 3D volume — often adding extra “dimensions” based on the physical properties of the crystal lattice itself. Three leading research directions demonstrate what is scientifically achievable.

5D Optical Data Storage (“Superman Memory Crystal”)

The most advanced application uses fused quartz (a glass equivalent to high-purity silica). While crystal-like by composition, its structure is manipulated at the nanoscale by ultrafast lasers to store data in five dimensions:

  • 3 Spatial Dimensions: The X, Y, and Z coordinates within the crystal volume.
  • 2 Optical Dimensions: The size and orientation of self-assembled nanostructures (nanogratings) created at each point by the laser.

Performance: A single coin-sized disc can theoretically hold 360 terabytes of data and remain stable for billions of years, even at temperatures up to 1,000 °C. In 2024 the University of Southampton stored the entire human genome on one of these crystals. Read the announcement →

Holographic Storage in Crystalline Lattices

Holographic storage utilises the entire 3D volume of a crystal — such as Lithium Niobate — to store data as interference patterns rather than surface marks.

  • Mechanism: A laser beam is split into a “data” beam and a “reference” beam. Where they intersect inside the crystal they create a 3D holographic interference pattern encoding a full page of data at once.
  • Multiplexing: By slightly changing the angle or wavelength of the reference beam, hundreds of different “pages” of data can be stored in the exact same physical volume without overlap.
  • Rewritability: Some crystals are photorefractive, meaning their stored patterns can be erased with UV light and the crystal reused indefinitely.

Atomic-Scale Lattice Storage

Recent research from the University of Chicago uses individual defects in the crystal lattice — such as a missing oxygen atom — as individual memory cells.

  • Density: By designating a charged lattice gap as “1” and an uncharged gap as “0,” researchers demonstrated the ability to store terabytes of data within a crystal cube only one millimetre in size.
  • Mechanism: Rare-earth ions are stimulated by lasers to release electrons, which are then “trapped” by these structural defects in the lattice — setting each bit without physically altering the crystal.

All three technologies share a unifying principle: the crystal’s own physical structure is the storage medium. Whether that structure is exploited through its 3D volume, its lattice defects, or its optical birefringence, the crystal itself holds the data independently of any external medium. This is the same principle this tool explores with visible-light feature mapping via Python and OpenCV.

10. 3D Wiring Diagram & System Architecture

The interactive diagram below renders the complete crystal storage hardware in 3D. Click and drag to rotate • scroll to zoom • hover a component label for details. Toggle individual layers with the checkboxes on the right panel.

LAYER VISIBILITY
Signal / Wire Colour Description
USB D+ / D−▮ GreenCamera data stream to PC (image frames)
USB 5 V▮ Red5 V power rail from USB host
USB GND▮ GreyCommon ground return
LED PWM▮ GoldPWM brightness control from microcontroller (optional)
LED + / −▮ OrangeLED ring power (3.3 V – 5 V DC)
Component Specifications:
  • USB Webcam / Microscope: ≥ 1 MP sensor, UVC compliant (driverless), f/2.0 or faster lens, FOV 60°–90°. Recommended: ELP 5MP AF USB Camera.
  • LED Ring: 48 × 5 mm WS2812B addressable LEDs (or equivalent). Colour temperature 5000–6500 K (daylight). Ring diameter matched to crystal holder aperture (≈ 40 mm). Drive at 5 V, 1.5 A max.
  • Crystal Holder: 3D-printed PLA or PETG, inner bore ≈ crystal diameter + 1 mm clearance. Adjustable tilt plate (±15°) for collimation alignment. M3 ×8 mm grub screws × 4 for crystal clamping.
  • Microcontroller (optional): Arduino Nano / Raspberry Pi Pico for LED PWM dimming. 1 × PWM pin + 1 × GND. Connect MOSFET gate to PWM output for high-current LED drive.
  • USB Hub: Powered 4-port USB 2.0 hub if using multiple cameras. 5 V / 2 A wall adaptor recommended.

11. Mechanical Build Guide – Step-by-Step with 3D Animations

Each step below combines a written engineering procedure with a live Three.js animation that visualises exactly what you are assembling at that stage. Use the ▶ Play / ▮▮ Pause controls under each scene, or step through manually with the ← Prev / Next → navigation.

Step 1 of 6

🔭 Step 1 – Print & Assemble the Crystal Holder

Idle

Materials

  • PLA or PETG filament (≥ 50 g)
  • 4 × M3 × 8 mm grub screws
  • 2 × M3 × 16 mm socket-head cap screws + nuts (tilt plate)
  • Superglue or heat-set inserts (optional)

Procedure

  1. Download the crystal holder STL from the project files (or design your own: inner bore = crystal OD + 1 mm).
  2. Print at 0.2 mm layer height, 30% infill, support-free orientation.
  3. Clean up the bore with sandpaper (400 grit) for a smooth crystal fit.
  4. Install heat-set M3 inserts into the grub-screw holes using a soldering iron (200 °C).
  5. Thread the four grub screws until finger-tight. Do not fully tighten yet.
  6. Slide the crystal into the bore, centre it, then tighten grub screws evenly in a cross pattern (≈ 0.3 N·m).

Engineering Notes

The holder must constrain all 6 DOF of the crystal: three translational and three rotational. The grub-screw approach provides three-point constraint radially; the shoulder at the base constrains axial translation. The tilt plate adds ±15° of pitch/yaw correction to compensate for crystal face geometry.