File: ArrayOperations.py

package info (click to toggle)
vistrails 2.1.1-1
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 74,208 kB
  • ctags: 46,250
  • sloc: python: 316,267; xml: 52,512; sql: 3,627; php: 731; sh: 260; makefile: 108
file content (632 lines) | stat: -rw-r--r-- 25,993 bytes parent folder | download
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
from core.modules.vistrails_module import Module, ModuleError
from Array import *

class ArrayOperationModule(object):
    my_namespace = 'numpy|array|operations'


class ArrayReshape(ArrayOperationModule, Module):
    """ Reshape the input array.  The dimension sizes are presented
    and used to reshape the array.  Please note that the total number
    of elements in the array must remain the same before and after
    reshaping. """
    def compute(self):
	a = self.getInputFromPort("Array")
        dims = self.getInputFromPort("Dims")
        newdims = []
	
	for i in xrange(dims):
	    pname = "dim" + str(i)
	    newdims.append(self.getInputFromPort(pname))

        try:
            a.reshape(tuple(newdims))
        except:
            raise ModuleError("Could not assign new shape.  Be sure the number of elements remains constant")
        
        self.setResult("Array Output", a.copy())

    @classmethod
    def register(cls, reg, basic):
        reg.add_module(cls, name="ReshapeArray", namespace=cls.my_namespace)
        reg.add_input_port(cls, "Array", (NDArray, 'Input Array'))
        reg.add_input_port(cls, "Dims", (basic.Integer, 'New Dimensionality'))
        reg.add_input_port(cls, "dim0", (basic.Integer, 'Dimension Size'))
        reg.add_input_port(cls, "dim1", (basic.Integer, 'Dimension Size'))
        reg.add_input_port(cls, "dim2", (basic.Integer, 'Dimension Size'))
        reg.add_input_port(cls, "dim3", (basic.Integer, 'Dimension Size'), True)
        reg.add_input_port(cls, "dim4", (basic.Integer, 'Dimension Size'), True)
        reg.add_input_port(cls, "dim5", (basic.Integer, 'Dimension Size'), True)
        reg.add_input_port(cls, "dim6", (basic.Integer, 'Dimension Size'), True)
        reg.add_output_port(cls, "Array Output", (NDArray, 'Output Array'))
    
class ArrayCumulativeSum(ArrayOperationModule, Module):
    """ Get the cumulative sum of a given array.  This is returned as a
    flattened array of the same size as the input where each element
    of the array serves as the cumulative sum up until that point."""
    def compute(self):
        a = self.getInputFromPort("Array")
        b = a.cumulative_sum()
        out = NDArray()
        out.set_array(b)
        self.setResult("Array Output", out)
        
    @classmethod
    def register(cls, reg, basic):
        reg.add_module(cls, namespace=cls.my_namespace)
        reg.add_input_port(cls, "Array", (NDArray, 'Input Array'))
        reg.add_output_port(cls, "Array Output", (NDArray, 'Output Array'))

class ArrayScalarMultiply(ArrayOperationModule, Module):
    """ Multiply the input array with a given scalar """
    def compute(self):
        a = self.getInputFromPort("Array")
        b = self.getInputFromPort("Scalar")
        out = NDArray()
        out.set_array(a.get_array() * b)
        self.setResult("Array Output", out)

    @classmethod
    def register(cls, reg, basic):
        reg.add_module(cls, namespace=cls.my_namespace)
        reg.add_input_port(cls, "Array", (NDArray, 'Input Array'))
        reg.add_input_port(cls, "Scalar", (basic.Float, 'Input Scalar'))
        reg.add_output_port(cls, "Array Output", (NDArray, 'Output Array'))

class ArraySort(ArrayOperationModule, Module):
    def __init__(self):
        Module.__init__(self)
        self.axis = -1
        self.kind = 'quicksort'
        self.order = None
        
    """ Sort the input array.  By default, a flattened representation
    of the input array is used as input to a quicksort.  Optional
    inputs are the axis in which to sort on and the type of sort to
    use.

    Sorting algorithms supported:
         quicksort - best average speed, unstable
         mergesort - needs additional working memory, stable
         heapsort  - good worst-case performance, unstable
    """
    def compute(self):
        a = self.getInputFromPort("Array")
        if self.hasInputFromPort("Axis"):
            self.axis = self.getInputFromPort("Axis")
        if self.hasInputFromPort("Sort"):
            self.kind = self.getInputFromPort("Sort")
        if self.hasInputFromPort("Order"):
            self.order = self.getInputFromPort("Order")

        b = a.sort_array(axis=self.axis, kind=self.kind, order=self.order)
        out = NDArray()
        out.set_array(b.copy())
        self.setResult("Sorted Array", out)

    @classmethod
    def register(cls, reg, basic):
        reg.add_module(cls, namespace=cls.my_namespace)
        reg.add_input_port(cls, "Array", (NDArray, 'Input Array'))
        reg.add_input_port(cls, "Axis", (basic.Integer, 'Axis to sort'), True)
        reg.add_input_port(cls, "Sort", (basic.String, 'Sort Algorithm'), True)
        reg.add_input_port(cls, "Order", (basic.Integer, 'Order'),True)
        reg.add_output_port(cls, "Sorted Array", (NDArray, 'Sorted Array'))

class ArrayCumulativeProduct(ArrayOperationModule, Module):
    """ Get the cumulative product of a given array.  This is returned as
    a flattened array of the same size as the input where each element of
    the array serves as the cumulative product up until that point"""
    def compute(self):
        a = self.getInputFromPort("Array")
        b = a.cumulative_product()
        out = NDArray()
        out.set_array(b)
        self.setResult("Array Output", out)

    @classmethod
    def register(cls, reg, basic):
        reg.add_module(cls, namespace=cls.my_namespace)
        reg.add_input_port(cls, "Array", (NDArray, 'Input Array'))
        reg.add_output_port(cls, "Array Output", (NDArray, 'Output Array'))

class ArrayFill(ArrayOperationModule, Module):
    """ Fill the input array with the given value. If no value is given
    it is filled with 0.0"""
    def compute(self):
        a = self.getInputFromPort("Array")
        if self.hasInputFromPort("Value"):
            val = self.getInputFromPort("Value")
        else:
            val = 0.
            
        a.fill_array(val)
        self.setResult("Array Output", a)

    @classmethod
    def register(cls, reg, basic):
        reg.add_module(cls, name="Fill Array", namespace=cls.my_namespace)
        reg.add_input_port(cls, "Array", (NDArray, 'Input Array'))
        reg.add_input_port(cls, "Value", (basic.Float, 'Value'))
        reg.add_output_port(cls, "Array Output", (NDArray, 'Output Array'))
        
class ArrayResize(ArrayOperationModule, Module):
    """ Resize the input array.  Unlike the ArrayReshape module,
    the number of elements of the array need not be conserved.
    If the shape is larger than the input array size, repeated
    copies of the input array will be copied to the resized version.
    If the shape is smaller, the input array will be cropped appropriately.
    """
    def compute(self):
	a = self.getInputFromPort("Array")
        dims = self.getInputFromPort("Dims")
        newdims = []
	
	for i in xrange(dims):
	    pname = "dim" + str(i)
	    newdims.append(self.getInputFromPort(pname))

        try:
            t = tuple(newdims)
            b = a.resize(t)
            out = NDArray()
            out.set_array(b.copy())
        except:
            raise ModuleError("Could not assign new shape.")
        
        self.setResult("Array Output", out)

    @classmethod
    def register(cls, reg, basic):
        reg.add_module(cls, namespace=cls.my_namespace)
        reg.add_input_port(cls, "Array", (NDArray, 'Input Array'))
        reg.add_input_port(cls, "Dims", (basic.Integer, 'Output Dimensionality'))
        reg.add_input_port(cls, "dim0", (basic.Integer, 'Dimension Size'))
        reg.add_input_port(cls, "dim1", (basic.Integer, 'Dimension Size'))
        reg.add_input_port(cls, "dim2", (basic.Integer, 'Dimension Size'))
        reg.add_input_port(cls, "dim3", (basic.Integer, 'Dimension Size'), True)
        reg.add_input_port(cls, "dim4", (basic.Integer, 'Dimension Size'), True)
        reg.add_input_port(cls, "dim5", (basic.Integer, 'Dimension Size'), True)
        reg.add_input_port(cls, "dim6", (basic.Integer, 'Dimension Size'), True)
        reg.add_input_port(cls, "dim7", (basic.Integer, 'Dimension Size'), True)
        reg.add_output_port(cls, "Array Output", (NDArray, 'Output Array'))

class ArrayExtractRegion(ArrayOperationModule, Module):
    """ Extract a region from array as specified by the
    dimension and starting and ending indices """
    def compute(self):
        import operator
        a = self.getInputFromPort("Array")
        dims = self.getInputFromPort("Dims")
        a_dims = len(a.get_shape())
        if dims > a_dims:
            raise ModuleError("Output Dimensionality larger than Input Dimensionality")

        slices = []
        for i in xrange(dims):
            (start, stop) = self.getInputFromPort("dim"+str(i))
            slices.append(slice(start, stop))

        ar = operator.__getitem__(a.get_array(), tuple(slices))
        out = NDArray()
        out.set_array(ar)
        self.setResult("Array Output", out)
        
    @classmethod
    def register(cls, reg, basic):
        l = [basic.Integer, basic.Integer]
        reg.add_module(cls, namespace=cls.my_namespace)
        reg.add_input_port(cls, "Array", (NDArray, 'Input Array'))
        reg.add_input_port(cls, "Dims", (basic.Integer, 'Output Dimensionality'))
        reg.add_input_port(cls, "dim0", l, True)
        reg.add_input_port(cls, "dim1", l, True)
        reg.add_input_port(cls, "dim2", l, True)
        reg.add_input_port(cls, "dim3", l, True)
        reg.add_input_port(cls, "dim4", l, True)
        reg.add_input_port(cls, "dim5", l, True)
        reg.add_input_port(cls, "dim6", l, True)
        reg.add_input_port(cls, "dim7", l, True)
        reg.add_output_port(cls, "Array Output", (NDArray, 'Output Array'))

class ArrayRavel(ArrayOperationModule, Module):
    """ Get a 1D array containing the elements of the input array"""
    def compute(self):
        a = self.getInputFromPort("Array")
        b = NDArray()
        b.set_array(a.ravel().copy())
        self.setResult("Array Output", b)

    @classmethod
    def register(cls, reg, basic):
        reg.add_module(cls, namespace=cls.my_namespace)
        reg.add_input_port(cls, "Array", (NDArray, 'Input Array'))
        reg.add_output_port(cls, "Array Output", (NDArray, 'Output Array'))
        
class ArrayRound(ArrayOperationModule, Module):
    """ Round each element of the array to the given number of
    decimal places.  This defaults to 0 resulting in a rounding
    to integers """
    def __init__(self):
        Module.__init__(self)
        self.decimals = 0

    def compute(self):
        a = self.getInputFromPort("Array")
        if self.hasInputFromPort("Decimals"):
            self.decimals = self.getInputFromPort("Decimals")

        out = NDArray()
        out.set_array(a.round(precision=self.decimals))
        self.setResult("Array Output", out)

    @classmethod
    def register(cls, reg, basic):
        reg.add_module(cls, namespace=cls.my_namespace)
        reg.add_input_port(cls, "Array", (NDArray, 'Input Array'))
        reg.add_input_port(cls, "Decimals", (basic.Integer, 'Precision'))
        reg.add_output_port(cls, "Array Output", (NDArray, 'Output Array'))

class ArrayGetSigma(ArrayOperationModule, Module):
    """ Return the standard deviation of elements in the array """
    def __init__(self):
        Module.__init__(self)
        self.axis=None

    def compute(self):
        a = self.getInputFromPort("Array")
        if self.hasInputFromPort("Axis"):
            self.axis = self.getInputFromPort("Axis")

        out = NDArray()
        out.set_array(a.get_standard_deviation(self.axis))
        self.setResult("Output Array", out)

    @classmethod
    def register(cls, reg, basic):
        reg.add_module(cls, name="ArrayStandardDeviation", namespace=cls.my_namespace)
        reg.add_input_port(cls, "Array", (NDArray, 'Input Array'))
        reg.add_input_port(cls, "Axis", (basic.Integer, 'Axis'))
        reg.add_output_port(cls, "Output Array", (NDArray, 'Output Array'))

class ArraySum(ArrayOperationModule, Module):
    """ Get the sum of all elements in the input array """
    def compute(self):
        a = self.getInputFromPort("Array")
        self.setResult("Array Sum", float(a.get_sum()))

    @classmethod
    def register(cls, reg, basic):
        reg.add_module(cls, namespace=cls.my_namespace)
        reg.add_input_port(cls, "Array", (NDArray, 'Input Array'))
        reg.add_output_port(cls, "Array Sum", (basic.Float, 'Sum'))

class ArrayElementMultiply(ArrayOperationModule, Module):
    """ Perform an element-wise multiply on the elements of two arrays """
    def compute(self):
        a1 = self.getInputFromPort("Array1")
        a2 = self.getInputFromPort("Array2")
        out = NDArray()
        out.set_array(a1.get_array() * a2.get_array())
        self.setResult("Output Array", out)

    @classmethod
    def register(cls, reg, basic):
        reg.add_module(cls, namespace=cls.my_namespace)
        reg.add_input_port(cls, "Array1", (NDArray, 'Input Array 1'))
        reg.add_input_port(cls, "Array2", (NDArray, 'Input Array 2'))
        reg.add_output_port(cls, "Output Array", (NDArray, 'Output Array'))
        
class ArraySetElement(ArrayOperationModule, Module):
    """ Set a set of array elements given arrays of values and indices

        Please note that this module creates a copy of the input to operate
        on to preserve the original array data. """
    def compute(self):
        a = self.getInputFromPort("Array")
        if self.hasInputFromPort("Scalar Value"):
            self.v = self.getInputFromPort("Scalar Value")
        else:
            self.v = self.getInputFromPort("Value Array")

        if self.hasInputFromPort("Single Index"):
            self.ind = self.getInputFromPort("Single Index")
        else:
            self.ind = self.getInputFromPort("Index Array")

        out_a = a.copy()
        
        out_a.put(self.ind, self.v)
        out = NDArray()
        out.set_array(out_a)
        self.setResult("Output Array", out)

    @classmethod
    def register(cls, reg, basic):
        reg.add_module(cls, namespace=cls.my_namespace)
        reg.add_input_port(cls, "Scalar Value", (basic.Float, 'Value to Set'))
        reg.add_input_port(cls, "Value Array", (NDArray, 'Values to Set'))
        reg.add_input_port(cls, "Single Index", (basic.Integer, 'Index to Set'))
        reg.add_input_port(cls, "Index Array", (NDArray, 'Indexes to Set'))
        reg.add_output_port(cls, "Output Array", (NDArray, 'Output Array'))
        
class ArrayVariance(ArrayOperationModule, Module):
    """ Calculate the variance of the elements of an array """
    def compute(self):
        a = self.getInputFromPort("Array")
        if self.hasInputFromPort("Axis"):
            self.setResult("Variance", float(a.get_variance(axis=self.getInputFromPort("Axis"))))
        else:
            self.setResult("Variance", float(a.get_variance()))

    @classmethod
    def register(cls, reg, basic):
        reg.add_module(cls, namespace=cls.my_namespace)
        reg.add_input_port(cls, "Array", (NDArray, 'Input Array'))
        reg.add_input_port(cls, "Axis", (basic.Integer, 'Axis'))
        reg.add_output_port(cls, "Variance", (basic.Float, 'Variance'))
        
class ArrayTrace(ArrayOperationModule, Module):
    """ Calculate the trace of the input array.

        The input array must have at least rank 2.  The trace is taken
        on the diagonal given by the inputs Axis1 and Axis2 using the
        given Offset.  If these values are not supplied, they default to:

        Axis1 = 0
        Axis2 = 1
        Offset = 0
    """
    def compute(self):
        a = self.getInputFromPort("Array")
        if self.hasInputFromPort("Axis1"):
            self.axis1 = self.getInputFromPort("Axis1")
        else:
            self.axis1 = 0

        if self.hasInputFromPort("Axis2"):
            self.axis2 = self.getInputFromPort("Axis2")
        else:
            self.axis2 = 1

        if self.hasInputFromPort("Offset"):
            self.offset = self.getInputFromPort("Offset")
        else:
            self.offset = 0

        self.setResult("Trace", float(a.get_trace(self.offset, self.axis1, self.axis2)))

    @classmethod
    def register(cls, reg, basic):
        reg.add_module(cls, namespace=cls.my_namespace)
        reg.add_input_port(cls, "Array", (NDArray, 'Input Array'))
        reg.add_input_port(cls, "Axis1", (basic.Integer, 'Axis 1'))
        reg.add_input_port(cls, "Axis2", (basic.Integer, 'Axis 2'))
        reg.add_input_port(cls, "Offset", (basic.Integer, 'Offset'))
        reg.add_output_port(cls, "Trace", (basic.Float, 'Array Trace'))
        
class ArraySwapAxes(ArrayOperationModule, Module):
    """ Create a new view of the input array with the
    given axes swapped.
    """
    def compute(self):
        a = self.getInputFromPort("Array")
        a1 = self.getInputFromPort("Axis1")
        a2 = self.getInputFromPort("Axis2")
        out = NDArray()
        out.set_array(a.swap_axes(a1, a2).copy())
        self.setResult("Output Array", out)

    @classmethod
    def register(cls, reg, basic):
        reg.add_module(cls, namespace=cls.my_namespace)
        reg.add_input_port(cls, "Array", (NDArray, 'Input Array'))
        reg.add_input_port(cls, "Axis1", (basic.Integer, 'Axis 1'))
        reg.add_input_port(cls, "Axis2", (basic.Integer, 'Axis 2'))
        reg.add_output_port(cls, "Output Array", (NDArray, 'Output Array'))

class ArraySqueeze(ArrayOperationModule, Module):
    """ Eliminate all length-1 dimensions in the input array. """
    def compute(self):
        a = self.getInputFromPort("Array")
        out = NDArray()
        out.set_array(a.get_array().squeeze().copy())
        self.setResult("Output Array", out)

    @classmethod
    def register(cls, reg, basic):
        reg.add_module(cls, namespace=cls.my_namespace)
        reg.add_input_port(cls, "Array", (NDArray, 'Input Array'))
        reg.add_output_port(cls, "Output Array", (NDArray, 'Output Array'))

class ArrayAdd(ArrayOperationModule, Module):
    """ Add two arrays of the same size and shape """
    def compute(self):
        a1 = self.getInputFromPort("Array One").get_array()
        a2 = self.getInputFromPort("Array Two").get_array()

        if a1.shape != a2.shape:
            raise ModuleError("Cannot add arrays with different shapes")

        out = NDArray()
        out.set_array(a1 + a2)
        self.setResult("Output Array", out)

    @classmethod
    def register(cls, reg, basic):
        reg.add_module(cls, namespace=cls.my_namespace)
        reg.add_input_port(cls, "Array One", (NDArray, 'Input Array 1'))
        reg.add_input_port(cls, "Array Two", (NDArray, 'Input Array 2'))
        reg.add_output_port(cls, "Output Array", (NDArray, 'Output Array'))

class ArrayScalarAdd(ArrayOperationModule, Module):
    """ Add two arrays of the same size and shape """
    def compute(self):
        a1 = self.getInputFromPort("Array One").get_array()
        s = self.getInputFromPort("Scalar")

        out = NDArray()
        out.set_array(a1 + s)
        self.setResult("Output Array", out)

    @classmethod
    def register(cls, reg, basic):
        reg.add_module(cls, namespace=cls.my_namespace)
        reg.add_input_port(cls, "Array One", (NDArray, 'Input Array 1'))
        reg.add_input_port(cls, "Scalar", (basic.Float, 'Scalar'))
        reg.add_output_port(cls, "Output Array", (NDArray, 'Output Array'))

class ArrayLog10(ArrayOperationModule, Module):
    """ Take the base-10 log of each element in the input array """
    def compute(self):
        a = self.getInputFromPort("Array").get_array()
        out = NDArray()
        out.set_array(numpy.log10(a))
        self.setResult("Output Array", out)

    @classmethod
    def register(cls, reg, basic):
        reg.add_module(cls, namespace=cls.my_namespace)
        reg.add_input_port(cls, "Array", (NDArray, 'Input Array'))
        reg.add_output_port(cls, "Output Array", (NDArray, 'Output Array'))
    
class ArrayAtan2(ArrayOperationModule,  Module):
    """ Calculate the oriented arc-tangent of a vector stored as two arrays.
    Reals:  Real components of complex vectors
    Imaginaries:  Imaginary components of complex vectors
    """
    def compute(self):
        r = self.getInputFromPort("Reals").get_array()
        i = self.getInputFromPort("Imaginaries").get_array()
        out = NDArray()
        out.set_array(numpy.arctan2(r,i))
        self.setResult("Output Array", out)

    @classmethod
    def register(cls, reg, basic):
        reg.add_module(cls, namespace=cls.my_namespace)
        reg.add_input_port(cls, "Reals", (NDArray, 'Real Components'))
        reg.add_input_port(cls, "Imaginaries", (NDArray, 'Imaginary Components'))
        reg.add_output_port(cls, "Output Array", (NDArray, 'Output Array'))

class ArraySqrt(ArrayOperationModule, Module):
    """ Calculate the element-wise square root of the input array """
    def compute(self):
        a = self.getInputFromPort("Input Array").get_array()
        out = NDArray()
        out.set_array(numpy.sqrt(a))
        self.setResult("Output Array", out)

    @classmethod
    def register(cls, reg, basic):
        reg.add_module(cls, namespace=cls.my_namespace)
        reg.add_input_port(cls, "Input Array", (NDArray, 'Input Array'))
        reg.add_output_port(cls, "Output Array", (NDArray, 'Output Array'))
           
class ArrayThreshold(ArrayOperationModule, Module):
    """ Threshold the array keeping only the values above the scalar value, v. """
    def compute(self):
        in_ar = self.getInputFromPort("Input Array").get_array()
        v = self.getInputFromPort("Value")
        r = self.forceGetInputFromPort("Replacement")
        if r == None:
            r = 0.
        out = NDArray()
        out.set_array(numpy.where(in_ar > v, in_ar, r))
        self.setResult("Output Array", out)

    @classmethod
    def register(cls, reg, basic):
        reg.add_module(cls, namespace=cls.my_namespace)
        reg.add_input_port(cls, "Input Array", (NDArray, 'Input Array'))
        reg.add_input_port(cls, "Value", (basic.Float, 'Threshold Value'))
        reg.add_input_port(cls, "Replacement", (basic.Float, 'Replacement Value'))
        reg.add_output_port(cls, "Output Array", (NDArray, 'Output Array'))
        
class ArrayWindow(ArrayOperationModule, Module):
    """ Threshold the array from both above and below, keeping only
    the values within the window. """
    def compute(self):
        in_ar = self.getInputFromPort("Input Array").get_array()
        lo = self.forceGetInputFromPort("Lower Bound")
        hi = self.forceGetInputFromPort("Upper Bound")
        r = self.forceGetInputFromPort("Replacement")
        if r == None:
            r = 0.
        if lo == None:
            lo = in_ar.min()
        if hi == None:
            hi = in_ar.max()

        out = NDArray()
        o = numpy.where(in_ar >= lo, in_ar, r)
        o = numpy.where(o <= hi, o, r)
        out.set_array(o)
        self.setResult("Output Array", out)

    @classmethod
    def register(cls, reg, basic):
        reg.add_module(cls, namespace=cls.my_namespace)
        reg.add_input_port(cls, "Input Array", (NDArray, 'Input Array'))
        reg.add_input_port(cls, "Lower Bound", (basic.Float, 'Lower Threshold Value'))
        reg.add_input_port(cls, "Upper Bound", (basic.Float, 'Upper Threshold Value'))
        reg.add_input_port(cls, "Replacement", (basic.Float, 'Replacement Value'))
        reg.add_output_port(cls, "Output Array", (NDArray, 'Output Array'))

class ArrayNormalize(ArrayOperationModule, Module):
    """ Normalize the input array """
    def compute(self):
        in_ar = self.getInputFromPort("Input Array").get_array()
        ar = numpy.zeros(in_ar.shape)
        if self.forceGetInputFromPort("Planes"):
            for i in range(in_ar.shape[0]):
                p = in_ar[i] - in_ar[i].min()
                ar[i] = p / p.max()
        else:
            ar = in_ar - in_ar.min()
            ar = ar/ar.max()
            
        out = NDArray()
        out.set_array(ar)
        self.setResult("Output Array", out)

    @classmethod
    def register(cls, reg, basic):
        reg.add_module(cls, namespace=cls.my_namespace)
        reg.add_input_port(cls, "Input Array", (NDArray, 'Input Array'))
        reg.add_input_port(cls, "Planes", (basic.Boolean, 'Plane-wise normalization'), True)
        reg.add_output_port(cls, "Output Array", (NDArray, 'Output Array'))
        
class ArrayName(ArrayOperationModule, Module):
    """ Assign a name or label to the entries of an array """
    def compute(self):
        in_ar = self.getInputFromPort("Input Array")
        gen_name = self.forceGetInputFromPort("Name")
        one_index = self.forceGetInputFromPort("One Indexed")
        if gen_name:
            in_ar.set_name(gen_name, index=one_index)

        name_list = self.forceGetInputListFromPort("Row Name")
        if name_list != None:
            for (i,n) in name_list:
                in_ar.set_row_name(n, i)

        dname = self.forceGetInputFromPort("Domain Name")
        if dname:
            in_ar.set_domain_name(dname)

        rname = self.forceGetInputFromPort("Range Name")
        if rname:
            in_ar.set_range_name(rname)

        self.setResult("Output Array", in_ar)

    @classmethod
    def register(cls, reg, basic):
        reg.add_module(cls, namespace=cls.my_namespace)
        reg.add_input_port(cls, "Input Array", (NDArray, 'Input Array'))
        reg.add_input_port(cls, "One Indexed", (basic.Boolean, 'One Indexed'))
        reg.add_input_port(cls, "Name", (basic.String, 'Array Name'))
        reg.add_input_port(cls, "Row Name", [basic.Integer, basic.String], True)
        reg.add_input_port(cls, "Domain Name", (basic.String, 'Domain Label'))
        reg.add_input_port(cls, "Range Name", (basic.String, 'Range Label'))
        reg.add_output_port(cls, "Output Array", (NDArray, 'Output Array'))