|
| 1 | +from matplotlib import pyplot as plt |
| 2 | +import numpy as np |
| 3 | +import json |
| 4 | +import math |
| 5 | +import os |
| 6 | +import argparse |
| 7 | +import sys |
| 8 | +from Player import Player |
| 9 | + |
| 10 | +# Global variables |
| 11 | +midline_plot = None |
| 12 | +perimeter_plot = None |
| 13 | + |
| 14 | +def validate_file(file_path): |
| 15 | + if not os.path.exists(file_path): |
| 16 | + raise argparse.ArgumentTypeError(f"The file {file_path} does not exist.") |
| 17 | + if not os.path.isfile(file_path): |
| 18 | + raise argparse.ArgumentTypeError(f"{file_path} is not a valid file.") |
| 19 | + return file_path |
| 20 | + |
| 21 | +def get_perimeter(x, y, r): |
| 22 | + n_bar = x.shape[0] |
| 23 | + num_steps = x.shape[1] |
| 24 | + |
| 25 | + n_seg = int(n_bar - 1) |
| 26 | + |
| 27 | + # radii along the body of the worm |
| 28 | + r_i = np.array([ |
| 29 | + r * abs(math.sin(math.acos(((i) - n_seg / 2.0) / (n_seg / 2.0 + 0.2)))) |
| 30 | + for i in range(n_bar) |
| 31 | + ]).reshape(-1, 1) |
| 32 | + |
| 33 | + diff_x = np.diff(x, axis=0) |
| 34 | + diff_y = np.diff(y, axis=0) |
| 35 | + |
| 36 | + arctan = np.arctan2(diff_x, -diff_y) |
| 37 | + d_arr = np.zeros((n_bar, num_steps)) |
| 38 | + |
| 39 | + d_mask = np.full((n_bar,num_steps), False) |
| 40 | + arctan_diff = np.abs(np.diff(arctan, axis = 0)) > np.pi |
| 41 | + d_mask[1:-1,:] = arctan_diff |
| 42 | + |
| 43 | + |
| 44 | + # d of worm endpoints is based off of two points, whereas d of non-endpoints is based off of 3 (x, y) points |
| 45 | + |
| 46 | + d_arr[:-1, :] = arctan |
| 47 | + d_arr[1:, :] = d_arr[1:, :] + arctan |
| 48 | + d_arr[1:-1, :] = d_arr[1:-1, :] / 2 |
| 49 | + d_arr = d_arr - np.pi*d_mask |
| 50 | + dx = np.cos(d_arr)*r_i |
| 51 | + dy = np.sin(d_arr)*r_i |
| 52 | + |
| 53 | + |
| 54 | + px = np.zeros((2*n_bar, x.shape[1])) |
| 55 | + py = np.zeros((2*n_bar, x.shape[1])) |
| 56 | + |
| 57 | + px[:n_bar, :] = x - dx |
| 58 | + px[n_bar:, :] = np.flipud(x + dx) # Make perimeter counter-clockwise |
| 59 | + |
| 60 | + py[:n_bar, :] = y - dy |
| 61 | + py[n_bar:, :] = np.flipud(y + dy) # Make perimeter counter-clockwise |
| 62 | + |
| 63 | + return px, py |
| 64 | + |
| 65 | + |
| 66 | +def main(): |
| 67 | + |
| 68 | + # Default behavior is to use (px, py) if it exists, and if it doesn’t then automatically generate the perimeter from the midline. |
| 69 | + parser = argparse.ArgumentParser(description="Open a player for the worm behaviour.") |
| 70 | + parser.add_argument('-f', '--wcon_file', type=validate_file, help='WCON file path', required=True ) |
| 71 | + parser.add_argument('-nogui', action='store_true', help="Just load file, don't show GUI") |
| 72 | + parser.add_argument('-s', '--suppress_automatic_generation', action='store_true', help='Suppress the automatic generation of a perimeter which would be computed from the midline of the worm. If (px, py) is not specified in the WCON, a perimeter will not be shown.') |
| 73 | + parser.add_argument('-i', '--ignore_wcon_perimeter', action='store_true', help='Ignore (px, py) values in the WCON. Instead, a perimeter is automatically generated based on the midline of the worm.') |
| 74 | + parser.add_argument('-r', '--minor_radius', type=float, default=40e-3, help='Minor radius of the worm in millimeters (default: 40e-3)', required=False) |
| 75 | + |
| 76 | + args = parser.parse_args() |
| 77 | + |
| 78 | + fig, ax = plt.subplots() |
| 79 | + plt.get_current_fig_manager().set_window_title("WCON replay") |
| 80 | + ax.set_aspect("equal") |
| 81 | + |
| 82 | + with open(args.wcon_file, 'r') as f: |
| 83 | + wcon = json.load(f) |
| 84 | + |
| 85 | + if "@CelegansNeuromechanicalGaitModulation" in wcon: |
| 86 | + center_x_arr = wcon["@CelegansNeuromechanicalGaitModulation"]["objects"]["circles"]["x"] |
| 87 | + center_y_arr = wcon["@CelegansNeuromechanicalGaitModulation"]["objects"]["circles"]["y"] |
| 88 | + radius_arr = wcon["@CelegansNeuromechanicalGaitModulation"]["objects"]["circles"]["r"] |
| 89 | + |
| 90 | + for center_x, center_y, radius in zip(center_x_arr, center_y_arr, radius_arr): |
| 91 | + circle = plt.Circle((center_x, center_y), radius, color="b") |
| 92 | + ax.add_patch(circle) |
| 93 | + else: |
| 94 | + print("No objects found") |
| 95 | + |
| 96 | + # Set the limits of the plot since we don't have any objects to help with autoscaling |
| 97 | + |
| 98 | + ax.set_ylim([-1.5, 1.5]) |
| 99 | + |
| 100 | + t = np.array(wcon["data"][0]["t"]) |
| 101 | + x = np.array(wcon["data"][0]["x"]).T |
| 102 | + y = np.array(wcon["data"][0]["y"]).T |
| 103 | + |
| 104 | + print(f"Range of time: {t[0]}->{t[0]}; x range: {x.max()}->{x.min()}; y range: {y.max()}->{y.min()}") |
| 105 | + factor = 0.05 |
| 106 | + if abs(x.max()-x.min())>abs(y.max()-y.min()): |
| 107 | + side = abs(x.max()-x.min()) |
| 108 | + ax.set_xlim([x.min()-side*factor, x.max()+side*factor]) |
| 109 | + mid = (y.max()+y.min())/2 |
| 110 | + ax.set_ylim([mid-side*(.5+factor), mid+side*(.5+factor)]) |
| 111 | + else: |
| 112 | + side = abs(y.max()-y.min()) |
| 113 | + ax.set_ylim([y.min()-side*factor, y.max()+side*factor]) |
| 114 | + mid = (x.max()+x.min())/2 |
| 115 | + ax.set_xlim([mid-side*(.5+factor), mid+side*(.5+factor)]) |
| 116 | + |
| 117 | + |
| 118 | + num_steps = t.size |
| 119 | + |
| 120 | + if "px" in wcon["data"][0] and "py" in wcon["data"][0]: |
| 121 | + if args.ignore_wcon_perimeter: |
| 122 | + print("Ignoring (px, py) values in WCON file and computing perimeter from midline.") |
| 123 | + px, py = get_perimeter(x, y, args.minor_radius) |
| 124 | + else: |
| 125 | + print("Using (px, py) from WCON file") |
| 126 | + px = np.array(wcon["data"][0]["px"]).T |
| 127 | + py = np.array(wcon["data"][0]["py"]).T |
| 128 | + else: |
| 129 | + if not args.suppress_automatic_generation: |
| 130 | + print("Computing perimeter from midline") |
| 131 | + px, py = get_perimeter(x, y, args.minor_radius) |
| 132 | + else: |
| 133 | + print("Not computing perimeter from midline") |
| 134 | + px = None |
| 135 | + py = None |
| 136 | + |
| 137 | + def update(ti): |
| 138 | + global midline_plot, perimeter_plot |
| 139 | + f = ti / num_steps |
| 140 | + |
| 141 | + color = "#%02x%02x00" % (int(0xFF * (f)), int(0xFF * (1 - f) * 0.8)) |
| 142 | + print("Time step: %s, fract: %f, color: %s" % (ti, f, color)) |
| 143 | + |
| 144 | + if midline_plot is None: |
| 145 | + (midline_plot,) = ax.plot(x[:, ti], y[:, ti], color="g", label="t=%sms" % t[ti], linewidth=0.5) |
| 146 | + else: |
| 147 | + midline_plot.set_data(x[:, ti], y[:, ti]) |
| 148 | + |
| 149 | + if px is not None and py is not None: |
| 150 | + if perimeter_plot is None: |
| 151 | + (perimeter_plot,) = ax.plot(px[:, ti], py[:, ti], color="grey", linewidth=1) |
| 152 | + else: |
| 153 | + perimeter_plot.set_data(px[:, ti], py[:, ti]) |
| 154 | + |
| 155 | + ani = Player(fig, update, maxi=num_steps - 1) |
| 156 | + |
| 157 | + # TODO WormViewCSV and WormViewWCON - should WormViewCSV just be the original WormView? That's what it initially did. |
| 158 | + # TODO Could take out Player and WormViewWCON into separate repo - Taking out Player could be ugly. It is quite coupled with WormView due to the update function. |
| 159 | + |
| 160 | + if not args.nogui: |
| 161 | + plt.show() |
| 162 | + |
| 163 | +if __name__ == "__main__": |
| 164 | + sys.exit(main()) |
0 commit comments