-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathknit3D.py
6724 lines (5411 loc) · 279 KB
/
knit3D.py
1
2
3
4
5
6
7
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from copy import deepcopy
from distutils import util
import math
import os
import warnings
import numpy as np
from PIL import Image, ImageColor
#NOTE: for gauge > 1: decided baseBed should consistently be front so as to make things less complicated (because doesn't really matter) --- so translation would be fn -> f(gauge*n) bn -> b((gauge*n)+1)
#---------------------------------------------
#--- CUSTOMIZABLE VARIABLES FOR EXTENSIONS ---
#---------------------------------------------
class KnitoutSpecs:
def __init__(self):
if not 'warnings' in self.__dict__: first_init = True
else: first_init = False
#for waste section
self.wasteSpeedNumber = 400
self.wasteStitchNumber = 5 #new (used to be 4)
#for main section
self.speedNumber = 300
self.stitchNumber = 4
self.rollerAdvance = 300
#for xfers
self.xferSpeedNumber = 300
self.xferStitchNumber = math.ceil(self.stitchNumber//2)
self.xferRollerAdvance = 0
#for splits
self.splitSpeedNumber = 100
self.splitStitchNumber = 4
self.splitRollerAdvance = 0
#for wasteWeights
self.wasteWeightsRowCount = 20
# if first_init:
self.warnings = []
def action_func(new_stitch):
try:
self.set_ext('stitchNumber', int(new_stitch), throw_warnings=False)
except ValueError:
print(f'Ok, leave stitch number as {self.stitchNumber}.')
self.add_warning(
message=f'Currently, the stitch number is {self.stitchNumber}, which often leads to yarn-breakage on your machine.\nIf you would like to change the stitch number, input that number (or press the Enter key to keep it): ',
condition=('gohlson/' in os.getcwd() and self.stitchNumber < 5),
action_func=action_func
)
self.throw_warnings()
# if 'gohlson/' in os.getcwd() and self.stitchNumber < 5:
# new_stitch = input(f'Currently, the stitch number is {self.stitchNumber}, which often leads to yarn-breakage on your machine.\nIf you would like to change the stitch number, input that number (or press the Enter key to keep it): ')
# try:
# self.set_ext('stitchNumber', int(new_stitch()))
# except ValueError:
# print(f'Ok, leave stitch number as {self.stitchNumber}.')
# func = lambda a,b: (
# if 'gohlson/' in os.getcwd() and self.stitchNumber < 5:
# new_stitch = input(f'Currently, the stitch number is {self.stitchNumber}, which often leads to yarn-breakage on your machine.\nIf you would like to change the stitch number, input that number (or press the Enter key to keep it): ')
# try:
# self.set_ext('stitchNumber', int(new_stitch))
# except ValueError:
# print(f'Ok, leave stitch number as {self.stitchNumber}.')
# )
# self.warnings.append(func)
# lambda x:
# if 'gohlson/' in os.getcwd() and self.stitchNumber < 5: new_stitch = input(f'Currently, the stitch number is {self.stitchNumber}, which often leads to yarn-breakage on your machine.\nIf you would like to change the stitch number, input that number (or press the Enter key to keep it): ')
# try:
# new_stitch = int(new_stitch)
# self.set_ext('stitchNumber', new_stitch)
# except ValueError:
# print(f'Ok, leave stitch number as {self.stitchNumber}.')
def set_ext(self, ext, val, throw_warnings=True):
self.__dict__[ext] = val
if throw_warnings: self.throw_warnings()
def defaults(self):
self.__init__()
def throw_warnings(self):
print(f'throwing {len(self.warnings)} warning(s):\n')
for warning_func in self.warnings:
warning_func()
# def warnings(self):
# if 'gohlson/' in os.getcwd() and self.stitchNumber < 5:
# new_stitch = input(f'Currently, the stitch number is {self.stitchNumber}, which often leads to yarn-breakage on your machine.\nIf you would like to change the stitch number, input that number (or press the Enter key to keep it): ')
# try:
# new_stitch = int(new_stitch)
# self.set_ext('stitchNumber', new_stitch)
# except ValueError:
# print(f'Ok, leave stitch number as {self.stitchNumber}.')
def add_warning(self, message, condition=None, action_func=None):
def warning_func(message=message, condition=condition, action_func=action_func):
if condition is None or condition:
response = input(message) # Enter key to ignore warning
if len(response.strip()):
if action_func is not None: action_func(response)
else: print('Ok, warning ignored.')
self.warnings.append(warning_func)
# self.warnings.append(
# lambda x:
# if condition is None or condition:
# response = input(message) # Enter key to ignore warning
# if len(response.strip()):
# if action_func is not None: action_func(response)
# else: print('Ok, warning ignored.')
# )
specs = KnitoutSpecs()
# #for waste section
# wasteSpeedNumber = 400
# wasteStitchNumber = 4
# #for main section
# speedNumber = 300
# stitchNumber = 4
# rollerAdvance = 300
# #for xfers
# xferSpeedNumber = 300
# xferStitchNumber = math.ceil(stitchNumber//2)
# xferRollerAdvance = 0
# #for splits
# splitSpeedNumber = 100
# splitStitchNumber = 4
# splitRollerAdvance = 0
# #for wasteWeights
# wasteWeightsRowCount = 20
#----------------------
#--- MISC FUNCTIONS ---
#----------------------
def query_yes_no(question, default=None):
if default is None:
prompt = " [y/n] "
elif default == 'yes':
prompt = " [Y/n] "
elif default == 'no':
prompt = " [y/N] "
else:
raise ValueError(f"Unknown setting '{default}' for default.")
while True:
try:
resp = input(question + prompt).strip().lower()
if default is not None and resp == '':
return default == 'yes'
else:
return util.strtobool(resp)
except ValueError:
print("Please respond with 'yes' or 'no' (or 'y' or 'n').\n")
def colorDistance(rgb1, rgb2, returnRGBs=False):
np_rgb1 = np.array(list(rgb1))
np_rgb2 = np.array(list(rgb2))
rm = 0.5*(np_rgb1[0]+np_rgb2[0])
d = abs(sum((2+rm, 4, 3-rm) * (np_rgb1-np_rgb2)**2))**0.5
if returnRGBs: return d, rgb1, rgb2
else: return d
def setSettings(k=None, speedNumber=None, stitchNumber=None, rollerAdvance=None, xferSpeedNumber=None, xferStitchNumber=None, xferRollerAdvance=None, splitSpeedNumber=None, splitStitchNumber=None, splitRollerAdvance=None, wasteSpeedNumber=None, wasteStitchNumber=None, wasteWeightsRowCount=None):
'''
*TODO
'''
settings = locals()
for key, val in settings.items():
if val is None or key == 'k': continue
else: specs.set_ext(key, val, throw_warnings=False)
specs.throw_warnings()
# if speed is not None:
# globals()['speedNumber'] = speed
# if k is not None: k.speedNumber(speed)
# if stitch is not None:
# globals()['stitchNumber'] = stitch
# if k is not None: k.stitchNumber(stitch)
# if roller is not None:
# globals()['rollerAdvance'] = roller
# if k is not None: k.rollerAdvance(roller)
# if xferSpeed is not None: globals()['xferSpeedNumber'] = xferSpeed
# if xferStitch is not None:
# globals()['xferStitchNumber'] = xferStitch
# if k is not None: k.xferStitchNumber(xferStitch) #only xfer setting with dedicated extension
# if xferRoller is not None: globals()['xferRollerAdvance'] = xferRoller
# if splitSpeed is not None: globals()['splitSpeedNumber'] = splitSpeed
# if splitStitch is not None: globals()['splitStitchNumber'] = splitStitch
# if splitRoller is not None: globals()['splitRollerAdvance'] = splitRoller
# if wasteSpeed is not None: globals()['wasteSpeedNumber'] = wasteSpeed
# if wasteStitch is not None: globals()['wasteStitchNumber'] = wasteStitch
def defaultSettings(k=None): #TODO: add warning here
specs.defaults()
# #for main section
# globals()['speedNumber'] = 300
# globals()['stitchNumber'] = 4
# globals()['rollerAdvance'] = 300
# #for xfers
# globals()['xferSpeedNumber'] = 300
# globals()['xferStitchNumber'] = math.ceil(stitchNumber//2)
# globals()['xferRollerAdvance'] = 0
# #for splits
# globals()['splitSpeedNumber'] = 100
# globals()['splitStitchNumber'] = 4
# globals()['splitRollerAdvance'] = 0
# #for waste section
# globals()['wasteSpeedNumber'] = 400
if k is not None:
k.speedNumber(specs.speedNumber)
k.stitchNumber(specs.stitchNumber)
k.rollerAdvance(specs.rollerAdvance)
k.xferStitchNumber(specs.xferStitchNumber)
def xferSettings(k, alterations={}):
'''
*TODO
'''
xSpeed = specs.xferSpeedNumber
xStitch = specs.xferStitchNumber
xRoll = specs.xferRollerAdvance
if 'speedNumber' in alterations: xSpeed = alterations['speedNumber']
if 'stitchNumber' in alterations: xStitch = alterations['stitchNumber']
if 'rollerAdvance' in alterations: xRoll = alterations['rollerAdvance']
k.speedNumber(xSpeed)
k.stitchNumber(xStitch)
k.rollerAdvance(xRoll)
def splitSettings(k, alterations={}):
'''
*TODO
'''
splitSpeed = specs.splitSpeedNumber
splitStitch = specs.splitStitchNumber
splitRoll = specs.splitRollerAdvance
if 'speedNumber' in alterations: splitSpeed = alterations['speedNumber']
if 'stitchNumber' in alterations: splitStitch = alterations['stitchNumber']
if 'rollerAdvance' in alterations: splitRoll = alterations['rollerAdvance']
k.speedNumber(splitSpeed)
k.stitchNumber(splitStitch)
k.rollerAdvance(splitRoll)
def resetSettings(k):
'''
*TODO
'''
k.speedNumber(specs.speedNumber)
k.stitchNumber(specs.stitchNumber)
k.rollerAdvance(specs.rollerAdvance)
def convertGauge(gauge=2, leftN=None, rightN=None):
'''
*TODO
'''
newLeftN = leftN
newRightN = rightN
if gauge > 1:
if leftN is not None: newLeftN = int(leftN*gauge)
if rightN is not None: newRightN = int(rightN*gauge)
if leftN is None: return newRightN
elif rightN is None: return newLeftN
else: return newLeftN, newRightN
def tempMissOut(k, width, direction, c=None, buffer=None):
'''
*TODO
'''
#if c is None, meant to just move carriage out of way, without carrier
autobuffer = np.floor((252-width)/2)
if buffer is not None and buffer > autobuffer:
buffer = None
warnings.warn(f'Passes buffer value is too large, using default buffer value {autobuffer} instead.')
if direction == '-':
if buffer is None: missN = 0 - np.floor((252-width)/2)
else: missN = 0 - buffer
if c is None: k.drop(f'f{missN}') #just move carriage out of way #TODO: add carriage move (no drop) to knitout-backend-kniterate
else: k.miss('-', f'f{missN}', c) #move carrier out of way
else:
if buffer is None: missN = (width-1) + np.floor((252-width)/2)
else: missN = (width-1) + buffer
if c is None: k.drop(f'f{missN}') #just move carriage out of way
else: k.miss('+', f'f{missN}', c) #move carrier out of way
def sortBedNeedles(bnList=[], direction='+'):
'''
*TODO
'''
sortedBnList = list(set(bnList.copy()))
if direction == '-': sortedBnList.sort(key=lambda bn: int(bn[1:]), reverse=True)
else: sortedBnList.sort(key=lambda bn: int(bn[1:]))
return sortedBnList
def placeCarrier(k, leftN=None, rightN=None, carrierOpts=[], gauge=2, opDetails={}):
'''
*TODO
'''
placedCarrier = None #for now
tuckDir = None
tuckDrop = []
lastOps = []
carrierOpts = list(filter(None, carrierOpts))
for c in carrierOpts:
lastLineC = k.returnLastOp(carrier=c, asDict=True, **opDetails)
if lastLineC is not None: lastOps.append(lastLineC)
else: lastOps.append({'op': None, 'carrier': c})
distances = {}
needleNums = {}
for ln in lastOps:
c = ln['carrier']
if type(c) == list:
for carr in c:
if carr in carrierOpts:
c = carr
break
if ln['op'] == 'in' or ln['op'] == 'out' or ln['op'] is None: needleNum = 0 #just assume 0 is the min needle (#TODO: have option for detecting min needle) #if None, means carrier hasn't been used yet
else: needleNum = ln['bn1']['needle']
needleNums[c] = needleNum
if leftN is not None: distances[abs(needleNum-leftN)] = {'carrier': c, 'sideN': leftN}
if rightN is not None: distances[abs(needleNum-rightN)] = {'carrier': c, 'sideN': rightN}
if len(distances):
minDist = min(distances.keys())
placedCarrier = distances[minDist]['carrier']
needleNum = needleNums[placedCarrier]
if (needleNum-(distances[minDist]['sideN'])) > 0: tuckDir = '-'
else: tuckDir = '+'
if minDist > 5: #need to tuck to get it in correct spot
tuckB = 0 #for tucking every other
tuckF = 0
k.comment(f'tuck to move carrier {placedCarrier} from {needleNum} to {distances[minDist]["sideN"]}')
k.rollerAdvance(0)
if tuckDir == '+':
for t in range(needleNums[placedCarrier]+1, distances[minDist]['sideN']):
if t % gauge == 0:
if tuckB % 2 == 0:
k.tuck('+', f'b{t}', placedCarrier)
tuckDrop.append(f'b{t}')
tuckB += 1
elif t % gauge != 0:
if tuckF % 2 == 0:
k.tuck('+', f'f{t}', placedCarrier)
tuckDrop.append(f'f{t}')
tuckF += 1
else:
for t in range(needleNums[placedCarrier]-1, distances[minDist]['sideN'], -1):
if t % gauge == 0:
if tuckB % 2 == 0:
k.tuck('-', f'b{t}', placedCarrier)
tuckDrop.append(f'b{t}')
tuckB += 1
elif t % gauge != 0:
if tuckF % 2 == 0:
k.tuck('-', f'f{t}', placedCarrier)
tuckDrop.append(f'f{t}')
tuckF += 1
k.rollerAdvance(specs.rollerAdvance)
return tuckDrop, placedCarrier, tuckDir
flatten = lambda *n: list(e for a in n for e in (flatten(*a) if isinstance(a, (tuple, list,)) else (a,)))
def includeNSecureSides(n, secureNeedles={}, knitBed=None):
'''
*n is the number associated with the needle we're checking
*secureNeedles is dict with needle numbers as key and bed as value (valid values are 'f', 'b', or 'both')
*knitBed is the bed that is currently knitting, if applicable (because this is only checking if we can't xfer it, so if it was unable to be xferred from a certain bed, it should still be knitted on that bed); value of None indicates we are just check for xfer
'''
if n in secureNeedles:
if knitBed is None: return False
else: #for knitting
if knitBed == secureNeedles[n]: return True
else: return False
else: return True
def convertToBN(needles, sort=True, gauge=2):
'''
for now, only works with: list (with potential sublists/sub-ranges), int, or str
'''
try:
int(needles)
return f'b{needles}' if (needles % gauge != 0) else f'f{needles}'
except Exception:
if type(needles) == str: return needles
else: # list of lists of range
needles = [convertToBN(n) for sublist in needles for n in ([sublist] if isinstance(sublist, (str, int, float)) else sublist)] #new # if type(needles[0]) == list or type(needles[0]) == range:
# if isinstance(needles[0], (list, range, tuple)): needles = [convertToBN(n) for sublist in needles for n in list(sublist)] #new # if type(needles[0]) == list or type(needles[0]) == range:
# else: needles = [convertToBN(n) for n in needles]
# needles = flatten(needles) #new
if sort: sortBedNeedles(needles)
return needles #otherwise, just return original list
# e.g.: `convertToBN([1, 2, 'f2', range(0, 10)])`
#----------------------------------------------------
#--- STANDARD KNITTING FUNCTIONS /STITCH PATTERNS ---
#----------------------------------------------------
#--- KNITTING PASSES ---
def knitPass(k, startN, endN, c, bed='f', gauge=1, emptyNeedles=[]):
'''
*TODO
'''
if endN > startN: #pass is pos
for n in range(startN, endN+1):
if f'{bed}{n}' not in emptyNeedles:
if (bed == 'f' and n % gauge == 0) or (bed == 'b' and (gauge == 1 or n % gauge != 0)): k.knit('+', f'{bed}{n}', c)
elif n == endN: k.miss('+', f'{bed}{n}', c)
elif n == endN: k.miss('+', f'{bed}{n}', c)
else: #pass is neg
for n in range(startN, endN-1, -1):
if f'{bed}{n}' not in emptyNeedles:
if (bed == 'f' and n % gauge == 0) or (bed == 'b' and (gauge == 1 or n % gauge != 0)): k.knit('-', f'{bed}{n}', c)
elif n == endN: k.miss('-', f'{bed}{n}', c)
elif n == endN: k.miss('-', f'{bed}{n}', c)
def jersey(k, startN, endN, length, c, currentBed='f', gauge=1, emptyNeedles=[]):
'''
*TODO
'''
k.comment('begin jersey')
for p in range(0, length):
if p % 2 == 0:
passStartN = startN
passEndN = endN
else:
passStartN = endN
passEndN = startN
knitPass(k, startN=passStartN, endN=passEndN, c=c, bed=currentBed, gauge=gauge, emptyNeedles=emptyNeedles)
k.comment('end jersey')
#--- FUNCTION FOR KNITTING ON ALT NEEDLES, PARITY SWITCHING FOR FRONT & BACK ---
def interlock(k, startN, endN, length, c, gauge=1, startCondition=1, emptyNeedles=[], currentBed=None, homeBed=None, secureStartN=False, secureEndN=False):
'''
Knits on every needle interlock starting on side indicated by which needle value is greater.
In this function length is the number of total passes knit so if you want an interlock segment that is 20 courses long on each side set length to 40. Useful if you want to have odd amounts of interlock.
*k is knitout Writer
*startN is the starting needle to knit on
*endN is the last needle to knit on (***note: no longer needs to be +1)
*length is total passes knit
*c is carrier
*gauge is the... well, gauge
*startCondition is *TODO
*emptyNeedles is *TODO
*currentBed is the bed(s) that current has knitting (valid values are: 'f' [front] and 'b' [back]); if value is None, will assume that the loops are already in position for interlock (e.g. not knitting circular half-gauge interlock)
*homeBed is the bed to transfer the loops back to at the end (if applicable); NOTE: this should only be added if knitting if half gauge tube will stitch patterns inserted on one bed (since the function will act accordingly)
*secureStartN and *secureEndN are booleans that indicate whether or not we should refrain from xferring the edge-most needles, for security (NOTE: this should be True if given edge needle is on the edge of the piece [rather than in the middle of it])
'''
emptyNeedles = convertToBN(emptyNeedles) #new #* #check
length *= 2
length = int(length) #incase doing e.g. .5 length (only a pass)
if endN > startN: #first pass is pos
beg = 0
leftN = startN
rightN = endN
else: #first pass is neg
beg = 1
length += 1
leftN = endN
rightN = startN
if startCondition == 1: startCondition = 2 #switch since starting at 1
else: startCondition = 1
if homeBed is not None:
if homeBed == 'f':
homeCondition = lambda n: (n % gauge == 0)
travelBed = 'b'
else:
homeCondition = lambda n: ((n-1) % gauge == 0)
travelBed = 'f'
def frontBed1(n, direction):
if ((n == startN and secureStartN) or (n == endN and secureEndN)) and currentBed == 'b': return False
if f'f{n}' not in emptyNeedles and n % gauge == 0 and (((n//gauge) % 2) == 0):
k.knit(direction, f'f{n}', c)
return True
else: return False
def backBed1(n, direction):
if ((n == startN and secureStartN) or (n == endN and secureEndN)) and currentBed == 'f': return False
if f'b{n}' not in emptyNeedles and (gauge == 1 or n % gauge != 0) and ((((n-1)//gauge) % 2) == 0):
k.knit(direction, f'b{n}', c)
return True
else: return False
def frontBed2(n, direction):
if ((n == startN and secureStartN) or (n == endN and secureEndN)) and currentBed == 'b': return False
if f'f{n}' not in emptyNeedles and n % gauge == 0 and (((n//gauge) % 2) != 0):
k.knit(direction, f'f{n}', c)
return True
else: return False
def backBed2(n, direction):
if ((n == startN and secureStartN) or (n == endN and secureEndN)) and currentBed == 'f': return False
if f'b{n}' not in emptyNeedles and (gauge == 1 or n % gauge != 0) and ((((n-1)//gauge) % 2) != 0):
k.knit(direction, f'b{n}', c)
return True
else: return False
if currentBed is not None: #currentBed indicates that we need to start by xferring to proper spots
xferSettings(k)
if currentBed == 'f':
otherBed = 'b'
currCondition = lambda n: (n % gauge == 0)
else:
otherBed = 'f'
currCondition = lambda n: ((n-1) % gauge == 0)
for n in range(leftN, rightN+1):
if (n == startN and secureStartN) or (n == endN and secureEndN): continue
if currCondition(n) and f'{currentBed}{n}' not in emptyNeedles and (((n//gauge) % (2*gauge)) % gauge) != 0: k.xfer(f'{currentBed}{n}', f'{otherBed}{n}') #check (especially check if works for gauge 1)
resetSettings(k)
#for if home bed
def homeBed1(n, direction):
if homeCondition(n) and f'{homeBed}{n}' not in emptyNeedles and ((n//gauge) % (2*gauge) == 0):
k.knit(direction, f'{homeBed}{n}', c)
return True
else: return False
def travelBed1(n, direction):
if (n == startN and secureStartN) or (n == endN and secureEndN):
if homeCondition(n):
k.knit(direction, f'{homeBed}{n}', c)
return True
else: return False
if homeCondition(n) and f'{travelBed}{n}' not in emptyNeedles and ((n//gauge) % (2*gauge) == (gauge+1)): #check for gauge 1
k.knit(direction, f'{travelBed}{n}', c)
return True
else: return False
def homeBed2(n, direction):
if homeCondition(n) and f'{homeBed}{n}' not in emptyNeedles and ((n//gauge) % (2*gauge) == gauge):
k.knit(direction, f'{homeBed}{n}', c)
return True
else: return False
def travelBed2(n, direction):
if (n == startN and secureStartN) or (n == endN and secureEndN):
if homeCondition(n):
k.knit(direction, f'{homeBed}{n}', c)
return True
else: return False
if homeCondition(n) and f'{travelBed}{n}' not in emptyNeedles and ((n//gauge) % (2*gauge) == (gauge-1)): #check for gauge 1
k.knit(direction, f'{travelBed}{n}', c)
return True
else: return False
#--- the knitting ---
for h in range(beg, length):
if h % 2 == 0:
for n in range(leftN, rightN+1):
if startCondition == 1: #first pass of interlock will knit on 0, 1, 4, 5, etc.
if homeBed is None or gauge == 1:
if frontBed1(n, '+'): continue
elif backBed1(n, '+'): continue
elif n == rightN: k.miss('+', f'f{n}', c)
else:
if homeBed1(n, '+'): continue
elif travelBed1(n, '+'): continue
elif n == rightN: k.miss('+', f'f{n}', c)
else: #first pass of interlock will knit on 2, 3, 6, 7, etc.
if homeBed is None or gauge == 1:
if frontBed2(n, '+'): continue
elif backBed2(n, '+'): continue
elif n == rightN: k.miss('+', f'f{n}', c)
else:
if homeBed2(n, '+'): continue
elif travelBed2(n, '+'): continue
elif n == rightN: k.miss('+', f'f{n}', c)
else:
for n in range(rightN, leftN-1, -1):
if startCondition == 2:
if homeBed is None or gauge == 1:
if frontBed1(n, '-'): continue
elif backBed1(n, '-'): continue
elif n == leftN: k.miss('-', f'f{n}', c)
else:
if homeBed1(n, '-'): continue
elif travelBed1(n, '-'): continue
elif n == leftN: k.miss('-', f'f{n}', c)
else:
if homeBed is None or gauge == 1:
if frontBed2(n, '-'): continue
elif backBed2(n, '-'): continue
elif n == leftN: k.miss('-', f'f{n}', c)
else:
if homeBed2(n, '-'): continue
elif travelBed2(n, '-'): continue
elif n == leftN: k.miss('-', f'f{n}', c)
if homeBed is not None and (gauge != 1 or startCondition != 1):
xferSettings(k)
for n in range(leftN, rightN+1):
if gauge == 1:
if n % 2 == 0: k.xfer(f'b{n}', f'f{n}')
else: k.xfer(f'f{n}', f'b{n}')
else:
if (n == startN and secureStartN) or (n == endN and secureEndN): continue
if currCondition(n) and f'{homeBed}{n}' not in emptyNeedles and (((n//gauge) % (2*gauge)) % gauge) != 0: k.xfer(f'{travelBed}{n}', f'{homeBed}{n}')
resetSettings(k)
#--- FUNCTION FOR DOING THE MAIN KNITTING OF CIRCULAR, OPEN TUBES ---
def circular(k, startN, endN, length, c, gauge=1):
'''
Knits on every needle circular tube starting on side indicated by which needle value is greater.
In this function length is the number of total passes knit so if you want a tube that
is 20 courses long on each side set length to 40.
*k is knitout Writer
*startN is the starting needle to knit on
*endN is the last needle to knit on
*length is total passes knit
*c is carrier
*gauge is... gauge
'''
if endN > startN: #first pass is pos
beg = 0
leftN = startN
rightN = endN
else: #first pass is neg
beg = 1
length += 1
leftN = endN
rightN = startN
for h in range(beg, length):
if h % 2 == 0:
for n in range(leftN, rightN+1):
if n % gauge == 0: k.knit('+', f'f{n}', c)
elif n == rightN: k.miss('+', f'f{n}', c)
else:
for n in range(rightN, leftN-1, -1):
if gauge == 1 or n % gauge != 0: k.knit('-', f'b{n}', c)
elif n == leftN: k.miss('-', f'b{n}', c)
def garter(k, startN, endN, length, c, patternRows=1, startBed='f', currentBed=None, originBed=None, homeBed=None, secureStartN=True, secureEndN=True, gauge=1): #TODO: add seed!
'''
*k is knitout Writer
*startN is the starting needle to knit on
*endN is the last needle to knit on
*length is total passes knit
*c is carrier
*patternRows is the number of knit/purl rows to knit before switch to the other (e.g. 2 -- knit 2 rows, purl 2 rows [repeat])
*startBed is the bed to start on
*currentBed is the bed(s) that current has knitting (valid values are: 'f' [front], 'b' [back], and 'both'); assumes you start on the front bed, unless otherwise indicated
*originBed is the bed that the section belongs to
*homeBed is the bed to transfer the loops back to at the end (if applicable)
*secureStartN and *secureEndN are booleans that indicate whether or not we should refrain from xferring the edge-most needles, for security (NOTE: this should be True if given edge needle is on the edge of the piece [rather than in the middle of it])
*gauge is... gauge
'''
if currentBed is None: currentBed = startBed
if originBed is None: originBed = currentBed
k.comment('begin garter')
if endN > startN: #first pass is pos
dir1 = '+'
dir2 = '-'
otherEndN = endN-1 #for gauge 2
otherStartN = startN+1
tuckEndShift = 1
tuckStartShift = -1
range1 = range(startN, endN+1)
range2 = range(endN, startN-1, -1)
else: #first pass is neg
dir1 = '-'
dir2 = '+'
otherEndN = endN+1 #for gauge 2
otherStartN = startN-1
tuckEndShift = -1
tuckStartShift = 1
range1 = range(startN, endN-1, -1)
range2 = range(endN, startN+1)
secureNeedles = {}
if originBed == 'f': otherBed = 'b'
else: otherBed = 'f'
if (startN % 2 == 0 and originBed == 'f') or ((startN+1) % 2 == 0 and originBed == 'b'):
secureNeedles[startN] = originBed
secureNeedles[otherStartN] = otherBed
else:
secureNeedles[startN] = otherBed
secureNeedles[otherStartN] = originBed
if (endN % 2 == 0 and originBed == 'f') or ((endN+1) % 2 == 0 and originBed == 'b'):
secureNeedles[endN] = originBed
secureNeedles[otherEndN] = otherBed
else:
secureNeedles[endN] = otherBed
secureNeedles[otherEndN] = originBed
if homeBed == 'b' or (homeBed is None and originBed == 'b'):
condition = lambda n: (n % gauge != 0 or gauge == 1)
else:
condition = lambda n: n % gauge == 0
if startBed == 'b':
bed1 = 'b'
bed2 = 'f'
if currentBed != 'b':
if currentBed == 'both' and gauge > 1:
shift = 1
k.rack(1)
# k.rack(-1)
else: shift = 0
xferSettings(k)
for n in range1:
if condition(n) and includeNSecureSides(n, secureNeedles=secureNeedles): k.xfer(f'f{n+shift}', f'b{n}')
elif currentBed == 'both' and condition(n): k.xfer(f'f{n+shift}', f'b{n}') #xfer it anyway if current bed is both
if currentBed == 'both' and gauge > 1: k.rack(0)
resetSettings(k)
currentBed = 'b'
else: #knit garter on front or both
bed1 = 'f'
bed2 = 'b'
if currentBed != 'f': #both
if currentBed == 'both' and gauge > 1:
shift = -1
k.rack(1)
else: shift = 0
xferSettings(k)
for n in range1:
if condition(n) and includeNSecureSides(n, secureNeedles=secureNeedles): k.xfer(f'b{n+shift}', f'f{n}')
elif currentBed == 'both' and condition(n): k.xfer(f'b{n+shift}', f'f{n}') #xfer it anyway if current bed is both
if currentBed == 'both' and gauge > 1: k.rack(0)
resetSettings(k)
currentBed = 'f'
direction = dir1
needleRange = range1
passCt = 0
for l in range(0, length):
for r in range(0, patternRows):
for n in needleRange: #TODO: maybe just do dir1 instead of direction ?
if condition(n):
if includeNSecureSides(n, secureNeedles=secureNeedles, knitBed=bed1): k.knit(direction, f'{bed1}{n}', c)
else: k.knit(direction, f'{bed2}{n}', c)
elif n == endN: k.miss(direction, f'{bed1}{n}', c)
if direction == dir1: direction = dir2
else: direction = dir1 #remove #?
if needleRange == range1: needleRange = range2 #TODO: maybe just make it needleRange = range2 since it will always be that?
else: needleRange = range1 #remove #?
passCt += 1
if passCt == length: break
if passCt == length and ((homeBed is None) or (currentBed == homeBed)): break
xferSettings(k)
for n in range1:
if condition(n) and includeNSecureSides(n, secureNeedles=secureNeedles): k.xfer(f'{bed1}{n}', f'{bed2}{n}')
currentBed = bed2
resetSettings(k)
if passCt == length: break
for r in range(0, patternRows):
for n in needleRange:
if condition(n):
if includeNSecureSides(n, secureNeedles=secureNeedles, knitBed=bed2): k.knit(direction, f'{bed2}{n}', c)
else: k.knit(direction, f'{bed1}{n}', c)
elif n == startN: k.miss(direction, f'{bed2}{n}', c)
if direction == dir1: direction = dir2 #remove #?
else: direction = dir1
if needleRange == range1: needleRange = range2 #remove #? #^
else: needleRange = range1 #TODO: maybe just make it needleRange = range1 since it will always be that?
passCt += 1
if passCt == length: break
if passCt == length and ((homeBed is None) or (currentBed == homeBed)): break
xferSettings(k)
for n in range2:
if condition(n) and includeNSecureSides(n, secureNeedles=secureNeedles): k.xfer(f'{bed2}{n}', f'{bed1}{n}')
currentBed = bed1
resetSettings(k)
if passCt == length: break
k.comment('end garter')
nextDirection = direction
if nextDirection == '+': nextSide = 'l'
else: nextSide = 'r'
return nextSide #so know where carrier is at (note: will be *next* side)
def lace(k, startN, endN, length, c, patBeg=0, patternRows=2, spaceBtwHoles=1, offset=1, offsetStart=0, offsetReset=None, currentBed='f', gauge='1', secureStartN=True, secureEndN=True): #TODO: ensure it works well for gauge 2
'''
*k is the knitout Writer
*startN is the first needle to knit on in first pass
*endN is the last needle to knit on in first pass
*length is the total number of rows
*c is the carrier
*patBeg is the pass number to start at (useful for if using this function in cactus and need to prevent reseting xfer pattern)
*patternRows is the number of rows between xfers to form new holes
*spaceBtwHoles is the number of needles that are skipped btw xfers to form the lace holes
*offset is the shift in lace hole placement for alternating rows (e.g. offset=0 would stack lace holes directly ontop of one another [NOTE: requires patternRows to have minimum value of 2], offset=1 would be checkerboard pattern, etc.)
*offsetStart is *TODO
*offsetReset is the number of rows after which the offset is set back to the beginning (if None, will just reset once offset automatically resets)
*currentBed is the needle bed where the main knitting will occur (other bed wil be used for xfers)
*gauge is gauge
*secureStartN and *secureEndN are booleans that indicate whether or not we should refrain from xferring the edge-most needles, for security (NOTE: this should be True if given edge needle is on the edge of the piece [rather than in the middle of it])
'''
if patBeg == 1 and length == 1: length += 1
if patternRows < 2:
patternRows = 2
print('\nwarning: changing patternRows to 2 so lace holes can properly form.')
if currentBed == 'f':
rack1 = -gauge
rack2 = gauge
bed2 = 'b'
else:
rack1 = gauge
rack2 = -gauge
bed2 = 'f'
if endN > startN: #first pass is pos
dir1 = '+'
dir2 = '-'
leftN = startN
rightN = endN
ranges = {dir1: range(startN, endN+1), dir2: range(endN, startN-1, -1)}
else: #first pass is neg
dir1 = '-'
dir2 = '+'
leftN = endN
rightN = startN
ranges = {dir1: range(startN, endN-1, -1), dir2: range(endN, startN+1)}
laceStitch = specs.stitchNumber+3
if laceStitch > 9: laceStitch = 9
k.comment('begin lace')
xferPasses = 0
mod = offsetStart
for p in range(patBeg, length):
if (p-patBeg) % 2 == 0:
direction = dir1
lastN = endN
else:
direction = dir2
lastN = startN
if p % patternRows == 0:
k.stitchNumber(specs.stitchNumber)
if gauge == 1:
if xferPasses % 2 == 0: rack = rack1
else: rack = rack2
shift = rack
else:
rack = rack1
shift = -gauge
xferPasses += 1
for n in ranges[dir1]:
if (n+shift >= leftN and n+shift <= rightN) and ((n - startN) % (gauge*(spaceBtwHoles+1)) == (gauge*mod)) and (not secureStartN or n != startN) and (not secureEndN or n != endN): #don't xfer edge-most stitches so don't have to worry about them dropping
if gauge == 1 or ((currentBed == 'f' and n % gauge == 0) or (currentBed == 'b' and (n-1) % gauge == 0)): k.xfer(f'{currentBed}{n}', f'{bed2}{n}')
k.rack(rack)
for n in ranges[dir1]:
if (n+shift >= leftN and n+shift <= rightN) and ((n-startN) % (gauge*(spaceBtwHoles+1)) == (gauge*mod)) and (not secureStartN or n != startN) and (not secureEndN or n != endN):
if gauge == 1 or ((currentBed == 'f' and n % gauge == 0) or (currentBed == 'b' and (n-1) % gauge == 0)): k.xfer(f'{bed2}{n}', f'{currentBed}{n+shift}')
k.rack(0)
mod += offset
if mod > spaceBtwHoles or (offsetReset is not None and xferPasses % offsetReset == 0): mod = 0
k.stitchNumber(laceStitch)
for n in ranges[direction]:
if gauge == 1 or ((currentBed == 'f' and n % gauge == 0) or (currentBed == 'b' and (n+1) % gauge == 0)): k.knit(direction, f'{currentBed}{n}', c)
elif n == lastN: k.miss(direction, f'f{n}', c)