Solve River Pollution problem with NAUTILUS V1 and E-NAUTILUS Methods
16934
def main(logfile=False):
    
    # Duplicate output to log file

    class NAUTILUSOptionValidator(Validator):

        def validate(self, document):
            if document.text not in "ao":
                raise ValidationError(
                    message="Please select a for apriori or o for optimization option",
                    cursor_position=0,
                )

    if logfile:
        Tee(logfile)
    first = True
    current_iter = 0
    while first or current_iter:
        # SciPy breaks box constraints

        nautilus_v1 = NAUTILUSv1(RiverPollution(), SciPyDE)
        if not first:
            nautilus_v1.current_iter = current_iter
        first = False
        nadir = nautilus_v1.problem.nadir
        ideal = nautilus_v1.problem.ideal

        solution = tui.iter_nautilus(nautilus_v1)

        current_iter = nautilus_v1.current_iter

        # TODO: Move to tui module
        method_e = None
        if current_iter > 0:
            option = _prompt_wrapper(
                "select a for apriori or o for optimization option: ",
                default="o",
                validator=NAUTILUSOptionValidator(),
            )
            if option.lower() == "a":
                wi = _prompt_wrapper(
                    "Number of PO solutions (10 or 20): ",
                    default="20",
                    validator=tui.NumberValidator(),
                )
                weights = WEIGHTS[wi]

                factory = IterationPointFactory(
                    SciPyDE(NautilusAchievementProblem(RiverPollution()))
                )
                points = misc.new_points(factory, solution, weights=weights)

                method_e = ENAUTILUS(PreGeneratedProblem(points=points), PointSearch)
                method_e.zh_prev = solution

            else:
                method_e = ENAUTILUS(RiverPollution(), SciPyDE)

            # method_e.zh = solution
            method_e.current_iter = nautilus_v1.current_iter
            method_e.user_iters = nautilus_v1.user_iters

            print(
                "E-NAUTILUS\nselected iteration point: %s:"
                % ",".join(map(str, solution))
            )

            while method_e and method_e.current_iter > 0:
                if solution is None:
                    solution = method_e.problem.nadir

                method_e.problem.nadir = nadir
                method_e.problem.ideal = ideal
                cmd = tui.iter_enautilus(
                    method_e, initial_iterpoint=solution, initial_bound=method_e.fh_lo
                )
                if cmd:
                    print(method_e.current_iter)
                    current_iter = method_e.current_iter
                    break
    if tui.HAS_INPUT:
        input("Press ENTER to exit")
1177249
function (renderer, text, x, y, stroke) {
            // "hacky patch" for backward compatibilty
            if (typeof this.ancestor === "undefined") {
                // update text cache
                this.setText(text);

                // update position if changed
                if (this.pos.x !== x || this.pos.y !== y) {
                    this.pos.x = x;
                    this.pos.y = y;
                    this.isDirty = true;
                }

                // force update bounds
                this.update(0);

                // save the previous context
                renderer.save();

                // apply the defined alpha value
                renderer.setGlobalAlpha(renderer.globalAlpha() * this.getOpacity());

            } else {
                // added directly to an object container
                x = this.pos.x;
                y = this.pos.y;
            }

            if (renderer.settings.subPixel === false) {
                // clamp to pixel grid if required
                x = ~~x;
                y = ~~y;
            }

            // draw the text
            renderer.drawFont(this._drawFont(renderer.getFontContext(), this._text, x, y, stroke || false));

            // for backward compatibilty
            if (typeof this.ancestor === "undefined") {
                // restore previous context
                renderer.restore();
            }

            // clear the dirty flag
            this.isDirty = false;
        }
300081
def burnin(self, n):
        """"""
        self.sediment_rate = self.sediment_rate[:, n:]
        self.headage = self.headage[n:]
        self.sediment_memory = self.sediment_memory[n:]
        self.objective = self.objective[n:]
232720
function charybdis (iterator) {
  iterator = iterator || K
  const stream = new Writable({objectMode: true})
  const deferred = Promise.defer()

  const stats = stream.stats = {
    objects: 0,
    operations: 0,
    pending: 0,
    start: Date.now(),
    inEnd: 0,
    end: 0,
  }

  var sources = refcount()
  stream.on('pipe', onPipe)
  function onPipe (src) {
    sources.push()
    src.on('end', function () {
      sources.pop()
    })
    src.once('error', cleanup)
  }
  sources.on('clear', function () {
    stats.inEnd = Date.now()
    stream.emit('inEnd')
    tryResolve()
  })

  stream._write = function(obj, encoding, cb) {
    stats.objects++
    var op = iterator(obj)
    if (!op || !op.then) {
      tick()
      return cb()
    }

    stats.pending++
    stats.operations++

    tick()

    op.then(function () {
      stats.pending--
      tryResolve()
    },
    cleanup)

    cb()
  }

  function tryResolve() {
    // in streams ended and no operations pending?
    if (stats.inEnd && !stats.pending) { cleanup() }
    else tick()
  }

  function tick() {
    stream.emit('tick', stats)
  }

  function cleanup(err) {
    stream.removeListener('pipe', onPipe)
    sources.removeAllListeners()

    if (err) {
      deferred.reject(err)
    }
    stats.end = Date.now()

    deferred.resolve(stats)
  }

  stream.then = deferred.promise.then.bind(deferred.promise)

  return stream
}
1181809
function () {

    /**
     * @type {number}
     */
    this.motionBlurFactor = 0.99;
    /**
     * Vector field lookup image
     * @type {clay.Texture2D}
     */
    this.vectorFieldTexture = new Texture2D({
        type: Texture.FLOAT,
        // minFilter: Texture.NEAREST,
        // magFilter: Texture.NEAREST,
        flipY: false
    });

    /**
     * Particle life range
     * @type {Array.<number>}
     */
    this.particleLife = [5, 20];

    this._particleType = 'point';

    /**
     * @type {number}
     */
    this._particleSize = 1;

    /**
     * @type {Array.<number>}
     */
    this.particleColor = [1, 1, 1, 1];

    /**
     * @type {number}
     */
    this.particleSpeedScaling = 1.0;

    /**
     * @type {clay.Texture2D}
     */
    this._thisFrameTexture = null;

    this._particlePass = null;
    this._spawnTexture = null;
    this._particleTexture0 = null;
    this._particleTexture1 = null;

    this._particlePointsMesh = null;

    this._surfaceFrameBuffer = null;

    this._elapsedTime = 0.0;

    this._scene = null;
    this._camera = null;

    this._lastFrameTexture = null;

    // this._temporalSS = new TemporalSS(50);

    // this._antialising = false;

    this._supersampling = 1;

    this._downsampleTextures = [];

    this._width = 512;
    this._height = 512;

    this.init();
}
512751
function() {
  this._waterline = new Waterline();
  
  // Adapters
  this._adapters = {
    memory: require('./adapters/memory.js'),
    disk:   require('./adapters/disk.js'),
    redis:  require('./adapters/redis.js')
  };
  
  // Models
  this._models = {
    account: Waterline.Collection.extend(require('./models/account.js')),
    keyword: Waterline.Collection.extend(require('./models/keyword.js'))
  };
}
148125
public void process( GrayU8 input ) {
		// input = im_0

		removedWatersheds = false;
		output.reshape(input.width+2,input.height+2);
		distance.reshape(input.width+2,input.height+2);

		ImageMiscOps.fill(output, INIT);
		ImageMiscOps.fill(distance, 0);
		fifo.reset();

		// sort pixels
		sortPixels(input);

		currentLabel = 0;

		for( int i = 0; i < histogram.length; i++ ) {
			GrowQueue_I32 level = histogram[i];
			if( level.size == 0 )
				continue;

			// Go through each pixel at this level and mark them according to their neighbors
			for( int j = 0; j < level.size; j++ ) {
				int index = level.data[j];
				output.data[index] = MASK;

				// see if its neighbors has been labeled, if so set its distance and add to queue
				assignNewToNeighbors(index);
			}

			currentDistance = 1;
			fifo.add(MARKER_PIXEL);

			while( true ) {
				int p = fifo.popHead();

				// end of a cycle.  Exit the loop if it is done or increase the distance and continue processing
				if( p == MARKER_PIXEL) {
					if( fifo.isEmpty() )
						break;
					else {
						fifo.add(MARKER_PIXEL);
						currentDistance++;
						p = fifo.popHead();
					}
				}

				// look at its neighbors and see if they have been labeled or belong to a watershed
				// and update its distance
				checkNeighborsAssign(p);
			}

			// see if new minima have been discovered
			for( int j = 0; j < level.size; j++ ) {
				int index = level.get(j);
				// distance associated with p is reset to 0
				distance.data[index] = 0;

				if( output.data[index] == MASK ) {
					currentLabel++;
					fifo.add(index);
					output.data[index] = currentLabel;

					// grow the new region into the surrounding connected pixels
					while( !fifo.isEmpty() ) {
						checkNeighborsMasks(fifo.popHead());
					}
				}
			}
		}
	}
483972
function Navit(options, engineOptions) {
  if (!(this instanceof Navit)) { return new Navit(options, engineOptions); }

  this.__options__ = _.defaults({}, options || {}, {
    engine: 'phantomjs',
    inject: [],
    timeout: 10000,
    prefix: ''
  });

  this.__options__.engine = this.__options__.engine.toLowerCase();

  if ([ 'phantomjs', 'slimerjs', 'electron' ].indexOf(this.__options__.engine) === -1) {
    throw new NavitError(`Unrecognized engine: '${this.__options__.engine}'`);
  }

  this.__engineOptions__ = _.defaults({}, engineOptions || {}, DEFAULT_ENGINE_OPTIONS);

  this.__engine__ = null;
  this.__page__ = null;
  this.__queue__ = [];
  this.__response__ = null;
  this.__sandbox__ = {};
  this.__tabs__ = [];
  this.__tabIndex__ = -1;
  this.__headers__ = {}; // Custom headers, joined to each request

  this.afterOpen = null;

  // Register functions
  let functions = this.__options__.engine === 'electron' ? elFunctions : phFunctions;

  functions.forEach(path =>
    require(path).forEach(data => this.registerMethod(data[0], data[1])));
}
862420
private void calculateGauklerStrickler( double q, double[] level, List<RiverPoint> sectionsList ) {
        double toll, conta_cicli;
        double IF, max_tir, tir_dx, tir_sx, tir_med, val_dx, val_sx, val_med;
        double[][] idrgeo;
        /* create a complete list to proceed with the next elaborations */
        int imax = sectionsList.size();
        double[] minsez = new double[imax];
        double[] maxsez = new double[imax];

        for( int i = 0; i < imax; i++ ) {
            RiverPoint section = sectionsList.get(i);
            minsez[i] = section.getMinElevation();
            maxsez[i] = section.getMaxElevation();
            level[i] = minsez[i] + 1;
        }
        /* calculate the steady flow water level for the sections of the j-esim segment */
        for( int i = 0; i < imax; i++ ) {
            /* the slope of the bottom of the i-esim section */
            if (i == 0 || i == 1)
                IF = (minsez[i] - minsez[i + 1])
                        / (sectionsList.get(i + 1).getProgressiveDistance() - sectionsList.get(i).getProgressiveDistance());
            else if (i == imax - 1 || i == imax - 2)
                IF = (minsez[i - 1] - minsez[i])
                        / (sectionsList.get(i).getProgressiveDistance() - sectionsList.get(i - 1).getProgressiveDistance());
            else
                IF = (minsez[i - 2] - minsez[i + 2])
                        / (sectionsList.get(i + 2).getProgressiveDistance() - sectionsList.get(i - 2).getProgressiveDistance());
            if (IF <= 0)
                IF = (minsez[0] - minsez[imax - 1])
                        / (sectionsList.get(imax - 1).getProgressiveDistance() - sectionsList.get(0).getProgressiveDistance());
            /*
             * the function is calculated for the extreme values looking for the minimun value
             * at the bank
             */
            max_tir = maxsez[i];
            tir_dx = max_tir;
            tir_sx = minsez[i] + MIN_TIR;
            toll = 100;
            conta_cicli = 0;

            while( toll >= TOLL && conta_cicli <= MAX_CICLI ) {
                level[i] = tir_dx;
                idrgeo = wettedArea(level, sectionsList);
                val_dx = q - idrgeo[i][0] * idrgeo[i][4] * Math.pow(IF, (0.5)) * Math.pow(idrgeo[i][2], (2.0 / 3.0));
                level[i] = tir_sx;
                idrgeo = wettedArea(level, sectionsList);
                val_sx = q - idrgeo[i][0] * idrgeo[i][4] * Math.pow(IF, (0.5)) * Math.pow(idrgeo[i][2], (2.0 / 3.0));
                if ((val_dx * val_sx) > 0) {
                    pm.errorMessage("Evaluation of the steady flow not possible for the section " + i + "solution not found.");
                }
                tir_med = (tir_dx + tir_sx) / 2.0;
                level[i] = tir_med;
                idrgeo = wettedArea(level, sectionsList);
                val_med = q - idrgeo[i][0] * idrgeo[i][4] * Math.pow(IF, (0.5)) * Math.pow(idrgeo[i][2], (2.0 / 3.0));
                toll = Math.abs(tir_dx - tir_sx);
                if ((val_dx * val_med) < 0)
                    tir_sx = tir_med;
                else
                    tir_dx = tir_med;
                conta_cicli = conta_cicli + 1;
            }
        }
    }
915719
def draw_rivers_on_image(world, target, factor=1):
    

    for y in range(world.height):
        for x in range(world.width):
            if world.is_land((x, y)) and (world.layers['river_map'].data[y, x] > 0.0):
                for dx in range(factor):
                    for dy in range(factor):
                        target.set_pixel(x * factor + dx, y * factor + dy, (0, 0, 128, 255))
            if world.is_land((x, y)) and (world.layers['lake_map'].data[y, x] != 0):
                for dx in range(factor):
                    for dy in range(factor):
                        target.set_pixel(x * factor + dx, y * factor + dy, (0, 100, 128, 255))
844720
def fric(FlowRate, Diam, Nu, PipeRough):
    
    #Checking input validity - inputs not checked here are checked by
    #functions this function calls.
    ut.check_range([PipeRough, "0-1", "Pipe roughness"])
    if re_pipe(FlowRate, Diam, Nu) >= RE_TRANSITION_PIPE:
        #Swamee-Jain friction factor for turbulent flow; best for
        #Re>3000 and ε/Diam < 0.02
        f = (0.25 / (np.log10(PipeRough / (3.7 * Diam)
                              + 5.74 / re_pipe(FlowRate, Diam, Nu) ** 0.9
                              )
                     ) ** 2
             )
    else:
        f = 64 / re_pipe(FlowRate, Diam, Nu)
    return f
159233
public static void go_upstream_a( int[] p, RandomIter flowRandomIter, RandomIter tcaRandomIter, RandomIter lRandomIter,
            int[] param ) {
        double area = 0, lenght = 0;
        int[] point = new int[2];
        int kk = 0, count = 0;

        point[0] = p[0];
        point[1] = p[1];
        // check how many pixels are draining in the considered pixel and select
        // the pixel with maximun tca
        for( int k = 1; k <= 8; k++ ) {
            if (flowRandomIter.getSampleDouble(p[0] + dirIn[k][1], p[1] + dirIn[k][0], 0) == dirIn[k][2]) {
                // counts how many pixels are draining in the considere
                count++;
                if (tcaRandomIter.getSampleDouble(p[0] + dirIn[k][1], p[1] + dirIn[k][0], 0) >= area) {
                    // if two pixels has the same tca select the pixel with the
                    // maximum vale of hacklength
                    if (tcaRandomIter.getSampleDouble(p[0] + dirIn[k][1], p[1] + dirIn[k][0], 0) == area) {
                        if (lRandomIter.getSampleDouble(p[0] + dirIn[k][1], p[1] + dirIn[k][0], 0) > lenght) {
                            kk = k;
                            area = tcaRandomIter.getSampleDouble(p[0] + dirIn[k][1], p[1] + dirIn[k][0], 0);
                            lenght = lRandomIter.getSampleDouble(p[0] + dirIn[k][1], p[1] + dirIn[k][0], 0);
                            point[0] = p[0] + dirIn[k][1];
                            point[1] = p[1] + dirIn[k][0];
                        }
                    } else {
                        kk = k;
                        area = tcaRandomIter.getSampleDouble(p[0] + dirIn[k][1], p[1] + dirIn[k][0], 0);
                        lenght = lRandomIter.getSampleDouble(p[0] + dirIn[k][1], p[1] + dirIn[k][0], 0);
                        point[0] = p[0] + dirIn[k][1];
                        point[1] = p[1] + dirIn[k][0];
                    }
                }
            }

        }
        p[0] = point[0];
        p[1] = point[1];
        param[0] = kk;
        param[1] = count;
    }
971504
def re_rect(FlowRate, Width, DistCenter, Nu, openchannel):
    """"""
    #Checking input validity - inputs not checked here are checked by
    #functions this function calls.
    ut.check_range([FlowRate, ">0", "Flow rate"], [Nu, ">0", "Nu"])
    return (4 * FlowRate
            * radius_hydraulic(Width, DistCenter, openchannel).magnitude
            / (Width * DistCenter * Nu))
375986
def execute(self, nc_file_list, index_list, in_weight_table,
                out_nc, grid_type, mp_lock):

        """"""
        if not os.path.exists(out_nc):
            raise Exception("Outfile has not been created. "
                            "You need to run: generateOutputInflowFile "
                            "function ...")

        if len(nc_file_list) != len(index_list):
            raise Exception("ERROR: Number of runoff files not equal to "
                            "number of indices ...")

        demo_file_list = nc_file_list[0]
        if not isinstance(nc_file_list[0], list):
            demo_file_list = [demo_file_list]

        self.data_validation(demo_file_list[0])
        self.read_in_weight_table(in_weight_table)

        conversion_factor = self.get_conversion_factor(demo_file_list[0],
                                                       len(demo_file_list))

        # get indices of subset of data
        lon_ind_all = [int(i) for i in self.dict_list[self.header_wt[2]]]
        lat_ind_all = [int(j) for j in self.dict_list[self.header_wt[3]]]

        # Obtain a subset of  runoff data based on the indices in the
        # weight table
        min_lon_ind_all = min(lon_ind_all)
        max_lon_ind_all = max(lon_ind_all)
        min_lat_ind_all = min(lat_ind_all)
        max_lat_ind_all = max(lat_ind_all)
        lon_slice = slice(min_lon_ind_all, max_lon_ind_all + 1)
        lat_slice = slice(min_lat_ind_all, max_lat_ind_all + 1)
        index_new = []

        # combine inflow data
        for nc_file_array_index, nc_file_array in enumerate(nc_file_list):

            index = index_list[nc_file_array_index]

            if not isinstance(nc_file_array, list):
                nc_file_array = [nc_file_array]

            data_subset_all = None
            for nc_file in nc_file_array:
                # Validate the netcdf dataset
                self.data_validation(nc_file)

                # Read the netcdf dataset
                data_in_nc = Dataset(nc_file)

                # Calculate water inflows
                runoff_dimension_size = \
                    len(data_in_nc.variables[self.runoff_vars[0]].dimensions)
                if runoff_dimension_size == 2:
                    # obtain subset of surface and subsurface runoff
                    data_subset_runoff = \
                        data_in_nc.variables[self.runoff_vars[0]][
                            lat_slice, lon_slice]
                    for var_name in self.runoff_vars[1:]:
                        data_subset_runoff += \
                            data_in_nc.variables[var_name][
                                lat_slice, lon_slice]

                    # get runoff dims
                    len_time_subset = 1
                    len_lat_subset = data_subset_runoff.shape[0]
                    len_lon_subset = data_subset_runoff.shape[1]

                    # reshape the runoff
                    data_subset_runoff = data_subset_runoff.reshape(
                        len_lat_subset * len_lon_subset)

                elif runoff_dimension_size == 3:
                    # obtain subset of surface and subsurface runoff
                    data_subset_runoff = \
                        data_in_nc.variables[self.runoff_vars[0]][
                            :, lat_slice, lon_slice]
                    for var_name in self.runoff_vars[1:]:
                        data_subset_runoff += \
                            data_in_nc.variables[var_name][
                                :, lat_slice, lon_slice]

                    # get runoff dims
                    len_time_subset = data_subset_runoff.shape[0]
                    len_lat_subset = data_subset_runoff.shape[1]
                    len_lon_subset = data_subset_runoff.shape[2]
                    # reshape the runoff
                    data_subset_runoff = \
                        data_subset_runoff.reshape(
                            len_time_subset,
                            (len_lat_subset * len_lon_subset))

                data_in_nc.close()

                if not index_new:
                    # compute new indices based on the data_subset_surface
                    for r in range(0, self.count):
                        ind_lat_orig = lat_ind_all[r]
                        ind_lon_orig = lon_ind_all[r]
                        index_new.append(
                            (ind_lat_orig - min_lat_ind_all) * len_lon_subset
                            + (ind_lon_orig - min_lon_ind_all))

                # obtain a new subset of data
                if runoff_dimension_size == 2:
                    data_subset_new = data_subset_runoff[index_new]
                elif runoff_dimension_size == 3:
                    data_subset_new = data_subset_runoff[:, index_new]

                # FILTER DATA
                try:
                    # set masked values to zero
                    data_subset_new = data_subset_new.filled(fill_value=0)
                except AttributeError:
                    pass
                # set negative values to zero
                data_subset_new[data_subset_new < 0] = 0

                # combine data
                if data_subset_all is None:
                    data_subset_all = data_subset_new
                else:
                    data_subset_all = np.add(data_subset_all, data_subset_new)

            if runoff_dimension_size == 3 and len_time_subset > 1:
                inflow_data = np.zeros((len_time_subset, self.size_stream_id))
            else:
                inflow_data = np.zeros(self.size_stream_id)

            pointer = 0
            for stream_index in xrange(self.size_stream_id):
                npoints = int(self.dict_list[self.header_wt[4]][pointer])
                # Check if all npoints points correspond to the same streamID
                if len(set(self.dict_list[self.header_wt[0]][
                           pointer: (pointer + npoints)])) != 1:
                    print("ROW INDEX {0}".format(pointer))
                    print("COMID {0}".format(
                        self.dict_list[self.header_wt[0]][pointer]))
                    raise Exception(self.error_messages[2])

                area_sqm_npoints = \
                    np.array([float(k) for k in
                              self.dict_list[self.header_wt[1]][
                              pointer: (pointer + npoints)]])

                # assume data is incremental
                if runoff_dimension_size == 3:
                    data_goal = data_subset_all[:, pointer:(pointer + npoints)]
                else:
                    data_goal = data_subset_all[pointer:(pointer + npoints)]

                if grid_type == 't255':
                    # A) ERA Interim Low Res (T255) - data is cumulative
                    # from time 3/6/9/12
                    # (time zero not included, so assumed to be zero)
                    ro_first_half = \
                        np.concatenate([data_goal[0:1, ],
                                        np.subtract(data_goal[1:4, ],
                                                    data_goal[0:3, ])])
                    # from time 15/18/21/24
                    # (time restarts at time 12, assumed to be zero)
                    ro_second_half = \
                        np.concatenate([data_goal[4:5, ],
                                        np.subtract(data_goal[5:, ],
                                                    data_goal[4:7, ])])
                    ro_stream = \
                        np.multiply(
                            np.concatenate([ro_first_half, ro_second_half]),
                            area_sqm_npoints)

                else:
                    ro_stream = data_goal * area_sqm_npoints * \
                                conversion_factor

                # filter nan
                ro_stream[np.isnan(ro_stream)] = 0

                if ro_stream.any():
                    if runoff_dimension_size == 3 and len_time_subset > 1:
                        inflow_data[:, stream_index] = ro_stream.sum(axis=1)
                    else:
                        inflow_data[stream_index] = ro_stream.sum()

                pointer += npoints

            # only one process is allowed to write at a time to netcdf file
            mp_lock.acquire()
            data_out_nc = Dataset(out_nc, "a", format="NETCDF3_CLASSIC")
            if runoff_dimension_size == 3 and len_time_subset > 1:
                data_out_nc.variables['m3_riv'][
                    index*len_time_subset:(index+1)*len_time_subset, :] = \
                    inflow_data
            else:
                data_out_nc.variables['m3_riv'][index] = inflow_data
            data_out_nc.close()
            mp_lock.release()
528051
def get_qout_index(self,
                       river_index_array=None,
                       date_search_start=None,
                       date_search_end=None,
                       time_index_start=None,
                       time_index_end=None,
                       time_index=None,
                       time_index_array=None,
                       daily=False,
                       pd_filter=None,
                       filter_mode="mean",
                       as_dataframe=False):
        
        if river_index_array is not None:
            if hasattr(river_index_array, "__len__"):
                if len(river_index_array) == 1:
                    river_index_array = river_index_array[0]

        if time_index_array is None:
            time_index_array = self.get_time_index_range(date_search_start,
                                                         date_search_end,
                                                         time_index_start,
                                                         time_index_end,
                                                         time_index)

        qout_variable = self.qout_nc.variables[self.q_var_name]
        qout_dimensions = qout_variable.dimensions
        if qout_dimensions[0].lower() == 'time' and \
                qout_dimensions[1].lower() == self.river_id_dimension.lower():
            if time_index_array is not None and river_index_array is not None:
                streamflow_array = qout_variable[time_index_array,
                                                 river_index_array].transpose()
            elif time_index_array is not None:
                streamflow_array = qout_variable[time_index_array, :] \
                                   .transpose()
            elif river_index_array is not None:
                streamflow_array = qout_variable[:, river_index_array] \
                                   .transpose()
            else:
                streamflow_array = qout_variable[:].transpose()
        elif qout_dimensions[1].lower() == 'time' and \
                qout_dimensions[0].lower() == self.river_id_dimension.lower():
            if time_index_array is not None and river_index_array is not None:
                streamflow_array = qout_variable[river_index_array,
                                                 time_index_array]
            elif time_index_array is not None:
                streamflow_array = qout_variable[:, time_index_array]
            elif river_index_array is not None:
                streamflow_array = qout_variable[river_index_array, :]
            else:
                streamflow_array = qout_variable[:]
        else:
            raise Exception("Invalid RAPID Qout file dimensions ...")

        if daily:
            pd_filter = "D"

        if pd_filter is not None or as_dataframe:
            time_array = self.get_time_array(return_datetime=True,
                                             time_index_array=time_index_array)
            qout_df = pd.DataFrame(streamflow_array.T, index=time_array)

            if pd_filter is not None:
                qout_df = qout_df.resample(pd_filter)
                if filter_mode == "mean":
                    qout_df = qout_df.mean()
                elif filter_mode == "max":
                    qout_df = qout_df.max()
                else:
                    raise Exception("Invalid filter_mode ...")

            if as_dataframe:
                return qout_df

            streamflow_array = qout_df.as_matrix().T

            if streamflow_array.ndim > 0 and streamflow_array.shape[0] == 1:
                streamflow_array = streamflow_array[0]

        return streamflow_array
503816
def japan_basin_model(vs30):
    
    coeff = 412.39 ** 2.0
    model = (-5.23 / 2.0) * np.log(
        ((vs30 ** 2.0) + coeff) / ((1360.0 ** 2.0) + coeff)
        ) - np.log(1000.)
    return np.exp(model)
742013
function(args) {

                var tpl = '<filter><feFlood flood-color="${color}" flood-opacity="${opacity}" result="colored"/><feMorphology result="morphed" in="SourceGraphic" operator="dilate" radius="${width}"/><feComposite result="composed" in="colored" in2="morphed" operator="in"/><feGaussianBlur result="blured" in="composed" stdDeviation="${blur}"/><feBlend in="SourceGraphic" in2="blured" mode="normal"/></filter>';

                return joint.util.template(tpl)({
                    color: args.color || 'red',
                    width: Number.isFinite(args.width) ? args.width : 1,
                    blur: Number.isFinite(args.blur) ? args.blur : 0,
                    opacity: Number.isFinite(args.opacity) ? args.opacity : 1
                });
            }