Draw graph paper for samples
500304
def draw_graph_paper(width, height)
      background color: 'white'
      grid width: 50,  height: 50,  stroke_color: '#659ae9', stroke_width: 1.5
      grid width: 200, height: 200, stroke_color: '#659ae9', stroke_width: 3, x: 50, y: 50
      (50..height).step(200) do |y|
        text str: "y=#{y}", x: 3, y: y - 18, font: 'Open Sans, Sans 10'
      end
    end
1061471
def draw(self):
        
        devs = normal(size=self._sig.shape[1])
        p = inner(self._sig, devs) + self._mu
        self._set_stochastics(p)
211033
def draw_tree(t, df, size=10, ratio=0.6, precision=0):
    
    s=export_graphviz(t, out_file=None, feature_names=df.columns, filled=True,
                      special_characters=True, rotate=True, precision=precision)
    IPython.display.display(graphviz.Source(re.sub('Tree {',
       f'Tree {{ size={size}; ratio={ratio}', s)))
366993
def examples(manager: Manager):
    """"""
    for graph in (sialic_acid_graph, statin_graph, homology_graph, braf_graph, egf_graph):
        if manager.has_name_version(graph.name, graph.version):
            click.echo('already inserted {}'.format(graph))
            continue
        click.echo('inserting {}'.format(graph))
        manager.insert_graph(graph, use_tqdm=True)
148654
def _grid_sample(x:TensorImage, coords:FlowField, mode:str='bilinear', padding_mode:str='reflection', remove_out:bool=True)->TensorImage:
    ""
    coords = coords.flow.permute(0, 3, 1, 2).contiguous().permute(0, 2, 3, 1) # optimize layout for grid_sample
    if mode=='bilinear': # hack to get smoother downwards resampling
        mn,mx = coords.min(),coords.max()
        # max amount we're affine zooming by (>1 means zooming in)
        z = 1/(mx-mn).item()*2
        # amount we're resizing by, with 100% extra margin
        d = min(x.shape[1]/coords.shape[1], x.shape[2]/coords.shape[2])/2
        # If we're resizing up by >200%, and we're zooming less than that, interpolate first
        if d>1 and d>z: x = F.interpolate(x[None], scale_factor=1/d, mode='area')[0]
    return F.grid_sample(x[None], coords, mode=mode, padding_mode=padding_mode)[0]
663835
def draw(args):
    """"""
    if len(args) != 2:
        log.error('Two arguments required: [build target] [output file]')
        app.quit(1)

    target = args[0]
    out = args[1]

    try:
        bb = Butcher()
        bb.load_graph(target)
    except error.BrokenGraph as lolno:
        log.fatal(lolno)
        app.quit(1)

    # Filter down to the target and all of its transitive dependencies.
    # TODO: make it possible to optionally draw the entire graph
    filtered_graph = bb.graph.subgraph(
        networkx.topological_sort(bb.graph, nbunch=[address.new(target)]))

    a = networkx.to_agraph(filtered_graph)
    a.draw(out, prog='dot')
    log.info('Graph written to %s', out)
772945
def pretty_view(graph, oriented=False, construction=False,
                graphviz_prog=DEFAULT_GRAPHVIZ_PROG):
    """"""
    layout = create_layout(graph, graphviz_prog=graphviz_prog)
    matrix_view = defaultdict(lambda: ' ')

    # Add the edge to the view

    # print('GRAPH EDGES:', tuple(graph.edges()))
    # print('LAYOUT:', layout)

    edges = ((layout[source], layout[target])
             for source, target in graph.edges())
    # print('EDGES:', tuple(edges))

    for source, target in edges:
        previous_edge_char = None
        previous_position = source
        while source != target:
            for is_dir, transform, edge_char in DIRECTIONS:
                first_loop = previous_edge_char is None
                if is_dir(source, target):
                    previous_source = source
                    source = transform(source)
                    if not first_loop:  # first loop: no previous char
                        char = CHARACTER[previous_edge_char, edge_char]
                        if not isinstance(char, str):
                            char = char.value
                        matrix_view[previous_source] = char
                        if construction:
                            old = defaultdict(lambda: ' ', matrix_view)
                            yield view.build(matrix_view)
                        assert isinstance(matrix_view[previous_source], str)
                    if source != target:
                        previous_edge_char = edge_char
                    previous_position = previous_source
                    break  # for loop ; don't test the remain directions

        if oriented:
            matrix_view[previous_position] = ORIENTATION[previous_edge_char, edge_char]
        if construction:
            yield view.build(matrix_view)

    # mark the place where nodes labels will be added
    # for node, coords in layout.items():
        # matrix_view[coords] = node[0]
    # Add the node labels to the view
    # matrix_view = view.clean(matrix_view)
    for node, (x, y) in layout.items():
        if len(node) == 1:
            matrix_view[x, y] = node
            continue
        row_min, row_max = (view.previous_unwrittable_on_row(matrix_view, (x, y)),
                            view.next_unwrittable_on_row(matrix_view, (x, y)))
        col_min, col_max = (view.previous_unwrittable_on_col(matrix_view, (x, y)),
                              view.next_unwrittable_on_col(matrix_view, (x, y)))
        # print('NODE ' + node + ':',
              # '→row: [{};{}]'.format(row_min, row_max).ljust(20),
              # '↓col: [{};{}]'.format(col_min, col_max))
        print_coords = [itertools.count(x), itertools.cycle((y,))]
        if row_min is None:  # write left to right, end at (x, y)
            if row_max is None or row_max > (x + len(node) / 2):  # enough space at the right
                factor = 2
            else:
                factor = 1
            print_coords[0] = tuple(
                x - (len(node) // factor) + offset + 1
                for offset in range(len(node))
            )
            # print('DEBUG 1:', y, len(node), print_coords[0])
        elif row_max is None:  # write left to right, beginning at (x, y)
            if row_min < (x - len(node) / 2):  # enough space at the left
                factor = 1
            else:
                factor = 0
            print_coords[0] = tuple(
                x + offset - (len(node) // 2) * factor
                for offset in range(len(node))
            )
            # print('DEBUG 2:', print_coords[0])
        elif (row_max - row_min) > len(node) + 1:  # write left to right, if enough place
            print_coords[0] = tuple(
                x + offset
                for offset in range(len(node))
            )
            # print('DEBUG 3:', print_coords[0])

        elif col_min is None:  # write up to down, end at (x, y)
            if col_max is None or col_max > (x + len(node) / 2):  # enough space at the right
                factor = 2
            else:
                factor = 1
            print_coords = (itertools.cycle((x,)), tuple(
                y - (len(node) // factor) + offset + 1
                for offset in range(len(node))
            ))
            # print('DEBUG 4:', y, len(node), print_coords[1])
        elif col_max is None:  # write up to down, beginning at (x, y)
            if col_min < (x - len(node) / 2):  # enough space at the left
                factor = 1
            else:
                factor = 0
            print_coords = (itertools.cycle((x,)), tuple(
                y + offset - (len(node) // 2) * factor
                for offset in range(len(node))
            ))
            # print('DEBUG 5:', print_coords[1])
        elif (col_max - col_min) > len(node) + 1:  # write up to down, if enough place
            print_coords = (itertools.cycle((x,)), tuple(
                y + offset
                for offset in range(len(node))
            ))
            # print('DEBUG 6:', print_coords[1])
        else:  # not enough space
            if (row_max - row_min) > (col_max - col_min):
                # more space on Y axis
                node = node[:row_max - row_min]  # cut the node
                print_coords = (itertools.cycle((x,)), tuple(
                    x + offset
                    for offset in range(len(node))
                ))
                # print('DEBUG 7:', print_coords[1])
            else:
                # more space on X axis
                node = node[:col_max - col_min]  # cut the node
                print_coords[0] = tuple(
                    x + offset
                    for offset in range(len(node))
                )
                # print('DEBUG 8:', print_coords[0])

        for letter, i, j in zip(node, *print_coords):
            matrix_view[i, j] = letter




    if construction:
        yield view.build(matrix_view)
    else:
        yield from view.build(matrix_view)
411972
def show_graphs(self):
        """"""
        elements = itertools.chain.from_iterable(
            ([graph]
             for graph in self.visible_graphs.values()))
        self.graph_place_holder.original_widget = urwid.Pile(elements)
1356980
def sample(self):
        
        lenghts = []
        angles = []
        coordinates = []
        fix = []
        sample_size = int(round(self.trajLen_borders[self.drawFrom('self.trajLen_cumsum', self.getrand('self.trajLen_cumsum'))]))

        coordinates.append([0, 0])
        fix.append(1)
        
        while len(coordinates) < sample_size:
            if len(lenghts) == 0 and len(angles) == 0:          
                angle, length = self._draw(self)
            else:
                angle, length = self._draw(prev_angle = angles[-1], 
                                            prev_length = lenghts[-1])  
                        
            x, y = self._calc_xy(coordinates[-1], angle, length) 
            
            coordinates.append([x, y])
            lenghts.append(length) 
            angles.append(angle)
            fix.append(fix[-1]+1)
        return coordinates
1101578
def random_draw(self, size=None):
        
        return scipy.asarray([scipy.stats.lognorm.rvs(s, loc=0, scale=em, size=size) for s, em in zip(self.sigma, self.emu)])
1085158
def get_draws(fit, variables=None, ignore=None):
    """"""
    if ignore is None:
        ignore = []
    if fit.mode == 1:
        msg = "Model in mode 'test_grad'. Sampling is not conducted."
        raise AttributeError(msg)

    if fit.mode == 2 or fit.sim.get("samples") is None:
        msg = "Fit doesn't contain samples."
        raise AttributeError(msg)

    dtypes = infer_dtypes(fit)

    if variables is None:
        variables = fit.sim["pars_oi"]
    elif isinstance(variables, str):
        variables = [variables]
    variables = list(variables)

    for var, dim in zip(fit.sim["pars_oi"], fit.sim["dims_oi"]):
        if var in variables and np.prod(dim) == 0:
            del variables[variables.index(var)]

    ndraws = [s - w for s, w in zip(fit.sim["n_save"], fit.sim["warmup2"])]
    nchain = len(fit.sim["samples"])

    # check if the values are in 0-based (<=2.17) or 1-based indexing (>=2.18)
    shift = 1
    if any(fit.sim["dims_oi"]):
        # choose variable with lowest number of dims > 1
        par_idx = min((dim, i) for i, dim in enumerate(fit.sim["dims_oi"]) if dim)[1]
        offset = int(sum(map(np.product, fit.sim["dims_oi"][:par_idx])))
        par_offset = int(np.product(fit.sim["dims_oi"][par_idx]))
        par_keys = fit.sim["fnames_oi"][offset : offset + par_offset]
        shift = len(par_keys)
        for item in par_keys:
            _, shape = item.replace("]", "").split("[")
            shape_idx_min = min(int(shape_value) for shape_value in shape.split(","))
            if shape_idx_min < shift:
                shift = shape_idx_min
        # If shift is higher than 1, this will probably mean that Stan
        # has implemented sparse structure (saves only non-zero parts),
        # but let's hope that dims are still corresponding the full shape
        shift = int(min(shift, 1))

    var_keys = OrderedDict((var, []) for var in fit.sim["pars_oi"])
    for key in fit.sim["fnames_oi"]:
        var, *tails = key.split("[")
        loc = [Ellipsis]
        for tail in tails:
            loc = []
            for i in tail[:-1].split(","):
                loc.append(int(i) - shift)
        var_keys[var].append((key, loc))

    shapes = dict(zip(fit.sim["pars_oi"], fit.sim["dims_oi"]))

    variables = [var for var in variables if var not in ignore]

    data = OrderedDict()

    for var in variables:
        if var in data:
            continue
        keys_locs = var_keys.get(var, [(var, [Ellipsis])])
        shape = shapes.get(var, [])
        dtype = dtypes.get(var)

        ndraw = max(ndraws)
        ary_shape = [nchain, ndraw] + shape
        ary = np.empty(ary_shape, dtype=dtype, order="F")
        for chain, (pyholder, ndraw) in enumerate(zip(fit.sim["samples"], ndraws)):
            axes = [chain, slice(None)]
            for key, loc in keys_locs:
                ary_slice = tuple(axes + loc)
                ary[ary_slice] = pyholder.chains[key][-ndraw:]
        data[var] = ary

    return data
654467
def random_graph(out_degree):
  '''
  '''
  n = len(out_degree)
  out_degree = np.asarray(out_degree, dtype=int)
  if (out_degree >= n).any():
    raise ValueError('Cannot have degree >= num_vertices')
  row = np.repeat(np.arange(n), out_degree)
  weights = np.ones_like(row, dtype=float)
  # Generate random edges from 0 to n-2, then shift by one to avoid self-edges.
  col = np.concatenate([np.random.choice(n-1, d, replace=False)
                        for d in out_degree])
  col[col >= row] += 1
  adj = coo_matrix((weights, (row, col)), shape=(n, n))
  return Graph.from_adj_matrix(adj)
735952
def draw(self):
        '''
        
        '''
        observed_arr = self.extract_conditions()
        conv_arr = self.inference(observed_arr)

        if self.__conditon_noise_sampler is not None:
            self.__conditon_noise_sampler.output_shape = conv_arr.shape
            noise_arr = self.__conditon_noise_sampler.generate()
            conv_arr += noise_arr

        deconv_arr = self.__deconvolution_model.inference(conv_arr)
        return np.concatenate((deconv_arr, observed_arr), axis=1)
106685
def show_graph_summary(g):
    
    sample_data = []
    print("list(g[RDFS.Class]) = " + str(len(list(g[RDFS.Class]))))
    # Get Subject Lists
    num_subj = 0
    for subj in g.subjects(RDF.type):
        num_subj += 1
        if num_subj < 5:
            sample_data.append("subjects.subject: " + get_string_from_rdf(subj))
    print("g.subjects(RDF.type) = " + str(num_subj))
    
    # Get Sample of Subjects, Predicates, Objects
    num_subj = 0
    for subj, pred, obj in g:
        num_subj += 1
        if num_subj < 5:
            sample_data.append("g.subject   : " + get_string_from_rdf(pred))
            sample_data.append("g.predicate : " + get_string_from_rdf(subj))
            sample_data.append("g.object    : " + get_string_from_rdf(obj))
            
    print("g.obj(RDF.type) = " + str(num_subj))
    
    
    print ("------ Sample Data ------")
    for line in sample_data:
        print(line)
903680
private int sampleLine(ResultPoint p1, ResultPoint p2, int size) {
    int result = 0;

    float d = distance(p1, p2);
    float moduleSize = d / size;
    float px = p1.getX();
    float py = p1.getY();
    float dx = moduleSize * (p2.getX() - p1.getX()) / d;
    float dy = moduleSize * (p2.getY() - p1.getY()) / d;
    for (int i = 0; i < size; i++) {
      if (image.get(MathUtils.round(px + i * dx), MathUtils.round(py + i * dy))) {
        result |= 1 << (size - i - 1);
      }
    }
    return result;
  }
134104
def _build_graph(self):
        ''''''

        # Set palette colors if necessary
        if not self.colors:
            self.palette = self.env.get_template('palette.js')
            self.template_vars.update({'palette': self.palette.render()})
            self.colors = {x['name']: 'palette.color()' for x in self.json_data}

        template_vars = []
        for index, dataset in enumerate(self.json_data):
            group = 'datagroup' + str(index)
            template_vars.append({'name': str(dataset['name']),
                                  'color': self.colors[dataset['name']],
                                  'data': 'json[{0}].data'.format(index)})

        variables = {'dataset': template_vars, 'width': self.width,
                     'height': self.height, 'render': self.renderer,
                     'chart_id': self.chart_id}
        if not self.y_zero:
            variables.update({'min': "min: 'auto',"})

        graph = self.env.get_template('graph.js')
        self.template_vars.update({'graph': graph.render(variables)})
242622
def _make_graph(self):
        """"""
        self.nodes['graph'] = self.svg.node(
            class_='graph %s-graph %s' % (
                self.__class__.__name__.lower(),
                'horizontal' if self.horizontal else 'vertical'
            )
        )
        self.svg.node(
            self.nodes['graph'],
            'rect',
            class_='background',
            x=0,
            y=0,
            width=self.width,
            height=self.height
        )
        self.nodes['plot'] = self.svg.node(
            self.nodes['graph'],
            class_="plot",
            transform="translate(%d, %d)" %
            (self.margin_box.left, self.margin_box.top)
        )
        self.svg.node(
            self.nodes['plot'],
            'rect',
            class_='background',
            x=0,
            y=0,
            width=self.view.width,
            height=self.view.height
        )
        self.nodes['title'] = self.svg.node(
            self.nodes['graph'], class_="titles"
        )
        self.nodes['overlay'] = self.svg.node(
            self.nodes['graph'],
            class_="plot overlay",
            transform="translate(%d, %d)" %
            (self.margin_box.left, self.margin_box.top)
        )
        self.nodes['text_overlay'] = self.svg.node(
            self.nodes['graph'],
            class_="plot text-overlay",
            transform="translate(%d, %d)" %
            (self.margin_box.left, self.margin_box.top)
        )
        self.nodes['tooltip_overlay'] = self.svg.node(
            self.nodes['graph'],
            class_="plot tooltip-overlay",
            transform="translate(%d, %d)" %
            (self.margin_box.left, self.margin_box.top)
        )
        self.nodes['tooltip'] = self.svg.node(
            self.nodes['tooltip_overlay'],
            transform='translate(0 0)',
            style="opacity: 0",
            **{'class': 'tooltip'}
        )

        self.svg.node(
            self.nodes['tooltip'],
            'rect',
            rx=self.tooltip_border_radius,
            ry=self.tooltip_border_radius,
            width=0,
            height=0,
            **{'class': 'tooltip-box'}
        )
        self.svg.node(self.nodes['tooltip'], 'g', class_='text')