<jupyter_start><jupyter_text>System Environments<jupyter_code>def air_collision_condition(ctraces):
        """ground collision premature termination condition
        """
        # get the aircraft states
        sa, sb = ctraces['plant_a']['states'], ctraces['plant_b']['states']
        if sa and sb:
            # look at distance between last state
            return (np.linalg.norm(np.array(sa[-1][9:11]) - np.array(sb[-1][9:11]))) < 100
        

class F16MultiAgentCentralEnv(csaf.SystemEnv):
    """System Environment Definition"""
    system_type = F16MultiAgentCentral
    agents = ["autopilot"]
    

# create an environment and check it
my_env = F16MultiAgentCentralEnv(terminating_conditions_all=air_collision_condition)
my_env.check()
# set the scenario states
my_env.set_state('plant_a', [500.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 6000.0, 9.0])
my_env.set_state('plant_b', [500.0, 0.0, 0.0, 0.0, 0.0, np.pi, 0.0, 0.0, 0.0, 6000.0, 0.0, 6000.0, 9.0])
# collect aircraft states
pstates = []

# send signal of zeros - for this example, send only zeros except for throttle
ctrl_signal = [0., 0.0, 0., 0.7]

# step through simulation and collect f16 states
# StopIteration is thrown when the terminating conditions are achieved
do_sim = True
ctime = 0.0
while do_sim:
    try:
        # send the outputs, can collect the inputs
        ctime, comp_input = my_env.step({"outputs_0": [0., 
                                                       np.cos(10 * ctime) * 2,  
                                                       np.sin(10 * ctime) * 10, 
                                                       0.5], 
                                         "outputs_1": ctrl_signal}) 
        
        # break if outside of time span
        if ctime > 10.0:
            break
        
        # get the states and track them over time
        pstates.append((comp_input))
    
    # stop iteration occurs when the termination conditions are satisfied
    except StopIteration as e:
        do_sim = False
        break
        
    # other errors can occur -- maybe solver error
    except Exception as e:
        print(e)
        raise e
        break
        
pstates = np.array(pstates)
plt.figure(figsize=(8, 8))
y, x = pstates[:, 9:11].T
plt.plot(x, y, label='Plant A')
y, x = pstates[:, 9+17:11+17].T
plt.plot(x, y, label='Plant B')
plt.axis('equal')
plt.xlabel("East / West Position (ft)")
plt.ylabel("North / South Position (ft)")
plt.title("Plant Positions")
plt.grid()
plt.legend()
plt.show()<jupyter_output><empty_output><jupyter_text>Parallel Simulations<jupyter_code>def task(show_status=False):
    my_sys = F16MultiAgentCentral()
    my_sys.set_state('plant_a', [500.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 6000.0, 9.0])
    my_sys.set_state('plant_b', [500.0, 0.0, 0.0, 0.0, 0.0, np.pi, 0.0, 0.0, 0.0, 
                                 random.random()*5000, random.random()*400-200, 6000.0, 9.0])
    return my_sys.simulate_tspan((0.0, 20.0), 
                                 terminating_conditions_all=air_collision_condition, 
                                 show_status=show_status)
task(True)
from joblib import Parallel, delayed
from time import perf_counter
from contextlib import contextmanager


@contextmanager
def catchtime() -> float:
    """simple way to capture time via a context manager"""
    start = perf_counter()
    yield lambda: perf_counter() - start


# simulate 100 samples using joblib
with catchtime() as t:
    trajsp = Parallel(n_jobs=16)(delayed(task)() for i in range(100))
print(f"[parallel for] Execution Time: {t():.4f} secs")
for t in trajsp:
    plt.scatter(*t['plant_b'].states[0][9:11], marker='x', c='k')
plt.axis('equal')
plt.xlabel("East / West Position (ft)")
plt.ylabel("North / South Position (ft)")
plt.title("Plant B Initial Position")
plt.grid()
plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13377926421404682, 'fraction_numerical': 0.052225366606637506, 'mean_word_length': 2.502702702702703, 'pattern_counts': {'":': 2, '<': 10, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 13, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '424100', 'license': 'BSD-3-Clause', 'n_tokens_mistral': 1443, 'n_tokens_neox': 1289, 'n_words': 342, 'path': 'new_csaf/notebooks/f16-multiagent-env.ipynb', 'repo_name': 'yokian/csaf', 'size': '3887'}