import hashlib import importlib.util import math from pathlib import Path import sys import numpy as np HERE = Path(__file__).resolve().parent ENGINE_PATH = HERE.parent / 'guitar-persistent-06/model.py' SPEC = importlib.util.spec_from_file_location('model', ENGINE_PATH) ENGINE = importlib.util.module_from_spec(SPEC) sys.modules[SPEC.name] = ENGINE SPEC.loader.exec_module(ENGINE) FROZEN_GEOMETRY = ENGINE.geometry ORIGINAL_DISTANCE = ENGINE.PARAMETERS['pickupFromBridgeMeters'] NECK_DISTANCE = .162 WIDTH = ENGINE.PARAMETERS['pickupWidthMeters'] def digest(path): return hashlib.sha256(path.read_bytes()).hexdigest() def aperture_weights(positions, length, distance, width): positions = np.asarray(positions, dtype=np.float64) if positions.ndim != 1 or len(positions) < 2 or not np.isfinite(positions).all(): raise ValueError('Invalid string observation mesh') if not all(math.isfinite(value) for value in (length, distance, width)) or width <= 0: raise ValueError('Invalid pickup geometry') points = np.r_[0., positions, length] if np.any(np.diff(points) <= 0): raise ValueError('String observation mesh must increase inside the scale') center = length - distance lower = center - width / 2 upper = center + width / 2 if lower < positions[0] or upper > positions[-1]: raise ValueError('Pickup aperture must stay inside the free mesh nodes') weights = np.zeros(len(positions)) for index, (left, right) in enumerate(zip(points[:-1], points[1:])): begin = max(left, lower) end = min(right, upper) if end <= begin: continue right_weight = ((end - left) ** 2 - (begin - left) ** 2) / (2 * (right - left) * width) left_weight = (end - begin) / width - right_weight if index: weights[index - 1] += left_weight if index < len(positions): weights[index] += right_weight if np.min(weights) < -1e-13 or abs(np.sum(weights) - 1) > 1e-12: raise AssertionError('Pickup aperture lost its spatial normalization') return weights def simulate(events, seconds, *, distance=NECK_DISTANCE, **controls): def observed_geometry(maximum_cell=None): shape = FROZEN_GEOMETRY(maximum_cell) weights = aperture_weights(shape['positions'], ENGINE.PARAMETERS['scaleLengthMeters'], distance, WIDTH) shape['pickupWeights'] = np.tile(weights, (6, 1)) return shape previous_geometry = ENGINE.geometry try: ENGINE.geometry = observed_geometry return ENGINE.simulate(events, seconds, **controls) finally: ENGINE.geometry = previous_geometry def source_hashes(): return {'observer.py': digest(HERE / 'observer.py'), 'persistentEngine': digest(ENGINE_PATH), 'frozenMechanicalGeometry': digest(ENGINE.FROZEN_PATH)}