def generateCircStream(self):
        stream = Stream()

        if self.PTInflowRec != None:
            stream.StartTemp.setAverageTemperature(self.PTInflowRec)
        else:
            stream.StartTemp.setAverageTemperature(self.PTInflow)

        stream.FluidDensity = self.FluidDensity
        stream.EndTemp.setAverageTemperature(self.PT)
        stream.Type = self.getStreamType(stream.StartTemp.getAvg(), stream.EndTemp.getAvg())
        stream.SpecHeatCap = self.FluidCp
        stream.SpecEnthalpy = self.getSpecificEnthalpy(
            stream.EndTemp.getAvg(), stream.StartTemp.getAvg(), stream.SpecHeatCap
        )
        stream.MassFlowAvg, stream.MassFlowVector = self.massFlow.getMassFlowCirc(
            stream.FluidDensity, self.VInflowCycle, self.mInflowNom, self.VInflowDay, self.HperDay
        )
        stream.EnthalpyNom, stream.EnthalpyVector = self.getEnthalpy(
            stream.EndTemp.getAvg(),
            stream.StartTemp.getAvg(),
            stream.SpecHeatCap,
            stream.MassFlowVector,
            stream.MassFlowAvg,
        )
        stream.HeatTransferCoeff = self.getHeatTransferCoefficient(self.FluidDensity)
        stream.HeatCap = self.getHeatCapacity(stream.MassFlowAvg, stream.SpecHeatCap)
        stream.HotColdType = self.getHotCold(stream.EnthalpyNom)
        operatingHours = self.periodSchedule.getInflowHoursPerYear()
        self.CircStream.append(stream)
Ejemplo n.º 2
0
def daemon_playing(queue):
    """Daemon which plays records in queue."""
    while True:
        if can_i_play:
            while not queue.is_empty():
                record = queue.get_record()
                St.play_voice(str(record))
Ejemplo n.º 3
0
def example_1():
    print "example_1"
    print "This example shows how multiple input streams are merged into a single output stream."
    print "op(f, in_streams): f is a function from a list of lists to a list"
    print "in_streams is a list of streams \n"
    print "In this example, the input streams are x and y."
    print "In this example, the function f() computes element by element sums of the input streams."
    print ""

    def f(in_streams):
        return map(sum, zip(*in_streams))

    x = Stream('x')
    y = Stream('y')

    a = merge_stateless(f, [x,y])
    a.set_name('a')

    x.extend([5, 11])
    y.extend([2, 4, 5])
    print "FIRST STEP"
    print_streams_recent([x, y, a])
    print""

    x.extend([9, 15, 19, 8, 20])
    y.extend([1, 3, 7])
    print "SECOND STEP"
    print_streams_recent([x, y, a])
Ejemplo n.º 4
0
def example_1():
    print "example_1"
    print "Calling signature:"
    print "split(f, in_stream, num_out_streams, state=None, call_streams=None)"
    print "Returns a list of num_out_streams streams."
    print "List function: f(lst) where lst is a list. "
    print "f() returns a list of num_out_streams lists."
    print "in_stream is a single stream. \n"

    print "In this example, split() returns two streams: multiples and nonmultiples of factor."
    print "x is the input stream."

    factor = 2
    print "factor = ", factor
    def f(lst):
        return [filter(lambda n: n%factor == 0, lst), \
                filter(lambda n: n%factor != 0, lst)]

    x = Stream('x')

    list_of_two_streams =split(f, x, 2)
    multiples, nonmultiples = list_of_two_streams

    multiples.set_name('multiples')
    nonmultiples.set_name('nonmultiples')

    x.extend([5, 11])
    print ""
    print "FIRST STEP"
    print_streams_recent([x, multiples, nonmultiples])
    print""

    x.extend([9, 15, 19, 8, 20])
    print "SECOND STEP"
    print_streams_recent([x, multiples, nonmultiples])
def example_2():
    def f(list_of_lists):
        return [[v * v for v in list_of_lists[0]]]

    x = Stream("x")
    y = many_to_many_stateless(f, [x], 1)[0]
    x.extend([5, 11])
    print_stream_recent(x)
    print_stream_recent(y)
    return
Ejemplo n.º 6
0
def main():
    def squares(l):
        return [v*v for v in l]
    def sums(v, state):
        return (v+state, v+state)
    
    def sums_asynch(v_and_i, state):
        v, i = v_and_i
        return (v+state, v+state)
    
    def max_min(v_and_i, state):
        max_so_far, min_so_far = state
        v, i = v_and_i
        max_so_far = max(max_so_far, v)
        min_so_far = min(min_so_far, v)
        state = (max_so_far, min_so_far)
        return([max_so_far, min_so_far], state)

    x_stream = Stream('x')
    w_stream = Stream('w')

    y_stream = stream_func(
        inputs=x_stream,
        f_type='element',
        f=sums,
        state=0.0,
        num_outputs=1)
    y_stream.set_name('cumulative sum of x')

    z_stream = stream_func(
        inputs=[x_stream, w_stream],
        f_type='asynch_element',
        f=sums_asynch,
        state=0.0,
        num_outputs=1)
    z_stream.set_name('asynch element. Cumulative sum of x and w')

    r_stream, s_stream = stream_func(
        inputs=[x_stream, w_stream],
        f_type='asynch_element',
        f=max_min,
        state=(0, 1000),
        num_outputs=2)
    r_stream.set_name('asynch element. max of x and w')
    s_stream.set_name('asynch element. min of x and w')

    x_stream.extend(range(5))
    w_stream.extend([100, -1, 10, 201, -31, 72])
    x_stream.print_recent()
    w_stream.print_recent()
    y_stream.print_recent()
    z_stream.print_recent()
    r_stream.print_recent()
    s_stream.print_recent()
Ejemplo n.º 7
0
    def AdjustOldCase(self, version):
        """
        fixup old versions
        """
        super(PumpWithCurve, self).AdjustOldCase(version)

        if version[0] < 12:
            newPort = self.GetPort(DELTAP_PORT)
            if not newPort:
                # Borrow the deltaP port
                self.BorrowChildPort(self.HPump.GetPort(DELTAP_PORT),
                                     DELTAP_PORT)

            newPort = self.GetPort(EFFICIENCY_PORT)
            if not newPort:
                # insert a signal stream between the 'LookupTable.SIG_PORT2' and IsenthalpicPump.EFFICIENCY_PORT
                # first break the old connection
                self.DisconnectPort('IsenthalpicPump', EFFICIENCY_PORT)
                # create the in-between signal stream and re-connect
                self.effStream = Stream.Stream_Signal()
                self.effStream.SetParameterValue(SIGTYPE_PAR, GENERIC_VAR)
                self.AddUnitOperation(self.effStream, 'EfficiencySig')
                effClone = Stream.ClonePort()
                self.effStream.AddObject(effClone, 'effClone')
                self.ConnectPorts('EfficiencySig', IN_PORT, 'LookupTable',
                                  SIG_PORT + '2')
                self.ConnectPorts('EfficiencySig', OUT_PORT, 'IsenthalpicPump',
                                  EFFICIENCY_PORT)
                self.BorrowChildPort(self.effStream.GetPort('effClone'),
                                     EFFICIENCY_PORT)

            newPort = self.GetPort(HEAD_PORT)
            if not newPort:
                # insert a signal stream between the 'CalcDelP.SIG_PORT0' and 'LookupTable.SIG_PORT1'
                # first break the old connection
                self.DisconnectPort('CalcDelP', SIG_PORT)
                # create the in-between signal stream and re-connect
                self.headStream = Stream.Stream_Signal()
                self.headStream.SetParameterValue(SIGTYPE_PAR, LENGTH_VAR)
                self.AddUnitOperation(self.headStream, 'HeadSig')
                headClone = Stream.ClonePort()
                self.headStream.AddObject(headClone, 'headClone')
                self.ConnectPorts('HeadSig', IN_PORT, 'LookupTable',
                                  SIG_PORT + '1')
                self.ConnectPorts('HeadSig', OUT_PORT, 'CalcDelP',
                                  SIG_PORT + '0')
                self.BorrowChildPort(self.headStream.GetPort('headClone'),
                                     HEAD_PORT)

        if version[0] < 61:
            prop = self.TotalQ.GetPort(IN_PORT).GetProperty()
            if prop.GetType().name == ENERGY_VAR:
                prop.SetTypeByName(WORK_VAR)
Ejemplo n.º 8
0
def example_1():
    print "example_1"
    print "example functions from list to value: sum(), mean(), mean_and_sigma() "
    window_size = 2
    step_size = 2
    print "window_size = ", window_size
    print "step_size = ", step_size
    print ""

    x = Stream('x')
    # x is the in_stream.
    # sum() is the function on the window
    window_sum = window_op(sum, x, window_size, step_size)
    window_sum.set_name('sum')

    # mean() is the function on the window
    window_mean = window_op(mean, x, window_size, step_size)
    window_mean.set_name('mean')

    window_mean_and_sigma = \
       window_op(mean_and_sigma, x, window_size, step_size)
    window_mean_and_sigma.set_name('mean_and_sigma')

    x.extend([5, 11])
    print_streams_recent([x, window_sum, window_mean, window_mean_and_sigma])
    print ""

    x.extend([9, 15, 19, 8, 20])
    print_streams_recent([x, window_sum, window_mean, window_mean_and_sigma])
    print ""

    x.extend([19, 10, 11, 28, 30])
    print_streams_recent([x, window_sum, window_mean, window_mean_and_sigma])
    print ""
Ejemplo n.º 9
0
    def commandPlay(self, info, _, file, start, length):
        stream = self.getStream(info[1][4])
        if stream is None:
            return

        self.log("%s - Playing: %s" % (self.address, file))  # debug

        stream.close()
        stream.channel_id = 5
        stream.time = getTime()

        if start is not None:
            stream.start = start
        if length is not None:
            stream.length = int(stream.start + length)

        try:
            stream.stream = Stream.createStream(stream.id, stream.channel_id, file, self.rtmp)
        except:
            self.sendNetStreamPlayStreamNotFound(stream, file)
            raise Exception, "Stream Not Found (%s)" % file

        if start > 0:
            self.seek(stream, start, BROADCAST_START)
        else:
            self.startBroadcast(stream, BROADCAST_START)
Ejemplo n.º 10
0
    def commandPlay(self, info, _, file, start, length):
        stream = self.getStream(info[1][4])
        if stream is None: return

        self.log("%s - Playing: %s" % (self.address, file))  #debug

        stream.close()
        stream.channel_id = 5
        stream.time = getTime()

        if start is not None:
            stream.start = start
        if length is not None:
            stream.length = int(stream.start + length)

        try:
            stream.stream = Stream.createStream(stream.id, stream.channel_id,
                                                file, self.rtmp)
        except:
            self.sendNetStreamPlayStreamNotFound(stream, file)
            raise Exception, "Stream Not Found (%s)" % file

        if start > 0:
            self.seek(stream, start, BROADCAST_START)
        else:
            self.startBroadcast(stream, BROADCAST_START)
Ejemplo n.º 11
0
 def __init__(self):
     self.stream = Stream.Stream()
     self.obj = []
     self.ObjList = {}
     self.Trailer = {}
     self.encrypt = None
     self.encryption_key = None
Ejemplo n.º 12
0
def p_streamOperation(p):
    '''streamStatement : IDENTIFIER PIPE STREAM LPAREN RPAREN SEMI'''
    try:
        p[0] = names[p[1]]
    except LookupError:
        print("Undefined name '%s''" % p[1])

    print ("Saw a Stream Statement")
    from java.util import Arrays
    from java.util import List
    import Stream
    newString = "Calling Stream Operation Result: "
    print (newString)
    Stream.streamOperation(alist)
    print ("")
    p[0] = [p[1]] + [p[2]] + [p[3]] + [p[4]] + [p[5]] + [p[6]]
Ejemplo n.º 13
0
def test_mean():
    s = Stream.Stream()
    xs = []
    for i in range(10000):
        x = random.random() * 10 - 5
        s.add(x)
        xs.append(x)
    assert np.isclose(s.mean, sum(xs) / len(xs)), s.mean - sum(xs) / len(xs)
def example_1():
    print "example_1"
    print "example functions from list to value: sum(), mean(), mean_and_sigma() "
    window_size = 2
    step_size = 2
    print "window_size = ", window_size
    print "step_size = ", step_size
    print ""

    x = Stream('x')
    # x is the in_stream.
    # sum() is the function on the window
    window_sum = window_op(sum, x, window_size, step_size)
    window_sum.set_name('sum')

    # mean() is the function on the window
    window_mean = window_op(mean, x, window_size, step_size)
    window_mean.set_name('mean')

    window_mean_and_sigma = \
       window_op(mean_and_sigma, x, window_size, step_size)
    window_mean_and_sigma.set_name('mean_and_sigma')


    x.extend([5, 11])
    print_streams_recent([x, window_sum, window_mean, window_mean_and_sigma])
    print""

    x.extend([9, 15, 19, 8, 20])
    print_streams_recent([x, window_sum, window_mean, window_mean_and_sigma])
    print""
    
    x.extend([19, 10, 11, 28, 30])
    print_streams_recent([x, window_sum, window_mean, window_mean_and_sigma])
    print""
def example_1():
    print "example_1"
    print "Calling signature:"
    print "many_to_many_stateless(f, in_streams, num_out_streams, state=None, call_streams=None)"
    print "Returns a list of num_out_streams streams."
    print "in_streams is a list of streams."
    print "List function: f(lists) where lists is a list of lists. "
    print "f() returns a list of num_out_streams lists. \n"

    print "In this example, many_to_many_stateless() returns two streams: multiples and nonmultiples."
    print "The input streams are summed element by element;"
    print "if this sum is a multiple  of factor(=2), then the sum appears in multiples"
    print "and otherwise it appears in nonmultiples."
    print "The input streams are x and y."

    factor = 2

    def f(lists):
        r = map(sum, zip(*lists))
        return [filter(lambda v: v % factor == 0, r), filter(lambda v: v % factor != 0, r)]

    x = Stream("x")
    y = Stream("y")

    list_of_two_streams = many_to_many_stateless(f, [x, y])
    multiples, nonmultiples = list_of_two_streams

    multiples.set_name("multiples")
    nonmultiples.set_name("nonmultiples")

    x.extend([5, 11])
    y.extend([2, 4, 5])
    print ""
    print "FIRST STEP"
    # Element by element sum of x and y is [5+2, 11+4].
    # Since these values are odd, they appear in nonmultiples,
    # and multiples is empty.
    print_streams_recent([x, y, multiples, nonmultiples])
    print ""

    print "SECOND STEP"
    x.extend([9, 15, 19, 8, 20])
    y.extend([1, 3, 7])
    print_streams_recent([x, y, multiples, nonmultiples])
    return
Ejemplo n.º 16
0
def window_func(f, inputs, num_outputs, state, call_streams, window_size, step_size):
    #f: list, state -> element, state
    def transition(in_lists, state=None):
        range_out = range((num_outputs))
        range_in = range(len(in_lists))
        # This function will set the k-th element of output_lists
        # to the value to be output on the k-th output stream.
        output_lists = [ [] for _ in range_out ]
        # window_starts is the list of starting indices for the
        # window in each input stream.
        window_starts = [in_list.start for in_list in in_lists]

        smallest_list_length = min(v.stop - v.start for v in in_lists)
        if window_size > smallest_list_length:
            # Do not have enough elements in an input stream
            # for an operation on the window.
            # So no changes are made.
            return (output_lists, state, window_starts)

        # Each input stream has enough elements for a window operation.
        # num_steps is the number of window operations that can be
        # carried out with the given numbers of elements in the input streams.
        num_steps = 1 + (smallest_list_length - window_size)/step_size
        for i in range(num_steps):
            # Calculate the output, 'increments', for this window operation.
            # windows is a list with a window for each input stream.
            # increments[k] will be appended to the k-th output stream
            # by this function.
            windows = [in_lists[j].list[window_starts[j]:window_starts[j]+window_size] \
                       for j in range_in]
            if state is None:
                increments = f(windows)
            else:
                increments, state = f(windows, state)
                
            # Remove _no_value and open up _multivalue elements in
            # each [increments[k]].
            # Note that increments[k] is a value to be appended to
            # the output stream. The function remove_novalue.. has
            # a parameter which is a list. So we call the function
            # with parameter [increments[k]] rather than increments[k]
            # and we extend output_lists[k] rather than append to it.
            for k in range_out:
                output_lists[k].extend(
                    remove_novalue_and_open_multivalue([increments[k]]))

            window_starts = [v+step_size for v in window_starts]

        in_lists_start_values = [in_list.start + num_steps*step_size for in_list in in_lists]
        return (output_lists, state, in_lists_start_values)

    # Create agent
    output_streams = [Stream() for v in range(num_outputs)]
    Agent(inputs, output_streams, transition, state, call_streams)

    return output_streams
Ejemplo n.º 17
0
def clock_stream(period, num_periods, name='clock_stream'):
    clock_stream = Stream(name)
    period_number = 0
    def tick(period_number):
        clock_stream.append(time.time())
        period_number += 1
        if period_number < num_periods:
            scheduler.enter(period, 1, tick, (period_number,))
    scheduler.enter(period, 1, tick, (period_number,))
    return clock_stream
Ejemplo n.º 18
0
def see_note():
    """Function for seeing note and its desctiption with opportunity to listen record."""
    os.system("clear")
    name = input("Write name of note to watch\n\n")
    if name not in notes:
        print("\nInvalid name of note")
        time.sleep(1)
        return

    desc = ""
    file = open("essential.txt", "r")
    for line in file:
        if line.startswith(name):
            desc = line.split(":")[1]
    os.system("clear")
    print("\t" + name)
    print("\n" + desc)
    if input("\nDo you want to play this record? [y]\n\n") == "y":
        St.play_voice(name)
Ejemplo n.º 19
0
def timed_many_to_many(f,
                       in_streams,
                       num_out_streams,
                       window_size,
                       step_size,
                       state=None):
    range_out = range((num_out_streams))
    range_in = range(len(in_streams))
    window_start_time = 0
    combined_state = (window_start_time, state)

    def transition(in_lists, combined_state):
        window_start_time, state = combined_state
        output_lists = [[] for _ in range_out]
        window_end_time = window_start_time + window_size
        window_start_indexes = [in_lists[j].start for j in range_in]
        while True:
            window_end_indexes = [
                list_index_for_timestamp(in_lists[j], window_start_indexes[j],
                                         window_end_time) for j in range_in
            ]
            if any(window_end_indexes[j] < 0 for j in range_in):
                break
            windows = [in_lists[j].list[window_start_indexes[j]: \
                                       window_end_indexes[j]] for j in range_in]
            increments = f(windows) if state is None else f(windows, state)

            for k in range_out:
                output_lists[k].append(
                    TimeAndValue(window_end_time, increments[k]))
            window_start_time += step_size
            window_end_time += step_size
            new_window_start_indexes = [
                list_index_for_timestamp(in_lists[j], window_start_indexes[j],
                                         window_start_time) for j in range_in
            ]
            if any(new_window_start_indexes[j] < 0 for j in range_in):
                break
            ## #CHECKING FOR PROGRESS TOWARDS TERMINATION
            ## if (any(new_window_start_indexes[j] < window_start_indexes[j]
            ##        for j in range_in) or
            ##        all(new_window_start_indexes[j] == window_start_indexes[j]
            ##        for j in range_in)):
            ##     raise Exception('TimedOperator: start_indexes')
            window_start_indexes = new_window_start_indexes

        combined_state = (window_start_time, state)
        return (output_lists, combined_state, window_start_indexes)

    # Create agent
    out_streams = [Stream() for v in range(num_out_streams)]
    combined_state = (window_start_time, state)
    Agent(in_streams, out_streams, transition, combined_state)

    return out_streams
Ejemplo n.º 20
0
def example_1():
    print "example_1"

    # This examples uses the function total()
    # from list and state to a list and state.
    # The state is cumulative --- the cumulative
    # sum up to this point in the stream.
    # The result_list is the list of cumulative
    # values of the input list.
    
    def total(lst, cumulative):
        result_list = []
        for v in lst:
            cumulative += v
            result_list.append(cumulative)
        return (result_list, cumulative)

    x = Stream('x')
    # The initial state is 0.
    state = 0
    y = op(total, x, state)
    # Since call_streams is not specified, values will be
    # appended to y when values are appended to x.
    print "initial state = ", state
    print 'function on stream is total()'
    print 'This function computes the cumulative sum of the stream'
    print 'x is the input stream and y is the output stream.'
    print 'The state is the cumulative so far.'

    y.set_name('y')

    x.extend([3, 7])
    # Now the value of x is [3, 7], and so the
    # value of y is [3, 10], and the state is 10
    print_streams_recent([x, y])
    print ""

    x.extend([0, 11, 5])
    # Now the value of x is [3, 7, 0, 11, 5]
    # so the value of y is [3, 10, 10, 21, 26] and
    # the value of state is 26.
    print_streams_recent([x, y])
Ejemplo n.º 21
0
	def check(self):
		#print(self.req_fields)
		s = Stream.Stream(self.filePath, 'Page', 'Translation').stream()
		_, kvs = s.__next__()
		keys = [keys for keys, _ in kvs.items()]
		#print(keys)
		missing = [f for f in self.req_fields if f not in keys]
		
		if missing:
			raise ValueError('\n\nThe following fields are missing from the spreadsheet: \n\n'\
			 + '\n'.join(missing) + '\n\nThey may be spelled incorrectly.')
Ejemplo n.º 22
0
def p_streamOperation(p):
    '''streamStatement : IDENTIFIER PIPE STREAM LPAREN RPAREN SEMI'''
    try:
        p[0] = names[p[1]]
    except LookupError:
        print("Undefined name '%s''" % p[1])
        p[0]
    from java.util import Arrays
    from java.util import List
    import Stream
    print ("Calling Stream Operation: ", Stream.streamOperation(alist))
Ejemplo n.º 23
0
def mergeCSVs(pathPattern, outPath, columns, sortBy=None, delimiter="\t"):
    Stream.openLog(outPath + "-log.txt")
    columns = getColumns(columns)
    rows = readCSVs(pathPattern, columns, sortBy=sortBy, delimiter=delimiter)
    if len(rows) == 0:
        print "No input rows"
        return
    rows = mergeRows(rows, columns)
    if sortBy != None:
        print "Sorting results by column", sortBy
        rows.sort(key=lambda x: x["importance"], reverse=True)
    print "Saving results to", outPath
    with (gzip.open(outPath, "wt") if outPath.endswith(".gz") else open(
            outPath, "wt")) as f:
        writer = csv.DictWriter(f,
                                fieldnames=sorted(columns.keys()),
                                delimiter=delimiter)
        writer.writeheader()
        for row in rows:
            writer.writerow(row)
Ejemplo n.º 24
0
def start_button_click():

    # print("start")
    curdoc().add_periodic_callback(update_counts, 1000)
    Stream.start_streaming(text_input.value)
    global straming
    straming = True

    rdf['count'] = 0
    if lod_changed:

        country_rdf = rdf[rdf['type'] != 'State']

        country_data = json.dumps(json.loads(country_rdf.to_json()))

        geosource.geojson = country_data
    else:
        rdf_us = rdf.drop(rdf.index[55])

        state_data = json.dumps(json.loads(rdf_us.to_json()))
        geosource.geojson = state_data
Ejemplo n.º 25
0
def add_note():
    """Function for adding new note."""
    can_i_play = False

    os.system("clear")
    uncorrect = True
    name = None
    desc = None
    time = None

    while uncorrect:
        print("Add name of note\n")
        name = input("")
        os.system("clear")
        print("Write some description")
        desc = input("")
        os.system("clear")
        print("Write time in format [Month day hours minutes year]")
        time = input("")
        os.system("clear")
        print("Everything alright? [y,n]\n")
        print(name)
        print(desc)
        print(time)
        if input("") == 'y':
            uncorrect = False
    print("Hit enter to start recording")
    input("")
    St.record_voice(name)
    os.system("clear")
    print("\nPlay new voice message [y]\n")
    if input("") == "y":
        St.play_voice(str(name))
    file = open("essential.txt", "a")
    file.write(name + ":" + desc + ":" + time + "\n")
    file.close()
    notes.append(name)
    unused_notes.append(name)
    can_i_play = True
	def __init__(self, inputFilePath, outputFilePath, personsFile, personsSheet='persName'):
		self.resolve = self._addPersonRefs
		self.transform = self._addPersonRefs
		self.dict_key = 'Letter'
		self.inputFilePath = inputFilePath
		self.outputFilePath = outputFilePath

		pers = Stream.Stream(personsFile, 'Person Name', sheet=personsSheet)
		self.personsDict = {k: v for k, v in pers.stream()}
		self.choices = [k for k, v in self.personsDict.items()]


		super().__init__()
Ejemplo n.º 27
0
def example_1():
    print "example_1"
    print "This example shows how multiple streams are merged into a single stream"
    print ""
    print "merge_stateful(f, in_streams, state, call_streams=None): f is a function"
    print "from a list of lists and state a to a list and state"
    print "in_streams is a list of streams \n"
    print "In this example, state is the cumulative of the zeroth input stream"
    print "The output stream is the sum of the state and the value in the first input stream."
    print "The input streams are x and y. The output stream is a."
    print ""

    def f(two_lists, state):
        result_list = []
        for j in range(len(two_lists[0])):
            result_list.append(state+two_lists[0][j]+two_lists[1][j])
            state += two_lists[0][j]
        return (result_list, state)

    x = Stream('x')
    y = Stream('y')

    a = merge_stateful(f, inputs=[x,y], state=0)
    a.set_name('a')

    x.extend([5, 11])
    y.extend([2, 4, 5])
    print "FIRST STEP"
    # The cumulative for x is [5, 16]. So the output is [5+2, 16+4]
    print_streams_recent([x, y, a])
    print""

    x.extend([9, 15, 19, 8, 20])
    y.extend([1, 3, 7])
    print "SECOND STEP"
    # The cumulative for x is [5, 16, 25, 40, 59, 67, 87]
    # So, the output is [5+2, 16+4, 25+5, 40+1, 59+3, 67+7]
    print_streams_recent([x, y, a])
def example_1():
    print "example_1"
    factor = 2
    # f is a function from a window (a list) to
    # a list, where the result list has one element
    # for each output stream.
    # This example has two output streams.
    # The zeroth output stream gets the sum of the window
    # if the sum is divisible by factor, and 0 otherwise.
    # The first output stream is symmetric.
    def f(window,state):
        s = sum(window) + state
        state += 1
        if s % factor == 0:
            return ([s, 0], state)
        else:
            return ([0, s], state)

    x = Stream('x')
    # f is the function that operates on a window and produces a list.
    # x is the input stream.
    # window_split returns a list of num_out_streams of streams.
    [y, z] = window_split(f, in_stream=x,
                          num_out_streams=2,
                          window_size=2, step_size=2, state=0)
    y.set_name('y')
    z.set_name('z')
    
    x.extend([5, 11, 3, 8, 5, 5, 2, 3, 9, 21, 7])
    # The windows are [5, 11], [3, 8], [5, 5], [2, 3], [9, 21]
    # with sums 16, 11, 10, 5, 30 and the even numbers are 16, 10, 30
    # and so the y stream is [16, 0, 10, 0, 30] and
    # the x stream is [0, 11, 0, 5, 0]
    print_streams_recent([x, y, z])
    print""

    x.extend([8, 15, 18, 8, 20])
    print_streams_recent([x, y, z])
    def __init__(self, main_req_stream, main_resp_stream, categories, delay):
        self.num_categories = len(categories)
        assert (self.num_categories > 0)
        self.main_req_stream = main_req_stream
        self.main_resp_stream = main_resp_stream
        dic = {}
        for i in categories:
            req_stream = Stream("Request_Category_" + str(i))
            resp_stream = Stream("Response_Category_" + str(i))
            timely_stream = Stream("Timely_Category_" + str(i))
            untimely_stream = Stream("Untimely_Category_" + str(i))
            dic.update({i: [req_stream, resp_stream, timely_stream,
                            untimely_stream,
                        MissingData(req_stream, resp_stream, timely_stream,
                                    untimely_stream, delay[i])]})
        self.struct_dic = dic
#        assert (self.struct_dic.keys()==categories)
#        assert (len(dic[categories[0]])==5)
#        assert (len(self.struct_dic)==self.num_categories)
        self.func1 = divide_with_op(self.struct_dic)
        self.divideAgent = Agent([self.main_req_stream, self.main_resp_stream],
                                 [],
                                 self.func1, None)
Ejemplo n.º 30
0
def example_3():
    
    def G(in_lists):
        def f(in_lists):
            return map(sum, zip(*in_lists))
        return merge_stateless(f, in_lists)

    x = Stream('x')
    y = Stream('y')

    a = G([x,y])
    a.set_name('a')

    x.extend([5, 11])
    y.extend([2, 4, 5])
    print "FIRST STEP"
    print_streams_recent([x, y, a])
    print""

    x.extend([9, 15, 19, 8, 20])
    y.extend([1, 3, 7])
    print "SECOND STEP"
    print_streams_recent([x, y, a])
Ejemplo n.º 31
0
    def setup(self):
        self.state = self.password()
        if not self.state:
            sys.exit()
        self.wifi_thr.start()

        print "Creating Interpret and Stream objects..."
        # Create Interpret Object
        self.oInterpret = Interpret.Interpret()
        # Create Stream Object
        self.oStream = Stream.Stream(self.oInterpret)
        # Create Notifying Object
        self.notifier = threading.Thread(target=self.notify, args=())
        # Wifi Control on Interpret and Output
        print "Task Completed."
Ejemplo n.º 32
0
    def __init__(self, initScript=None):
        super(ConvReactor, self).__init__(initScript)
        self.isoRxn = IsothermalConvReactor()
        self.AddUnitOperation(self.isoRxn, 'IsoRxn')
        self.isoRxn.containerUnitOp = self

        self.heater = Heater.Heater()
        self.AddUnitOperation(self.heater, 'RxnHeater')

        self.baln = Balance.BalanceOp()
        self.AddUnitOperation(self.baln, 'EneBalance')

        #Initialize with one energy In and Out as a default
        #The parameter QEXOTHERMIC_ISPOS_PAR will set the missing energy port
        self.baln.SetParameterValue(NUSTIN_PAR + Balance.S_ENE, 1)
        self.baln.SetParameterValue(NUSTOUT_PAR + Balance.S_ENE, 1)
        self.baln.SetParameterValue(Balance.BALANCETYPE_PAR,
                                    Balance.ENERGY_BALANCE)

        # to create an Energy Out port for export
        self.balEneSensor = Sensor.EnergySensor()
        self.AddUnitOperation(self.balEneSensor, 'BalEneSensor')
        self.eneSensor = Sensor.EnergySensor()
        self.AddUnitOperation(self.eneSensor, 'EneSensor')
        self.eneStream = Stream.Stream_Energy()
        self.AddUnitOperation(self.eneStream, 'EneStream')

        # connect the child unit ops
        self.ConnectPorts('IsoRxn', OUT_PORT + 'Q', 'EneBalance',
                          IN_PORT + 'Q0')
        self.ConnectPorts('RxnHeater', IN_PORT + 'Q', 'EneBalance',
                          OUT_PORT + 'Q0')
        self.ConnectPorts('IsoRxn', OUT_PORT, 'RxnHeater', IN_PORT)

        self.ConnectPorts('EneSensor', OUT_PORT, 'EneStream', IN_PORT)
        #
        self.ConnectPorts('BalEneSensor', SIG_PORT, 'EneSensor', SIG_PORT)

        # borrow child ports
        self.BorrowChildPort(self.eneStream.GetPort(OUT_PORT), OUT_PORT + 'Q')
        self.BorrowChildPort(self.isoRxn.GetPort(IN_PORT), IN_PORT)
        self.BorrowChildPort(self.heater.GetPort(OUT_PORT), OUT_PORT)
        self.BorrowChildPort(self.heater.GetPort(DELTAP_PORT), DELTAP_PORT)

        self.SetParameterValue(NURXN_PAR, 0)
        self.SetParameterValue(SIMULTANEOUSRXN_PAR, 1)
        self.SetParameterValue(QEXOTHERMIC_ISPOS_PAR, 1)
Ejemplo n.º 33
0
def element_func(f, inputs, num_outputs, state, call_streams,
                 window_size, step_size):
    
    assert_is_list_of_streams_or_None(call_streams)

    def transition(in_lists, state):
        input_lists = zip(*[v.list[v.start:v.stop] for v in in_lists])
        # If the new input data is empty then return empty lists for
        # each output stream, and leave the state and the starting point
        # for each input stream unchanged.
        if not input_lists:
            return ([[]]*num_outputs, state, [v.start for v in in_lists])

        #list_of_output_list[i] will be set to the output value
        # corresponding to the i-th value in each of the input
        # streams
        list_of_output_list = [[]]*len(input_lists)
        for i,input_list in enumerate(input_lists):
            if state is None:
                output_list = f(input_list)
            else:
                output_list, state = f(input_list, state)
            # The output_list returned by f must have
            # one element for each output stream.
            # The output list must be a list; so convert
            # None values (for sinks) into empty lists.
            if output_list is None: output_list = []
            assert len(output_list) == num_outputs
            list_of_output_list[i] = output_list

        # This function has at least one output because the sink case
        # was considered in the last line.
        # list_of_output_list[i] is a list with one element for each output stream.
        # zip them up to get output_lists where output_lists[j] is the list that
        # gets appended to output stream j.
        output_lists = [list(v) for v in zip(*list_of_output_list)]
        # Remove _no_value elements from the output list because they do not
        # appear in streams.
        # Open up _multivalue([a,b]) into separate a, b values.
        output_lists = \
          [remove_novalue_and_open_multivalue(l) for l in output_lists]
        return (output_lists, state, [v.start+len(input_lists) for v in in_lists])

    # Create agent
    output_streams = [Stream() for i in range(num_outputs)]
    Agent(inputs, output_streams, transition, state, call_streams)
    return output_streams
Ejemplo n.º 34
0
def main():
    #os.system("python hackathon_object_detection.py ;2D") #runs kush's script
    os.environ[
        "GOOGLE_APPLICATION_CREDENTIALS"] = "/Users/akarshkumar0101/Developer/Hackathons/BlindHandAssistance/Google_Key/Blind_Assistance.json"

    desired_object = Stream.main(get_category_index())

    video_capture = cv.VideoCapture(0)

    while (True):
        # prev_dist = math.inf
        ret, frame = video_capture.read()
        if not ret:
            continue
        # print(frame.shape)
        ############ HAND POSITION ############
        hand_position = hand_detect_model(frame)
        if hand_position is not None:
            prevHandPos = hand_position
            cv.circle(frame, hand_position, 5, (255, 0, 0), -1)

        ############ OBJECT POSITION ############
        object_dictionary = object_detect_model(frame)
        if desired_object not in object_dictionary:
            desired_object_locations_list = []
        else:
            desired_object_locations_list = object_dictionary[desired_object]

        if hand_position is not None:
            #calculate distance to correct object
            #beep = WavePlayerLoop("/Users/akarshkumar0101/Developer/Hackathons/BlindHandAssistance/Sounds/shortbeep.wav")
            #beep.run()
            beep = Beep2(
                "/Users/akarshkumar0101/Developer/Hackathons/BlindHandAssistance/Sounds/shortbeep.wav"
            )
            beep.play()
            dist = getMinimumDistance(desired_object_locations_list,
                                      hand_position, frame)
            print(dist)
            print(100000 / dist)
            beep.change_volume(min(1, max(.1, 100000 / dist)))

        cv.imshow('frame', frame)
        cv.waitKey(1)

    video_capture.release()
    cv.destroyAllWindows()
    def __init__(self,
                 inputFilePath,
                 outputFilePath,
                 instListFile,
                 instSheet='MAIN',
                 instColumn='NAME'):
        self.resolve = self._addInstitutionRef
        self.transform = self._addInstitutionRef
        self.dict_key = 'Letter'
        self.inputFilePath = inputFilePath
        self.outputFilePath = outputFilePath

        ins = Stream.Stream(instListFile, instColumn, sheet=instSheet)
        self.institutionsDict = {k: v for k, v in ins.stream()}
        self.choices = [k for k, v in self.institutionsDict.items()]

        super().__init__()
Ejemplo n.º 36
0
def asynch_element_func(
        f, inputs, num_outputs, state, call_streams,
        window_size, step_size):
    
    assert_is_list_of_streams_or_None(call_streams)

    def transition(in_lists, state):
        # If the input data is empty then return empty lists for
        # each output stream, and leave the state and the starting point
        # for each input stream unchanged.
        if all(v.stop <= v.start for v in in_lists):
            return ([[]]*num_outputs, state, [v.start for v in in_lists])

        # Assert at least one input stream has unprocessed data.
        
        # output_lists[j] will be sent on output stream j
        output_lists = [[]]*num_outputs
        for stream_number, v in enumerate(in_lists):
            # if v.stop <= v.start then skip this input stream
            if v.stop > v.start:
                # Carry out a state transition for this input
                # stream.
                # input_list is the list of new values on this
                # stream. Compute the incremental list generated
                # by each element in input list due to a transition,
                # i.e., an execution of f.
                input_list = v.list[v.start:v.stop]
                for element in input_list:
                    if state is None:
                        output_lists_increment = \
                          f((element, stream_number))
                    else:
                        # This function has state.
                        output_lists_increment, state = \
                          f((element, stream_number), state)
                    assert len(output_lists_increment) == num_outputs
                    for k in range(num_outputs):
                        output_lists[k].append(output_lists_increment[k])
        return (output_lists, state, [v.stop for v in in_lists])

    
    # Create agent
    output_streams = [Stream() for i in range(num_outputs)]
    Agent(inputs, output_streams, transition, state, call_streams)
    return output_streams
Ejemplo n.º 37
0
    def __init__(self, initScript=None):
        super(EquilibriumReactor, self).__init__(initScript)
        self.itnRxn = InternalEqmReactor()
        self.AddUnitOperation(self.itnRxn, 'itnRxn')
        self.itnRxn.containerUnitOp = self

        self.baln = Balance.BalanceOp()
        self.AddUnitOperation(self.baln, 'EneBalance')

        self.baln.SetParameterValue(NUSTIN_PAR + Balance.S_ENE, 1)
        self.baln.SetParameterValue(Balance.BALANCETYPE_PAR,
                                    Balance.ENERGY_BALANCE)

        # to create an Energy Out port for export
        self.balEneSensor = Sensor.EnergySensor()
        self.AddUnitOperation(self.balEneSensor, 'BalEneSensor')
        self.eneSensor = Sensor.EnergySensor()
        self.AddUnitOperation(self.eneSensor, 'EneSensor')
        self.eneStream = Stream.Stream_Energy()
        self.AddUnitOperation(self.eneStream, 'EneStream')

        # connect the child unit ops
        self.ConnectPorts('itnRxn', OUT_PORT + 'Q', 'EneBalance',
                          IN_PORT + 'Q0')
        self.ConnectPorts('EneSensor', OUT_PORT, 'EneStream', IN_PORT)
        self.ConnectPorts('BalEneSensor', SIG_PORT, 'EneSensor', SIG_PORT)

        # borrow child ports
        self.BorrowChildPort(self.eneStream.GetPort(OUT_PORT), OUT_PORT + 'Q')
        self.BorrowChildPort(self.itnRxn.GetPort(IN_PORT), IN_PORT)
        self.BorrowChildPort(self.itnRxn.GetPort(OUT_PORT), OUT_PORT)
        self.BorrowChildPort(self.itnRxn.GetPort(DELTAP_PORT), DELTAP_PORT)

        self.SetParameterValue(NURXN_PAR, 0)
        self.SetParameterValue(CALCOPTION_PAR,
                               1)  #use table to correlate constant
        self.SetParameterValue(CONSTBASIS_PAR,
                               1)  #use partial pressure to calculate constant
        self.SetParameterValue(
            BASISPUNIT_PAR,
            'atm')  #VMG pressure unit when partial pressure as basis
        self.SetParameterValue(QEXOTHERMIC_ISPOS_PAR, 1)
Ejemplo n.º 38
0
    def __init__(self,
                 inputFilePath,
                 outputFilePath,
                 placeListFile,
                 placeSheet='new'):
        self.resolve = self._addPlaceRef
        self.transform = self._addPlaceRef
        self.dict_key = 'Letter'
        self.inputFilePath = inputFilePath
        self.outputFilePath = outputFilePath

        places = Stream.Stream(placeListFile, 'Place', sheet=placeSheet)

        self.placesLookupDict = {
            self.assemblePlaceTuple(v): v
            for _, v in places.stream()
        }

        self.placeChoices = list(
            set([k[0] for k, _ in self.placesLookupDict.items() if k]))
        self.countyChoices = list(
            set([k[1] for k, _ in self.placesLookupDict.items()
                 if len(k) > 1]))
        self.countryChoices = list(
            set([k[2] for k, _ in self.placesLookupDict.items()
                 if len(k) > 2]))

        placesDict = {}
        for country in self.countryChoices:
            placesDict[country] = {}
            for k, v in self.placesLookupDict.items():
                if len(k) > 2 and k[2] == country:
                    placesDict[country][k[1]] = []
                    for l, m in self.placesLookupDict.items():
                        if len(l) > 2 and l[1] == k[1]:
                            placesDict[country][k[1]].append(l[0])

        self.placesDict = placesDict

        super().__init__()
Ejemplo n.º 39
0
def example_1():
    print "example_1"
    print "Calling signature:"
    print "split(f, in_stream, num_out_streams, state, call_streams=None)"
    print "Returns a list of num_out_streams streams."
    print "List function: f(lst, state) where lst is a list. "
    print "f() returns a list of num_out_streams lists and state"
    print "in_stream is a single stream. \n"

    print "THIS EXAMPLE"
    print "The input stream is x and the output streams are a and b."
    print "The input stream is fed to one of the output streams until"
    print "the next even number (multiple of factor=2); at that point"
    print "the stream is fed to the other output stream."
    print "This function switches x between a and b where the switch is triggered"
    print "by an event: namely the appearance of an even value."
    print ""

    factor = 2

    def f(lst, state):
        a = []
        b = []
        for j in range(len(lst)):
            if (lst[j]+state) % factor == 0:
                state = 1
                a.append(lst[j])
            else:
                state = 0
                b.append(lst[j])
        return ([a,b], state)


    x = Stream('x')

    a, b =split(f, in_stream=x, num_out_streams=2, state=0)
    a.set_name('a')
    b.set_name('b')

    x.extend([4, 5, 10, 11, 13, 16, 9])
    print "FIRST STEP"
    print_streams_recent([x, a, b])
    print""

    x.extend([15, 19, 8, 7, 20, 21])
    print "SECOND STEP"
    print_streams_recent([x, a, b])
Ejemplo n.º 40
0
def update_counts():

    if straming:

        new_dict = Stream.get_counts()
        for index, place in enumerate(new_dict):
            if rdf.iloc[index]['count'] != new_dict[place]:
                rdf.loc[rdf['name'] == place, 'count'] = new_dict[place]
                rdf.loc[rdf['name'] == place, 'flash'] = 1

        if lod_changed:

            country_rdf = rdf[rdf['type'] != 'State']

            country_data = json.dumps(json.loads(country_rdf.to_json()))

            geosource.geojson = country_data

        else:
            rdf_us = rdf.drop(rdf.index[55])

            state_data = json.dumps(json.loads(rdf_us.to_json()))
            geosource.geojson = state_data
Ejemplo n.º 41
0
def window_many_to_many(f,
                        in_streams,
                        num_out_streams,
                        window_size,
                        step_size,
                        state=None):
    def transition(in_lists, state=None):
        range_out = range((num_out_streams))
        range_in = range(len(in_streams))
        output_lists = [[] for _ in range_out]
        window_starts = [in_list.start for in_list in in_lists]

        smallest_list_length = min(v.stop - v.start for v in in_lists)
        if window_size > smallest_list_length:
            #in_lists_start_values = [in_list.start for in_list in in_lists]
            return (output_lists, state,
                    [in_list.start for in_list in in_lists])

        num_steps = 1 + (smallest_list_length - window_size) / step_size
        for i in range(num_steps):
            windows = [in_lists[j].list[window_starts[j]:window_starts[j]+window_size] \
                       for j in range_in]
            increments = f(windows) if state is None else f(windows, state)
            for k in range_out:
                output_lists[k].append(increments[k])
            window_starts = map(lambda v: v + step_size, window_starts)

        in_lists_start_values = [
            in_list.start + num_steps * step_size for in_list in in_lists
        ]
        return (output_lists, state, in_lists_start_values)

    # Create agent
    out_streams = [Stream() for v in range(num_out_streams)]
    Agent(in_streams, out_streams, transition, state)

    return out_streams
Ejemplo n.º 42
0
def list_func(f, inputs, num_outputs, state, call_streams,
              window_size, step_size):
    # f: list of lists, state -> list of lists, state
    assert_is_list_of_streams_or_None(call_streams)

    def transition(in_lists, state):
        smallest_list_length = min(v.stop - v.start for v in in_lists)
        input_lists = [v.list[v.start:v.start+smallest_list_length] for v in in_lists]
        if not input_lists:
            return ([[]]*num_outputs, state, [v.start for v in in_lists])
        if state is None:
            output_lists = f(input_lists)
        else:
            output_lists, state = f(input_lists, state)

        if num_outputs:
            assert_is_list_of_lists(output_lists, num_outputs)
        in_lists_start_values = [v.start+smallest_list_length for v in in_lists]
        return (output_lists, state, in_lists_start_values)

    # Create agent
    output_streams = [Stream() for i in range(num_outputs)]
    Agent(inputs, output_streams, transition, state, call_streams)
    return output_streams
Ejemplo n.º 43
0
def example_1():
    print "example_1"

    # This examples uses the function total()
    # from list and state to a list and state.
    # The state is cumulative --- the cumulative
    # sum up to this point in the stream.
    # The result_list is the list of cumulative
    # values of the input list.

    def total(lst, cumulative):
        result_list = []
        for v in lst:
            cumulative += v
            result_list.append(cumulative)
        return (result_list, cumulative)

    x = Stream('x')
    # The initial state is 0.
    state = 0
    y = op(total, x, state)
    # Since call_streams is not specified, values will be
    # appended to y when values are appended to x.
    print "initial state = ", state
    print 'function on stream is total()'
    print 'This function computes the cumulative sum of the stream'
    print 'x is the input stream and y is the output stream.'
    print 'The state is the cumulative so far.'

    y.set_name('y')

    x.extend([3, 7])
    # Now the value of x is [3, 7], and so the
    # value of y is [3, 10], and the state is 10
    print_streams_recent([x, y])
    print ""

    x.extend([0, 11, 5])
    # Now the value of x is [3, 7, 0, 11, 5]
    # so the value of y is [3, 10, 10, 21, 26] and
    # the value of state is 26.
    print_streams_recent([x, y])
Ejemplo n.º 44
0
def example_1():
    print "example_1"
    factor = 2
    # f is a function from a window (a list) to
    # a list, where the result list has one element
    # for each output stream.
    # This example has two output streams.
    # The zeroth output stream gets the sum of the window
    # if the sum is divisible by factor, and 0 otherwise.
    # The first output stream is symmetric.
    def f(window):
        s = sum(window)
        if s % factor == 0:
            return [s, 0]
        else:
            return [0, s]

    x = Stream('x')
    # f is the function that operates on a window and produces a list.
    # x is the input stream.
    # window_split returns a list of num_out_streams of streams.
    [y, z] = window_split(f, in_stream=x,
                          num_out_streams=2,
                          window_size=2, step_size=2)
    y.set_name('y')
    z.set_name('z')
    
    x.extend([5, 11, 3, 8, 5, 5, 2, 3, 9, 21, 7])
    # The windows are [5, 11], [3, 8], [5, 5], [2, 3], [9, 21]
    # with sums 16, 11, 10, 5, 30 and the even numbers are 16, 10, 30
    # and so the y stream is [16, 0, 10, 0, 30] and
    # the x stream is [0, 11, 0, 5, 0]
    print_streams_recent([x, y, z])
    print""

    x.extend([8, 15, 18, 8, 20])
    print_streams_recent([x, y, z])
def example_1():
    print "example_1"
    factor = 2

    # f takes windows as input, where windows is a list
    # in which each element is a window (a list).
    # The output of f is a list with an element for each
    # output stream.
    # This example is for a list with two output streams.
    # Sum corresponding elements of all input windows.
    # If the sum of the corresponding windows is divisible by
    # factor, then that sum is added to the zeroth output
    # stream, and otherwise it is added to the first output
    # stream.
    def f(windows):
        r = map(sum, zip(*windows))
        multiples = filter(lambda v: v % factor == 0, r)
        nonmultiples = filter(lambda v: v % factor != 0, r)
        return [sum(multiples), sum(nonmultiples)]

    x = Stream('x')
    y = Stream('y')

    list_of_two_streams = window_many_to_many(f,
                                              in_streams=[x,y],
                                              num_out_streams=2,
                                              window_size=2,
                                              step_size=2)
    multiples, nonmultiples = list_of_two_streams

    multiples.set_name('multiples')
    nonmultiples.set_name('nonmultiples')

    x.extend([5, 11])
    y.extend([2, 4, 5])
    # The windows for the two input streams x, y are:
    # [5, 11] and [2, 4] respectively.
    # The sums of the input streams, element by element are:
    # [5+2, 11+4] or [7, 15]. Since these elements are not
    # multiples of factor, the multiples stream outputs [0] 
    # and the nonmultiples stream outputs [7+15] or [22]
    print_streams_recent([x, y, multiples, nonmultiples])
    print""

    x.extend([9, 15, 19, 8, 20])
    y.extend([1, 3, 7])
    # The new windows for x are [9, 15], [19, 8] and
    # for y are [5, 1], [3, 7].
    # The sums of the input streams, element by element are:
    # [14, 16], [22, 15].
    # The multiples stream outputs [14+16], [22], and the
    # nonmultiples stream outputs [0], [15].
    print_streams_recent([x, y, multiples, nonmultiples])
    print""

    x.extend([19, 10, 11, 28, 30])
    y.extend([1, 3, 7, 13, 17, 19, 20, 40, 80])
    print_streams_recent([x, y, multiples, nonmultiples])
    print""
    def generateMaintainanceStream(self):

        stream = Stream()
        stream.StartTemp.setAverageTemperature(self.PT)
        stream.EndTemp.setAverageTemperature(self.PT + 0.1)
        stream.FluidDensity = self.FluidDensity
        stream.Type = self.getProcessStreamType(stream.StartTemp.getAvg(), stream.EndTemp.getAvg())
        stream.SpecHeatCap = 3600
        stream.SpecEnthalpy = self.getSpecificEnthalpy(
            stream.EndTemp.getAvg(), stream.StartTemp.getAvg(), stream.SpecHeatCap
        )
        stream.Enthalpy = []
        for elem in self.periodSchedule.getYearlyBatchOperationProfile():
            stream.Enthalpy.append(elem * self.Qdot)

        stream.MassFlowAvg, stream.MassFlowVector = self.massFlow.getMassFlowOp(stream.Enthalpy, stream.SpecHeatCap)
        stream.HeatTransferCoeff = 5000
        stream.HeatCap = self.getHeatCapacity(stream.MassFlowAvg, stream.SpecHeatCap)
        stream.HotColdType = self.getHotCold(stream.EnthalpyNom)
        stream.OperatingHours = self.periodSchedule.getOperationHoursPerYear()
        self.MaintainanceStream.append(stream)
    def generateWHCondStream(self):
        """
        Generate Waste Heat Cond Stream
        TODO Correct to Waste Heat
        """
        stream = Stream()
        stream.FluidDensity = 1000
        stream.StartTemp.setAverageTemperature(self.Tcond)
        stream.EndTemp.setAverageTemperature(self.Tcond - 0.1)
        stream.Type = self.getProcessStreamType(stream.StartTemp.getAvg(), stream.EndTemp.getAvg())

        stream.SpecEnthalpy = self.LatentHeat
        stream.SpecHeatCap = stream.SpecEnthalpy * 10
        stream.MassFlowAvg, stream.MassFlowVector = self.massFlow.getMassFlowWHCond(
            VOutflowCycle=self.VOutflowCycle,
            FluidDensity=stream.FluidDensity,
            XOutFlow=self.XOutFlow,
            mOutflowNom=self.mOutFlowNom,
        )
        stream.EnthalpyNom, stream.EnthalpyVector = self.getEnthalpy(
            stream.EndTemp.getAvg(),
            stream.StartTemp.getAvg(),
            stream.SpecHeatCap,
            stream.MassFlowVector,
            stream.MassFlowAvg,
        )
        stream.HeatTransferCoeff = 10000
        stream.HeatCap = self.getHeatCapacity(stream.MassFlowAvg, stream.SpecHeatCap)
        stream.HotColdType = self.getHotCold(stream.EnthalpyNom)
        stream.OperatingHours = self.periodSchedule.getOutflowHoursPerYear()
        self.WasteHeatC.append(stream)
 def generateWHBelowCondStream(self):
     """
     Generate Waste heat below Cond Stream
     TODO Correct to Waste Heat
     """
     stream = Stream()
     stream.FluidDensity = self.FluidDensity
     stream.StartTemp.setAverageTemperature(self.Tcond)
     stream.EndTemp.setAverageTemperature(self.PTFinal)
     stream.Type = self.getStreamType(stream.StartTemp.getAvg(), stream.EndTemp.getAvg())
     stream.SpecHeatCap = self.FluidCp
     stream.SpecEnthalpy = self.getSpecificEnthalpy(
         stream.EndTemp.getAvg(), stream.StartTemp.getAvg(), stream.SpecHeatCap
     )
     if self.VOutflowCycle != None:
         stream.MassFlowAvg, stream.MassFlowVector = self.massFlow.getMassFlowWH(
             stream.FluidDensity, VOutflowCycle=self.VOutflowCycle
         )
     elif self.mOutflowNom != None:
         stream.MassFlowAvg, stream.MassFlowVector = self.massFlow.getMassFlowWH(
             stream.FluidDensity, mOutflowNom=self.mOutFlowNom
         )
     stream.EnthalpyNom, stream.EnthalpyVector = self.getEnthalpy(
         stream.EndTemp.getAvg(),
         stream.StartTemp.getAvg(),
         stream.SpecHeatCap,
         stream.MassFlowVector,
         stream.MassFlowAvg,
     )
     stream.HeatTransferCoeff = 5000
     stream.HeatCap = self.getHeatCapacity(stream.MassFlowAvg, stream.SpecHeatCap)
     stream.HotColdType = self.getHotCold(stream.EnthalpyNom)
     stream.OperatingHours = self.periodSchedule.getOutflowHoursPerYear()
     self.WasteHeatBC.append(stream)
    def generateStUpStream(self):
        stream = Stream()
        stream.FluidDensity = self.FluidDensity
        stream.StartTemp.setAverageTemperature(self.PTStartUp)
        stream.EndTemp.setAverageTemperature(self.PT)
        stream.Type = self.getStreamType(stream.StartTemp.getAvg(), stream.EndTemp.getAvg())
        stream.SpecHeatCap = self.FluidCp
        stream.SpecEnthalpy = self.getSpecificEnthalpy(
            stream.EndTemp.getAvg(), stream.StartTemp.getAvg(), stream.SpecHeatCap
        )
        stream.MassFlowAvg = self.massFlow.getMassFlowStUpNom(self.VolProcMed, self.FluidDensity)
        stream.EnthalpyNom = self.getEnthalpyNom(
            stream.EndTemp, stream.StartTemp, stream.SpecHeatCap, stream.MassFlowAvg
        )
        stream.EnthalpyVector = Status.int.UPH_s_t[self.Process]
        stream.MassFlowVector = self.getMassFlowVector(
            stream.EnthalpyVector, stream.SpecHeatCap, stream.EndTemp, stream.StartTemp
        )
        # stream.EnthalpyNom, stream.EnthalpyVector = self.getEnthalpy(stream.EndTemp.getAvg(), stream.StartTemp.getAvg(), stream.SpecHeatCap, stream.MassFlowVector, stream.MassFlowAvg)
        # stream.MassFlowAvg, stream.MassFlowVector = self.massFlow.getMassFlowStUp(self.VolProcMed, self.FluidDensity, stream.EnthalpyVector, stream.EnthalpyNom)

        stream.HeatTransferCoeff = self.getHeatTransferCoefficient(self.FluidDensity)
        stream.HeatCap = self.getHeatCapacity(stream.MassFlowAvg, stream.SpecHeatCap)
        stream.HotColdType = self.getHotCold(stream.EnthalpyNom)
        stream.OperatingHours = self.massFlow.getStUpOperatingHours()
        self.StUpStream.append(stream)
Ejemplo n.º 50
0
def main():
    x_stream = Stream('x_stream')
    print_stream(x_stream)
    x_stream.extend([3, 5, 7])
Ejemplo n.º 51
0
def example_2():
    print ""
    print "example_2"

    # This example uses the function:
    # avg_since_last_drop()
    # from a list and state to a list and state.
    # The output list is the list of averages of
    # the input list from the point that the value
    # in the input list drops by more than
    # drop_threshold.
    # The state is a tuple:
    # (time_since_last_drop, sum_since_last_drop,
    #  last_value, drop_threshold)
    # where time_since_last_drop is the number of
    # values since the last drop over the threshold,
    # sum_since_last_drop is the sum of the values
    # since the last drop over the threshold,
    # last_value is the most recent value read from
    # the input stream, and
    # drop_threshold is the specified threshold.

    def avg_since_last_drop(lst, state):
        time_since_last_drop, sum_since_last_drop,\
          last_value, drop_threshold = state
        result_list = []
        if lst == []:
            return (result_list, state)
        if last_value is None:
            last_value = lst[0]
        for v in lst:
            if last_value - v < drop_threshold:
                time_since_last_drop += 1
                sum_since_last_drop += v
            else:
                time_since_last_drop = 1
                sum_since_last_drop = v
            last_value = float(v)
            avg = sum_since_last_drop/float(time_since_last_drop)
            result_list.append(avg)
        return (result_list, state)

    x = Stream('x')
    time_since_last_drop = 0
    sum_since_last_drop = 0
    last_value = None
    drop_threshold = 100
    print "INITIAL VALUES"
    print 'time_since_last_drop = ', time_since_last_drop
    print 'sum_since_last_drop = ', sum_since_last_drop
    print 'last_value = ', last_value
    print 'drop_threshold = ', drop_threshold
    print ''
    state = (time_since_last_drop, sum_since_last_drop, last_value, drop_threshold)

    y = op(avg_since_last_drop, x, state)
    y.set_name('y')

    print 'first step'
    x.extend([16500, 16750, 16550, 16600, 16581])
    # The first drop of over drop_threshold is from 16750 to 16550
    # So, the output before that drop is the average for the window:
    # 16500.0, followed by average of (16500, 16750) = 16625.0
    # The output then starts computing averages afresh after the drop
    # starting with the value after the drop: 16550.0, 16575.0, 16577.0
    print_streams_recent([x, y])
    print ""

    print 'second step'
    x.extend([16400, 16500, 17002])
    # Another drop over the threshold of 100 occurs from 16581 to 16400
    # So, compute averages afresh from this point to get:
    # 16400.0, 16450.0, 16634.0
    print_streams_recent([x, y])
def example_1():
    print "example_1"
    factor = 2
    def f(windows, state):
        r = map(sum, zip(*windows))
        multiples = filter(lambda v: v % factor == 0, [v+state for v in r])
        state += 1
        return (sum(multiples), state)

    x = Stream('x')
    y = Stream('y')

    # In window_merge: f is a function that operates on a lis
    # of windows. [x, y] are the streams that are merged.
    # window_size and step_size specify the size of the sliding
    # window and how the window is moved at each step.
    # Sum x, y element by element. If the sum is a multiple
    # of factor (factor=2), then return the sum for the window.
    z = window_merge(f, [x,y], window_size=2, step_size=2, state=0)
    z.set_name('z')

    x.extend([5, 11])
    y.extend([2, 4, 5])
    # Since window_size=2 and step_size=2, the first windows are:
    # for x: [5, 11], and for y: [2, 4]. So, the sum is [7, 15].
    # Since 7, 15 are not divisible by factor (2), set z to [0]
    print_streams_recent([x, y, z])
    print""

    x.extend([9, 15, 19, 8, 20])
    y.extend([1, 3, 7])
    # The next windows are: for x: [9, 15], [19, 8], and
    # for y: [5, 1], and [3, 7]. So, the sums are [14, 16]
    # and [22, 15]. Since 14, 16 are divisible by factor return
    # their sum: 30. Since 22 is divisible by factor and 15 is not
    # return 22. So the new value of z is [0, 30, 22].
    print_streams_recent([x, y, z])
    print""

    x.extend([19, 10, 11, 28, 30])
    y.extend([1, 3, 7, 13, 17, 19, 20, 40, 80])
    print_streams_recent([x, y, z])
    print""