numpy.random.random

Here are the examples of the python api numpy.random.random taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

180 Examples 7

Example 101

Project: fracture Source File: main.py
Function: main
def main():

  from iutils.render import Animate
  from modules.fracture import Fractures

  # from dddUtils.ioOBJ import export_2d as export
  from fn import Fn
  fn = Fn(prefix='./res/',postfix='.2obj')

  F = Fractures(
    INIT_NUM,
    INIT_RAD,
    SOURCE_DST,
    FRAC_DOT,
    FRAC_DST,
    FRAC_STP,
    FRAC_SPD,
    FRAC_DIMINISH,
    FRAC_SPAWN_DIMINISH,
    domain = 'rect'
  )

  print(F.sources.shape)

  # uniform square distribution
  from numpy.random import random
  for _ in range(5):
    F.blow(2, random(size=2))

  # uniform circular distribution
  # for _ in xrange(5):
    # F.blow(3, random_uniform_circle(INIT_RAD, num=1))

  def wrap(render):

    if not F.i % 20:
      show(render,F)
      # vertices, paths = F.get_vertices_and_paths()
      # export('fractures', fn.name(), vertices, lines=paths)
      render.write_to_png(fn.name()+'.png')

    F.print_stats()
    res = F.step(dbg=False)
    n = F.spawn_front(factor=SPAWN_FACTOR, angle=SPAWN_ANGLE)
    print('spawned: {:d}'.format(n))

    # fn = './asdf_{:04d}.png'.format(F.i)
    # render.write_to_png(fn)

    # if not res:
      # vertices, paths = F.get_vertices_and_paths()
      # export('fractures', fn.name(), vertices, lines=paths)

    return res

  render = Animate(SIZE, BACK, FRONT, wrap)
  render.start()

Example 102

Project: hyphae_ani Source File: hyphae.py
Function: init_data
  def __init_data(self):

    self.Z = [[] for i in xrange((ZONES+2)**2)]

    self.R = np.zeros(NMAX,'float') # radius
    self.X = np.zeros(NMAX,'float') # x position
    self.Y = np.zeros(NMAX,'float') # y position
    self.THE = np.zeros(NMAX,'float') # angle
    self.GE = np.zeros(NMAX,'float') # generation
    self.P = np.zeros(NMAX,'int') # index of parent node
    self.C = np.zeros(NMAX,'int') # number of branch attempts
    self.D = np.zeros(NMAX,'int')-1 # index of first descendant
    self.DQ = deque()

    self.num = 0

    rot = random()*pi*2

    for i in xrange(SOURCE_NUM):

      ## randomly on canvas
      #x = X_MIN*5 + random()*(X_MAX-X_MIN)
      #y = Y_MIN*5 + random()*(Y_MAX-Y_MIN)

      ## on circle
      x = 0.5 + sin(rot + (i*pi*2)/float(SOURCE_NUM))*0.1
      y = 0.5 + cos(rot + (i*pi*2)/float(SOURCE_NUM))*0.1

      self.X[i] = x
      self.Y[i] = y
      self.THE[i] = random()*pi*2.
      self.GE[i] = 1
      self.P[i] = -1 # no parent
      self.R[i] = RAD
      self.DQ.append(i)

      z = get_z(x,y)
      self.Z[z].append(self.num)
      self.num += 1

      ## draw inicator circle
      self.ctx.set_source_rgba(*CONTRASTA)
      self.circle(x,y,RAD*0.5)

Example 103

Project: chaco Source File: zoomable_colorbar.py
def _create_plot_component():

    # Create some data
    numpts = 1000
    x = sort(random(numpts))
    y = random(numpts)
    color = exp(-(x**2 + y**2))

    # Create a plot data obect and give it this data
    pd = ArrayPlotData()
    pd.set_data("index", x)
    pd.set_data("value", y)
    pd.set_data("color", color)

    # Create the plot
    plot = Plot(pd)
    plot.plot(("index", "value", "color"),
              type="cmap_scatter",
              name="my_plot",
              color_mapper=gist_earth,
              marker = "square",
              fill_alpha = 0.5,
              marker_size = 8,
              outline_color = "black",
              border_visible = True,
              bgcolor = "white")

    # Tweak some of the plot properties
    plot.title = "Colormapped Scatter Plot with Pan/Zoom Color Bar"
    plot.padding = 50
    plot.x_grid.visible = False
    plot.y_grid.visible = False
    plot.x_axis.font = "modern 16"
    plot.y_axis.font = "modern 16"

    # Add pan and zoom to the plot
    plot.tools.append(PanTool(plot, constrain_key="shift"))
    zoom = ZoomTool(plot)
    plot.overlays.append(zoom)

    # Create the colorbar, handing in the appropriate range and colormap
    colorbar = ColorBar(index_mapper=LinearMapper(range=plot.color_mapper.range),
                        color_mapper=plot.color_mapper,
                        orientation='v',
                        resizable='v',
                        width=30,
                        padding=20)
    colorbar.plot = plot
    colorbar.padding_top = plot.padding_top
    colorbar.padding_bottom = plot.padding_bottom

    # Add pan and zoom tools to the colorbar
    colorbar.tools.append(PanTool(colorbar, constrain_direction="y", constrain=True))
    zoom_overlay = ZoomTool(colorbar, axis="index", tool_mode="range",
                            always_on=True, drag_button="right")
    colorbar.overlays.append(zoom_overlay)

    # Create a container to position the plot and the colorbar side-by-side
    container = HPlotContainer(plot, colorbar, use_backbuffer=True, bgcolor="lightgray")

    return container

Example 104

Project: differential-mesh Source File: main.py
def main():

  from differentialMesh import DifferentialMesh
  from iutils.render import Render
  from time import time
  from modules.helpers import print_stats
  from numpy import array

  from modules.utils import get_exporter
  exporter = get_exporter(NMAX)

  DM = DifferentialMesh(NMAX, 2*FARL, NEARL, FARL, PROCS)

  DM.new_faces_in_ngon(MID, MID, H, 6, 0.0)

  render = Render(SIZE, BACK, FRONT)
  render.set_line_width(LINEWIDTH)

  fn = Fn(prefix='./res/')


  # st = named_sub_timers()

  tsum = 0


  for i in range(10000000):

    t1 = time()
    for _ in range(STEPS_ITT):

      # st.start()
      DM.optimize_position(
        ATTRACT_STP,
        REJECT_STP,
        TRIANGLE_STP,
        ALPHA,
        DIMINISH,
        -1
      )
      # st.t('opt')

      henum = DM.get_henum()
      # st.t('rnd')

      surface_edges = array(
        [DM.is_surface_edge(e)>0
        for e in range(henum)],
        'bool').nonzero()[0]

      # st.t('surf')

      rnd = random(size=len(surface_edges)*2)
      the = (1.-2*rnd[::2])*pi
      rad = rnd[1::2]*0.5*H
      dx = cos(the)*rad
      dy = sin(the)*rad
      # st.t('rnd2')

      DM.new_triangles_from_surface_edges(
        surface_edges,
        len(surface_edges),
        H,
        dx,
        dy,
        MINIMUM_LENGTH,
        MAXIMUM_LENGTH,
        1
      )
      # st.t('tri')

      # st.start()
      DM.optimize_edges(
        SPLIT_LIMIT,
        FLIP_LIMIT
      )
      # st.t('opte')

      tsum += time() - t1

    print_stats(i*STEPS_ITT, tsum, DM)
    name = fn.name()

    ## export png
    show(render, DM, name+'.png')

    ## export obj
    exporter(
      DM,
      name + '.2obj',
      {
        'procs': PROCS,
        'nearl': NEARL,
        'farl': FARL,
        'reject_stp': 0,
        'attract_stp': 0,
        'triangle_stp': 0,
        'size': SIZE
      },
      i*STEPS_ITT
    )
    tsum = 0

Example 105

Project: EQcorrscan Source File: synth_seis.py
def generate_synth_data(nsta, ntemplates, nseeds, samp_rate, t_length,
                        max_amp, max_lag, debug=0):
    """
    Generate a synthetic dataset to be used for testing.

    This will generate both templates and data to scan through.
    Templates will be generated using the utils.synth_seis functions.
    The day of data will be random noise, with random signal-to-noise
    ratio copies of the templates randomly seeded throughout the day.
    It also returns the seed times and signal-to-noise ratios used.

    :type nsta: int
    :param nsta: Number of stations to generate data for < 15.
    :type ntemplates: int
    :param ntemplates: Number of templates to generate, will be generated \
        with random arrival times.
    :type nseeds: int
    :param nseeds: Number of copies of the template to seed within the \
        day of noisy data for each template.
    :type samp_rate: float
    :param samp_rate: Sampling rate to use in Hz
    :type t_length: float
    :param t_length: Length of templates in seconds.
    :type max_amp: float
    :param max_amp: Maximum signal-to-noise ratio of seeds.
    :param max_lag: Maximum lag time in seconds (randomised).
    :type max_lag: float
    :type debug: int
    :param debug: Debug level, bigger the number, the more plotting/output.

    :returns: Templates: List of :class:`obspy.core.stream.Stream`
    :rtype: list
    :returns: Data: :class:`obspy.core.stream.Stream` of seeded noisy data
    :rtype: :class:`obspy.core.stream.Stream`
    :returns: Seeds: dictionary of seed SNR and time with time in samples.
    :rtype: dict
    """
    # Generate random arrival times
    t_times = np.abs(np.random.random([nsta, ntemplates])) * max_lag
    # Generate random node locations - these do not matter as they are only
    # used for naming
    lats = np.random.random(ntemplates) * 90.0
    lons = np.random.random(ntemplates) * 90.0
    depths = np.abs(np.random.random(ntemplates) * 40.0)
    nodes = zip(lats, lons, depths)
    # Generating a 5x3 array to make 3 templates
    stations = ['ALPH', 'BETA', 'GAMM', 'KAPP', 'ZETA', 'BOB', 'MAGG',
                'ALF', 'WALR', 'ALBA', 'PENG', 'BANA', 'WIGG', 'SAUS',
                'MALC']
    if debug > 1:
        print(nodes)
        print(t_times)
        print(stations[0:nsta])
    templates = template_grid(stations=stations[0:nsta], nodes=nodes,
                              travel_times=t_times, phase='S',
                              samp_rate=samp_rate,
                              flength=int(t_length * samp_rate))
    if debug > 2:
        for template in templates:
            print(template)
            template.plot(size=(800, 600), equal_scale=False)
    # Now we want to create a day of synthetic data
    seeds = []
    data = templates[0].copy()  # Copy a template to get the correct length
    # and stats for data, we will overwrite the data on this copy
    for tr in data:
        tr.data = np.zeros(86400 * int(samp_rate))
        # Set all the traces to have a day of zeros
        tr.stats.starttime = UTCDateTime(0)
    for i, template in enumerate(templates):
        impulses = np.zeros(86400 * int(samp_rate))
        # Generate a series of impulses for seeding
        # Need three seperate impulse traces for each of the three templates,
        # all will be convolved within the data though.
        impulse_times = np.random.randint(86400 * int(samp_rate),
                                          size=nseeds)
        impulse_amplitudes = np.random.randn(nseeds) * max_amp
        # Generate amplitudes up to maximum amplitude in a normal distribution
        seeds.append({'SNR': impulse_amplitudes,
                      'time': impulse_times})
        for j in range(nseeds):
            impulses[impulse_times[j]] = impulse_amplitudes[j]
        # We now have one vector of impulses, we need nsta numbers of them,
        # shifted with the appropriate lags
        mintime = min([template_tr.stats.starttime
                       for template_tr in template])
        for j, template_tr in enumerate(template):
            offset = int((template_tr.stats.starttime - mintime) * samp_rate)
            pad = np.zeros(offset)
            tr_impulses = np.append(pad, impulses)[0:len(impulses)]
            # Convolve this with the template trace to give the daylong seeds
            data[j].data += np.convolve(tr_impulses,
                                        template_tr.data)[0:len(impulses)]
        if debug > 2:
            data.plot(starttime=UTCDateTime(0) +
                      impulse_times[0] / samp_rate - 3,
                      endtime=UTCDateTime(0) +
                      impulse_times[0] / samp_rate + 15)
    # Add the noise
    for tr in data:
        noise = np.random.randn(86400 * int(samp_rate))
        tr.data += noise / max(noise)
        if debug > 2:
            tr.plot()

    return templates, data, seeds

Example 106

Project: image_captioning Source File: coco.py
Function: showanns
    def showAnns(self, anns):
        """
        Display the specified annotations.
        :param anns (array of object): annotations to display
        :return: None
        """
        if len(anns) == 0:
            return 0
        if 'segmentation' in anns[0]:
            datasetType = 'instances'
        elif 'caption' in anns[0]:
            datasetType = 'captions'
        if datasetType == 'instances':
            ax = plt.gca()
            ax.set_autoscale_on(False)
            polygons = []
            color = []
            for ann in anns:
                c = (np.random.random((1, 3))*0.6+0.4).tolist()[0]
                if type(ann['segmentation']) == list:
                    # polygon
                    for seg in ann['segmentation']:
                        poly = np.array(seg).reshape((len(seg)/2, 2))
                        polygons.append(Polygon(poly))
                        color.append(c)
                else:
                    # mask
                    t = self.imgs[ann['image_id']]
                    if type(ann['segmentation']['counts']) == list:
                        rle = mask.frPyObjects([ann['segmentation']], t['height'], t['width'])
                    else:
                        rle = [ann['segmentation']]
                    m = mask.decode(rle)
                    img = np.ones( (m.shape[0], m.shape[1], 3) )
                    if ann['iscrowd'] == 1:
                        color_mask = np.array([2.0,166.0,101.0])/255
                    if ann['iscrowd'] == 0:
                        color_mask = np.random.random((1, 3)).tolist()[0]
                    for i in range(3):
                        img[:,:,i] = color_mask[i]
                    ax.imshow(np.dstack( (img, m*0.5) ))
                if 'keypoints' in ann and type(ann['keypoints']) == list:
                    # turn skeleton into zero-based index
                    sks = np.array(self.loadCats(ann['category_id'])[0]['skeleton'])-1
                    kp = np.array(ann['keypoints'])
                    x = kp[0::3]
                    y = kp[1::3]
                    v = kp[2::3]
                    for sk in sks:
                        if np.all(v[sk]>0):
                            plt.plot(x[sk],y[sk], linewidth=3, color=c)
                    plt.plot(x[v==1], y[v==1],'o',markersize=8, markerfacecolor=c, markeredgecolor='k',markeredgewidth=2)
                    plt.plot(x[v==2], y[v==2],'o',markersize=8, markerfacecolor=c, markeredgecolor=c, markeredgewidth=2)
            p = PatchCollection(polygons, facecolor=color, linewidths=0, alpha=0.4)
            ax.add_collection(p)
            p = PatchCollection(polygons, facecolor="none", edgecolors=color, linewidths=2)
            ax.add_collection(p)
        elif datasetType == 'captions':
            for ann in anns:
                print ann['caption']

Example 107

Project: generativebot Source File: main.py
Function: run
def run(fn):
  from differentialMesh import DifferentialMesh
  from sand import Sand
  from time import time
  from .modules.helpers import darts
  from .modules.helpers import print_stats
  from numpy import array

  DM = DifferentialMesh(NMAX, 2*FARL, NEARL, FARL, PROCS)

  DM.new_faces_in_ngon(MID, MID, H, 6, 0.0)
  DM.set_edge_intensity(1, 1)

  sources = [(x,y) for x,y in darts(NUM_SOURCES, MID, MID, 0.43, 0.002)]
  DM.initialize_sources(sources, NEARL)

  sand = Sand(SIZE)
  sand.set_bg(BACK)
  sand.set_rgba(FRONT)


  tsum = 0


  for i in range(3000):
    t1 = time()

    DM.find_nearby_sources()

    henum = DM.get_henum()

    surface_edges = array(
      [DM.is_surface_edge(e)>0 and r<DM.get_edge_intensity(e)
      for e,r in enumerate(random(size=henum))],
      'bool').nonzero()[0]

    rnd = random(size=len(surface_edges)*2)
    the = (1.-2*rnd[::2])*pi
    rad = rnd[1::2]*0.5*H
    dx = cos(the)*rad
    dy = sin(the)*rad

    DM.new_triangles_from_surface_edges(
      surface_edges,
      len(surface_edges),
      H,
      dx,
      dy,
      MINIMUM_LENGTH,
      MAXIMUM_LENGTH,
      1
    )

    DM.optimize_position(
      ATTRACT_STP,
      REJECT_STP,
      TRIANGLE_STP,
      ALPHA,
      DIMINISH,
      -1
    )

    henum = DM.get_henum()

    DM.optimize_edges(
      SPLIT_LIMIT,
      FLIP_LIMIT
    )

    tsum += time() - t1

    if not i % 10:
      print_stats(i, tsum, DM)

    if DM.safe_vertex_positions(0.05)<0:
      show(sand, DM)

      sand.set_transparent_pixel()
      print(fn)
      sand.write_to_png(fn)

      return

Example 108

Project: tvb-framework Source File: stand_alone_hdf5.py
def test_using_h5py(nr_of_threads):
    
    storage_path = os.path.join(ROOT_STORAGE, TEST_FILE_NAME)
    
    if os.path.exists(storage_path):
        os.remove(storage_path)
    
    def init_some_data():
        dummy_data = numpy.random.random(size=(16000, 3))
        h5_file = h5py.File(storage_path, 'w')
        h5_file.create_dataset('vertices', data=dummy_data)
        h5_file.close()
        
    def read_some_data(th_nr):
        global isok
        global exception
        try:
            h5_file = h5py.File(storage_path, 'r')
            read_data = h5_file['/vertices']
            if read_data.shape != (16000, 3):
                raise Exception("Actually got shape : " + str(read_data.shape))
            h5_file.close()
            if int(th_nr) > 50000:
                raise Exception("GOT TO 50000 SHOULD STOP NOW")
        except Exception, ex:
            isok = False
            exception = ex.message
        
    init_some_data()
    read_some_data('1')
    
    th_nr = 1
    while isok:
        th_nr += 1
        for i in xrange(80):
            th = threading.Thread(target=read_some_data, kwargs={"th_nr": str(th_nr * 80 + i)})
            th.start()
        for thread in threading.enumerate():
            if thread is not threading.currentThread():
                thread.join()
    print "RAN FINE FOR " + str(th_nr * 80) + " THREADS"
    print "STOPPED DUE TO EXCEPTION " + str(exception)

Example 109

Project: tree Source File: render.py
  def branch2(self,b):

    a = b.a
    r = b.r
    x = b.x
    y = b.y

    rx = self.ctx

    one = self.one

    x1 = x + cos(a-0.5*pi)*r
    x2 = x + cos(a+0.5*pi)*r
    y1 = y + sin(a-0.5*pi)*r
    y2 = y + sin(a+0.5*pi)*r
    dd = sqrt(square(x-x2) + square(y-y2))

    ## TRUNK STROKE
    rx.set_source_rgba(*self.trunk)
    for _ in xrange(10):
      rx.move_to(x1,y1)
      rx.line_to(x2,y2)
      rx.stroke()

    ## OUTLINE
    rx.set_source_rgba(*self.trunk_stroke)
    rx.rectangle(x1,y1,one,one)
    rx.fill()
    rx.rectangle(x1,y1,one,one)
    rx.fill()

    rx.rectangle(x2,y2,one,one)
    rx.fill()
    rx.rectangle(x2,y2,one,one)
    rx.fill()

    rx.rectangle(x1,y1,one,one)
    rx.fill()
    rx.rectangle(x2,y2,one,one)
    rx.fill()

    ## TRUNK SHADE RIGHT
    the = 0.5*pi + a

    # TODO: shade increments
    scales = random(self.grains)*dd*random()
    xxp = x2 - scales*cos(the)
    yyp = y2 - scales*sin(the)

    for xx,yy in zip(xxp,yyp):
      rx.rectangle(xx,yy,one,one)
      rx.fill()

    ## TRUNK SHADE LEFT
    dd = sqrt(square(x-x1) + square(y-y1))
    the = a - 0.5*pi

    scales = random(int(self.grains/5.))*dd*random()
    xxp = x1 - scales*cos(the)
    yyp = y1 - scales*sin(the)

    for xx,yy in zip(xxp,yyp):
      rx.rectangle(xx,yy,one,one)
      rx.fill()

Example 110

Project: borg Source File: ll_vs_features.py
@borg.annotations(
    out_path = ("results output path"),
    experiments = ("path to experiments JSON", "positional", None, borg.util.load_json),
    workers = ("submit jobs?", "option", "w", int),
    local = ("workers are local?", "flag"),
    )
def main(out_path, experiments, workers = 0, local = False):
    """Run the specified model evaluations."""

    logger.info("running %i experiments", len(experiments))

    get_run_data = borg.util.memoize(borg.storage.RunData.from_bundle)

    def yield_jobs():
        for experiment in experiments:
            logger.info("preparing experiment: %s", experiment)

            run_data = get_run_data(experiment["run_data"])
            validation = sklearn.cross_validation.KFold(len(run_data), 5, indices = False)
            (train_mask, test_mask) = iter(validation).next()
            training = run_data.masked(train_mask).collect_systematic([2])
            testing = run_data.masked(test_mask).collect_systematic([4])
            feature_counts = range(0, len(run_data.common_features) + 1, 2)
            replications = xrange(32)
            parameters = list(itertools.product(feature_counts, replications))

            for model_name in experiment["model_names"]:
                model = borg.experiments.common.train_model(model_name, training)
                model.name = model_name

                for (feature_count, _) in parameters:
                    shuffled_names = sorted(run_data.common_features, key = lambda _: numpy.random.random())
                    selected_names = sorted(shuffled_names[:feature_count])

                    yield (
                        evaluate_features,
                        [
                            model,
                            testing,
                            selected_names,
                            ],
                        )

    with borg.util.openz(out_path, "wb") as out_file:
        writer = csv.writer(out_file)

        writer.writerow(["model_name", "features", "score_name", "score"])

        for (_, rows) in condor.do(yield_jobs(), workers, local):
            writer.writerows(rows)

            out_file.flush()

Example 111

Project: differential-line Source File: main_line.py
def main():

  from time import time
  from itertools import count

  from differentialLine import DifferentialLine

  from iutils.render import Render
  from modules.helpers import print_stats

  from modules.show import sandstroke
  from modules.show import show
  from modules.show import dots


  np_coords = zeros(shape=(NMAX,4), dtype='float')
  np_vert_coords = zeros(shape=(NMAX,2), dtype='float')


  DF = DifferentialLine(NMAX, FARL*2, NEARL, FARL, PROCS)

  render = Render(SIZE, BACK, FRONT)

  render.ctx.set_source_rgba(*FRONT)
  render.ctx.set_line_width(LINEWIDTH)

  # angles = sorted(random(INIT_NUM)*TWOPI)
  # DF.init_circle_segment(MID,MID,0.2, angles)

  ## arc

  angles = sorted(random(INIT_NUM)*pi*1.5)
  xys = []
  for a in angles:
    x = 0.5 + cos(a)*0.2
    y = 0.5 + sin(a)*0.2
    xys.append((x,y))

  DF.init_line_segment(xys, lock_edges=1)

  ## vertical line

  #yy = sorted(MID + 0.2*(1-2*random(INIT_NUM)))
  #xx = MID+0.005*(0.5-random(INIT_NUM))
  #xys = []
  #for x,y in zip(xx,yy):
    #xys.append((x,y))

  #DF.init_line_segment(xys, lock_edges=1)

  ## diagonal line

  # yy = sorted(MID + 0.2*(1-2*random(INIT_NUM)))
  # xx = sorted(MID + 0.2*(1-2*random(INIT_NUM)))
  # xys = []
  # for x,y in zip(xx,yy):
    # xys.append((x,y))

  # DF.init_line_segment(xys, lock_edges=1)


  for i in count():

    t_start = time()

    DF.optimize_position(STP)
    spawn_curl(DF,NEARL,0.016)

    if i%100==0:
      fn = './res/chris_bd_{:04d}.png'.format(i)
    else:
      fn = None

    render.set_front(FRONT)
    num = DF.np_get_edges_coordinates(np_coords)
    sandstroke(render,np_coords[:num,:],20,fn)


    if random()<0.05:
      sandstroke(render,np_coords[:num,:],30,None)

    vert_num = DF.np_get_vert_coordinates(np_vert_coords)
    dots(render,np_vert_coords[:vert_num,:],None)


    t_stop = time()

    print_stats(i,t_stop-t_start,DF)

Example 112

Project: fos-legacy Source File: test_engine.py
def test_engine2windows():
    
    eng = Engine()
    eng.run()
    # create a world
    w = World(0)
    
    # create default camera
    cam = DefaultCamera()
    
    # add camera
    w.add(cam)
    
    # create image viewr
    a=np.random.random( ( 100, 100, 100) )
    aff = np.eye(4)
    cds = ConnectedSlices(aff,a)
    
    # add cds to world
    w.add(cds)
    
    # add world to engine
    eng.add(w)
    
    # create a window
    wi = FosWindow()
    
    # attach window to world
    wi.attach(w)
    
    wi2 = FosWindow()
    # attach window to world
    wi2.attach(w)

Example 113

Project: recurrentshop Source File: test_container.py
Function: test_all
@keras_test
def test_all():
	rc = RecurrentContainer()
	rc.add(SimpleRNNCell(4, input_dim=5))
	rc.add(GRUCell(3))
	rc.add(LSTMCell(2))

	model = Sequential()
	model.add(rc)
	model.compile(loss='mse', optimizer='sgd')

	x = np.random.random((100, 10, 5))
	y = np.random.random((100, 2))

	model.fit(x, y, nb_epoch=1)


	#### with readout=True
	rc = RecurrentContainer(readout=True)
	rc.add(SimpleRNNCell(4, input_dim=5))
	rc.add(GRUCell(3))
	rc.add(LSTMCell(5))

	model = Sequential()
	model.add(rc)
	model.compile(loss='mse', optimizer='sgd')

	x = np.random.random((100, 10, 5))
	y = np.random.random((100, 5))

	model.fit(x, y, nb_epoch=1)


	#### with state_sync=True
	rc = RecurrentContainer(state_sync=True)
	rc.add(GRUCell(3, input_dim=4))
	rc.add(GRUCell(3))

	model = Sequential()
	model.add(rc)
	model.compile(loss='mse', optimizer='sgd')

	x = np.random.random((100, 10, 4))
	y = np.random.random((100, 3))

	model.fit(x, y, nb_epoch=1)

	#### with state_sync=True, readout=True
	rc = RecurrentContainer(state_sync=True, readout=True)
	rc.add(GRUCell(4, input_dim=4))
	rc.add(GRUCell(4))

	model = Sequential()
	model.add(rc)
	model.compile(loss='mse', optimizer='sgd')

	x = np.random.random((100, 10, 4))
	y = np.random.random((100, 4))

	model.fit(x, y, nb_epoch=1)

	#### with dropout

	rc = RecurrentContainer()
	rc.add(SimpleRNNCell(3, input_dim=3))
	rc.add(Dropout(0.5))
	model = Sequential()
	model.add(rc)
	model.compile(loss='mse', optimizer='sgd')

	x = np.random.random((100, 3, 3))
	y = np.random.random((100, 3))

	model.fit(x, y, nb_epoch=1)

Example 114

Project: differential-mesh Source File: main_island_ani.py
Function: steps
def steps(dm):

  from numpy import cos
  from numpy import sin
  from numpy import unique
  from numpy.random import randint, random
  from time import time
  from modules.helpers import print_stats

  global steps_runs
  steps_runs += 1

  t1 = time()
  for i in range(STEPS_ITT):

    dm.optimize_position(
      ATTRACT_STP,
      REJECT_STP,
      TRIANGLE_STP,
      ALPHA,
      DIMINISH,
      -1
    )

    henum = dm.get_henum()

    edges = unique(randint(henum,size=(henum)))
    en = len(edges)
    rnd = 1-2*random(en*2)
    make_island = random(size=en)>0.85

    for i,(he,isl) in enumerate(zip(edges,make_island)):

      if dm.is_surface_edge(he)>0:

        the = pi*rnd[2*i]
        rad = rnd[2*i+1]*0.5
        dx = cos(the)
        dy = sin(the)

        if not isl:

          dm.new_triangle_from_surface_edge(
            he,
            H,
            dx*rad*H,
            dy*rad*H,
            minimum_length=MINIMUM_LENGTH,
            maximum_length=MAXIMUM_LENGTH,
            merge_ragged_edge=1
          )

        else:

          dm.throw_seed_triangle(
            he,
            H,
            dx*rad*H,
            dy*rad*H,
            NEARL*0.5,
            the
          )

    dm.optimize_edges(
      SPLIT_LIMIT,
      FLIP_LIMIT
    )

    if dm.safe_vertex_positions(3*H)<0:

      print('vertices reached the boundary. stopping.')
      return False

  t2 = time()
  print_stats(steps_runs, t2-t1, dm)

  return True

Example 115

Project: Mariana Source File: layers.py
Function: init
	def __init__(self,
		size,
		layerType,
		activation = MA.Pass(),
		regularizations = [],
		initializations=[],
		learningScenario=None,
		decorators=[],
		name=None
	):

		self.isLayer = True

		#a unique tag associated to the layer
		self.appelido = numpy.random.random()

		if name is not None :
			self.name = name
		else :
			self.name = "%s_%s" %(self.__class__.__name__, self.appelido)

		self.type = layerType

		self.nbInputs = None
		self.inputs = None
		self.nbOutputs = size
		self.outputs = None # this is a symbolic var
		self.testOutputs = None # this is a symbolic var

		self.preactivation_outputs = None
		self.preactivation_testOutputs = None

		self.activation = activation
		self.regularizationObjects = regularizations
		self.regularizations = []
		self.decorators = decorators
		self.initializations = initializations
		self.learningScenario=learningScenario

		self.network = MNET.Network()
		self.network._addLayer(self)

		self._inputRegistrations = set()

		self._mustInit = True
		self._mustReset = True
		self._decorating = False

Example 116

Project: fracture-cuda Source File: fracture.py
  def frac_front(self, factor, angle, dbg=False):
    inds = (random(self.anum)<factor).nonzero()[0]

    n = len(inds)
    if n<1:
      return 0

    cand_aa = self.active[inds, 0]
    cand_ii = self.fid_node[cand_aa, 1]

    num = self.num
    fnum = self.fnum
    anum = self.anum

    xy = self.xy[:num, :]
    visited = self.visited[:num, 0]
    new = arange(fnum, fnum+n)
    orig_dxy = self.dxy[cand_aa, :]

    diff_theta = (-1)**randint(2, size=n)*HPI + (0.5-random(n)) * angle
    theta = arctan2(orig_dxy[:, 1], orig_dxy[:, 0]) + diff_theta

    fid_node = column_stack((
        new,
        cand_ii
        ))
    cand_dxy = column_stack((
        cos(theta),
        sin(theta)
        ))

    nactive = arange(n)

    tmp_dxy = self.tmp_dxy[:n, :]

    self.update_zone_map()

    self.cuda_calc_stp(
        npint(self.nz),
        npint(self.zone_leap),
        npint(num),
        npint(n),
        npint(n),
        npfloat(self.frac_dot),
        npfloat(self.frac_dst),
        npfloat(self.frac_stp),
        npint(self.ignore_fracture_sources),
        drv.In(visited),
        drv.In(fid_node),
        drv.In(nactive),
        drv.Out(self.tmp[:n, :]),
        drv.In(xy),
        drv.In(cand_dxy),
        drv.Out(tmp_dxy),
        drv.In(self.zone_num),
        drv.In(self.zone_node),
        block=(self.threads,1,1),
        grid=(int(n//self.threads + 1), 1) # this cant be a numpy int for some reason
        )

    mask = tmp_dxy[:, 0] >= -1.0
    n = mask.sum()

    if n<1:
      return 0

    nodes = cand_ii[mask]
    self._add_fracs(cand_dxy[mask, :], nodes)

    if dbg:
      self.print_debug(num, fnum, anum, meta='new: {:d}'.format(n))
    return n

Example 117

Project: chaco Source File: cmap_scatter.py
def _create_plot_component():

    # Create some data
    numpts = 1000
    x = sort(random(numpts))
    y = random(numpts)
    color = exp(-(x**2 + y**2))

    # Create a plot data obect and give it this data
    pd = ArrayPlotData()
    pd.set_data("index", x)
    pd.set_data("value", y)
    pd.set_data("color", color)

    # Create the plot
    plot = Plot(pd)
    plot.plot(("index", "value", "color"),
              type="cmap_scatter",
              name="my_plot",
              color_mapper=jet,
              marker = "square",
              fill_alpha = 0.5,
              marker_size = 6,
              outline_color = "black",
              border_visible = True,
              bgcolor = "white")

    # Tweak some of the plot properties
    plot.title = "Colormapped Scatter Plot with Range-selectable Data Points"
    plot.padding = 50
    plot.x_grid.visible = False
    plot.y_grid.visible = False
    plot.x_axis.font = "modern 16"
    plot.y_axis.font = "modern 16"

    # Right now, some of the tools are a little invasive, and we need the
    # actual ColomappedScatterPlot object to give to them
    cmap_renderer = plot.plots["my_plot"][0]

    # Attach some tools to the plot
    plot.tools.append(PanTool(plot, constrain_key="shift"))
    zoom = ZoomTool(component=plot, tool_mode="box", always_on=False)
    plot.overlays.append(zoom)
    selection = ColormappedSelectionOverlay(cmap_renderer, fade_alpha=0.35,
                                            selection_type="mask")
    cmap_renderer.overlays.append(selection)

    # Create the colorbar, handing in the appropriate range and colormap
    colorbar = create_colorbar(plot.color_mapper)
    colorbar.plot = cmap_renderer
    colorbar.padding_top = plot.padding_top
    colorbar.padding_bottom = plot.padding_bottom

    # Create a container to position the plot and the colorbar side-by-side
    container = HPlotContainer(use_backbuffer = True)
    container.add(plot)
    container.add(colorbar)
    container.bgcolor = "lightgray"
    return container

Example 118

Project: generativebot Source File: hyphae.py
Function: steps
  def steps(self):

    num = self.num
    itt = 0

    while True:

      itt += 1

      if not itt%2000:
        print((itt, num, self.misses))

      if self.misses>2000:
        print('too many misses')
        break

      k = int(random()*num)
      self.C[k] += 1

      if self.C[k]>self.ck_max:

        ## node is dead
        self.misses += 1
        continue

      r = self.R[k]*self.rad_scale if self.D[k]>-1 else self.R[k]

      if r<self.one*1.5:

        ## node dies
        self.C[k] = self.ck_max+1
        self.misses += 1
        continue

      ge = self.GE[k]+1 if self.D[k]>-1 else self.GE[k]
      the = self.THE[k] + (1.-1./((ge+1)**0.1))*normal()*self.search_angle_max

      x = self.X[k] + sin(the)*r
      y = self.Y[k] + cos(the)*r

      # stop nodes at edge of canvas
      if x<self.frame or x>1.0-self.frame or y<self.frame or y>1.0-self.frame:

        # node is outside canvas
        self.misses += 1
        continue

      ## stop nodes at edge of circle
      ## remember to set initial node inside circle.
      # circle_rad = sqrt(square(x-0.5)+square(y-0.5))
      # if circle_rad>CIRCLE_RADIUS:

        # ## node is outside circle
        # continue

      try:

        inds = self.__near_zone_inds(x,y)
        inds = array([a for a in inds if not a==k and not a==self.P[k]])

      except IndexError:

        self.misses += 1
        continue

      good = True
      if len(inds)>0:
        dd = square(self.X[inds]-x) + square(self.Y[inds]-y)

        sqrt(dd,dd)
        mask = dd*2 > self.R[inds]+r
        good = mask.all()

      if good:
        self.X[num] = x
        self.Y[num] = y
        self.R[num] = r
        self.THE[num] = the
        self.P[num] = k
        self.GE[num] = ge

        if self.D[k]<0:
          self.D[k] = num

        z = self.__get_z(x,y)

        self.Z[z].append(num)

        num += 1
        self.num = num
        self.misses = 0

      else:
        self.misses += 1

Example 119

Project: qgisSpaceSyntaxToolkit Source File: layout.py
def random_layout(G, dim=2, scale=1., center=None):
    """Position nodes uniformly at random.

    For every node, a position is generated by choosing each of dim
    coordinates uniformly at random on the default interval [0.0, 1.0),
    or on an interval of length `scale` centered at `center`.

    NumPy (http://scipy.org) is required for this function.

    Parameters
    ----------
    G : NetworkX graph or list of nodes
       A position will be assigned to every node in G.

    dim : int
       Dimension of layout.

    scale : float (default 1)
        Scale factor for positions

    center : array-like (default scale*0.5 in each dim)
       Coordinate around which to center the layout.

    Returns
    -------
    pos : dict
       A dictionary of positions keyed by node

    Examples
    --------
    >>> G = nx.lollipop_graph(4, 3)
    >>> pos = nx.random_layout(G)
    """
    import numpy as np

    shape = (len(G), dim)
    pos = np.random.random(shape) * scale
    if center is not None:
        pos += np.asarray(center) - 0.5 * scale
    return dict(zip(G, pos))

Example 120

Project: tree Source File: render.py
  def branch(self,b):

    a = b.a
    r = b.r
    x = b.x
    y = b.y

    rx = self.ctx

    one = self.one

    x1 = x + cos(a-0.5*pi)*r
    x2 = x + cos(a+0.5*pi)*r
    y1 = y + sin(a-0.5*pi)*r
    y2 = y + sin(a+0.5*pi)*r
    dd = sqrt(square(x-x2) + square(y-y2))

    ## TRUNK STROKE
    rx.set_source_rgba(*self.trunk)
    for _ in xrange(10):
      rx.move_to(x1,y1)
      rx.line_to(x2,y2)
      rx.stroke()

    ## OUTLINE
    rx.set_source_rgba(*self.trunk_stroke)
    rx.rectangle(x1,y1,one,one)
    rx.fill()
    rx.rectangle(x1,y1,one,one)
    rx.fill()

    rx.rectangle(x2,y2,one,one)
    rx.fill()
    rx.rectangle(x2,y2,one,one)
    rx.fill()

    ## TRUNK SHADE RIGHT
    the = 0.5*pi + a

    # TODO: shade increments
    scales = random(self.grains)*dd*random()
    xxp = x2 - scales*cos(the)
    yyp = y2 - scales*sin(the)

    for xx,yy in zip(xxp,yyp):
      rx.rectangle(xx,yy,one,one)
      rx.fill()

    ## TRUNK SHADE LEFT
    dd = sqrt(square(x-x1) + square(y-y1))
    the = a - 0.5*pi

    scales = random(int(self.grains/5.))*dd*random()
    xxp = x1 - scales*cos(the)
    yyp = y1 - scales*sin(the)

    for xx,yy in zip(xxp,yyp):
      rx.rectangle(xx,yy,one,one)
      rx.fill()

Example 121

Project: mayavi Source File: test_mlab_source_integration.py
Function: test_infinite
    def test_infinite(self):
        """ Check that passing in arrays with infinite values raises
            errors """
        # Some arrays
        x = np.random.random((10, 3, 4))
        y = np.random.random((10, 3, 4))
        z = np.random.random((10, 3, 4))
        u = np.random.random((10, 3, 4))
        v = np.random.random((10, 3, 4))
        w = np.random.random((10, 3, 4))
        s = np.random.random((10, 3, 4))

        # Add a few infinite values:
        u[2, 2, 1] = np.inf
        s[0, 0, 0] = -np.inf

        # Check value errors are raised because of the infinite values
        self.assertRaises(ValueError,
                    sources.grid_source, x[0], y[0], z[0], scalars=s[0],
                    figure=None)

        self.assertRaises(ValueError,
                    sources.vertical_vectors_source, x, y, z, s,
                    figure=None)

        self.assertRaises(ValueError,
                    sources.array2d_source, x[0], y[0], s[0],
                    figure=None)

        self.assertRaises(ValueError,
                    sources.scalar_field, x, y, z, s,
                    figure=None)

        self.assertRaises(ValueError,
                    sources.scalar_scatter, x, y, z, s,
                    figure=None)

        self.assertRaises(ValueError,
                    sources.vector_scatter, x, y, z, u, v, w,
                    figure=None)

        self.assertRaises(ValueError,
                    sources.vector_field, x, y, z, u, v, w,
                    figure=None)

        self.assertRaises(ValueError,
                    sources.line_source, x[0, 0], y[0, 0], z[0, 0], s[0, 0],
                    figure=None)

Example 122

Project: pygsp Source File: graph.py
Function: sparse_fruchterman_reingold
def _sparse_fruchterman_reingold(A, dim=2, k=None, pos=None, fixed=None,
                                 iterations=50):
    # Position nodes in adjacency matrix A using Fruchterman-Reingold
    nnodes = A.shape[0]

    # make sure we have a LIst of Lists representation
    try:
        A = A.tolil()
    except:
        A = (coo_matrix(A)).tolil()

    if pos is None:
        # random initial positions
        pos = np.random.random((nnodes, dim))

    # no fixed nodes
    if fixed is None:
        fixed = []

    # optimal distance between nodes
    if k is None:
        k = np.sqrt(1.0/nnodes)

    # simple cooling scheme.
    # linearly step down by dt on each iteration so last iteration is size dt.
    t = 0.1
    dt = t/float(iterations+1)

    displacement = np.zeros((dim, nnodes))
    for iteration in range(iterations):
        displacement *= 0
        # loop over rows
        for i in range(nnodes):
            if i in fixed:
                continue
            # difference between this row's node position and all others
            delta = (pos[i]-pos).T
            # distance between points
            distance = np.sqrt((delta**2).sum(axis=0))
            # enforce minimum distance of 0.01
            distance = np.where(distance < 0.01, 0.01, distance)
            # the adjacency matrix row
            Ai = np.asarray(A[i, :].toarray())
            # displacement "force"
            displacement[:, i] += \
                (delta*(k*k/distance**2-Ai*distance/k)).sum(axis=1)
        # update positions
        length = np.sqrt((displacement**2).sum(axis=0))
        length = np.where(length < 0.01, 0.1, length)
        pos += (displacement*t/length).T
        # cool temperature
        t -= dt
    return pos

Example 123

Project: qgisSpaceSyntaxToolkit Source File: layout.py
def _sparse_fruchterman_reingold(A, dim=2, k=None, pos=None, fixed=None,
                                 iterations=50):
    # Position nodes in adjacency matrix A using Fruchterman-Reingold
    # Entry point for NetworkX graph is fruchterman_reingold_layout()
    # Sparse version
    import numpy as np
    try:
        nnodes,_=A.shape
    except AttributeError:
        raise nx.NetworkXError(
            "fruchterman_reingold() takes an adjacency matrix as input")
    try:
        from scipy.sparse import spdiags,coo_matrix
    except ImportError:
        raise ImportError("_sparse_fruchterman_reingold() scipy numpy: http://scipy.org/ ")
    # make sure we have a LIst of Lists representation
    try:
        A=A.tolil()
    except:
        A=(coo_matrix(A)).tolil()

    if pos is None:
        # random initial positions
        pos=np.asarray(np.random.random((nnodes,dim)),dtype=A.dtype)
    else:
        # make sure positions are of same type as matrix
        pos=pos.astype(A.dtype)

    # no fixed nodes
    if fixed is None:
        fixed=[]

    # optimal distance between nodes
    if k is None:
        k=np.sqrt(1.0/nnodes)
    # the initial "temperature"  is about .1 of domain area (=1x1)
    # this is the largest step allowed in the dynamics.
    # Calculate domain in case our fixed positions are bigger than 1x1
    t = max(max(pos.T[0]) - min(pos.T[0]), max(pos.T[1]) - min(pos.T[1]))*0.1
    # simple cooling scheme.
    # linearly step down by dt on each iteration so last iteration is size dt.
    dt=t/float(iterations+1)

    displacement=np.zeros((dim,nnodes))
    for iteration in range(iterations):
        displacement*=0
        # loop over rows
        for i in range(A.shape[0]):
            if i in fixed:
                continue
            # difference between this row's node position and all others
            delta=(pos[i]-pos).T
            # distance between points
            distance=np.sqrt((delta**2).sum(axis=0))
            # enforce minimum distance of 0.01
            distance=np.where(distance<0.01,0.01,distance)
            # the adjacency matrix row
            Ai=np.asarray(A.getrowview(i).toarray())
            # displacement "force"
            displacement[:,i]+=\
                (delta*(k*k/distance**2-Ai*distance/k)).sum(axis=1)
        # update positions
        length=np.sqrt((displacement**2).sum(axis=0))
        length=np.where(length<0.01,0.01,length)
        pos+=(displacement*t/length).T
        # cool temperature
        t-=dt
        if fixed is None:
            pos = _rescale_layout(pos)
    return pos

Example 124

Project: Ragout Source File: layout.py
def _sparse_fruchterman_reingold(A, dim=2, k=None, pos=None, fixed=None, 
                                 iterations=50):
    # Position nodes in adjacency matrix A using Fruchterman-Reingold  
    # Entry point for NetworkX graph is fruchterman_reingold_layout()
    # Sparse version
    try:
        import numpy as np
    except ImportError:
        raise ImportError("_sparse_fruchterman_reingold() requires numpy: http://scipy.org/ ")
    try:
        nnodes,_=A.shape
    except AttributeError:
        raise nx.NetworkXError(
            "fruchterman_reingold() takes an adjacency matrix as input")
    try:
        from scipy.sparse import spdiags,coo_matrix
    except ImportError:
        raise ImportError("_sparse_fruchterman_reingold() scipy numpy: http://scipy.org/ ")
    # make sure we have a LIst of Lists representation
    try:
        A=A.tolil()
    except:
        A=(coo_matrix(A)).tolil()

    if pos==None:
        # random initial positions
        pos=np.asarray(np.random.random((nnodes,dim)),dtype=A.dtype)
    else:
        # make sure positions are of same type as matrix
        pos=pos.astype(A.dtype)

    # no fixed nodes
    if fixed==None:
        fixed=[]

    # optimal distance between nodes
    if k is None:
        k=np.sqrt(1.0/nnodes)
    # the initial "temperature"  is about .1 of domain area (=1x1)
    # this is the largest step allowed in the dynamics.
    t=0.1
    # simple cooling scheme.
    # linearly step down by dt on each iteration so last iteration is size dt.
    dt=t/float(iterations+1)

    displacement=np.zeros((dim,nnodes))
    for iteration in range(iterations):
        displacement*=0
        # loop over rows
        for i in range(A.shape[0]):
            if i in fixed:
                continue
            # difference between this row's node position and all others
            delta=(pos[i]-pos).T
            # distance between points
            distance=np.sqrt((delta**2).sum(axis=0))
            # enforce minimum distance of 0.01
            distance=np.where(distance<0.01,0.01,distance)
            # the adjacency matrix row
            Ai=np.asarray(A.getrowview(i).toarray())
            # displacement "force"
            displacement[:,i]+=\
                (delta*(k*k/distance**2-Ai*distance/k)).sum(axis=1)
        # update positions
        length=np.sqrt((displacement**2).sum(axis=0))
        length=np.where(length<0.01,0.1,length)
        pos+=(displacement*t/length).T
        # cool temperature
        t-=dt
        pos=_rescale_layout(pos)
    return pos

Example 125

Project: gala Source File: test_orbit.py
Function: test_slice
def test_slice():

    # simple
    x = np.random.random(size=(3,10))
    v = np.random.random(size=(3,10))
    o = CartesianOrbit(pos=x, vel=v)
    new_o = o[:5]
    assert new_o.pos.shape == (3,5)

    # 1d slice on 3d
    x = np.random.random(size=(3,100,8))
    v = np.random.random(size=(3,100,8))
    t = np.arange(x.shape[1])
    o = CartesianOrbit(pos=x, vel=v, t=t)
    new_o = o[:5]
    assert new_o.pos.shape == (3,5,8)
    assert new_o.t.shape == (5,)

    # 3d slice on 3d
    o = CartesianOrbit(pos=x, vel=v, t=t)
    new_o = o[:5,:4]
    assert new_o.pos.shape == (3,5,4)
    assert new_o.t.shape == (5,)

    # boolean array
    x = np.random.random(size=(3,10))
    v = np.random.random(size=(3,10))
    t = np.arange(x.shape[1])
    o = CartesianOrbit(pos=x, vel=v, t=t)
    ix = np.array([0,0,0,0,0,1,1,1,1,1]).astype(bool)
    new_o = o[ix]
    assert new_o.shape == (sum(ix),)
    assert new_o.t.shape == (5,)

    # boolean array - 3D
    x = np.random.random(size=(3,10,4))
    v = np.random.random(size=(3,10,4))
    t = np.arange(x.shape[1])
    o = CartesianOrbit(pos=x, vel=v, t=t)
    ix = np.array([0,0,0,0,0,1,1,1,1,1]).astype(bool)
    new_o = o[ix]
    assert new_o.shape == (sum(ix),x.shape[-1])
    assert new_o.t.shape == (5,)

    # integer array
    x = np.random.random(size=(3,10))
    v = np.random.random(size=(3,10))
    t = np.arange(x.shape[1])
    o = CartesianOrbit(pos=x, vel=v, t=t)
    ix = np.array([0,3,5])
    new_o = o[ix]
    assert new_o.shape == (len(ix),)
    assert new_o.t.shape == (len(ix),)

Example 126

Project: differential-line Source File: main.py
def main():

  from time import time
  from itertools import count

  from iutils.render import Render
  from modules.helpers import print_stats
  from modules.show import show
  # from modules.show import show_closed

  from differentialLine import DifferentialLine
  from modules.helpers import get_exporter

  from numpy.random import random

  from fn import Fn

  DF = DifferentialLine(NMAX, FARL*2, NEARL, FARL, PROCS)

  fn = Fn(prefix='./res/')

  exporter = get_exporter(
    NMAX,
    {
      'nearl': NEARL,
      'farl': FARL,
      'stp': STP,
      'size': SIZE,
      'procs': PROCS
    }
  )

  render = Render(SIZE, BACK, FRONT)

  render.ctx.set_source_rgba(*FRONT)
  render.ctx.set_line_width(LINEWIDTH)

  angles = sorted(random(INIT_NUM)*TWOPI)

  DF.init_circle_segment(MID,MID,INIT_RAD, angles)

  t_start = time()


  for i in count():

    DF.optimize_position(STP)
    # spawn_curl(DF,NEARL)
    spawn(DF, NEARL, 0.03)

    if i % STAT_ITT == 0:

      print_stats(i,time()-t_start,DF)

    if i % EXPORT_ITT == 0:

      name = fn.name()

      num = DF.np_get_edges_coordinates(np_edges)
      show(render,np_edges[:num,:],name+'.png')

      exporter(
        DF,
        name+'.2obj'
      )

Example 127

Project: corex_topic Source File: corex_topic.py
Function: fit_transform
    def fit_transform(self, X, anchors=None, anchor_strength=1):
        """Fit CorEx on the data

        Parameters
        ----------
        X : scipy sparse CSR or a numpy matrix, shape = [n_samples, n_visible]
            Count data or some other sparse binary data.

        anchors : A list of variables anchor each corresponding latent factor to.

        anchor_strength : How strongly to weight the anchors.

        Returns
        -------
        Y: array-like, shape = [n_samples, n_hidden]
           Learned values for each latent factor for each sample.
           Y's are sorted so that Y_1 explains most correlation, etc.
        """
        X = self.preprocess(X)
        self.initialize_parameters(X)
        p_y_given_x = np.random.random((self.n_samples, self.n_hidden))
        if anchors is not None:
            for j, a in enumerate(anchors):
                p_y_given_x[:, j] = 0.5 * p_y_given_x[:, j] + 0.5 * X[:, a].mean(axis=1).A1  # Assumes X is a binary matrix

        for nloop in range(self.max_iter):
            if nloop > 1:
                for j in range(self.n_hidden):
                    if self.sign[j, np.argmax(self.mis[j])] < 0:
                        # Switch label for Y_j so that it is correlated with the top word
                        p_y_given_x[:, j] = 1. - p_y_given_x[:, j]
            self.log_p_y = self.calculate_p_y(p_y_given_x)
            self.theta = self.calculate_theta(X, p_y_given_x, self.log_p_y)  # log p(x_i=1|y)  nv by m by k

            if nloop > 0:  # Structure learning step
                self.alpha = self.calculate_alpha(X, p_y_given_x, self.theta, self.log_p_y, self.tcs)
            if anchors is not None:
                for a in flatten(anchors):
                    self.alpha[:, a] = 0
                for ia, a in enumerate(anchors):
                    self.alpha[ia, a] = anchor_strength

            p_y_given_x, log_z = self.calculate_latent(X, self.theta)

            self.update_tc(log_z)  # Calculate TC and record history to check convergence
            self.print_verbose()
            if self.convergence():
                break

        if self.verbose:
            print 'Overall tc:', self.tc

        if anchors is None:
            self.sort_and_output(X)
        self.p_y_given_x, self.log_z = self.calculate_latent(X, self.theta)  # Needed to output labels
        self.mis = self.calculate_mis(self.theta, self.log_p_y)  # / self.h_x  # could normalize MIs
        return self.labels

Example 128

Project: recurrentshop Source File: test_cells.py
def cell_test(layer_cls, kwargs={}, input_shape=None, input_dtype=None,
               input_data=None, expected_output=None,
               expected_output_dtype=None, fixed_batch_size=False):
    '''Test routine for a layer with a single input tensor
    and single output tensor.
    '''
    if input_data is None:
        assert input_shape
        if not input_dtype:
            input_dtype = K.floatx()
        input_data = (10 * np.random.random(input_shape)).astype(input_dtype)
    elif input_shape is None:
        input_shape = input_data.shape

    if expected_output_dtype is None:
        expected_output_dtype = input_dtype

    # instantiation
    layer = layer_cls(**kwargs).get_layer()

    # test get_weights , set_weights
    weights = layer.get_weights()
    layer.set_weights(weights)

    # test and instantiation from weights
    if 'weights' in inspect.getargspec(layer_cls.__init__):
        kwargs['weights'] = weights
        layer = layer_cls(**kwargs).get_layer()

    # test in functional API
    if fixed_batch_size:
        x = Input(batch_shape=input_shape, dtype=input_dtype)
    else:
        x = Input(shape=input_shape[1:], dtype=input_dtype)
    y = layer(x)
    assert K.dtype(y) == expected_output_dtype

    model = Model(input=x, output=y)
    model.compile('rmsprop', 'mse')

    expected_output_shape = layer.get_output_shape_for(input_shape)
    actual_output = model.predict(input_data)
    actual_output_shape = actual_output.shape
    assert expected_output_shape == actual_output_shape
    if expected_output is not None:
        assert_allclose(actual_output, expected_output, rtol=1e-3)

    # test serialization
    model_config = model.get_config()
    model = Model.from_config(model_config, custom_objects=recurrentshop.__dict__)
    model.compile('rmsprop', 'mse')

    # test as first layer in Sequential API
    layer_config = layer.get_config()
    layer_config['batch_input_shape'] = input_shape
    layer = layer.__class__.from_config(layer_config)

    model = Sequential()
    model.add(layer)
    model.compile('rmsprop', 'mse')
    actual_output = model.predict(input_data)
    actual_output_shape = actual_output.shape
    assert expected_output_shape == actual_output_shape
    if expected_output is not None:
        assert_allclose(actual_output, expected_output, rtol=1e-3)

    # test JSON serialization
    json_model = model.to_json()
    model = model_from_json(json_model)

    # for further checks in the caller function
    return actual_output

Example 129

Project: differential-line Source File: main_line_ani.py
Function: main
def main():

  from iutils.render import Animate
  from differentialLine import DifferentialLine

  from fn import Fn

  from modules.show import sandstroke
  from modules.show import dots

  DF = DifferentialLine(NMAX, FARL*2, NEARL, FARL, PROCS)

  ## arc
  # angles = sorted(random(INIT_NUM)*pi*1.5)
  # xys = []
  # for a in angles:
    # x = 0.5 + cos(a)*0.06
    # y = 0.5 + sin(a)*0.06
    # xys.append((x,y))
  # DF.init_line_segment(xys, lock_edges=1)

  ## vertical line
  #xx = sorted(0.45+0.1*random(INIT_NUM))
  #yy = MID+0.005*(0.5-random(INIT_NUM))
  #xys = []
  #for x,y in zip(xx,yy):
    #xys.append((x,y))
  #DF.init_line_segment(xys, lock_edges=1)

  # diagonal line
  # yy = sorted(0.3+0.4*random(INIT_NUM))
  # xx = 0.3+linspace(0,0.4,num=INIT_NUM)
  # xys = []
  # for x,y in zip(xx,yy):
    # xys.append((x,y))
  # DF.init_line_segment(xys, lock_edges=1)


  angles = sorted(random(INIT_NUM)*TWOPI)
  DF.init_circle_segment(MID,MID,FARL*0.2, angles)

  fn = Fn(prefix='./res/', postfix='.png')


  def wrap(render):

    global np_coords
    global np_vert_coords
    global grains

    ## if fn is a path each image will be saved to that path

    if not render.steps%3:
      f = fn.name()
    else:
      f = None

    grains += (-1)**floor(2*random())
    print(grains)
    if grains<0:
      grains = 0

    res = steps(DF)
    render.set_front(FRONT)

    coord_num = DF.np_get_edges_coordinates(np_coords)
    sandstroke(render,np_coords[:coord_num,:],grains,f)

    if not random()<0.1:
      vert_num = DF.np_get_vert_coordinates(np_vert_coords)
      dots(render,np_vert_coords[:vert_num,:],None)

    return res

  render = Animate(SIZE, BACK, FRONT, wrap)
  render.start()

Example 130

Project: statsmodels Source File: test_functional.py
@dec.skipif(not have_matplotlib)
def test_fboxplot_rainbowplot():
    # Test fboxplot and rainbowplot together, is much faster.
    def harmfunc(t):
        """Test function, combination of a few harmonic terms."""
        # Constant, 0 with p=0.9, 1 with p=1 - for creating outliers
        ci = int(np.random.random() > 0.9)
        a1i = np.random.random() * 0.05
        a2i = np.random.random() * 0.05
        b1i = (0.15 - 0.1) * np.random.random() + 0.1
        b2i = (0.15 - 0.1) * np.random.random() + 0.1

        func = (1 - ci) * (a1i * np.sin(t) + a2i * np.cos(t)) + \
               ci * (b1i * np.sin(t) + b2i * np.cos(t))

        return func

    np.random.seed(1234567)
    # Some basic test data, Model 6 from Sun and Genton.
    t = np.linspace(0, 2 * np.pi, 250)
    data = []
    for ii in range(20):
        data.append(harmfunc(t))

    # fboxplot test
    fig = plt.figure()
    ax = fig.add_subplot(111)
    _, depth, ix_depth, ix_outliers = fboxplot(data, wfactor=2, ax=ax)

    ix_expected = np.array([13, 4, 15, 19, 8, 6, 3, 16, 9, 7, 1, 5, 2,
                            12, 17, 11, 14, 10, 0, 18])
    assert_equal(ix_depth, ix_expected)
    ix_expected2 = np.array([2, 11, 17, 18])
    assert_equal(ix_outliers, ix_expected2)

    plt.close(fig)

    # rainbowplot test (re-uses depth variable)
    xdata = np.arange(data[0].size)
    fig = rainbowplot(data, xdata=xdata, depth=depth, cmap=plt.cm.rainbow)
    plt.close(fig)

Example 131

Project: differential-mesh Source File: main_island.py
Function: main
def main():

  from differentialMesh import DifferentialMesh
  from iutils.render import Render
  from time import time
  from modules.helpers import print_stats

  from numpy.random import randint, random

  from numpy import unique


  DM = DifferentialMesh(NMAX, 2*FARL, NEARL, FARL, PROCS)

  DM.new_faces_in_ngon(MID, MID, H, 6, 0.0)

  render = Render(SIZE, BACK, FRONT)
  render.set_line_width(LINEWIDTH)


  tsum = 0

  for i in range(10000):

    t1 = time()
    for _ in range(STEPS_ITT):

      DM.optimize_position(
        ATTRACT_STP,
        REJECT_STP,
        TRIANGLE_STP,
        ALPHA,
        DIMINISH,
        -1
      )

      henum = DM.get_henum()

      edges = unique(randint(henum,size=(henum)))
      en = len(edges)
      rnd = 1-2*random(size=en*2)
      make_island = random(size=en)>0.85

      for i,(he,isl) in enumerate(zip(edges,make_island)):

        if DM.is_surface_edge(he)>0:

          the = pi*rnd[2*i]
          rad = rnd[2*i+1]*0.5
          dx = cos(the)*rad*H
          dy = sin(the)*rad*H

          if not isl:

            DM.new_triangle_from_surface_edge(
              he,
              H,
              dx*rad*H,
              dy*rad*H,
              minimum_length=MINIMUM_LENGTH,
              maximum_length=MAXIMUM_LENGTH,
              merge_ragged_edge=1
            )

          else:

            DM.throw_seed_triangle(
              he,
              H,
              dx*rad*H,
              dy*rad*H,
              NEARL*0.5,
              the
            )

      DM.optimize_edges(
        SPLIT_LIMIT,
        FLIP_LIMIT
      )

      tsum += time() - t1

    print_stats(render.num_img, tsum, DM)
    show(render, DM)
    tsum = 0

Example 132

Project: deepchem Source File: test_utils.py
Function: test_moment
  def testMoment(self):
    with self.test_session() as sess:
      features = np.random.random((3, 4, 5))
      features_t = tf.constant(features, dtype=tf.float32)

      # test k = 1..4
      for k in [1, 2, 3, 4]:
        # central moments
        self.assertAllClose(
            sess.run(utils.Moment(k, features_t)[1]),
            scipy.stats.moment(features, k, axis=None),
            rtol=1e-5, atol=1e-5)

        # standardized moments
        self.assertAllClose(
            sess.run(utils.Moment(k, features_t, standardize=True)[1]),
            np.divide(scipy.stats.moment(features, k, axis=None),
                      np.power(features.std(), k)),
            rtol=1e-5, atol=1e-5)

        # central across one axis
        self.assertAllClose(
            sess.run(utils.Moment(k, features_t, reduction_indices=1)[1]),
            scipy.stats.moment(features, k, axis=1),
            rtol=1e-5, atol=1e-5)

        # standardized across one axis
        self.assertAllClose(
            sess.run(utils.Moment(k, features_t, standardize=True,
                                  reduction_indices=1)[1]),
            np.divide(scipy.stats.moment(features, k, axis=1),
                      np.power(features.std(axis=1), k)),
            rtol=1e-5, atol=1e-5)

Example 133

Project: differential-mesh Source File: main_sources.py
def main():

  from time import time
  from iutils.render import Render
  from differentialMesh import DifferentialMesh
  from modules.helpers import darts
  from modules.helpers import print_stats
  from numpy import array


  DM = DifferentialMesh(NMAX, 2*FARL, NEARL, FARL, PROCS)

  DM.new_faces_in_ngon(MID,MID, H, 7, 0)
  DM.set_edge_intensity(1, 1)

  sources = [(x,y) for x,y in darts(NUM_SOURCES, MID, MID, 0.43, 0.002)]
  DM.initialize_sources(sources, NEARL)

  render = Render(SIZE, BACK, FRONT)


  for i in range(1000000):

    t1 = time()
    for _ in range(STEPS_ITT):

      DM.find_nearby_sources()

      henum = DM.get_henum()

      surface_edges = array(
        [DM.is_surface_edge(e)>0 and r<DM.get_edge_intensity(e)
        for e,r in enumerate(random(size=henum))],
        'bool').nonzero()[0]

      rnd = random(size=len(surface_edges)*2)
      the = (1.-2*rnd[::2])*pi
      rad = rnd[1::2]*0.5*H
      dx = cos(the)*rad
      dy = sin(the)*rad

      DM.new_triangles_from_surface_edges(
        surface_edges,
        len(surface_edges),
        H,
        dx,
        dy,
        MINIMUM_LENGTH,
        MAXIMUM_LENGTH,
        1
      )

      DM.optimize_position(
        ATTRACT_STP,
        REJECT_STP,
        TRIANGLE_STP,
        ALPHA,
        DIMINISH,
        -1
      )

      henum = DM.get_henum()

      DM.optimize_edges(
        SPLIT_LIMIT,
        FLIP_LIMIT
      )

      if DM.safe_vertex_positions(3*H)<0:

        show_circles(render, DM, sources)
        print('vertices reached the boundary. stopping.')
        return

    show_circles(render, DM, sources)

    t2 = time()
    print_stats(i*STEPS_ITT, t2-t1, DM)

Example 134

Project: trackpy Source File: test_feature.py
    def test_mass(self):
        # The mass calculated from the processed image should be independent
        # of added noise. Its absolute value is untested.

        # The mass calculated from the raw image should equal
        # noiseless mass + noise_size/2 * Npx_in_mask.
        self.check_skip()
        ndim = 2
        radius = 6
        N = 20
        shape = (128, 127)

        # Calculate the expected mass from a single spot using the set masksize
        center = (radius*2,) * ndim
        spot = draw_spots((radius*4,) * ndim, [center], radius*3, bitdepth=12)
        rect = [slice(c - radius, c + radius + 1) for c in center]
        mask = tp.masks.binary_mask(radius, 2)
        Npx = mask.sum()
        EXPECTED_MASS = (spot[rect] * mask).sum()

        # Generate feature locations and make the image
        expected = gen_nonoverlapping_locations(shape, N, radius*3, radius+2)
        expected = expected + np.random.random(expected.shape)
        N = expected.shape[0]
        image = draw_spots(shape, expected, radius*3, bitdepth=12)

        # analyze the image without noise
        f = tp.locate(image, radius*2+1, engine=self.engine, topn=N)
        PROCESSED_MASS = f['mass'].mean()
        assert_allclose(f['raw_mass'].mean(), EXPECTED_MASS, rtol=0.01)

        for n, noise in enumerate(np.arange(0.05, 0.8, 0.05)):
            noise_level = int((2**12 - 1) * noise)
            image_noisy = image + np.array(np.random.randint(0, noise_level,
                                                             image.shape),
                                           dtype=image.dtype)
            f = tp.locate(image_noisy, radius*2+1, engine=self.engine, topn=N)
            assert_allclose(f['mass'].mean(), PROCESSED_MASS, rtol=0.1)
            assert_allclose(f['raw_mass'].mean(),
                            EXPECTED_MASS + Npx*noise_level/2, rtol=0.1)

Example 135

Project: fracture-cuda Source File: fracture.py
  def frac(self, factor, angle, max_active, dbg=False):
    num = self.num
    fnum = self.fnum
    anum = self.anum

    if anum>max_active:
      return 0

    f_inds = (random(fnum)<factor).nonzero()[0]

    n = len(f_inds)
    if n<1:
      return 0

    visited = self.visited[:num]
    cand_ii = self.fid_node[f_inds, 1]

    xy = self.xy[:num, :]
    new = arange(fnum, fnum+n)
    orig_dxy = self.dxy[f_inds, :]

    diff_theta = (-1)**randint(2, size=n)*HPI + (0.5-random(n)) * angle
    theta = arctan2(orig_dxy[:, 1], orig_dxy[:, 0]) + diff_theta

    fid_node = column_stack((
        new,
        cand_ii
        ))
    cand_dxy = column_stack((
        cos(theta),
        sin(theta)
        ))

    nactive = arange(n)

    tmp_dxy = self.tmp_dxy[:n, :]

    self.update_zone_map()

    self.cuda_calc_stp(
        npint(self.nz),
        npint(self.zone_leap),
        npint(num),
        npint(n),
        npint(n),
        npfloat(self.frac_dot),
        npfloat(self.frac_dst),
        npfloat(self.frac_stp),
        npint(self.ignore_fracture_sources),
        drv.In(visited),
        drv.In(fid_node),
        drv.In(nactive),
        drv.Out(self.tmp[:n, :]),
        drv.In(xy),
        drv.In(cand_dxy),
        drv.Out(tmp_dxy),
        drv.In(self.zone_num),
        drv.In(self.zone_node),
        block=(self.threads,1,1),
        grid=(int(n//self.threads + 1), 1) # this cant be a numpy int for some reason
        )

    mask = tmp_dxy[:, 0] >= -1.0
    n = mask.sum()

    if n<1:
      return 0

    nodes = cand_ii[mask]
    self._add_fracs(cand_dxy[mask, :], nodes)

    if dbg:
      self.print_debug(num, fnum, anum, meta='new: {:d}'.format(n))
    return n

Example 136

Project: givinggraph Source File: forceatlas.py
def forceatlas2_layout(G, iterations=10, linlog=False, pos=None, nohubs=False, kr=0.001, k=None, dim=2):
    """
    Options values are

    g                The graph to layout
    iterations       Number of iterations to do
    linlog           Whether to use linear or log repulsion
    random_init      Start with a random position
                     If false, start with FR
    avoidoverlap     Whether to avoid overlap of points
    degreebased      Degree based repulsion
    """
    # We add attributes to store the current and previous convergence speed
    for n in G:
        G.node[n]['prevcs'] = 0
        G.node[n]['currcs'] = 0
    # To numpy matrix
    # This comes from the spares FR layout in nx
    A = nx.to_scipy_sparse_matrix(G, dtype='f')
    nnodes, _ = A.shape
    from scipy.sparse import coo_matrix
    try:
        A = A.tolil()
    except:
        A = (coo_matrix(A)).tolil()
    if pos is None:
        pos = np.asarray(np.random.random((nnodes, dim)), dtype=A.dtype)
    else:
        pos = pos.astype(A.dtype)
    if k is None:
        k = np.sqrt(1.0 / nnodes)
    # Iterations
    # the initial "temperature" is about .1 of domain area (=1x1)
    # this is the largest step allowed in the dynamics.
    t = 0.1
    # simple cooling scheme.
    # linearly step down by dt on each iteration so last iteration is size dt.
    dt = t / float(iterations + 1)
    displacement = np.zeros((dim, nnodes))
    for iteration in range(iterations):
        print "layout percentage:\t" + str(iteration / float(iterations) * 100) + "%"
        displacement *= 0
        # loop over rows
        for i in range(A.shape[0]):
            # difference between this row's node position and all others
            delta = (pos[i] - pos).T
            # distance between points
            distance = np.sqrt((delta ** 2).sum(axis=0))
            # enforce minimum distance of 0.01
            distance = np.where(distance < 0.01, 0.01, distance)
            # the adjacency matrix row
            Ai = np.asarray(A.getrowview(i).toarray())
            # displacement "force"
            Dist = k * k / distance ** 2
            if nohubs:
                Dist = Dist / float(Ai.sum(axis=1) + 1)
            if linlog:
                Dist = np.log(Dist + 1)
            displacement[:, i] +=\
                (delta * (Dist - Ai * distance / k)).sum(axis=1)
        # update positions
        # print np.average(displacement)
        length = np.sqrt((displacement ** 2).sum(axis=0))
        length = np.where(length < 0.01, 0.1, length)
        pos += (displacement * t / length).T
        # cool temperature
        t -= dt
        if t < 0:
            break
        print t
    # Return the layout
    return dict(zip(G, pos))

Example 137

Project: generativebot Source File: main.py
Function: run
def run(fn):
  from time import time
  from itertools import count
  from numpy.random import randint
  from numpy import ones

  from differentialLine import DifferentialLine
  from .modules.helpers import print_stats
  from sand import Sand

  np_coords = zeros(shape=(NMAX,4), dtype='float')
  np_vert_coords = zeros(shape=(NMAX,2), dtype='float')


  DF = DifferentialLine(NMAX, FARL*2, NEARL, FARL, PROCS)

  sand = Sand(SIZE)
  sand.set_bg(BACK)
  sand.set_rgba(FRONT)

  rnd = randint(2)

  if rnd == 0: # circle
    print('circle')

    angles = sorted(random(INIT_NUM)*TWOPI)
    DF.init_circle_segment(MID,MID,0.2, angles)

  elif rnd == 1: # arc
    print('arc')

    angles = sorted((random()*2+random(INIT_NUM)*1.5)*pi)
    xys = []
    for a in angles:
      r = 0.1+random()*0.1
      x = 0.5 + cos(a)*r
      y = 0.5 + sin(a)*r
      xys.append((x,y))
    DF.init_line_segment(xys, lock_edges=1)

  else:
    print('no selection')
    return

  grains = get_grains()

  for i in count():
    t_start = time()

    DF.optimize_position(STP)
    spawn_curl(DF, NEARL, 0.016)

    coord_num = DF.np_get_edges_coordinates(np_coords)

    g = next(grains())
    sand.paint_strokes(np_coords[:coord_num, 0:2], np_coords[:coord_num, 2:5], ones(coord_num, 'int')*g)


    vert_num = DF.np_get_vert_coordinates(np_vert_coords)

    if random()<0.9:
      sand.paint_dots(np_vert_coords[:vert_num, :])

    if random()<0.1:
      sand.paint_strokes(np_coords[:coord_num, 0:2], np_coords[:coord_num, 2:5], ones(coord_num, 'int')*g)

    mi = np_vert_coords[:vert_num, :].min()
    ma = np_vert_coords[:vert_num, :].max()

    if ma>0.93 or mi<0.07:

      sand.set_transparent_pixel()
      print(fn)
      sand.write_to_png(fn)

      return

    t_stop = time()

    if not i%300:
      print(('grains', g))
      print(('min, max', mi, ma))
      print_stats(i,t_stop-t_start,DF)

Example 138

Project: tensorly Source File: test_partial_svd.py
def test_partial_svd():
    """Test for partial_svd"""
    sizes = [(100, 100), (100, 5), (10, 10), (5, 100)]
    n_eigenvecs = [10, 4, 5, 4]

    # Compare with sparse SVD
    for s, n in zip(sizes, n_eigenvecs):
        matrix = np.random.random(s)
        fU, fS, fV = partial_svd(matrix, n_eigenvecs=n)
        U, S, V = svds(matrix, k=n, which='LM')
        U, S, V = U[:, ::-1], S[::-1], V[::-1, :]
        assert_array_almost_equal(np.abs(S), np.abs(fS))
        assert_array_almost_equal(np.abs(U), np.abs(fU))
        assert_array_almost_equal(np.abs(V), np.abs(fV))

    # Compare with standard SVD
    sizes = [(100, 100), (100, 5), (10, 10), (10, 4), (5, 100)]
    n_eigenvecs = [10, 4, 5, 4, 4]
    for s, n in zip(sizes, n_eigenvecs):
        matrix = np.random.random(s)
        fU, fS, fV = partial_svd(matrix, n_eigenvecs=n)

        U, S, V = svd(matrix)
        U, S, V = U[:, :n], S[:n], V[:n, :]
        # Test for SVD
        assert_array_almost_equal(np.abs(S), np.abs(fS))
        assert_array_almost_equal(np.abs(U), np.abs(fU))
        assert_array_almost_equal(np.abs(V), np.abs(fV))

    with assert_raises(ValueError):
        tensor = np.random.random((3, 3, 3))
        partial_svd(tensor)

Example 139

Project: generativebot Source File: main2.py
Function: run
def run(fn):
  from differentialMesh import DifferentialMesh
  from sand import Sand
  from time import time
  from .modules.helpers import darts
  from .modules.helpers import print_stats
  from numpy import array

  DM = DifferentialMesh(NMAX, 2*FARL, NEARL, FARL, PROCS)

  DM.new_faces_in_ngon(MID, MID, H, 6, 0.0)
  DM.set_edge_intensity(1, 1)

  sources = [(x,y) for x,y in darts(NUM_SOURCES, MID, MID, 0.43, 0.002)]
  DM.initialize_sources(sources, NEARL)

  sand = Sand(SIZE)
  sand.set_bg(BACK)
  sand.set_rgba(FRONT)


  tsum = 0


  for i in range(3000):
    t1 = time()

    DM.find_nearby_sources()

    henum = DM.get_henum()

    surface_edges = array(
      [DM.is_surface_edge(e)>0 and r<DM.get_edge_intensity(e)
      for e,r in enumerate(random(size=henum))],
      'bool').nonzero()[0]

    rnd = random(size=len(surface_edges)*2)
    the = (1.-2*rnd[::2])*pi
    rad = rnd[1::2]*0.5*H
    dx = cos(the)*rad
    dy = sin(the)*rad

    DM.new_triangles_from_surface_edges(
      surface_edges,
      len(surface_edges),
      H,
      dx,
      dy,
      MINIMUM_LENGTH,
      MAXIMUM_LENGTH,
      1
    )

    DM.optimize_position(
      ATTRACT_STP,
      REJECT_STP,
      TRIANGLE_STP,
      ALPHA,
      DIMINISH,
      -1
    )

    henum = DM.get_henum()

    DM.optimize_edges(
      SPLIT_LIMIT,
      FLIP_LIMIT
    )

    tsum += time() - t1

    if not i % 10:
      print_stats(i, tsum, DM)

    if DM.safe_vertex_positions(0.05)<0:
      break

  show(sand, DM)
  sand.set_transparent_pixel()
  print(fn)
  sand.write_to_png(fn)

  return

Example 140

Project: chaco Source File: scatter_1d.py
def _create_plot_component():

    # Create some data
    numpts = 50
    x = sort(random(numpts))
    y = random(numpts)

    # Create a plot data object and give it this data
    pd = ArrayPlotData()
    pd.set_data("index", x)
    pd.set_data("value", y)

    # Create the plot
    plot = Plot(pd, use_backbuffer=True, auto_grid=False)

    plot.plot_1d(
        'index',
        type='line_scatter_1d',
        orientation='h',
        color='lightgrey',
        line_style='dot',
    )

    plot.plot_1d(
        'index',
        type='scatter_1d',
        orientation='h',
        marker='plus',
        alignment='bottom'
    )

    plot.plot_1d(
        'value',
        type='line_scatter_1d',
        orientation='v',
        color='lightgrey',
        line_style='dot',
    )

    plot.plot_1d(
        'value',
        type='scatter_1d',
        orientation='v',
        marker='plus',
        alignment='left'
    )

    plot.plot(("index", "value"),
              type="scatter",
              marker="square",
              index_sort="ascending",
              color="orange",
              marker_size=3, #randint(1,5, numpts),
              bgcolor="white",
              use_backbuffer=True)


    # Tweak some of the plot properties
    plot.title = "1D Scatter Plots"
    plot.line_width = 0.5
    plot.padding = 50

    # Attach some tools to the plot
    plot.tools.append(PanTool(plot, constrain_key="shift"))
    zoom = ZoomTool(component=plot, tool_mode="box", always_on=False)
    plot.overlays.append(zoom)

    return plot

Example 141

Project: hyphae Source File: hyphae.py
def main():

  render = Render(SIZE)
  #render.get_colors(COLOR_FILENAME)

  Z = [[] for i in xrange((ZONES+2)**2)]

  R = np.zeros(NMAX,'float')
  X = np.zeros(NMAX,'float')
  Y = np.zeros(NMAX,'float')
  THE = np.zeros(NMAX,'float')
  GE = np.zeros(NMAX,'float')
  P = np.zeros(NMAX,'int')
  C = np.zeros(NMAX,'int')
  D = np.zeros(NMAX,'int')-1

  ## number of nodes
  i = 0

  ## initialize source nodes
  while i<SOURCE_NUM:

    ## in circle
    x = random()
    y = random()
    if sqrt(square(x-0.5)+square(y-0.5))<INIT_CIRCLE:
      X[i] = x
      Y[i] = y
      R[i] = (RAD + 0.2*RAD*(1.-2.*random()))
      P[i] = -1
    else:

      ## try again
      continue

    ## on canvas
    #X[i] = random()
    #Y[i] = random()

    ## center
    #X[i] = 0.5
    #Y[i] = 0.5

    ## on circle
    #gamma = i*2.*pi/float(SOURCE_NUM)
    #X[i] = 0.5 + cos(gamma)*0.1
    #Y[i] = 0.5 + sin(gamma)*0.1

    THE[i] = random()*pi*2.
    GE[i] = 1
    P[i] = -1 # no parent
    R[i] = RAD
    z = get_z(X[i],Y[i])
    Z[z].append(i)
    i += 1

  num = i

  itt = 0
  ti = time()
  drawn = -1

  while True:

    try:

      itt += 1
      if not itt%1000:
        print itt, num, filename

      added_new = False

      k = int(random()*num)
      C[k] += 1

      if C[k]>CK_MAX:

        ## node is dead
        continue

      #r = RAD + random()*ONE*R_RAND_SIZE
      r = R[k]*RAD_SCALE if D[k]>-1 else R[k]

      if r<ONE:

        ## node dies
        C[k] = CK_MAX+1
        continue

      ge = GE[k]+1 if D[k]>-1 else GE[k]
      the = THE[k] + (1.-1./((ge+1)**0.1))*normal()*SEARCH_ANGLE_MAX

      #x = X[k] + sin(the)*(r+R[k])
      #y = Y[k] + cos(the)*(r+R[k])
      x = X[k] + sin(the)*r
      y = Y[k] + cos(the)*r

      # stop nodes at edge of canvas
      #if x>X_MAX or x<X_MIN or y>Y_MAX or y<Y_MIN:

        ## node is outside canvas
        #continue

      ## stop nodes at edge of circle
      ## remember to set initial node inside circle.
      circle_rad = sqrt(square(x-0.5)+square(y-0.5))
      if circle_rad>CIRCLE_RADIUS:

        ## node is outside circle
        continue
      
      try:

        inds = near_zone_inds(x,y,Z)
        inds = array([a for a in inds if not a==k and not a==P[k]])

      except IndexError:

        ## node is outside zonemapped area
        continue

      good = True
      if len(inds)>0:
        dd = square(X[inds]-x) + square(Y[inds]-y)

        sqrt(dd,dd)
        mask = dd*2 > R[inds]+r
        good = mask.all()
        
      if good: 
        X[num] = x
        Y[num] = y
        R[num] = r
        THE[num] = the
        P[num] = k
        GE[num] = ge

        ## set first descendant if node has no descendants
        if D[k]<0:
          D[k] = num

        z = get_z(x,y) 

        Z[z].append(num)

        render.ctx.set_source_rgb(FRONT,FRONT,FRONT)
        render.circles(X[k],Y[k],x,y,r*0.35)


        ### render node radii
        #render.ctx.set_line_width(ONE)
        #render.ctx.set_source_rgba(1,0,0,1)
        #render.circle(x,y,r)

        num += 1
        added_new = True

        if not num % DRAW_SKIP and added_new:
          render.sur.write_to_png('{:s}.{:d}.png'.format(filename,num))
          print itt, num, time()-ti
          ti = time()
          drawn = num

      else:
        pass

        #render.sandpaint_color_line(X[k],Y[k],x,y,k)

    except KeyboardInterrupt:
      break

  return

Example 142

Project: postpic Source File: particleshapedemo.py
def main():
    import numpy as np
    import postpic as pp

    # postpic will use matplotlib for plotting. Changing matplotlibs backend
    # to "Agg" makes it possible to save plots without a display attached.
    # This is necessary to run this example within the "run-tests" script
    # on travis-ci.
    import matplotlib; matplotlib.use('Agg')


    # choose the dummy reader. This reader will create fake data for testing.
    pp.chooseCode('dummy')

    # Create a dummy reader with 300 particles, not initialized with a seed and use
    # uniform distribution
    dr = pp.readDump(300, seed=None, randfunc=np.random.random)
    # set and create directory for pictures.
    savedir = '_examplepictures/'
    import os
    if not os.path.exists(savedir):
        os.mkdir(savedir)

    # initialze the plotter object.
    # project name will be prepended to all output names
    plotter = pp.plotting.plottercls(dr, outdir=savedir, autosave=True, project='particleshapedemo')

    # we will need a refrence to the MultiSpecies quite often
    from postpic import MultiSpecies as MS

    # create MultiSpecies object for every particle species that exists.
    pas = [MS(dr, s) for s in dr.listSpecies()]

    # --- 1D visualization of particle contributions ---

    def particleshapedemo(shape):
        import postpic.cythonfunctions as cf
        import matplotlib.pyplot as plt
        ptclpos = np.array([4.5, 9.75, 15.0, 20.25])
        y, edges = cf.histogram(ptclpos, bins=25, range=(0,25), shape=shape)
        x = np.convolve(edges, [0.5, 0.5], mode='valid')
        fig = plt.figure()
        fig.suptitle('ParticleShape: {:s}'.format(str(shape)))
        ax = fig.add_subplot(111)
        ax.plot(x,y)
        ax.set_ylim((0,1))
        ax.set_xticks(x, minor=True)
        ax.grid(which='minor')
        for ix in ptclpos:
            ax.axvline(x=ix, color='y')
        fig.savefig(savedir + 'particleshapedemo{:s}.png'.format(str(shape)), dpi=160)
        plt.close(fig)

    if True:
        particleshapedemo(0)
        particleshapedemo(1)
        particleshapedemo(2)

    # --- 1D ---
    if True:
            pa = pas[0]
            plotargs = {'ylim': (0,1600), 'log10plot': False}

            # 1 particle per cell
            plotter.plotField(pa.createField(MS.X, optargsh={'bins': 300, 'shape': 0}, title='1ppc_order0', rangex=(0,1)), **plotargs)
            plotter.plotField(pa.createField(MS.X, optargsh={'bins': 300, 'shape': 1}, title='1ppc_order1', rangex=(0,1)), **plotargs)
            plotter.plotField(pa.createField(MS.X, optargsh={'bins': 300, 'shape': 2}, title='1ppc_order2', rangex=(0,1)), **plotargs)

            # 3 particles per cell
            plotter.plotField(pa.createField(MS.X, optargsh={'bins': 100, 'shape': 0}, title='3ppc_order0', rangex=(0,1)), **plotargs)
            plotter.plotField(pa.createField(MS.X, optargsh={'bins': 100, 'shape': 1}, title='3ppc_order1', rangex=(0,1)), **plotargs)
            plotter.plotField(pa.createField(MS.X, optargsh={'bins': 100, 'shape': 2}, title='3ppc_order2', rangex=(0,1)), **plotargs)

            # 10 particles per cell
            plotter.plotField(pa.createField(MS.X, optargsh={'bins': 30, 'shape': 0}, title='10ppc_order0', rangex=(0,1)), **plotargs)
            plotter.plotField(pa.createField(MS.X, optargsh={'bins': 30, 'shape': 1}, title='10ppc_order1', rangex=(0,1)), **plotargs)
            plotter.plotField(pa.createField(MS.X, optargsh={'bins': 30, 'shape': 2}, title='10ppc_order2', rangex=(0,1)), **plotargs)


    # --- 2D ---
    if True:
            dr = pp.readDump(300*30, seed=None, randfunc=np.random.random)
            pa = MS(dr, dr.listSpecies()[0])
            plotargs = {'clim': (0,3e4), 'log10plot': False}

            # 1 particle per cell
            plotter.plotField(pa.createField(MS.X, MS.Y, optargsh={'bins': (300,30), 'shape': 0}, title='1ppc_order0', rangex=(0,1), rangey=(0,1)), **plotargs)
            plotter.plotField(pa.createField(MS.X, MS.Y, optargsh={'bins': (300,30), 'shape': 1}, title='1ppc_order1', rangex=(0,1), rangey=(0,1)), **plotargs)
            plotter.plotField(pa.createField(MS.X, MS.Y, optargsh={'bins': (300,30), 'shape': 2}, title='1ppc_order2', rangex=(0,1), rangey=(0,1)), **plotargs)

            # 3 particles per cell
            plotter.plotField(pa.createField(MS.X, MS.Y, optargsh={'bins': (100,10), 'shape': 0}, title='3ppc_order0', rangex=(0,1), rangey=(0,1)), **plotargs)
            plotter.plotField(pa.createField(MS.X, MS.Y, optargsh={'bins': (100,10), 'shape': 1}, title='3ppc_order1', rangex=(0,1), rangey=(0,1)), **plotargs)
            plotter.plotField(pa.createField(MS.X, MS.Y, optargsh={'bins': (100,10), 'shape': 2}, title='3ppc_order2', rangex=(0,1), rangey=(0,1)), **plotargs)


    # --- 3D ---
    if True:
        dr = pp.readDump(300*30, seed=None, randfunc=np.random.random, dimensions=3)
        pa = MS(dr, dr.listSpecies()[0])
        # just try to create the field. not plotting routines yet
        f = pa.createField(MS.X, MS.Y, MS.Z, optargsh={'bins': (30,30,10), 'shape': 2}, title='1ppc_order2', rangex=(0,1), rangey=(0,1), rangez=(0,1))

Example 143

Project: orbitals Source File: orbitals.py
def main():

  render = Render()

  X = zeros(NUM,'float')
  Y = zeros(NUM,'float')
  SX = zeros(NUM,'float')
  SY = zeros(NUM,'float')
  R = zeros((NUM,NUM),'float')
  A = zeros((NUM,NUM),'float')
  F = zeros((NUM,NUM),'byte')

  for i in xrange(NUM):
    the = random()*TWOPI
    x = RAD * sin(the)
    y = RAD * cos(the)
    X[i] = 0.5+x
    Y[i] = 0.5+y

  t_cuem = 0.
  for itt in xrange(STEPS):

    set_distances(X,Y,A,R)
    
    SX[:] = 0.
    SY[:] = 0.

    t = time()
    
    for i in xrange(NUM):
      xF = logical_not(F[i,:])
      d = R[i,:]
      a = A[i,:]
      near = d > NEARL
      near[xF] = False
      far = d < FARL
      far[near] = False
      near[i] = False
      far[i] = False
      speed = FARL - d[far]

      SX[near] += cos(a[near])
      SY[near] += sin(a[near])
      SX[far] -= speed*cos(a[far])
      SY[far] -= speed*sin(a[far])

    X += SX*STP
    Y += SY*STP

    if not (itt+1)%100:

      print itt, sqrt(square(SX)+square(SY)).max()

    if random()<FRIENDSHIP_INITIATE_PROB:

      k = randint(NUM)
      make_friends(k,F,R)

    render.connections(X,Y,F,A,R)

    t_cuem += time()-t

    if not (itt+1)%UPDATE_NUM:


      fn = FILENAME.format(itt+1)
      print fn, t_cuem
      render.sur.write_to_png(fn)

      t_cuem = 0.

Example 144

Project: mayavi Source File: test_ipw_multiple_scalars.py
Function: do
    def do(self):
        ############################################################
        # Imports.
        script = self.script
        from mayavi.sources.vtk_data_source import VTKDataSource
        from mayavi.modules.api import ImagePlaneWidget

        # Create dataset with multiple scalars.
        arr1 = zeros(27, 'f')
        for n in range(27):
            arr1[n] = (1+float(n))/10.0
        arr2 = (arr1 + 1).astype('d')
        arr3 = arr1 + 2.0*(0.5 - random.random(27))
        arr3 = arr3.astype('f')

        p = tvtk.ImageData(dimensions=[3,3,3], spacing=[1,1,1])
        if is_old_pipeline():
            p.scalar_type = 'int'

        p.point_data.scalars = arr1
        p.point_data.scalars.name = 'first'
        j2 = p.point_data.add_array(arr2)
        p.point_data.get_array(j2).name='second'
        j3 = p.point_data.add_array(arr3)
        p.point_data.get_array(j3).name='third'
        if is_old_pipeline():
            p.update()

        # Make the pipeline.
        self.new_scene()
        src = VTKDataSource(data=p)
        script.add_source(src)
        ipw = ImagePlaneWidget()
        script.add_module(ipw)

        # Test.
        ipw = ipw.ipw
        scalars = ipw.input.point_data.scalars
        r = scalars.range
        expect = min(arr1), max(arr1)
        assert r == expect
        o = src.outputs[0]
        o.update_traits()
        if is_old_pipeline():
            st = ipw.input.scalar_type
            assert scalars.data_type == 10
            assert st == 'float'

        src.point_scalars_name = 'second'
        scalars = ipw.input.point_data.scalars
        r = scalars.range
        expect = min(arr2), max(arr2)
        assert r == expect
        o.update_traits()
        if is_old_pipeline():
            st = ipw.input.scalar_type
            assert scalars.data_type == 11
            assert st == 'double'

        src.point_scalars_name = 'third'
        scalars = ipw.input.point_data.scalars
        r = scalars.range
        expect = min(arr3), max(arr3)
        assert r == expect
        o.update_traits()
        if is_old_pipeline():
            st = ipw.input.scalar_type
            assert scalars.data_type == 10
            assert st == 'float'

Example 145

Project: bokeh Source File: color_scatter_server.py
Function: render_plot
def render_plot():
    import numpy as np

    from bokeh.embed import autoload_static
    from bokeh.plotting import figure
    from bokeh.resources import CDN

    N = 4000
    x = np.random.random(size=N) * 100
    y = np.random.random(size=N) * 100
    radii = np.random.random(size=N) * 1.5
    colors = [
        "#%02x%02x%02x" % (int(r), int(g), 150) for r, g in zip(50+2*x, 30+2*y)
    ]

    TOOLS="crosshair,pan,wheel_zoom,box_zoom,reset,tap,save,box_select,poly_select,lasso_select"

    p = figure(tools=TOOLS)

    p.scatter(x, y, radius=radii,
              fill_color=colors, fill_alpha=0.6,
              line_color=None)

    js, tag = autoload_static(p, CDN, "http://localhost:%s/plot.js" % port)

    html = """
    <html>
        <head>
            <title>color_scatter example</title>
        </head>
        <body>
            %s
        </body>
    </html>
    """ % tag

    return html, js

Example 146

Project: scikit-learn Source File: test_mlp.py
Function: test_gradient
def test_gradient():
    # Test gradient.

    # This makes sure that the activation functions and their derivatives
    # are correct. The numerical and analytical computation of the gradient
    # should be close.
    for n_labels in [2, 3]:
        n_samples = 5
        n_features = 10
        X = np.random.random((n_samples, n_features))
        y = 1 + np.mod(np.arange(n_samples) + 1, n_labels)
        Y = LabelBinarizer().fit_transform(y)

        for activation in ACTIVATION_TYPES:
            mlp = MLPClassifier(activation=activation, hidden_layer_sizes=10,
                                solver='lbfgs', alpha=1e-5,
                                learning_rate_init=0.2, max_iter=1,
                                random_state=1)
            mlp.fit(X, y)

            theta = np.hstack([l.ravel() for l in mlp.coefs_ +
                               mlp.intercepts_])

            layer_units = ([X.shape[1]] + [mlp.hidden_layer_sizes] +
                           [mlp.n_outputs_])

            activations = []
            deltas = []
            coef_grads = []
            intercept_grads = []

            activations.append(X)
            for i in range(mlp.n_layers_ - 1):
                activations.append(np.empty((X.shape[0],
                                             layer_units[i + 1])))
                deltas.append(np.empty((X.shape[0],
                                        layer_units[i + 1])))

                fan_in = layer_units[i]
                fan_out = layer_units[i + 1]
                coef_grads.append(np.empty((fan_in, fan_out)))
                intercept_grads.append(np.empty(fan_out))

            # analytically compute the gradients
            def loss_grad_fun(t):
                return mlp._loss_grad_lbfgs(t, X, Y, activations, deltas,
                                            coef_grads, intercept_grads)

            [value, grad] = loss_grad_fun(theta)
            numgrad = np.zeros(np.size(theta))
            n = np.size(theta, 0)
            E = np.eye(n)
            epsilon = 1e-5
            # numerically compute the gradients
            for i in range(n):
                dtheta = E[:, i] * epsilon
                numgrad[i] = ((loss_grad_fun(theta + dtheta)[0] -
                              loss_grad_fun(theta - dtheta)[0]) /
                              (epsilon * 2.0))
            assert_almost_equal(numgrad, grad)

Example 147

Project: postpic Source File: time_cythonfunctions.py
Function: main
def main():
    import timeit
    import numpy as np
    import postpic.cythonfunctions as cf

    # --- 1D

    def time1D(data, bins, weights, shape, tn):
        t = timeit.Timer(lambda: cf.histogram(data, range=(0.001,0.999), bins=bins, weights=weights, shape=shape))
        tc = t.timeit(number=5)/5.0
        ws = '       ' if weights is None else 'weights'
        print('1D, {:d} shape, {:s}: {:0.2e} sec -> factor {:5.2f} faster'.format(shape, ws, tc, tn/tc))

    bins = 1000
    npart = 1e6
    print('=== Histogram 1D bins: {:6d}, npart: {:.1e} ==='.format(bins, npart))
    data = np.random.random(npart)
    weights = np.random.random(npart)
    # time numpy function
    t = timeit.Timer(lambda: np.histogram(data, range=(0.001,0.999), bins=bins, weights=None))
    tn = t.timeit(number=2)/2.0
    t = timeit.Timer(lambda: np.histogram(data, range=(0.001,0.999), bins=bins, weights=weights))
    tnw = t.timeit(number=2)/2.0
    print('numpy        : {:0.2e} sec'.format(tn))
    print('numpy weights: {:0.2e} sec'.format(tnw))
    time1D(data, bins, None, 0, tn)
    time1D(data, bins, weights, 0, tnw)
    time1D(data, bins, None, 1, tn)
    time1D(data, bins, weights, 1, tnw)
    time1D(data, bins, None, 2, tn)
    time1D(data, bins, weights, 2, tnw)

    # --- 2D

    def time2D(datax, datay, bins, weights, shape, tn):
        t = timeit.Timer(lambda: cf.histogram2d(datax, datay, range=((0.01,0.99),(0.01,0.99)), bins=bins, weights=weights, shape=shape))
        tc = t.timeit(number=3)/3.0
        ws = '       ' if weights is None else 'weights'
        print('2D, {:d} shape, {:s}: {:0.2e} sec -> factor {:5.2f} faster'.format(shape, ws, tc, tn/tc))

    bins = (1000,700)
    npart = 1e6
    print('=== Histogram 2D bins: {:6s}, npart: {:.1e} ==='.format(str(bins), npart))
    datax = np.random.rand(npart)
    datay = np.random.rand(npart)
    weights = np.random.random(npart)
    # time numpy function
    t = timeit.Timer(lambda: np.histogram2d(datax, datay, range=((0.01,0.99),(0.01,0.99)), bins=bins, weights=None))
    tn = t.timeit(number=1)/1.0
    t = timeit.Timer(lambda: np.histogram2d(datax, datay, range=((0.01,0.99),(0.01,0.99)), bins=bins, weights=weights))
    tnw = t.timeit(number=1)/1.0
    print('numpy        : {:0.2e} sec'.format(tn))
    print('numpy weights: {:0.2e} sec'.format(tnw))
    time2D(datax,datay, bins, None, 0, tn)
    time2D(datax, datay, bins, weights, 0, tnw)
    time2D(datax,datay, bins, None, 1, tn)
    time2D(datax, datay, bins, weights, 1, tnw)
    time2D(datax,datay, bins, None, 2, tn)
    time2D(datax, datay, bins, weights, 2, tnw)


    # --- 3D

    def time3D(datax, datay, dataz, bins, weights, shape, tn):
        t = timeit.Timer(lambda: cf.histogram3d(datax, datay, dataz, range=((0.01,0.99),(0.01,0.99),(0.01,0.99)), bins=bins, weights=weights, shape=shape))
        tc = t.timeit(number=1)/1.0
        ws = '       ' if weights is None else 'weights'
        print('3D, {:d} shape, {:s}: {:0.2e} sec -> factor {:5.2f} faster'.format(shape, ws, tc, tn/tc))

    bins = (200,250,300)  # 15e6 Cells
    npart = 1e6
    print('=== Histogram 3D bins: {:6s}, npart: {:.1e} ==='.format(str(bins), npart))
    datax = np.random.rand(npart)
    datay = np.random.rand(npart)
    dataz = np.random.rand(npart)
    weights = np.random.random(npart)
    # time numpy function
    t = timeit.Timer(lambda: np.histogramdd((datax, datay, dataz), range=((0.01,0.99),(0.01,0.99),(0.01,0.99)), bins=bins, weights=None))
    tn = t.timeit(number=1)/1.0
    t = timeit.Timer(lambda: np.histogramdd((datax, datay, dataz), range=((0.01,0.99),(0.01,0.99),(0.01,0.99)), bins=bins, weights=weights))
    tnw = t.timeit(number=1)/1.0
    print('numpy        : {:0.2e} sec'.format(tn))
    print('numpy weights: {:0.2e} sec'.format(tnw))
    time3D(datax, datay, dataz, bins, None, 0, tn)
    time3D(datax, datay, dataz, bins, weights, 0, tnw)
    time3D(datax, datay, dataz, bins, None, 1, tn)
    time3D(datax, datay, dataz, bins, weights, 1, tnw)
    time3D(datax, datay, dataz, bins, None, 2, tn)
    time3D(datax, datay, dataz, bins, weights, 2, tnw)

Example 148

Project: spectralDNS Source File: test_shentransforms.py
Function: test_transforms
def test_transforms(ST):
    points, weights = ST.points_and_weights(N)
    fj = np.random.random(N)    

    # Project function to space first
    if not ST.__class__.__name__ == "ChebyshevTransform":
        f_hat = np.zeros(N)
        f_hat = ST.fst(fj, f_hat)
        fj = ST.ifst(f_hat, fj)

    # Then check if transformations work as they should
    u0 = np.zeros(N)    
    u1 = np.zeros(N)
    if ST.__class__.__name__ == "ChebyshevTransform":
        u0 = ST.fct(fj, u0)
        u1 = ST.ifct(u0, u1)
    else:
        u0 = ST.fst(fj, u0)
        u1 = ST.ifst(u0, u1)

    #from IPython import embed; embed()
    assert np.allclose(fj, u1)
    
    # Multidimensional version
    fj = fj.repeat(16).reshape((N, 4, 4)) + 1j*fj.repeat(16).reshape((N, 4, 4))
    u0 = np.zeros((N, 4, 4), dtype=np.complex)    
    u1 = np.zeros((N, 4, 4), dtype=np.complex)
    if ST.__class__.__name__ == "ChebyshevTransform":
        u0 = ST.fct(fj, u0)
        u1 = ST.ifct(u0, u1)
    else:
        u0 = ST.fst(fj, u0)
        u1 = ST.ifst(u0, u1)
    
    assert np.allclose(fj, u1)

Example 149

Project: abstract_rendering Source File: fast_project.py
Function: simple_test
def simple_test():
    from time import time

    use_shape = (4, 10**8)
    chunksize = 10**4
    mock_in = np.random.random(use_shape)
    xform = [3.0, 4.0, 2.0, 2.0]

    t = time()
    check_sum = 0
    for arr in _projectRectsGenerator(xform, mock_in, chunksize):
        check_sum += arr.shape[1]
        np.random.random(1000)
    t = time() - t
    print("checksum (_projectRectsGenerator) took %f ms" % (t*1000))
    chk1 = check_sum

    t = time()
    check_sum = 0
    for arr in _projectRectsGenerator(xform, mock_in, chunksize, use_dispatch = True):
        check_sum += arr.shape[1]
        np.random.random(1000)

    t = time() - t
    print("checksum (_projectRectsGenerator libdispatch) took %f ms" % (t*1000))
    chk2 = check_sum

    t = time()
    out = np.empty(use_shape, dtype=np.int32)
    res = _projectRects(xform, mock_in, out)
    t = time() - t
    print("checksum (_projectRects) took %f ms" % (t*1000))

    if not (chk1 == chk2 == out.shape[1]):
        print('checksums diverge')
        print('%s == %s' % ('chk1', chk1))
        print('%s == %s' % ('chk2', chk2))

    t = time()
    _projectRects(xform, mock_in, out, use_dispatch=True)
    t = time() - t
    out0 = np.copy(out)
    print("c version - libdispatch (double) took %f ms" % (t*1000))

    t = time()
    _projectRects(xform, mock_in, out)
    t = time() - t
    out1 = np.copy(out)
    print("c version (double) took %f ms" % (t*1000))

    t = time()
    _project_element(xform, mock_in, out)
    t = time() - t
    out2 = np.copy(out)
    print("numpy version (double) took %f ms" % (t*1000))

    mock_in = mock_in.astype(np.float32)

    t = time()
    _projectRects(xform, mock_in, out, use_dispatch=True)
    t = time() - t
    out3 = np.copy(out)
    print("c version - libdispatch (single) took %f ms" % (t*1000))

    t = time()
    _projectRects(xform, mock_in, out)
    t = time() - t
    out4 = np.copy(out)
    print("c version (single) took %f ms" % (t*1000))

    t = time()
    _project_element(xform, mock_in, out)
    t = time() - t
    out5 = np.copy(out)
    print("numpy version (single) took %f ms" % (t*1000))


    report_diffs(out0, out2, "libdispatch (double)")
    report_diffs(out1, out2, "plain C (double)")
    report_diffs(out3, out5, "libdispatch (single)")
    report_diffs(out4, out5, "plain C (single)")

Example 150

Project: python-rl Source File: bicycle.py
Function: take_action
    def takeAction(self, intAction):
        T = 2. * ((int(intAction)/3) - 1) # Torque on handle bars
        d = 0.02 * ((intAction % 3) - 1) # Displacement of center of mass (in meters)
        if self.noise > 0:
            d += (numpy.random.random()-0.5)*self.noise # Noise between [-0.02, 0.02] meters

        omega, omega_dot, omega_ddot, theta, theta_dot = tuple(self.state)
        x_f, y_f, x_b, y_b, psi = tuple(self.position)

        for step in range(self.sim_steps):
            if theta == 0: # Infinite radius tends to not be handled well
                r_f = r_b = r_CM = 1.e8
            else:
                r_f = self.l / numpy.abs(numpy.sin(theta))
                r_b = self.l / numpy.abs(numpy.tan(theta))
                r_CM = numpy.sqrt((self.l - self.c)**2 + (self.l**2 / numpy.tan(theta)**2))

            varphi = omega + numpy.arctan(d / self.h)

            omega_ddot = self.h * self.M * self.gravity * numpy.sin(varphi)
            omega_ddot -= numpy.cos(varphi) * (self.Inertia_dv * self.sigma_dot * theta_dot + numpy.sign(theta)*self.v**2*(self.M_d * self.r *(1./r_f + 1./r_b) + self.M*self.h/r_CM))
            omega_ddot /= self.Inertia_bc

            theta_ddot = (T - self.Inertia_dv * self.sigma_dot * omega_dot) / self.Inertia_dl

            df = (self.delta_time / float(self.sim_steps))
            omega_dot += df * omega_ddot
            omega += df * omega_dot
            theta_dot += df * theta_ddot
            theta += df * theta_dot

            # Handle bar limits (80 deg.)
            theta = numpy.clip(theta, self.state_range[3,0], self.state_range[3,1])

            # Update position (x,y) of tires
            front_term = psi + theta + numpy.sign(psi + theta)*numpy.arcsin(self.v * df / (2.*r_f))
            back_term = psi + numpy.sign(psi)*numpy.arcsin(self.v * df / (2.*r_b))
            x_f += -numpy.sin(front_term)
            y_f += numpy.cos(front_term)
            x_b += -numpy.sin(back_term)
            y_b += numpy.cos(back_term)

            # Handle Roundoff errors, to keep the length of the bicycle constant
            dist = numpy.sqrt((x_f-x_b)**2 + (y_f-y_b)**2)
            if numpy.abs(dist - self.l) > 0.01:
                x_b += (x_b - x_f) * (self.l - dist)/dist
                y_b += (y_b - y_f) * (self.l - dist)/dist

            # Update psi
            if x_f==x_b and y_f-y_b < 0:
                psi = numpy.pi
            elif y_f - y_b > 0:
                psi = numpy.arctan((x_b - x_f)/(y_f - y_b))
            else:
                psi = numpy.sign(x_b - x_f)*(numpy.pi/2.) - numpy.arctan((y_f - y_b)/(x_b-x_f))

        self.state = numpy.array([omega, omega_dot, omega_ddot, theta, theta_dot])
        self.position = numpy.array([x_f, y_f, x_b, y_b, psi])

        if numpy.abs(omega) > self.state_range[0,1]: # Bicycle fell over
            return -1.0, True
        elif self.isAtGoal():
            return self.reward_goal, True
        elif not self.navigate:
            return self.reward_shaping, False
        else:
            goal_angle = matrix.vector_angle(self.goal_loc, numpy.array([x_f-x_b, y_f-y_b])) * numpy.pi / 180.
            return (4. - goal_angle**2) * self.reward_shaping, False
See More Examples - Go to Next Page
Page 1 Page 2 Page 3 Selected Page 4