Create GSSHAPY TimeSeries and TimeSeriesValue Objects Method
428811
def _createTimeSeriesObjects(self, timeSeries, filename):
        
        try:
            # Determine number of value columns
            valColumns = len(timeSeries[0]['values'])

            # Create List of GSSHAPY TimeSeries objects
            series = []
            for i in range(0, valColumns):
                ts = TimeSeries()
                ts.timeSeriesFile = self
                series.append(ts)

            for record in timeSeries:
                for index, value in enumerate(record['values']):
                    # Create GSSHAPY TimeSeriesValue objects
                    tsVal = TimeSeriesValue(simTime=record['time'],
                                            value=value)

                    # Associate with appropriate TimeSeries object via the index
                    tsVal.timeSeries = series[index]
        except IndexError:
            log.warning(('%s was opened, but the contents of the file were empty.'
                     'This file will not be read into the database.') % filename)
        except:
            raise
245771
function buildAxis() {
            let minor, major;

            if (xAxisFormat === 'custom' && typeof xAxisCustomFormat === 'string') {
                minor = {
                    tick: xTicks,
                    format: d3TimeFormat.timeFormat(xAxisCustomFormat)
                };
                major = null;
            } else {
                ({minor, major} = getTimeSeriesAxis(dataByDate, width, xAxisFormat, locale));

                xMonthAxis = d3Axis.axisBottom(xScale)
                    .ticks(major.tick)
                    .tickSize(0, 0)
                    .tickFormat(major.format);
            }

            xAxis = d3Axis.axisBottom(xScale)
                .ticks(minor.tick)
                .tickSize(10, 0)
                .tickPadding(tickPadding)
                .tickFormat(minor.format);

            yAxis = d3Axis.axisLeft(yScale)
                .ticks(yTicks)
                .tickSize([0])
                .tickPadding(tickPadding)
                .tickFormat(getFormattedValue);

            drawGridLines(minor.tick, yTicks);
        }
763755
def decode_timeseries_row(self, tsrow, tscols=None,
                              convert_timestamp=False):
        
        row = []
        for i, cell in enumerate(tsrow.cells):
            col = None
            if tscols is not None:
                col = tscols[i]
            if cell.HasField('varchar_value'):
                if col and not (col.type == TsColumnType.Value('VARCHAR') or
                                col.type == TsColumnType.Value('BLOB')):
                    raise TypeError('expected VARCHAR or BLOB column')
                else:
                    row.append(cell.varchar_value)
            elif cell.HasField('sint64_value'):
                if col and col.type != TsColumnType.Value('SINT64'):
                    raise TypeError('expected SINT64 column')
                else:
                    row.append(cell.sint64_value)
            elif cell.HasField('double_value'):
                if col and col.type != TsColumnType.Value('DOUBLE'):
                    raise TypeError('expected DOUBLE column')
                else:
                    row.append(cell.double_value)
            elif cell.HasField('timestamp_value'):
                if col and col.type != TsColumnType.Value('TIMESTAMP'):
                    raise TypeError('expected TIMESTAMP column')
                else:
                    dt = cell.timestamp_value
                    if convert_timestamp:
                        dt = datetime_from_unix_time_millis(
                            cell.timestamp_value)
                    row.append(dt)
            elif cell.HasField('boolean_value'):
                if col and col.type != TsColumnType.Value('BOOLEAN'):
                    raise TypeError('expected BOOLEAN column')
                else:
                    row.append(cell.boolean_value)
            else:
                row.append(None)
        return row
730629
def _ts_slice(self, Xt, y):
        '''  '''
        Ns = len(Xt)
        Xt_new = []
        for i in range(self.n_splits):
            for j in range(Ns):
                Njs = int(len(Xt[j]) / self.n_splits)
                Xt_new.append(Xt[j][(Njs * i):(Njs * (i + 1))])
        Xt_new = np.array(Xt_new)

        if len(np.atleast_1d(y[0])) == len(Xt[0]):
            # y is a time series
            y_new = []
            for i in range(self.n_splits):
                for j in range(Ns):
                    Njs = int(len(y[j]) / self.n_splits)
                    y_new.append(y[j][(Njs * i):(Njs * (i + 1))])
            y_new = np.array(y_new)
        else:
            # y is contextual to each series
            y_new = np.concatenate([y for i in range(self.n_splits)])

        return Xt_new, y_new
1187052
private Tuple2<Object, T> mapPkToRow(String timestamp, JSONObject jsonRow, List<String> joinFields) {
        Object joinValue = null;
        T rowValues = null;
        try {
            rowValues = rowMapper.newInstance();
            rowValues.getClass().getMethod("setTimestamp", String.class).invoke(rowValues, timestamp);
            for (Object key : jsonRow.keySet()) {
                String colValue = key.toString();
                Util.applyKVToBean(rowValues, colValue, jsonRow.get(colValue));
                if (joinFields.contains(colValue)) {
                    joinValue = (joinValue == null)?jsonRow.get(colValue):(joinValue + "\u0001" + jsonRow.get(colValue));
                }
            }
            if (joinFields.contains("timestamp")) {// Join field could contain timestamp(timestamp can be out of the actual data JSON, so we try this way)
                joinValue = (joinValue == null)?timestamp:(joinValue + "\u0001" + timestamp);
            }
        } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException ex) {
            Logger.getLogger(Joiner4Bean.class.getName()).log(Level.SEVERE, null, ex);
        }
        return new Tuple2<>(joinValue, rowValues);
    }
12234
def iter_merge(cls, timeseries_list):
        
        # using return without an argument is the way to say "the
        # iterator is empty" when there is nothing to iterate over
        # (the more you know...)
        if not timeseries_list:
            return

        # for ts in timeseries_list:
        #     if ts.is_floating():
        #         msg = "can't merge empty TimeSeries with no default value"
        #         raise KeyError(msg)

        # This function mostly wraps _iter_merge, the main point of
        # this is to deal with the case of tied times, where we only
        # want to yield the last list of values that occurs for any
        # group of tied times.
        index, previous_t, previous_state = -1, object(), object()
        for index, (t, state) in enumerate(cls._iter_merge(timeseries_list)):
            if index > 0 and t != previous_t:
                yield previous_t, previous_state
            previous_t, previous_state = t, state

        # only yield final thing if there was at least one element
        # yielded by _iter_merge
        if index > -1:
            yield previous_t, previous_state
1266951
def WriteClientGraphSeries(
      self,
      graph_series,
      client_label,
      timestamp,
      cursor=None,
  ):
    """"""
    args = {
        "client_label": client_label,
        "report_type": graph_series.report_type.SerializeToDataStore(),
        "timestamp": mysql_utils.RDFDatetimeToTimestamp(timestamp),
        "graph_series": graph_series.SerializeToString(),
    }

    query = """
      INSERT INTO client_report_graphs (client_label, report_type, timestamp,
                                        graph_series)
      VALUES (%(client_label)s, %(report_type)s, FROM_UNIXTIME(%(timestamp)s),
              %(graph_series)s)
      ON DUPLICATE KEY UPDATE graph_series = VALUES(graph_series)
    """

    cursor.execute(query, args)
211199
def _wrap_results(result, dtype, fill_value=None):
    

    if is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype):
        if fill_value is None:
            # GH#24293
            fill_value = iNaT
        if not isinstance(result, np.ndarray):
            tz = getattr(dtype, 'tz', None)
            assert not isna(fill_value), "Expected non-null fill_value"
            if result == fill_value:
                result = np.nan
            result = tslibs.Timestamp(result, tz=tz)
        else:
            result = result.view(dtype)
    elif is_timedelta64_dtype(dtype):
        if not isinstance(result, np.ndarray):
            if result == fill_value:
                result = np.nan

            # raise if we have a timedelta64[ns] which is too large
            if np.fabs(result) > _int64_max:
                raise ValueError("overflow in timedelta operation")

            result = tslibs.Timedelta(result, unit='ns')
        else:
            result = result.astype('i8').view(dtype)

    return result
657580
def _write(self, session, openFile, replaceParamFile):
        
        # Retrieve all time series
        timeSeries = self.timeSeries

        # Num TimeSeries
        numTS = len(timeSeries)

        # Transform into list of dictionaries for pivot tool
        valList = []

        for tsNum, ts in enumerate(timeSeries):
            values = ts.values
            for value in values:
                valDict = {'time': value.simTime,
                           'tsNum': tsNum,
                           'value': value.value}
                valList.append(valDict)

        # Use pivot function (from lib) to pivot the values into
        # a format that is easy to write.
        result = pivot(valList, ('time',), ('tsNum',), 'value')

        # Write lines
        for line in result:

            valString = ''
            # Compile value string
            for n in range(0, numTS):
                val = '%.6f' % line[(n,)]
                valString = '%s%s%s' % (
                    valString,
                    ' ' * (13 - len(str(val))),  # Fancy spacing trick
                    val)

            openFile.write('   %.8f%s\n' % (line['time'], valString))
1086740
public tsfile_data data(TimeSeriesCollection ts_data) {
        final dictionary_delta dict_delta = new dictionary_delta();
        dict_delta.gdd = new path_dictionary_delta[0];
        dict_delta.mdd = new path_dictionary_delta[0];
        dict_delta.sdd = new strval_dictionary_delta[0];
        dict_delta.tdd = new tag_dictionary_delta[0];

        final List<tsfile_record> records = new ArrayList<>();
        final Iterator<TimeSeriesValue> tsv_iter = ts_data.getTSValues().stream().iterator();
        while (tsv_iter.hasNext()) {
            final TimeSeriesValue tsv = tsv_iter.next();
            tsfile_record record = new tsfile_record();

            record.group_ref = simpleGroupPath_index(dict_delta, tsv.getGroup().getPath());
            record.tag_ref = tags_index(dict_delta, tsv.getGroup().getTags());
            record.metrics = tsv.getMetrics().entrySet().stream()
                    .map(entry -> {
                        tsfile_record_entry tre = new tsfile_record_entry();
                        tre.metric_ref = metricName_index(dict_delta, entry.getKey());
                        tre.v = metric_value_(dict_delta, entry.getValue());
                        return tre;
                    })
                    .toArray(tsfile_record_entry[]::new);
            records.add(record);
        }

        tsfile_data result = new tsfile_data();
        result.records = records.stream().toArray(tsfile_record[]::new);
        result.ts = timestamp(ts_data.getTimestamp());
        if (dict_delta.gdd.length > 0 || dict_delta.mdd.length > 0 || dict_delta.sdd.length > 0 || dict_delta.tdd.length > 0)
            result.dd = dict_delta;
        return result;
    }
653880
public static TimeSeries create(List<LabelValue> labelValues) {
    return createInternal(labelValues, Collections.<Point>emptyList(), null);
  }
1072414
def write(tsdict, outfile, start=None, end=None, name='gwpy', run=0,
          compression=257, compression_level=6):
    
    # set frame header metadata
    if not start:
        starts = {LIGOTimeGPS(tsdict[key].x0.value) for key in tsdict}
        if len(starts) != 1:
            raise RuntimeError("Cannot write multiple TimeSeries to a single "
                               "frame with different start times, "
                               "please write into different frames")
        start = list(starts)[0]
    if not end:
        ends = {tsdict[key].span[1] for key in tsdict}
        if len(ends) != 1:
            raise RuntimeError("Cannot write multiple TimeSeries to a single "
                               "frame with different end times, "
                               "please write into different frames")
        end = list(ends)[0]
    duration = end - start
    start = LIGOTimeGPS(start)
    ifos = {ts.channel.ifo for ts in tsdict.values() if
            ts.channel and ts.channel.ifo and
            hasattr(frameCPP, 'DETECTOR_LOCATION_{0}'.format(ts.channel.ifo))}

    # create frame
    frame = io_gwf.create_frame(time=start, duration=duration, name=name,
                                run=run, ifos=ifos)

    # append channels
    for i, key in enumerate(tsdict):
        try:
            # pylint: disable=protected-access
            ctype = tsdict[key].channel._ctype or 'proc'
        except AttributeError:
            ctype = 'proc'
        append_to_frame(frame, tsdict[key].crop(start, end),
                        type=ctype, channelid=i)

    # write frame to file
    io_gwf.write_frames(outfile, [frame], compression=compression,
                        compression_level=compression_level)
24279
@Override
    public V put(Long timestamp, V object) {
        return this.timeSeriesMap.put(buildKeyTimestamp(timestamp), object);
    }
1051015
def _simple_new(cls, values, name=None, dtype=None, **kwargs):
        
        if not hasattr(values, 'dtype'):
            if (values is None or not len(values)) and dtype is not None:
                values = np.empty(0, dtype=dtype)
            else:
                values = np.array(values, copy=False)
                if is_object_dtype(values):
                    values = cls(values, name=name, dtype=dtype,
                                 **kwargs)._ndarray_values

        if isinstance(values, (ABCSeries, ABCIndexClass)):
            # Index._data must always be an ndarray.
            # This is no-copy for when _values is an ndarray,
            # which should be always at this point.
            values = np.asarray(values._values)

        result = object.__new__(cls)
        result._data = values
        # _index_data is a (temporary?) fix to ensure that the direct data
        # manipulation we do in `_libs/reduction.pyx` continues to work.
        # We need access to the actual ndarray, since we're messing with
        # data buffers and strides. We don't re-use `_ndarray_values`, since
        # we actually set this value too.
        result._index_data = values
        result.name = name
        for k, v in kwargs.items():
            setattr(result, k, v)
        return result._reset_identity()
1145918
def datasetScalarTimeStepChunk(lines, numberColumns, numberCells):
    
    END_DATASET_TAG = 'ENDDS'

    # Define the result object
    result = {'iStatus': None,
              'timestamp': None,
              'cellArray': None,
              'rasterText': None}

    # Split the chunks
    timeStep = pt.splitLine(lines.pop(0))

    # Extract cells, ignoring the status indicators
    startCellsIndex = numberCells

    # Handle case when status cells are not included (istat = 0)
    iStatus = int(timeStep[1])

    if iStatus == 0:
        startCellsIndex = 0

    # Strip off ending dataset tag
    if END_DATASET_TAG in lines[-1]:
        lines.pop(-1)

    # Assemble the array string
    arrayString = '[['
    columnCounter = 1
    lenLines = len(lines) - 1

    # Also assemble raster text field to preserve for spatial datasets
    rasterText = ''

    for index in range(startCellsIndex, len(lines)):
        # Check columns condition
        if columnCounter % numberColumns != 0 and index != lenLines:
            arrayString += lines[index].strip() + ', '
        elif columnCounter % numberColumns == 0 and index != lenLines:
            arrayString += lines[index].strip() + '], ['
        elif index == lenLines:
            arrayString += lines[index].strip() + ']]'

        # Advance counter
        columnCounter += 1

        rasterText += lines[index]

    # Get Value Array
    result['cellArray'] = arrayString
    result['rasterText'] = rasterText

    # Assign Result
    result['iStatus'] = iStatus
    result['timestamp'] = float(timeStep[2])

    return result
31838
def timeseries(X, **kwargs):
    """"""
    pl.figure(figsize=(2*rcParams['figure.figsize'][0], rcParams['figure.figsize'][1]),
              subplotpars=sppars(left=0.12, right=0.98, bottom=0.13))
    timeseries_subplot(X, **kwargs)
381549
def _possibly_convert_objects(values):
    
    return np.asarray(pd.Series(values.ravel())).reshape(values.shape)