[zt]第三章 Draw2D简介

Draw2D图形组件详解

FROM:http://www.blog.edu.cn/user1/19180/archives/2005/375038.shtml

3.1 概述
Draw2D是一个轻量级图形组件工具包,这些组件称为Figure。所谓轻量级系统,就是说Draw2D的组件与操作系统中的图形系统没有对应关系,Draw2D对象不过是一个普通的Java对象。Figure可以通过一种父子关系组合起来。每一个Figure都有一个边界(Bounds),它的子女必须都在这个边界中,而布局管理器用来管理子女的位置。一般来说,子女的位置会根据边界而变化,但是对于线状图元,它的边界会根据子女的位置和自己的形状发生变化。

    一个轻量级系统将一个Figure和一个SWT画布(Canvas)相关联,它的EventDispatcher监听大部分SWT的事件,并将这些事件传递给相应的Figure。对于Paint消息,轻量级系统将它传递给UpdateManager,这个UpdateManager将负责重新验证Figure和它子女的位置。

 

3.2 Draw2D的基本概念
Draw2D是一个很有用的工具包,它借用Java AWT窗口系统的基本思想(主要是布局的概念)进行绘图,同时提供丰富的概念,用于解决绘图过程中的遇到的问题。总体来说,Draw2D就是希望将绘图自动化,这也使得Draw2D在设计各种eclipse工具中扮演着极其重要的地位。Draw2D和GEF没有绝对联系,Draw2D可以独立于GEF存在并使用,因为它只和SWT相关。

    Draw2D的问题可以写很多,这里只介绍基本的概念和思想。

3.2.1 Figure
Draw2D最重要一个概念就是Figure,它可以看作是所有Draw2D图元的基类,事实上所有的Draw2D图元都继承自IFigure接口。所有Draw2D图元的都是Figure,不论是块状元素还是线状元素。

    Figure类是一个IFigure接口的基本实现,可以用它描述一个区域(矩形或者线形)。Shape类继承自Figure类,它的子类实现了很多基本图形的功能,这包括Ellipse、Polyline、RectangleFigure、RoundedRectangle、Triangle。Figure类的其他子类中,还有一些比较常用的(对于绘图来说),比如Label、Layer、Panel。

3.2.2 Layout
LayoutManager是布局的接口,它负责定位Figure子女的位置。

    XYLayout和FreeformLayout相当于绝对布局,使用这种布局的Figure,它的子女位置可以自由分布。

    ToolbarLayout是工具栏布局,使用这个布局的Figure,它的子女按照水平或者垂直的方式排布。

    FlowLayout是流布局,使用这个布局的Figure,它的子女首先会尽量水平排布,如果排不下了,则进行垂直排布。

    Draw2D中还提供了其他的布局,这里不再一一进行介绍。关于布局的话题,以后有时间再研究。

3.2.3 Anchor和Router
Anchor是用来定位连接线端点的对象。

    ChopboxAnchor将锚点设为矩形的中心,连接线的端点将定位到矩形的边界上。EllipseAnchor将锚点定位到椭圆形的中心上,连接线的端点将定位到椭圆形的边界上。XYAnchor则用来描述独立的锚点。

    Router用来负责计算连接线的中间点,根据不同的方案,折线的中间点将计算为不同的位置。

3.2.4 Locator
Locator用来定位Figure的位置,和Anchor不同,Locator的不是处理线端,而是处理Figure。

    ConnectionEndpointLocator用来描述Figure和线端的位置。

import numpy as np from scipy import interpolate import matplotlib.pyplot as plt import pylab as mpl mpl.rcParams['font.sans-serif'] = ['SimHei'] # 地图模型类 class Model: def __init__(self, start, target, bound, obstacle, n, vpr=0.1): [self.xs, self.ys], [self.xt, self.yt] = start, target [[self.xmin, self.xmax], [self.ymin, self.ymax]] = bound self.vxmax, self.vxmin = vpr * (self.xmax - self.xmin), -vpr * (self.xmax - self.xmin) self.vymax, self.vymin = vpr * (self.ymax - self.ymin), -vpr * (self.ymax - self.ymin) self.xobs = np.array([obs[0] for obs in obstacle]) self.yobs = np.array([obs[1] for obs in obstacle]) self.robs = np.array([obs[2] for obs in obstacle]) self.n = n def straight_path(self): return np.linspace(self.xs, self.xt, self.n + 2)[1:-1], np.linspace(self.ys, self.yt, self.n + 2)[1:-1] def random_path(self): return np.random.uniform(self.xmin, self.xmax, self.n), np.random.uniform(self.ymin, self.ymax, self.n) def random_velocity(self): return np.random.uniform(self.vxmin, self.vxmax, self.n), np.random.uniform(self.vymin, self.vymax, self.n) # 路径规划和碰撞检测 def plan_path(x, y, model): XS = np.insert(np.array([model.xs, model.xt]), 1, x) YS = np.insert(np.array([model.ys, model.yt]), 1, y) TS = np.linspace(0, 1, model.n + 2) tt = np.linspace(0, 1, 200) #将路径等切为200段,减少因段数较少导致部分段的欧几里得距离穿过障碍物 f1 = interpolate.UnivariateSpline(TS, XS, s=0) f2 = interpolate.UnivariateSpline(TS, YS, s=0) xx, yy = f1(tt), f2(tt) dx, dy = np.diff(xx), np.diff(yy) L = np.sum(np.sqrt(dx ** 2 + dy ** 2)) d = np.sqrt((xx[:, None] - model.xobs) ** 2 + (yy[:, None] - model.yobs) ** 2) violation = np.sum(np.clip(1 - d / model.robs, 0, None).mean(axis=0)) return xx, yy, L, violation # 画图函数 def draw_path(model, x, y, xx, yy, title='路径规划'): plt.title(title) plt.scatter(model.xs, model.ys, label='起点', marker='o', color='red') plt.scatter(model.xt, model.yt, label='终点', marker='*', color='green') theta = np.linspace(0, 2 * np.pi, 100) for i in range(len(model.robs)): plt.fill(model.xobs[i] + model.robs[i] * np.cos(theta), model.yobs[i] + model.robs[i] * np.sin(theta), 'gray') plt.scatter(x, y, label='决策点', marker='x', color='blue') plt.plot(xx, yy, label='路径') plt.legend() plt.grid() plt.axis('equal') plt.show() # PSO路径规划(替换优化策略和方式) def pso_path_planning(model, T=200, swarm_size=100, w=0.7, c1_start=2.5, c1_end=0.5, c2_start=0.5, c2_end=2.5, clone_rate=0.1, mutation_rate=0.05): # 初始化种群 swarm = [] for i in range(swarm_size): if i == 0: x, y = model.straight_path() else: x, y = model.random_path() vx, vy = model.random_velocity() xx, yy, L, violation = plan_path(x, y, model) swarm.append({ 'position': np.array([x, y]), 'velocity': np.array([vx, vy]), 'best_position': np.array([x.copy(), y.copy()]), 'cost': L * (1 + violation * 100), 'is_feasible': violation == 0 }) gbest = sorted(swarm, key=lambda p: p['cost'])[0] # 记录全局最佳历史 best_costs_history = [] # PSO迭代 for t in range(T): # 非线性更新c1和c2 c1 = c1_start - (c1_start - c1_end) * (1 - np.cos(np.pi * t / (2 * T))) c2 = c2_start + (c2_end - c2_start) * (1 - np.cos(np.pi * t / (2 * T))) # 更新粒子速度和位置 for particle in swarm: # 更新速度和位置 r1, r2 = np.random.rand(), np.random.rand() particle['velocity'] = w * particle['velocity'] + \ c1 * r1 * (particle['best_position'] - particle['position']) + \ c2 * r2 * (gbest['position'] - particle['position']) # 速度限制 particle['velocity'] = np.clip(particle['velocity'], np.array([model.vxmin, model.vymin])[:, None], np.array([model.vxmax, model.vymax])[:, None]) # 更新位置 particle['position'] += particle['velocity'] # 位置限制 particle['position'][0] = np.clip(particle['position'][0], model.xmin, model.xmax) particle['position'][1] = np.clip(particle['position'][1], model.ymin, model.ymax) # 计算新路径 xx, yy, L, violation = plan_path(particle['position'][0], particle['position'][1], model) # 更新个人最佳 new_cost = L * (1 + violation * 100) if new_cost < particle['cost']: particle['best_position'] = particle['position'].copy() particle['cost'] = new_cost particle['is_feasible'] = violation == 0 # 更新全局最佳 if particle['cost'] < gbest['cost']: gbest = particle.copy() # 免疫克隆和突变操作 fitness_values = np.array([particle['cost'] for particle in swarm]) sorted_indices = np.argsort(fitness_values) c_num = int(swarm_size * clone_rate) cloned_swarm = [] for idx in sorted_indices[:c_num]: cloned_particle = { 'position': swarm[idx]['position'].copy(), 'velocity': swarm[idx]['velocity'].copy(), 'best_position': swarm[idx]['best_position'].copy(), 'cost': swarm[idx]['cost'], 'is_feasible': swarm[idx]['is_feasible'] } cloned_swarm.append(cloned_particle) for particle in cloned_swarm: if np.random.rand() < mutation_rate: for dim in range(2): # 对x和y两个维度进行突变 mutation_idx = np.random.randint(0, model.n) particle['position'][dim][mutation_idx] += np.random.uniform(-0.5, 0.5) particle['position'][dim] = np.clip(particle['position'][dim], [model.xmin if dim == 0 else model.ymin], [model.xmax if dim == 0 else model.ymax]) # 重新计算速度(可选) particle['velocity'][dim][mutation_idx] = np.random.uniform( model.vxmin if dim == 0 else model.vymin, model.vxmax if dim == 0 else model.vymax ) # 随机扰动 particle['position'][dim] += np.random.uniform(-0.1, 0.1, size=model.n) particle['position'][dim] = np.clip(particle['position'][dim], [model.xmin if dim == 0 else model.ymin], [model.xmax if dim == 0 else model.ymax] ) swarm.extend(cloned_swarm) # 记录当前最佳成本 best_costs_history.append(gbest['cost']) print(f"第{t + 1}代: cost={gbest['cost']:.2f}") return gbest, best_costs_history if __name__ == '__main__': # 创建模型 start = [0.0, 0.0] target = [5.0, 4.0] bound = [[-10.0, 10.0], [-10.0, 10.0]] obstacle = [[1.5, 4.5, 1.3], [4.0, 3.0, 1.0], [1.2, 1.5, 0.8]] model = Model(start, target, bound, obstacle, 3) # PSO路径规划 gbest, costs = pso_path_planning(model) # 绘制结果 xx, yy, _, _ = plan_path(gbest['position'][0], gbest['position'][1], model) draw_path(model, gbest['position'][0], gbest['position'][1], xx, yy) plt.plot(costs) plt.title('The shortest path varies with the number of iterations') plt.xlabel('Number of iterations') plt.ylabel('Shortest path') plt.grid() plt.show() 我提供的是改进的PSO算法在二维层面的避障,请将算法拓展到三维层面(障碍物包括一个圆柱体和两个球体),目标点设置为(400,200,300)
08-10
【无人机】基于改进粒子群算法的无人机路径规划研究[和遗传算法、粒子群算法进行比较](Matlab代码实现)内容概要:本文围绕基于改进粒子群算法的无人机路径规划展开研究,重点探讨了在复杂环境中利用改进粒子群算法(PSO)实现无人机三维路径规划的方法,并将其与遗传算法(GA)、标准粒子群算法等传统优化算法进行对比分析。研究内容涵盖路径规划的多目标优化、避障策略、航路点约束以及算法收敛性和寻优能力的评估,所有实验均通过Matlab代码实现,提供了完整的仿真验证流程。文章还提到了多种智能优化算法在无人机路径规划中的应用比较,突出了改进PSO在收敛速度和全局寻优方面的优势。; 适合人群:具备一定Matlab编程基础和优化算法知识的研究生、科研人员及从事无人机路径规划、智能优化算法研究的相关技术人员。; 使用场景及目标:①用于无人机在复杂地形或动态环境下的三维路径规划仿真研究;②比较不同智能优化算法(如PSO、GA、蚁群算法、RRT等)在路径规划中的性能差异;③为多目标优化问题提供算法选型和改进思路。; 阅读建议:建议读者结合文中提供的Matlab代码进行实践操作,重点关注算法的参数设置、适应度函数设计及路径约束处理方式,同时可参考文中提到的多种算法对比思路,拓展到其他智能优化算法的研究与改进中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值