gen_cube3d.py 8.08 KB
Newer Older
1
2
3
4
5
6
#!/usr/bin/env python3
from sympy import *
from gcode2contour import Position, contour
from sympy.plotting import plot3d
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.colors as mcolors
Jayant Khatkar's avatar
Jayant Khatkar committed
7
from copy import deepcopy, copy
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80

import matplotlib.pyplot as plt
import numpy as np


def set_aspect_equal_3d(ax):
    """Fix equal aspect bug for 3D plots."""

    xlim = ax.get_xlim3d()
    ylim = ax.get_ylim3d()
    zlim = ax.get_zlim3d()

    from numpy import mean
    xmean = mean(xlim)
    ymean = mean(ylim)
    zmean = mean(zlim)

    plot_radius = max([abs(lim - mean_)
                       for lims, mean_ in ((xlim, xmean),
                                           (ylim, ymean),
                                           (zlim, zmean))
                       for lim in lims])

    ax.set_xlim3d([xmean - plot_radius, xmean + plot_radius])
    ax.set_ylim3d([ymean - plot_radius, ymean + plot_radius])
    ax.set_zlim3d([zmean - plot_radius, zmean + plot_radius])


def plot_contours(*args):
    """
    Plots a list of contours

    Each input arguement is a list of contours
      All contours within each list will be the same color
      Contours in different lists will be different colors
    """
    fig = plt.figure()
    ax = Axes3D(fig)
#    colors = [k for k in mcolors.cnames]
    colors = ['blue', 'red', 'green']

    for i, contours in enumerate(args):
        for c in contours:
            xs = [pos[0] for pos in c.pos]
            ys = [pos[1] for pos in c.pos]
            zs = [pos[2] for pos in c.pos]
            ax.plot(xs, ys, zs, color=colors[i])

    set_aspect_equal_3d(ax)
    plt.show()
    return


class solver:
    """
    Handles symbolic variables to solve for layer 
    positions in various planes
    """

    def __init__(self, cl, cx, cy, dz):

        self.x, self.y, self.z, self.cz = symbols('x y z cz')
        self.layer = cl * sin(cx*self.x)*sin(cy*self.y) + self.cz

        self.dz = dz

        self.def_prism()


    def get_z(self, x, y, layer=0):
        return float(self.layer.subs([(self.x, x), (self.y, y), (self.cz, layer*self.dz)]))


81
82
83
    def def_prism(self, x_range = (-0.05, 0.05),
                 y_range = (-0.05, 0.05),
                 z_range = (0., 0.1)):
84
85
86
87
88
        """
        save the prism size
        """

        self.range = {
89
90
91
            self.x: x_range,
            self.y: y_range,
            self.z: z_range,
92
93
94
95
96
97
98
99
100
101
102
103
104
105
        }


    def plane_intersection(self, sym, val, layer = 0):
        """
        Takes a plane (not any plane, only x,y or z=val)
        and interesects it with the nth layer

        Returns symbolic expression for the intersection.
        Need to sample
        """
        return self.layer.subs([(sym, val), (self.cz, layer*self.dz)])


106
    def sample(self, expression, sym_in, res = 0.001, lims = None):
107
108
109
110
        """
        sample across one variable, get values of second variable in an expression
        """

111
112
113
114
115
        if lims is None:
            lims = self.range[sym_in]

        v1 = np.arange(lims[0], lims[1] + res, res)

116
117
118
119
120
121
122
        zs = []
        for v in v1:
            zs.append(float(expression.subs(sym_in, v)))

        return v1, zs


123
    def trim_contour(self, c):
Jayant Khatkar's avatar
Jayant Khatkar committed
124
125
126
127
128
129
130
131
132
        """
        take a contour and split it at z limits

        returns a list of contours.
        This list will be the original contour if it doesnt reach out of the limits
        If it doesn, regions outside the limits will be cut off, and regions inside 
        will be split
        """

133
        zlims = self.range[self.z]
Jayant Khatkar's avatar
Jayant Khatkar committed
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
        c_out = []
        j = 0 # index of last intersection with limit
        state = zlims[0] < c.pos[0][2] < zlims[1]
        for i, pos in enumerate(c):
            if (zlims[0] < pos[2] < zlims[1]) is not state:
                # State change has happened
                if state:
                    # Leaving zlim, save contour so far
                    c_out.append(contour(c.pos[j:i],0))
                else:
                    # Entering zlim, set start point
                    j = i

                state = not state #save new state

        if state:
            # the last stretch was in range
            c_out.append(contour(c.pos[j:i],0))
        return c_out

154
155
156
157
158
159
160
161
162
163
    def contour_n(self, n):
        """
        Get 4 contours for the nth layer
        4 sides of the prism unlinked
        """

        contours = []

        expr1 = self.plane_intersection(self.x, self.range[self.x][0], layer = n)
        ys, zs = self.sample(expr1, self.y)
Jayant Khatkar's avatar
Jayant Khatkar committed
164
        contours += self.trim_contour(
165
            contour([Position(self.range[self.x][0],ys[i],zs[i]) for i in range(len(ys))], 0)
Jayant Khatkar's avatar
Jayant Khatkar committed
166
        )
167
168
169

        expr2 = self.plane_intersection(self.x, self.range[self.x][1], layer = n)
        ys, zs = self.sample(expr2, self.y)
Jayant Khatkar's avatar
Jayant Khatkar committed
170
        contours += self.trim_contour(
171
            contour([Position(self.range[self.x][1],ys[i],zs[i]) for i in range(len(ys))], 0)
Jayant Khatkar's avatar
Jayant Khatkar committed
172
        )
173
174
175

        expr3 = self.plane_intersection(self.y, self.range[self.y][0], layer = n)
        xs, zs = self.sample(expr3, self.x)
Jayant Khatkar's avatar
Jayant Khatkar committed
176
        contours += self.trim_contour(
177
            contour([Position(xs[i],self.range[self.y][0],zs[i]) for i in range(len(ys))], 0)
Jayant Khatkar's avatar
Jayant Khatkar committed
178
        )
179
180
181

        expr4 = self.plane_intersection(self.y, self.range[self.y][1], layer = n)
        xs, zs = self.sample(expr4, self.x)
Jayant Khatkar's avatar
Jayant Khatkar committed
182
        contours += self.trim_contour(
183
            contour([Position(xs[i],self.range[self.y][1],zs[i]) for i in range(len(ys))], 0)
Jayant Khatkar's avatar
Jayant Khatkar committed
184
        )
185

Jayant Khatkar's avatar
Jayant Khatkar committed
186
        # TODO Join adjacent contours into one
187
188
189
        return contours


190
191
192
193
194
    def infill_contour(self, n, density):
        """
        return one contour for the infill
        if n is even, the infill for that layer is parallel to the x-axis
        """
195

196
197
198
199
200
201
202
203
204
205
206
207
208
209
        # Get the direction to print in
        if n%2 == 0:
            main = self.x
            other = self.y
        else:
            main = self.y
            other = self.x

        # get the list of rows to do
        main_vals = np.arange(self.range[main][0],self.range[main][1], density)[1:]

        # do the first row
        expr1 = self.plane_intersection(main, main_vals[0], layer = n)
        os, zs = self.sample(expr1, other)
210
211
212
213
        if main is self.x:
            poses = [Position(main_vals[0], os[i], zs[i]) for i in range(len(os))]
        else:
            poses = [Position(os[i], main_vals[0], zs[i]) for i in range(len(os))]
214
215

        # loop through th remaining rows, linking them
216
        direction = True
217
218
        for row in main_vals[1:]:

219
220
221
222
223
224
225
226
227
            # Connection to next row
            if main is self.y:
                expr1 = self.plane_intersection(other, poses[-1][0], layer = n)
                os, zs = self.sample(expr1, main, lims = (row - density, row))
                poses += [Position(poses[-1][0], os[i], zs[i]) for i in range(len(os))]
            else:
                expr1 = self.plane_intersection(other, poses[-1][1], layer = n)
                os, zs = self.sample(expr1, main, lims = (row - density, row))
                poses += [Position(os[i], poses[-1][1], zs[i]) for i in range(len(os))]
228
229
230
231

            expr1 = self.plane_intersection(main, row, layer = n)
            os, zs = self.sample(expr1, other)

232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
            # Reverse direction each time to get zig-zagging
            if direction:
                direction = False
                os = os[::-1]
                zs = zs[::-1]
            else:
                direction = True

            # Join the next row
            if main is self.x:
                poses += [Position(row, os[i], zs[i]) for i in range(len(os))]
            else:
                poses += [Position(os[i], row, zs[i]) for i in range(len(os))]

        return self.trim_contour(contour(poses, 0))
247
248


249
250
251
252
253
254
255
256
257
258
259
    def show(self):
        """
        Show the surface of the layer
        in the range of the cube at layer 0
        """
        plot3d(self.layer.subs(self.cz, 0),
               (self.x, self.range[self.x][0], self.range[self.x][1]),
               (self.y, self.range[self.y][0], self.range[self.y][1]))


if __name__ == '__main__':
260
    s =  solver(0.02, 100, 100, 0.01)
261

262
263
    o_contours = []
    i_contours = []
Jayant Khatkar's avatar
Jayant Khatkar committed
264
    for i in np.arange(-15,55):
265
266
        o_contours += s.contour_n(i)
        i_contours += s.infill_contour(i, 0.02)
267

268
    plot_contours(o_contours, i_contours)